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
starqiu/RDMP1
src/main/java/ustc/sse/controller/UserController.java
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // }
import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ustc.sse.model.User; import ustc.sse.service.UserService;
/* * ============================================================ * The SSE USTC Software License * * UserController.java * 2014-4-22 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.controller; /** * 实现功能: 对用户的增删改查 * <p> * date author email notes<br /> * ----------------------------------------------------------------<br /> *2014-2-19 邱星 [email protected] 新建类<br /></p> * */ @Controller public class UserController { private final static Log log = LogFactory.getLog(UserController.class); @Resource
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // } // Path: src/main/java/ustc/sse/controller/UserController.java import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ustc.sse.model.User; import ustc.sse.service.UserService; /* * ============================================================ * The SSE USTC Software License * * UserController.java * 2014-4-22 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.controller; /** * 实现功能: 对用户的增删改查 * <p> * date author email notes<br /> * ----------------------------------------------------------------<br /> *2014-2-19 邱星 [email protected] 新建类<br /></p> * */ @Controller public class UserController { private final static Log log = LogFactory.getLog(UserController.class); @Resource
private UserService userService;
starqiu/RDMP1
src/main/java/ustc/sse/controller/UserController.java
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // }
import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ustc.sse.model.User; import ustc.sse.service.UserService;
/* * ============================================================ * The SSE USTC Software License * * UserController.java * 2014-4-22 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.controller; /** * 实现功能: 对用户的增删改查 * <p> * date author email notes<br /> * ----------------------------------------------------------------<br /> *2014-2-19 邱星 [email protected] 新建类<br /></p> * */ @Controller public class UserController { private final static Log log = LogFactory.getLog(UserController.class); @Resource private UserService userService; private String userName; public UserController() { super(); } /** * 显示用户资料 * * @param request * @param response * @return */ @RequestMapping("userInfo") public String userInfo(HttpServletRequest request, HttpServletResponse response) { userName = request.getParameter("userName");//管理员点击 if (null == userName) {//点击设置修改自身用户资料 userName = (String) request.getSession().getAttribute("userName"); } if (null != userName) {
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // } // Path: src/main/java/ustc/sse/controller/UserController.java import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ustc.sse.model.User; import ustc.sse.service.UserService; /* * ============================================================ * The SSE USTC Software License * * UserController.java * 2014-4-22 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.controller; /** * 实现功能: 对用户的增删改查 * <p> * date author email notes<br /> * ----------------------------------------------------------------<br /> *2014-2-19 邱星 [email protected] 新建类<br /></p> * */ @Controller public class UserController { private final static Log log = LogFactory.getLog(UserController.class); @Resource private UserService userService; private String userName; public UserController() { super(); } /** * 显示用户资料 * * @param request * @param response * @return */ @RequestMapping("userInfo") public String userInfo(HttpServletRequest request, HttpServletResponse response) { userName = request.getParameter("userName");//管理员点击 if (null == userName) {//点击设置修改自身用户资料 userName = (String) request.getSession().getAttribute("userName"); } if (null != userName) {
User param = new User();
apache/activemq-activeio
activeio-core/src/test/java/org/apache/activeio/journal/active/DataStruturesTest.java
// Path: activeio-core/src/main/java/org/apache/activeio/journal/active/Location.java // final public class Location implements RecordLocation { // // static final public int SERIALIZED_SIZE=8; // // final private int logFileId; // final private int logFileOffset; // // public Location(int logFileId, int fileOffset) { // this.logFileId = logFileId; // this.logFileOffset = fileOffset; // } // // public int compareTo(Object o) { // int rc = logFileId - ((Location) o).logFileId; // if (rc != 0) // return rc; // // return logFileOffset - ((Location) o).logFileOffset; // } // // public int hashCode() { // return logFileOffset ^ logFileId; // } // // public boolean equals(Object o) { // if (o == null || o.getClass() != Location.class) // return false; // Location rl = (Location) o; // return rl.logFileId == this.logFileId && rl.logFileOffset == this.logFileOffset; // } // // public String toString() { // return "" + logFileId + ":" + logFileOffset; // } // // public int getLogFileId() { // return logFileId; // } // // public int getLogFileOffset() { // return logFileOffset; // } // // public void writeToPacket(Packet packet) throws IOException { // PacketData data = new PacketData(packet); // data.writeInt(logFileId); // data.writeInt(logFileOffset); // } // // public void writeToDataOutput(DataOutput data) throws IOException { // data.writeInt(logFileId); // data.writeInt(logFileOffset); // } // // static public Location readFromPacket(Packet packet) throws IOException { // PacketData data = new PacketData(packet); // return new Location(data.readInt(), data.readInt()); // } // // public static Location readFromDataInput(DataInput data) throws IOException { // return new Location(data.readInt(), data.readInt()); // } // // // }
import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import org.apache.activeio.journal.active.Location; import junit.framework.TestCase;
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; /** * Tests the data structures used JournalImpl * * @version $Revision: 1.1 $ */ public class DataStruturesTest extends TestCase { synchronized public void testRecordLocationImplComparison() throws IOException {
// Path: activeio-core/src/main/java/org/apache/activeio/journal/active/Location.java // final public class Location implements RecordLocation { // // static final public int SERIALIZED_SIZE=8; // // final private int logFileId; // final private int logFileOffset; // // public Location(int logFileId, int fileOffset) { // this.logFileId = logFileId; // this.logFileOffset = fileOffset; // } // // public int compareTo(Object o) { // int rc = logFileId - ((Location) o).logFileId; // if (rc != 0) // return rc; // // return logFileOffset - ((Location) o).logFileOffset; // } // // public int hashCode() { // return logFileOffset ^ logFileId; // } // // public boolean equals(Object o) { // if (o == null || o.getClass() != Location.class) // return false; // Location rl = (Location) o; // return rl.logFileId == this.logFileId && rl.logFileOffset == this.logFileOffset; // } // // public String toString() { // return "" + logFileId + ":" + logFileOffset; // } // // public int getLogFileId() { // return logFileId; // } // // public int getLogFileOffset() { // return logFileOffset; // } // // public void writeToPacket(Packet packet) throws IOException { // PacketData data = new PacketData(packet); // data.writeInt(logFileId); // data.writeInt(logFileOffset); // } // // public void writeToDataOutput(DataOutput data) throws IOException { // data.writeInt(logFileId); // data.writeInt(logFileOffset); // } // // static public Location readFromPacket(Packet packet) throws IOException { // PacketData data = new PacketData(packet); // return new Location(data.readInt(), data.readInt()); // } // // public static Location readFromDataInput(DataInput data) throws IOException { // return new Location(data.readInt(), data.readInt()); // } // // // } // Path: activeio-core/src/test/java/org/apache/activeio/journal/active/DataStruturesTest.java import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import org.apache.activeio.journal.active.Location; import junit.framework.TestCase; /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.journal.active; /** * Tests the data structures used JournalImpl * * @version $Revision: 1.1 $ */ public class DataStruturesTest extends TestCase { synchronized public void testRecordLocationImplComparison() throws IOException {
Location l1 = new Location(0, 1);
apache/activemq-activeio
activeio-core/src/main/java/org/apache/activeio/xnet/hba/ServiceAccessController.java
// Path: activeio-core/src/main/java/org/apache/activeio/xnet/ServerService.java // public interface ServerService extends SocketService { // // public void init(Properties props) throws Exception; // // public void start() throws ServiceException; // // public void stop() throws ServiceException; // // // /** // * Gets the ip number that the // * daemon is listening on. // */ // public String getIP(); // // /** // * Gets the port number that the // * daemon is listening on. // */ // public int getPort(); // // // } // // Path: activeio-core/src/main/java/org/apache/activeio/xnet/ServiceException.java // public class ServiceException extends Exception { // // /** // * <p/> // * Default constructor, which simply delegates exception // * handling up the inheritance chain to <code>Exception</code>. // * </p> // */ // public ServiceException() { // super(); // } // // /** // * <p/> // * This constructor allows a message to be supplied indicating the source // * of the problem that occurred. // * </p> // * // * @param message <code>String</code> identifying the cause of the problem. // */ // public ServiceException(String message) { // super(message); // } // // /** // * <p/> // * This constructor allows a "root cause" exception to be supplied, // * which may later be used by the wrapping application. // * </p> // * // * @param rootCause <code>Throwable</code> that triggered the problem. // */ // public ServiceException(Throwable rootCause) { // super(rootCause); // } // // /** // * This constructor allows both a message identifying the // * problem that occurred as well as a "root cause" exception // * to be supplied, which may later be used by the wrapping // * application. // * // * @param message <code>String</code> identifying the cause of the problem. // * @param rootCause <code>Throwable</code> that triggered this problem. // */ // public ServiceException(String message, Throwable rootCause) { // super(message, rootCause); // } // // }
import org.apache.activeio.xnet.ServerService; import org.apache.activeio.xnet.ServiceException; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.Properties; import java.util.StringTokenizer;
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; public class ServiceAccessController implements ServerService { private final ServerService next; private IPAddressPermission[] allowHosts; public ServiceAccessController(ServerService next) { this.next = next; } public ServiceAccessController(String name, ServerService next, IPAddressPermission[] ipAddressMasks) { this.next = next; this.allowHosts = ipAddressMasks; }
// Path: activeio-core/src/main/java/org/apache/activeio/xnet/ServerService.java // public interface ServerService extends SocketService { // // public void init(Properties props) throws Exception; // // public void start() throws ServiceException; // // public void stop() throws ServiceException; // // // /** // * Gets the ip number that the // * daemon is listening on. // */ // public String getIP(); // // /** // * Gets the port number that the // * daemon is listening on. // */ // public int getPort(); // // // } // // Path: activeio-core/src/main/java/org/apache/activeio/xnet/ServiceException.java // public class ServiceException extends Exception { // // /** // * <p/> // * Default constructor, which simply delegates exception // * handling up the inheritance chain to <code>Exception</code>. // * </p> // */ // public ServiceException() { // super(); // } // // /** // * <p/> // * This constructor allows a message to be supplied indicating the source // * of the problem that occurred. // * </p> // * // * @param message <code>String</code> identifying the cause of the problem. // */ // public ServiceException(String message) { // super(message); // } // // /** // * <p/> // * This constructor allows a "root cause" exception to be supplied, // * which may later be used by the wrapping application. // * </p> // * // * @param rootCause <code>Throwable</code> that triggered the problem. // */ // public ServiceException(Throwable rootCause) { // super(rootCause); // } // // /** // * This constructor allows both a message identifying the // * problem that occurred as well as a "root cause" exception // * to be supplied, which may later be used by the wrapping // * application. // * // * @param message <code>String</code> identifying the cause of the problem. // * @param rootCause <code>Throwable</code> that triggered this problem. // */ // public ServiceException(String message, Throwable rootCause) { // super(message, rootCause); // } // // } // Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/ServiceAccessController.java import org.apache.activeio.xnet.ServerService; import org.apache.activeio.xnet.ServiceException; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.Properties; import java.util.StringTokenizer; /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet.hba; public class ServiceAccessController implements ServerService { private final ServerService next; private IPAddressPermission[] allowHosts; public ServiceAccessController(ServerService next) { this.next = next; } public ServiceAccessController(String name, ServerService next, IPAddressPermission[] ipAddressMasks) { this.next = next; this.allowHosts = ipAddressMasks; }
public void service(Socket socket) throws ServiceException, IOException {
apache/activemq-activeio
activeio-core/src/main/java/org/apache/activeio/xnet/StandardServiceStack.java
// Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/IPAddressPermission.java // public interface IPAddressPermission extends Serializable { // public boolean implies(InetAddress address); // } // // Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/ServiceAccessController.java // public class ServiceAccessController implements ServerService { // private final ServerService next; // private IPAddressPermission[] allowHosts; // // public ServiceAccessController(ServerService next) { // this.next = next; // } // // public ServiceAccessController(String name, ServerService next, IPAddressPermission[] ipAddressMasks) { // this.next = next; // this.allowHosts = ipAddressMasks; // } // // public void service(Socket socket) throws ServiceException, IOException { // // Check authorization // checkHostsAuthorization(socket.getInetAddress(), socket.getLocalAddress()); // // next.service(socket); // } // // public IPAddressPermission[] getAllowHosts() { // return allowHosts; // } // // public void setAllowHosts(IPAddressPermission[] ipAddressMasks) { // this.allowHosts = ipAddressMasks; // } // // public void checkHostsAuthorization(InetAddress clientAddress, InetAddress serverAddress) throws SecurityException { // // Check the client ip against the server ip. Hosts are // // allowed to access themselves, so if these ips // // match, the following for loop will be skipped. // if (clientAddress.equals(serverAddress)) { // return; // } // // for (int i = 0; i < allowHosts.length; i++) { // if (allowHosts[i].implies(clientAddress)) { // return; // } // } // // throw new SecurityException("Host " + clientAddress.getHostAddress() + " is not authorized to access this service."); // } // // private void parseAdminIPs(Properties props) throws ServiceException { // LinkedList ipAddressMasksList = new LinkedList(); // // try { // InetAddress[] localIps = InetAddress.getAllByName("localhost"); // for (int i = 0; i < localIps.length; i++) { // if (localIps[i] instanceof Inet4Address) { // ipAddressMasksList.add(new ExactIPAddressPermission(localIps[i].getAddress())); // } else { // ipAddressMasksList.add(new ExactIPv6AddressPermission(localIps[i].getAddress())); // } // } // } catch (UnknownHostException e) { // throw new ServiceException("Could not get localhost inet address", e); // } // // String ipString = props.getProperty("only_from"); // if (ipString != null) { // StringTokenizer st = new StringTokenizer(ipString, " "); // while (st.hasMoreTokens()) { // String mask = st.nextToken(); // ipAddressMasksList.add(IPAddressPermissionFactory.getIPAddressMask(mask)); // } // } // // allowHosts = (IPAddressPermission[]) ipAddressMasksList.toArray(new IPAddressPermission[ipAddressMasksList.size()]); // } // // public void init(Properties props) throws Exception { // parseAdminIPs(props); // next.init(props); // } // // public void start() throws ServiceException { // next.start(); // } // // public void stop() throws ServiceException { // next.stop(); // } // // public String getName() { // return next.getName(); // } // // public String getIP() { // return next.getIP(); // } // // public int getPort() { // return next.getPort(); // } // // }
import edu.emory.mathcs.backport.java.util.concurrent.Executor; import org.apache.activeio.xnet.hba.IPAddressPermission; import org.apache.activeio.xnet.hba.ServiceAccessController; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException;
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; public class StandardServiceStack { private String name; private ServiceDaemon daemon; private ServiceLogger logger;
// Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/IPAddressPermission.java // public interface IPAddressPermission extends Serializable { // public boolean implies(InetAddress address); // } // // Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/ServiceAccessController.java // public class ServiceAccessController implements ServerService { // private final ServerService next; // private IPAddressPermission[] allowHosts; // // public ServiceAccessController(ServerService next) { // this.next = next; // } // // public ServiceAccessController(String name, ServerService next, IPAddressPermission[] ipAddressMasks) { // this.next = next; // this.allowHosts = ipAddressMasks; // } // // public void service(Socket socket) throws ServiceException, IOException { // // Check authorization // checkHostsAuthorization(socket.getInetAddress(), socket.getLocalAddress()); // // next.service(socket); // } // // public IPAddressPermission[] getAllowHosts() { // return allowHosts; // } // // public void setAllowHosts(IPAddressPermission[] ipAddressMasks) { // this.allowHosts = ipAddressMasks; // } // // public void checkHostsAuthorization(InetAddress clientAddress, InetAddress serverAddress) throws SecurityException { // // Check the client ip against the server ip. Hosts are // // allowed to access themselves, so if these ips // // match, the following for loop will be skipped. // if (clientAddress.equals(serverAddress)) { // return; // } // // for (int i = 0; i < allowHosts.length; i++) { // if (allowHosts[i].implies(clientAddress)) { // return; // } // } // // throw new SecurityException("Host " + clientAddress.getHostAddress() + " is not authorized to access this service."); // } // // private void parseAdminIPs(Properties props) throws ServiceException { // LinkedList ipAddressMasksList = new LinkedList(); // // try { // InetAddress[] localIps = InetAddress.getAllByName("localhost"); // for (int i = 0; i < localIps.length; i++) { // if (localIps[i] instanceof Inet4Address) { // ipAddressMasksList.add(new ExactIPAddressPermission(localIps[i].getAddress())); // } else { // ipAddressMasksList.add(new ExactIPv6AddressPermission(localIps[i].getAddress())); // } // } // } catch (UnknownHostException e) { // throw new ServiceException("Could not get localhost inet address", e); // } // // String ipString = props.getProperty("only_from"); // if (ipString != null) { // StringTokenizer st = new StringTokenizer(ipString, " "); // while (st.hasMoreTokens()) { // String mask = st.nextToken(); // ipAddressMasksList.add(IPAddressPermissionFactory.getIPAddressMask(mask)); // } // } // // allowHosts = (IPAddressPermission[]) ipAddressMasksList.toArray(new IPAddressPermission[ipAddressMasksList.size()]); // } // // public void init(Properties props) throws Exception { // parseAdminIPs(props); // next.init(props); // } // // public void start() throws ServiceException { // next.start(); // } // // public void stop() throws ServiceException { // next.stop(); // } // // public String getName() { // return next.getName(); // } // // public String getIP() { // return next.getIP(); // } // // public int getPort() { // return next.getPort(); // } // // } // Path: activeio-core/src/main/java/org/apache/activeio/xnet/StandardServiceStack.java import edu.emory.mathcs.backport.java.util.concurrent.Executor; import org.apache.activeio.xnet.hba.IPAddressPermission; import org.apache.activeio.xnet.hba.ServiceAccessController; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; public class StandardServiceStack { private String name; private ServiceDaemon daemon; private ServiceLogger logger;
private ServiceAccessController hba;
apache/activemq-activeio
activeio-core/src/main/java/org/apache/activeio/xnet/StandardServiceStack.java
// Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/IPAddressPermission.java // public interface IPAddressPermission extends Serializable { // public boolean implies(InetAddress address); // } // // Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/ServiceAccessController.java // public class ServiceAccessController implements ServerService { // private final ServerService next; // private IPAddressPermission[] allowHosts; // // public ServiceAccessController(ServerService next) { // this.next = next; // } // // public ServiceAccessController(String name, ServerService next, IPAddressPermission[] ipAddressMasks) { // this.next = next; // this.allowHosts = ipAddressMasks; // } // // public void service(Socket socket) throws ServiceException, IOException { // // Check authorization // checkHostsAuthorization(socket.getInetAddress(), socket.getLocalAddress()); // // next.service(socket); // } // // public IPAddressPermission[] getAllowHosts() { // return allowHosts; // } // // public void setAllowHosts(IPAddressPermission[] ipAddressMasks) { // this.allowHosts = ipAddressMasks; // } // // public void checkHostsAuthorization(InetAddress clientAddress, InetAddress serverAddress) throws SecurityException { // // Check the client ip against the server ip. Hosts are // // allowed to access themselves, so if these ips // // match, the following for loop will be skipped. // if (clientAddress.equals(serverAddress)) { // return; // } // // for (int i = 0; i < allowHosts.length; i++) { // if (allowHosts[i].implies(clientAddress)) { // return; // } // } // // throw new SecurityException("Host " + clientAddress.getHostAddress() + " is not authorized to access this service."); // } // // private void parseAdminIPs(Properties props) throws ServiceException { // LinkedList ipAddressMasksList = new LinkedList(); // // try { // InetAddress[] localIps = InetAddress.getAllByName("localhost"); // for (int i = 0; i < localIps.length; i++) { // if (localIps[i] instanceof Inet4Address) { // ipAddressMasksList.add(new ExactIPAddressPermission(localIps[i].getAddress())); // } else { // ipAddressMasksList.add(new ExactIPv6AddressPermission(localIps[i].getAddress())); // } // } // } catch (UnknownHostException e) { // throw new ServiceException("Could not get localhost inet address", e); // } // // String ipString = props.getProperty("only_from"); // if (ipString != null) { // StringTokenizer st = new StringTokenizer(ipString, " "); // while (st.hasMoreTokens()) { // String mask = st.nextToken(); // ipAddressMasksList.add(IPAddressPermissionFactory.getIPAddressMask(mask)); // } // } // // allowHosts = (IPAddressPermission[]) ipAddressMasksList.toArray(new IPAddressPermission[ipAddressMasksList.size()]); // } // // public void init(Properties props) throws Exception { // parseAdminIPs(props); // next.init(props); // } // // public void start() throws ServiceException { // next.start(); // } // // public void stop() throws ServiceException { // next.stop(); // } // // public String getName() { // return next.getName(); // } // // public String getIP() { // return next.getIP(); // } // // public int getPort() { // return next.getPort(); // } // // }
import edu.emory.mathcs.backport.java.util.concurrent.Executor; import org.apache.activeio.xnet.hba.IPAddressPermission; import org.apache.activeio.xnet.hba.ServiceAccessController; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException;
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; public class StandardServiceStack { private String name; private ServiceDaemon daemon; private ServiceLogger logger; private ServiceAccessController hba; private ServicePool pool; private ServerService server; private String host;
// Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/IPAddressPermission.java // public interface IPAddressPermission extends Serializable { // public boolean implies(InetAddress address); // } // // Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/ServiceAccessController.java // public class ServiceAccessController implements ServerService { // private final ServerService next; // private IPAddressPermission[] allowHosts; // // public ServiceAccessController(ServerService next) { // this.next = next; // } // // public ServiceAccessController(String name, ServerService next, IPAddressPermission[] ipAddressMasks) { // this.next = next; // this.allowHosts = ipAddressMasks; // } // // public void service(Socket socket) throws ServiceException, IOException { // // Check authorization // checkHostsAuthorization(socket.getInetAddress(), socket.getLocalAddress()); // // next.service(socket); // } // // public IPAddressPermission[] getAllowHosts() { // return allowHosts; // } // // public void setAllowHosts(IPAddressPermission[] ipAddressMasks) { // this.allowHosts = ipAddressMasks; // } // // public void checkHostsAuthorization(InetAddress clientAddress, InetAddress serverAddress) throws SecurityException { // // Check the client ip against the server ip. Hosts are // // allowed to access themselves, so if these ips // // match, the following for loop will be skipped. // if (clientAddress.equals(serverAddress)) { // return; // } // // for (int i = 0; i < allowHosts.length; i++) { // if (allowHosts[i].implies(clientAddress)) { // return; // } // } // // throw new SecurityException("Host " + clientAddress.getHostAddress() + " is not authorized to access this service."); // } // // private void parseAdminIPs(Properties props) throws ServiceException { // LinkedList ipAddressMasksList = new LinkedList(); // // try { // InetAddress[] localIps = InetAddress.getAllByName("localhost"); // for (int i = 0; i < localIps.length; i++) { // if (localIps[i] instanceof Inet4Address) { // ipAddressMasksList.add(new ExactIPAddressPermission(localIps[i].getAddress())); // } else { // ipAddressMasksList.add(new ExactIPv6AddressPermission(localIps[i].getAddress())); // } // } // } catch (UnknownHostException e) { // throw new ServiceException("Could not get localhost inet address", e); // } // // String ipString = props.getProperty("only_from"); // if (ipString != null) { // StringTokenizer st = new StringTokenizer(ipString, " "); // while (st.hasMoreTokens()) { // String mask = st.nextToken(); // ipAddressMasksList.add(IPAddressPermissionFactory.getIPAddressMask(mask)); // } // } // // allowHosts = (IPAddressPermission[]) ipAddressMasksList.toArray(new IPAddressPermission[ipAddressMasksList.size()]); // } // // public void init(Properties props) throws Exception { // parseAdminIPs(props); // next.init(props); // } // // public void start() throws ServiceException { // next.start(); // } // // public void stop() throws ServiceException { // next.stop(); // } // // public String getName() { // return next.getName(); // } // // public String getIP() { // return next.getIP(); // } // // public int getPort() { // return next.getPort(); // } // // } // Path: activeio-core/src/main/java/org/apache/activeio/xnet/StandardServiceStack.java import edu.emory.mathcs.backport.java.util.concurrent.Executor; import org.apache.activeio.xnet.hba.IPAddressPermission; import org.apache.activeio.xnet.hba.ServiceAccessController; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; public class StandardServiceStack { private String name; private ServiceDaemon daemon; private ServiceLogger logger; private ServiceAccessController hba; private ServicePool pool; private ServerService server; private String host;
public StandardServiceStack(String name, int port, String host, IPAddressPermission[] allowHosts, String[] logOnSuccess, String[] logOnFailure, Executor executor, ServerService server) throws UnknownHostException {
apache/activemq-activeio
activeio-core/src/main/java/org/apache/activeio/oneport/HttpRecognizer.java
// Path: activeio-core/src/main/java/org/apache/activeio/packet/Packet.java // public interface Packet { // // public int position(); // public void position(int position); // public int limit(); // public void limit(int limit); // public void flip(); // public int remaining(); // public void rewind(); // public boolean hasRemaining(); // public void clear(); // public Packet slice(); // public Packet duplicate(); // public Object duplicate(ClassLoader cl) throws IOException; // public int capacity(); // public void dispose(); // // public ByteSequence asByteSequence(); // public byte[] sliceAsBytes(); // // /** // * @Return object that is an instance of requested type and is associated this this object. May return null if no // * object of that type is associated. // */ // Object getAdapter(Class target); // // // /** // * Writes the remaing bytes in the packet to the output stream. // * // * @param out // * @return // */ // void writeTo(OutputStream out) throws IOException; // void writeTo(DataOutput out) throws IOException; // // // To read data out of the packet. // public int read(); // public int read(byte data[], int offset, int length); // // // To write data into the packet. // public boolean write( int data ); // public int write( byte data[], int offset, int length ); // public int read(Packet dest); // // }
import java.util.HashSet; import org.apache.activeio.packet.Packet;
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; public class HttpRecognizer implements ProtocolRecognizer { static private HashSet methods = new HashSet(); static { // This list built using: http://www.w3.org/Protocols/HTTP/Methods.html methods.add("GET "); methods.add("PUT "); methods.add("POST "); methods.add("HEAD "); methods.add("LINK "); methods.add("TRACE "); methods.add("UNLINK "); methods.add("SEARCH "); methods.add("DELETE "); methods.add("CHECKIN "); methods.add("OPTIONS "); methods.add("CONNECT "); methods.add("CHECKOUT "); methods.add("SPACEJUMP "); methods.add("SHOWMETHOD "); methods.add("TEXTSEARCH "); } static final public HttpRecognizer HTTP_RECOGNIZER = new HttpRecognizer(); private HttpRecognizer() {}
// Path: activeio-core/src/main/java/org/apache/activeio/packet/Packet.java // public interface Packet { // // public int position(); // public void position(int position); // public int limit(); // public void limit(int limit); // public void flip(); // public int remaining(); // public void rewind(); // public boolean hasRemaining(); // public void clear(); // public Packet slice(); // public Packet duplicate(); // public Object duplicate(ClassLoader cl) throws IOException; // public int capacity(); // public void dispose(); // // public ByteSequence asByteSequence(); // public byte[] sliceAsBytes(); // // /** // * @Return object that is an instance of requested type and is associated this this object. May return null if no // * object of that type is associated. // */ // Object getAdapter(Class target); // // // /** // * Writes the remaing bytes in the packet to the output stream. // * // * @param out // * @return // */ // void writeTo(OutputStream out) throws IOException; // void writeTo(DataOutput out) throws IOException; // // // To read data out of the packet. // public int read(); // public int read(byte data[], int offset, int length); // // // To write data into the packet. // public boolean write( int data ); // public int write( byte data[], int offset, int length ); // public int read(Packet dest); // // } // Path: activeio-core/src/main/java/org/apache/activeio/oneport/HttpRecognizer.java import java.util.HashSet; import org.apache.activeio.packet.Packet; /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; public class HttpRecognizer implements ProtocolRecognizer { static private HashSet methods = new HashSet(); static { // This list built using: http://www.w3.org/Protocols/HTTP/Methods.html methods.add("GET "); methods.add("PUT "); methods.add("POST "); methods.add("HEAD "); methods.add("LINK "); methods.add("TRACE "); methods.add("UNLINK "); methods.add("SEARCH "); methods.add("DELETE "); methods.add("CHECKIN "); methods.add("OPTIONS "); methods.add("CONNECT "); methods.add("CHECKOUT "); methods.add("SPACEJUMP "); methods.add("SHOWMETHOD "); methods.add("TEXTSEARCH "); } static final public HttpRecognizer HTTP_RECOGNIZER = new HttpRecognizer(); private HttpRecognizer() {}
public boolean recognizes(Packet packet) {
apache/activemq-activeio
activeio-core/src/main/java/org/apache/activeio/xnet/StandardServiceStackGBean.java
// Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/IPAddressPermission.java // public interface IPAddressPermission extends Serializable { // public boolean implies(InetAddress address); // }
import javax.management.ObjectName; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.net.SocketException; import java.io.IOException; import edu.emory.mathcs.backport.java.util.concurrent.Executor; import org.apache.activeio.xnet.hba.IPAddressPermission; import org.apache.geronimo.gbean.GBeanData; import org.apache.geronimo.gbean.GBeanInfo; import org.apache.geronimo.gbean.GBeanInfoBuilder; import org.apache.geronimo.gbean.GBeanLifecycle; import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory; import org.apache.geronimo.kernel.GBeanAlreadyExistsException; import org.apache.geronimo.kernel.GBeanNotFoundException; import org.apache.geronimo.kernel.Kernel; import org.apache.geronimo.kernel.jmx.JMXUtil;
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; public class StandardServiceStackGBean implements GBeanLifecycle { private final StandardServiceStack standardServiceStack;
// Path: activeio-core/src/main/java/org/apache/activeio/xnet/hba/IPAddressPermission.java // public interface IPAddressPermission extends Serializable { // public boolean implies(InetAddress address); // } // Path: activeio-core/src/main/java/org/apache/activeio/xnet/StandardServiceStackGBean.java import javax.management.ObjectName; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.net.SocketException; import java.io.IOException; import edu.emory.mathcs.backport.java.util.concurrent.Executor; import org.apache.activeio.xnet.hba.IPAddressPermission; import org.apache.geronimo.gbean.GBeanData; import org.apache.geronimo.gbean.GBeanInfo; import org.apache.geronimo.gbean.GBeanInfoBuilder; import org.apache.geronimo.gbean.GBeanLifecycle; import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory; import org.apache.geronimo.kernel.GBeanAlreadyExistsException; import org.apache.geronimo.kernel.GBeanNotFoundException; import org.apache.geronimo.kernel.Kernel; import org.apache.geronimo.kernel.jmx.JMXUtil; /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.xnet; public class StandardServiceStackGBean implements GBeanLifecycle { private final StandardServiceStack standardServiceStack;
public StandardServiceStackGBean(String name, int port, String host, IPAddressPermission[] allowHosts, String[] logOnSuccess, String[] logOnFailure, Executor executor, ServerService server) throws UnknownHostException {
apache/activemq-activeio
activeio-core/src/main/java/org/apache/activeio/oneport/IIOPRecognizer.java
// Path: activeio-core/src/main/java/org/apache/activeio/packet/Packet.java // public interface Packet { // // public int position(); // public void position(int position); // public int limit(); // public void limit(int limit); // public void flip(); // public int remaining(); // public void rewind(); // public boolean hasRemaining(); // public void clear(); // public Packet slice(); // public Packet duplicate(); // public Object duplicate(ClassLoader cl) throws IOException; // public int capacity(); // public void dispose(); // // public ByteSequence asByteSequence(); // public byte[] sliceAsBytes(); // // /** // * @Return object that is an instance of requested type and is associated this this object. May return null if no // * object of that type is associated. // */ // Object getAdapter(Class target); // // // /** // * Writes the remaing bytes in the packet to the output stream. // * // * @param out // * @return // */ // void writeTo(OutputStream out) throws IOException; // void writeTo(DataOutput out) throws IOException; // // // To read data out of the packet. // public int read(); // public int read(byte data[], int offset, int length); // // // To write data into the packet. // public boolean write( int data ); // public int write( byte data[], int offset, int length ); // public int read(Packet dest); // // }
import org.apache.activeio.packet.Packet;
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; public class IIOPRecognizer implements ProtocolRecognizer { static final public IIOPRecognizer IIOP_RECOGNIZER = new IIOPRecognizer(); private IIOPRecognizer() {}
// Path: activeio-core/src/main/java/org/apache/activeio/packet/Packet.java // public interface Packet { // // public int position(); // public void position(int position); // public int limit(); // public void limit(int limit); // public void flip(); // public int remaining(); // public void rewind(); // public boolean hasRemaining(); // public void clear(); // public Packet slice(); // public Packet duplicate(); // public Object duplicate(ClassLoader cl) throws IOException; // public int capacity(); // public void dispose(); // // public ByteSequence asByteSequence(); // public byte[] sliceAsBytes(); // // /** // * @Return object that is an instance of requested type and is associated this this object. May return null if no // * object of that type is associated. // */ // Object getAdapter(Class target); // // // /** // * Writes the remaing bytes in the packet to the output stream. // * // * @param out // * @return // */ // void writeTo(OutputStream out) throws IOException; // void writeTo(DataOutput out) throws IOException; // // // To read data out of the packet. // public int read(); // public int read(byte data[], int offset, int length); // // // To write data into the packet. // public boolean write( int data ); // public int write( byte data[], int offset, int length ); // public int read(Packet dest); // // } // Path: activeio-core/src/main/java/org/apache/activeio/oneport/IIOPRecognizer.java import org.apache.activeio.packet.Packet; /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; public class IIOPRecognizer implements ProtocolRecognizer { static final public IIOPRecognizer IIOP_RECOGNIZER = new IIOPRecognizer(); private IIOPRecognizer() {}
public boolean recognizes(Packet packet) {
apache/activemq-activeio
activeio-core/src/main/java/org/apache/activeio/oneport/UnknownRecognizer.java
// Path: activeio-core/src/main/java/org/apache/activeio/packet/Packet.java // public interface Packet { // // public int position(); // public void position(int position); // public int limit(); // public void limit(int limit); // public void flip(); // public int remaining(); // public void rewind(); // public boolean hasRemaining(); // public void clear(); // public Packet slice(); // public Packet duplicate(); // public Object duplicate(ClassLoader cl) throws IOException; // public int capacity(); // public void dispose(); // // public ByteSequence asByteSequence(); // public byte[] sliceAsBytes(); // // /** // * @Return object that is an instance of requested type and is associated this this object. May return null if no // * object of that type is associated. // */ // Object getAdapter(Class target); // // // /** // * Writes the remaing bytes in the packet to the output stream. // * // * @param out // * @return // */ // void writeTo(OutputStream out) throws IOException; // void writeTo(DataOutput out) throws IOException; // // // To read data out of the packet. // public int read(); // public int read(byte data[], int offset, int length); // // // To write data into the packet. // public boolean write( int data ); // public int write( byte data[], int offset, int length ); // public int read(Packet dest); // // }
import org.apache.activeio.packet.Packet;
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; class UnknownRecognizer implements ProtocolRecognizer { static public final ProtocolRecognizer UNKNOWN_RECOGNIZER = new UnknownRecognizer(); private UnknownRecognizer() { }
// Path: activeio-core/src/main/java/org/apache/activeio/packet/Packet.java // public interface Packet { // // public int position(); // public void position(int position); // public int limit(); // public void limit(int limit); // public void flip(); // public int remaining(); // public void rewind(); // public boolean hasRemaining(); // public void clear(); // public Packet slice(); // public Packet duplicate(); // public Object duplicate(ClassLoader cl) throws IOException; // public int capacity(); // public void dispose(); // // public ByteSequence asByteSequence(); // public byte[] sliceAsBytes(); // // /** // * @Return object that is an instance of requested type and is associated this this object. May return null if no // * object of that type is associated. // */ // Object getAdapter(Class target); // // // /** // * Writes the remaing bytes in the packet to the output stream. // * // * @param out // * @return // */ // void writeTo(OutputStream out) throws IOException; // void writeTo(DataOutput out) throws IOException; // // // To read data out of the packet. // public int read(); // public int read(byte data[], int offset, int length); // // // To write data into the packet. // public boolean write( int data ); // public int write( byte data[], int offset, int length ); // public int read(Packet dest); // // } // Path: activeio-core/src/main/java/org/apache/activeio/oneport/UnknownRecognizer.java import org.apache.activeio.packet.Packet; /** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activeio.oneport; class UnknownRecognizer implements ProtocolRecognizer { static public final ProtocolRecognizer UNKNOWN_RECOGNIZER = new UnknownRecognizer(); private UnknownRecognizer() { }
public boolean recognizes(Packet packet) {
maofw/netty_push_server
src/com/netty/push/sdk/client/NettyClientHandler.java
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // } // // Path: src/com/netty/push/sdk/pojo/MessageResult.java // public class MessageResult implements Serializable { // /** // * // */ // private static final long serialVersionUID = -3628849782554026441L; // private Long msgId; // private boolean success; // // public Long getMsgId() { // return msgId; // } // // public void setMsgId(Long msgId) { // this.msgId = msgId; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // }
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message; import com.netty.push.sdk.pojo.MessageResult;
package com.netty.push.sdk.client; /** * 客户端消息处理Handler * * @author maofw * */ public class NettyClientHandler extends SimpleChannelInboundHandler<Object> { private NettyClient nettyClient;
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // } // // Path: src/com/netty/push/sdk/pojo/MessageResult.java // public class MessageResult implements Serializable { // /** // * // */ // private static final long serialVersionUID = -3628849782554026441L; // private Long msgId; // private boolean success; // // public Long getMsgId() { // return msgId; // } // // public void setMsgId(Long msgId) { // this.msgId = msgId; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // } // Path: src/com/netty/push/sdk/client/NettyClientHandler.java import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message; import com.netty.push.sdk.pojo.MessageResult; package com.netty.push.sdk.client; /** * 客户端消息处理Handler * * @author maofw * */ public class NettyClientHandler extends SimpleChannelInboundHandler<Object> { private NettyClient nettyClient;
private Message message;
maofw/netty_push_server
src/com/netty/push/sdk/client/NettyClientHandler.java
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // } // // Path: src/com/netty/push/sdk/pojo/MessageResult.java // public class MessageResult implements Serializable { // /** // * // */ // private static final long serialVersionUID = -3628849782554026441L; // private Long msgId; // private boolean success; // // public Long getMsgId() { // return msgId; // } // // public void setMsgId(Long msgId) { // this.msgId = msgId; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // }
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message; import com.netty.push.sdk.pojo.MessageResult;
package com.netty.push.sdk.client; /** * 客户端消息处理Handler * * @author maofw * */ public class NettyClientHandler extends SimpleChannelInboundHandler<Object> { private NettyClient nettyClient; private Message message;
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // } // // Path: src/com/netty/push/sdk/pojo/MessageResult.java // public class MessageResult implements Serializable { // /** // * // */ // private static final long serialVersionUID = -3628849782554026441L; // private Long msgId; // private boolean success; // // public Long getMsgId() { // return msgId; // } // // public void setMsgId(Long msgId) { // this.msgId = msgId; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // } // Path: src/com/netty/push/sdk/client/NettyClientHandler.java import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message; import com.netty.push.sdk.pojo.MessageResult; package com.netty.push.sdk.client; /** * 客户端消息处理Handler * * @author maofw * */ public class NettyClientHandler extends SimpleChannelInboundHandler<Object> { private NettyClient nettyClient; private Message message;
private INettyClientHandlerListener listener;
maofw/netty_push_server
src/com/netty/push/sdk/client/NettyClientHandler.java
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // } // // Path: src/com/netty/push/sdk/pojo/MessageResult.java // public class MessageResult implements Serializable { // /** // * // */ // private static final long serialVersionUID = -3628849782554026441L; // private Long msgId; // private boolean success; // // public Long getMsgId() { // return msgId; // } // // public void setMsgId(Long msgId) { // this.msgId = msgId; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // }
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message; import com.netty.push.sdk.pojo.MessageResult;
package com.netty.push.sdk.client; /** * 客户端消息处理Handler * * @author maofw * */ public class NettyClientHandler extends SimpleChannelInboundHandler<Object> { private NettyClient nettyClient; private Message message; private INettyClientHandlerListener listener; public NettyClientHandler(NettyClient nettyClient, Message message, INettyClientHandlerListener listener) { this.nettyClient = nettyClient; this.message = message; this.listener = listener; } /** * 此方法会在连接到服务器后被调用 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (nettyClient != null) { nettyClient.setCtx(ctx); } if (message != null) { // 成功后发送消息 ctx.writeAndFlush(message); } } @Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { System.out.println("channelRead");
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // } // // Path: src/com/netty/push/sdk/pojo/MessageResult.java // public class MessageResult implements Serializable { // /** // * // */ // private static final long serialVersionUID = -3628849782554026441L; // private Long msgId; // private boolean success; // // public Long getMsgId() { // return msgId; // } // // public void setMsgId(Long msgId) { // this.msgId = msgId; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // } // Path: src/com/netty/push/sdk/client/NettyClientHandler.java import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message; import com.netty.push.sdk.pojo.MessageResult; package com.netty.push.sdk.client; /** * 客户端消息处理Handler * * @author maofw * */ public class NettyClientHandler extends SimpleChannelInboundHandler<Object> { private NettyClient nettyClient; private Message message; private INettyClientHandlerListener listener; public NettyClientHandler(NettyClient nettyClient, Message message, INettyClientHandlerListener listener) { this.nettyClient = nettyClient; this.message = message; this.listener = listener; } /** * 此方法会在连接到服务器后被调用 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (nettyClient != null) { nettyClient.setCtx(ctx); } if (message != null) { // 成功后发送消息 ctx.writeAndFlush(message); } } @Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { System.out.println("channelRead");
if (obj != null && obj instanceof MessageResult) {
maofw/netty_push_server
src/com/netty/push/sdk/client/NettyClient.java
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // }
import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; import java.net.InetSocketAddress; import java.net.SocketAddress; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message;
public void setCtx(ChannelHandlerContext ctx) { this.ctx = ctx; } /** * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例 没有绑定关系,而且只有被调用到时才会装载,从而实现了延迟加载。 */ private static class SingletonHolder { /** * 静态初始化器,由JVM来保证线程安全 */ private static NettyClient instance = new NettyClient(); } public static NettyClient getInstance(final String host, final int port) { if (nettyClient == null) { nettyClient = SingletonHolder.instance; nettyClient.host = host; nettyClient.port = port; } return nettyClient; } /** * 连接方法 * * @param host * @param port * @throws Exception */
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // } // Path: src/com/netty/push/sdk/client/NettyClient.java import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; import java.net.InetSocketAddress; import java.net.SocketAddress; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message; public void setCtx(ChannelHandlerContext ctx) { this.ctx = ctx; } /** * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例 没有绑定关系,而且只有被调用到时才会装载,从而实现了延迟加载。 */ private static class SingletonHolder { /** * 静态初始化器,由JVM来保证线程安全 */ private static NettyClient instance = new NettyClient(); } public static NettyClient getInstance(final String host, final int port) { if (nettyClient == null) { nettyClient = SingletonHolder.instance; nettyClient.host = host; nettyClient.port = port; } return nettyClient; } /** * 连接方法 * * @param host * @param port * @throws Exception */
public void sendMessage(final Message message, final INettyClientHandlerListener listener) throws Exception {
maofw/netty_push_server
src/com/netty/push/sdk/client/NettyClient.java
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // }
import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; import java.net.InetSocketAddress; import java.net.SocketAddress; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message;
public void setCtx(ChannelHandlerContext ctx) { this.ctx = ctx; } /** * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例 没有绑定关系,而且只有被调用到时才会装载,从而实现了延迟加载。 */ private static class SingletonHolder { /** * 静态初始化器,由JVM来保证线程安全 */ private static NettyClient instance = new NettyClient(); } public static NettyClient getInstance(final String host, final int port) { if (nettyClient == null) { nettyClient = SingletonHolder.instance; nettyClient.host = host; nettyClient.port = port; } return nettyClient; } /** * 连接方法 * * @param host * @param port * @throws Exception */
// Path: src/com/netty/push/sdk/client/listener/INettyClientHandlerListener.java // public interface INettyClientHandlerListener { // public void receive(MessageResult messageResult); // } // // Path: src/com/netty/push/sdk/pojo/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 8882696265942622650L; // private String appKey; // private String title; // private String content; // private boolean isOfflineShow; // // 是否需要回执 // private boolean isReceipt; // // private boolean isAllPush; // private List<String> devices; // // public String getAppKey() { // return appKey; // } // // public void setAppKey(String appKey) { // this.appKey = appKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public boolean isOfflineShow() { // return isOfflineShow; // } // // public void setOfflineShow(boolean isOfflineShow) { // this.isOfflineShow = isOfflineShow; // } // // public boolean isReceipt() { // return isReceipt; // } // // public void setReceipt(boolean isReceipt) { // this.isReceipt = isReceipt; // } // // public List<String> getDevices() { // return devices; // } // // public void setDevices(List<String> devices) { // this.devices = devices; // } // // public boolean isAllPush() { // return isAllPush; // } // // public void setAllPush(boolean isAllPush) { // this.isAllPush = isAllPush; // } // // } // Path: src/com/netty/push/sdk/client/NettyClient.java import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; import java.net.InetSocketAddress; import java.net.SocketAddress; import com.netty.push.sdk.client.listener.INettyClientHandlerListener; import com.netty.push.sdk.pojo.Message; public void setCtx(ChannelHandlerContext ctx) { this.ctx = ctx; } /** * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例 没有绑定关系,而且只有被调用到时才会装载,从而实现了延迟加载。 */ private static class SingletonHolder { /** * 静态初始化器,由JVM来保证线程安全 */ private static NettyClient instance = new NettyClient(); } public static NettyClient getInstance(final String host, final int port) { if (nettyClient == null) { nettyClient = SingletonHolder.instance; nettyClient.host = host; nettyClient.port = port; } return nettyClient; } /** * 连接方法 * * @param host * @param port * @throws Exception */
public void sendMessage(final Message message, final INettyClientHandlerListener listener) throws Exception {
maofw/netty_push_server
src/com/netty/push/Application.java
// Path: src/com/netty/push/server/IServer.java // public interface IServer { // public void start() throws Exception; // // public void stop() throws Exception; // // public void restart() throws Exception; // }
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.netty.push.server.IServer;
package com.netty.push; public class Application { /** * @param args */ public static void main(String[] args) throws Exception { String params = (args != null && args.length > 0) ? args[0] : null; // 启动服务器 ApplicationContext context = getApplicationContext(params); if (context != null) {
// Path: src/com/netty/push/server/IServer.java // public interface IServer { // public void start() throws Exception; // // public void stop() throws Exception; // // public void restart() throws Exception; // } // Path: src/com/netty/push/Application.java import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.netty.push.server.IServer; package com.netty.push; public class Application { /** * @param args */ public static void main(String[] args) throws Exception { String params = (args != null && args.length > 0) ? args[0] : null; // 启动服务器 ApplicationContext context = getApplicationContext(params); if (context != null) {
IServer server = (IServer) context.getBean("nettyServer");
maofw/netty_push_server
src/com/netty/push/handler/process/RegistrationProcessor.java
// Path: src/com/netty/push/pojo/DeviceInfo.java // public class DeviceInfo { // private String regId ; // private Long userId ; // private Long appId ; // private String appKey ; // private int isOnline ; // private String deviceId ; // private String imei ; // private String channel ; // private Date onlineTime ; // private Date offlineTime ; // public String getRegId() { // return regId; // } // public void setRegId(String regId) { // this.regId = regId; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public int getIsOnline() { // return isOnline; // } // public void setIsOnline(int isOnline) { // this.isOnline = isOnline; // } // public String getDeviceId() { // return deviceId; // } // public void setDeviceId(String deviceId) { // this.deviceId = deviceId; // } // public String getImei() { // return imei; // } // public void setImei(String imei) { // this.imei = imei; // } // public String getChannel() { // return channel; // } // public void setChannel(String channel) { // this.channel = channel; // } // public Date getOnlineTime() { // return onlineTime; // } // public void setOnlineTime(Date onlineTime) { // this.onlineTime = onlineTime; // } // public Date getOfflineTime() { // return offlineTime; // } // public void setOfflineTime(Date offlineTime) { // this.offlineTime = offlineTime; // } // // public String toString(){ // StringBuffer sb = new StringBuffer(); // sb.append("regId:"+regId); // sb.append("-userId:"+userId); // sb.append("-appId:"+appId); // sb.append("-appKey:"+appKey); // sb.append("-isOnline:"+(isOnline==1?"ONLINE":"OFFLINE")); // sb.append("-deviceId:"+deviceId); // sb.append("-imei:"+imei); // sb.append("-channel:"+channel); // sb.append("-onlineTime:"+((onlineTime==null)?"":onlineTime.toString())); // sb.append("-offlineTime:"+((offlineTime==null)?"":offlineTime.toString())); // return sb.toString(); // } // // }
import io.netty.channel.ChannelHandlerContext; import com.netty.push.pojo.DeviceInfo; import com.xwtec.protoc.CommandProtoc; import com.xwtec.protoc.CommandProtoc.PushMessage;
package com.netty.push.handler.process; /** * 设备注册消息请求 * * @author maofw * */ public class RegistrationProcessor extends AbstractHandleProcessor<CommandProtoc.Registration> { @Override public PushMessage process(ChannelHandlerContext ctx) { // 服务器解析注册数据请求 // 判断注册是否成功 CommandProtoc.Registration registration = this.getProcessObject(); int result = applicationContext.registDevice(ctx.channel(), registration); String regId = null; if (result > 0) { // 成功了 返回RegistrationResult
// Path: src/com/netty/push/pojo/DeviceInfo.java // public class DeviceInfo { // private String regId ; // private Long userId ; // private Long appId ; // private String appKey ; // private int isOnline ; // private String deviceId ; // private String imei ; // private String channel ; // private Date onlineTime ; // private Date offlineTime ; // public String getRegId() { // return regId; // } // public void setRegId(String regId) { // this.regId = regId; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public int getIsOnline() { // return isOnline; // } // public void setIsOnline(int isOnline) { // this.isOnline = isOnline; // } // public String getDeviceId() { // return deviceId; // } // public void setDeviceId(String deviceId) { // this.deviceId = deviceId; // } // public String getImei() { // return imei; // } // public void setImei(String imei) { // this.imei = imei; // } // public String getChannel() { // return channel; // } // public void setChannel(String channel) { // this.channel = channel; // } // public Date getOnlineTime() { // return onlineTime; // } // public void setOnlineTime(Date onlineTime) { // this.onlineTime = onlineTime; // } // public Date getOfflineTime() { // return offlineTime; // } // public void setOfflineTime(Date offlineTime) { // this.offlineTime = offlineTime; // } // // public String toString(){ // StringBuffer sb = new StringBuffer(); // sb.append("regId:"+regId); // sb.append("-userId:"+userId); // sb.append("-appId:"+appId); // sb.append("-appKey:"+appKey); // sb.append("-isOnline:"+(isOnline==1?"ONLINE":"OFFLINE")); // sb.append("-deviceId:"+deviceId); // sb.append("-imei:"+imei); // sb.append("-channel:"+channel); // sb.append("-onlineTime:"+((onlineTime==null)?"":onlineTime.toString())); // sb.append("-offlineTime:"+((offlineTime==null)?"":offlineTime.toString())); // return sb.toString(); // } // // } // Path: src/com/netty/push/handler/process/RegistrationProcessor.java import io.netty.channel.ChannelHandlerContext; import com.netty.push.pojo.DeviceInfo; import com.xwtec.protoc.CommandProtoc; import com.xwtec.protoc.CommandProtoc.PushMessage; package com.netty.push.handler.process; /** * 设备注册消息请求 * * @author maofw * */ public class RegistrationProcessor extends AbstractHandleProcessor<CommandProtoc.Registration> { @Override public PushMessage process(ChannelHandlerContext ctx) { // 服务器解析注册数据请求 // 判断注册是否成功 CommandProtoc.Registration registration = this.getProcessObject(); int result = applicationContext.registDevice(ctx.channel(), registration); String regId = null; if (result > 0) { // 成功了 返回RegistrationResult
DeviceInfo deviceInfo = applicationContext.getDeviceInfo(registration.getDeviceId());
maofw/netty_push_server
src/com/netty/push/handler/process/DeviceOfflineProcessor.java
// Path: src/com/netty/push/pojo/AppInfo.java // public class AppInfo { // private Long appId; // private String appPackage; // private String appKey; // private Long userId; // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppPackage() { // return appPackage; // } // public void setAppPackage(String appPackage) { // this.appPackage = appPackage; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // // // // } // // Path: src/com/netty/push/pojo/DeviceInfo.java // public class DeviceInfo { // private String regId ; // private Long userId ; // private Long appId ; // private String appKey ; // private int isOnline ; // private String deviceId ; // private String imei ; // private String channel ; // private Date onlineTime ; // private Date offlineTime ; // public String getRegId() { // return regId; // } // public void setRegId(String regId) { // this.regId = regId; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public int getIsOnline() { // return isOnline; // } // public void setIsOnline(int isOnline) { // this.isOnline = isOnline; // } // public String getDeviceId() { // return deviceId; // } // public void setDeviceId(String deviceId) { // this.deviceId = deviceId; // } // public String getImei() { // return imei; // } // public void setImei(String imei) { // this.imei = imei; // } // public String getChannel() { // return channel; // } // public void setChannel(String channel) { // this.channel = channel; // } // public Date getOnlineTime() { // return onlineTime; // } // public void setOnlineTime(Date onlineTime) { // this.onlineTime = onlineTime; // } // public Date getOfflineTime() { // return offlineTime; // } // public void setOfflineTime(Date offlineTime) { // this.offlineTime = offlineTime; // } // // public String toString(){ // StringBuffer sb = new StringBuffer(); // sb.append("regId:"+regId); // sb.append("-userId:"+userId); // sb.append("-appId:"+appId); // sb.append("-appKey:"+appKey); // sb.append("-isOnline:"+(isOnline==1?"ONLINE":"OFFLINE")); // sb.append("-deviceId:"+deviceId); // sb.append("-imei:"+imei); // sb.append("-channel:"+channel); // sb.append("-onlineTime:"+((onlineTime==null)?"":onlineTime.toString())); // sb.append("-offlineTime:"+((offlineTime==null)?"":offlineTime.toString())); // return sb.toString(); // } // // }
import io.netty.channel.ChannelHandlerContext; import com.netty.push.pojo.AppInfo; import com.netty.push.pojo.DeviceInfo; import com.xwtec.protoc.CommandProtoc; import com.xwtec.protoc.CommandProtoc.PushMessage;
package com.netty.push.handler.process; /** * 设备下线消息处理 * * @author maofw * */ public class DeviceOfflineProcessor extends AbstractHandleProcessor<CommandProtoc.DeviceOffline> { @Override public PushMessage process(ChannelHandlerContext ctx) { CommandProtoc.DeviceOnoffResult.ResultCode resultCode = null; CommandProtoc.Message.UserStatus userStatus = CommandProtoc.Message.UserStatus.OFFLINE; // 获取设备id String deviceId = this.getProcessObject().getDeviceId();
// Path: src/com/netty/push/pojo/AppInfo.java // public class AppInfo { // private Long appId; // private String appPackage; // private String appKey; // private Long userId; // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppPackage() { // return appPackage; // } // public void setAppPackage(String appPackage) { // this.appPackage = appPackage; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // // // // } // // Path: src/com/netty/push/pojo/DeviceInfo.java // public class DeviceInfo { // private String regId ; // private Long userId ; // private Long appId ; // private String appKey ; // private int isOnline ; // private String deviceId ; // private String imei ; // private String channel ; // private Date onlineTime ; // private Date offlineTime ; // public String getRegId() { // return regId; // } // public void setRegId(String regId) { // this.regId = regId; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public int getIsOnline() { // return isOnline; // } // public void setIsOnline(int isOnline) { // this.isOnline = isOnline; // } // public String getDeviceId() { // return deviceId; // } // public void setDeviceId(String deviceId) { // this.deviceId = deviceId; // } // public String getImei() { // return imei; // } // public void setImei(String imei) { // this.imei = imei; // } // public String getChannel() { // return channel; // } // public void setChannel(String channel) { // this.channel = channel; // } // public Date getOnlineTime() { // return onlineTime; // } // public void setOnlineTime(Date onlineTime) { // this.onlineTime = onlineTime; // } // public Date getOfflineTime() { // return offlineTime; // } // public void setOfflineTime(Date offlineTime) { // this.offlineTime = offlineTime; // } // // public String toString(){ // StringBuffer sb = new StringBuffer(); // sb.append("regId:"+regId); // sb.append("-userId:"+userId); // sb.append("-appId:"+appId); // sb.append("-appKey:"+appKey); // sb.append("-isOnline:"+(isOnline==1?"ONLINE":"OFFLINE")); // sb.append("-deviceId:"+deviceId); // sb.append("-imei:"+imei); // sb.append("-channel:"+channel); // sb.append("-onlineTime:"+((onlineTime==null)?"":onlineTime.toString())); // sb.append("-offlineTime:"+((offlineTime==null)?"":offlineTime.toString())); // return sb.toString(); // } // // } // Path: src/com/netty/push/handler/process/DeviceOfflineProcessor.java import io.netty.channel.ChannelHandlerContext; import com.netty.push.pojo.AppInfo; import com.netty.push.pojo.DeviceInfo; import com.xwtec.protoc.CommandProtoc; import com.xwtec.protoc.CommandProtoc.PushMessage; package com.netty.push.handler.process; /** * 设备下线消息处理 * * @author maofw * */ public class DeviceOfflineProcessor extends AbstractHandleProcessor<CommandProtoc.DeviceOffline> { @Override public PushMessage process(ChannelHandlerContext ctx) { CommandProtoc.DeviceOnoffResult.ResultCode resultCode = null; CommandProtoc.Message.UserStatus userStatus = CommandProtoc.Message.UserStatus.OFFLINE; // 获取设备id String deviceId = this.getProcessObject().getDeviceId();
DeviceInfo deviceInfo = this.applicationContext.getDeviceInfo(deviceId);
maofw/netty_push_server
src/com/netty/push/handler/process/DeviceOfflineProcessor.java
// Path: src/com/netty/push/pojo/AppInfo.java // public class AppInfo { // private Long appId; // private String appPackage; // private String appKey; // private Long userId; // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppPackage() { // return appPackage; // } // public void setAppPackage(String appPackage) { // this.appPackage = appPackage; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // // // // } // // Path: src/com/netty/push/pojo/DeviceInfo.java // public class DeviceInfo { // private String regId ; // private Long userId ; // private Long appId ; // private String appKey ; // private int isOnline ; // private String deviceId ; // private String imei ; // private String channel ; // private Date onlineTime ; // private Date offlineTime ; // public String getRegId() { // return regId; // } // public void setRegId(String regId) { // this.regId = regId; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public int getIsOnline() { // return isOnline; // } // public void setIsOnline(int isOnline) { // this.isOnline = isOnline; // } // public String getDeviceId() { // return deviceId; // } // public void setDeviceId(String deviceId) { // this.deviceId = deviceId; // } // public String getImei() { // return imei; // } // public void setImei(String imei) { // this.imei = imei; // } // public String getChannel() { // return channel; // } // public void setChannel(String channel) { // this.channel = channel; // } // public Date getOnlineTime() { // return onlineTime; // } // public void setOnlineTime(Date onlineTime) { // this.onlineTime = onlineTime; // } // public Date getOfflineTime() { // return offlineTime; // } // public void setOfflineTime(Date offlineTime) { // this.offlineTime = offlineTime; // } // // public String toString(){ // StringBuffer sb = new StringBuffer(); // sb.append("regId:"+regId); // sb.append("-userId:"+userId); // sb.append("-appId:"+appId); // sb.append("-appKey:"+appKey); // sb.append("-isOnline:"+(isOnline==1?"ONLINE":"OFFLINE")); // sb.append("-deviceId:"+deviceId); // sb.append("-imei:"+imei); // sb.append("-channel:"+channel); // sb.append("-onlineTime:"+((onlineTime==null)?"":onlineTime.toString())); // sb.append("-offlineTime:"+((offlineTime==null)?"":offlineTime.toString())); // return sb.toString(); // } // // }
import io.netty.channel.ChannelHandlerContext; import com.netty.push.pojo.AppInfo; import com.netty.push.pojo.DeviceInfo; import com.xwtec.protoc.CommandProtoc; import com.xwtec.protoc.CommandProtoc.PushMessage;
package com.netty.push.handler.process; /** * 设备下线消息处理 * * @author maofw * */ public class DeviceOfflineProcessor extends AbstractHandleProcessor<CommandProtoc.DeviceOffline> { @Override public PushMessage process(ChannelHandlerContext ctx) { CommandProtoc.DeviceOnoffResult.ResultCode resultCode = null; CommandProtoc.Message.UserStatus userStatus = CommandProtoc.Message.UserStatus.OFFLINE; // 获取设备id String deviceId = this.getProcessObject().getDeviceId(); DeviceInfo deviceInfo = this.applicationContext.getDeviceInfo(deviceId);
// Path: src/com/netty/push/pojo/AppInfo.java // public class AppInfo { // private Long appId; // private String appPackage; // private String appKey; // private Long userId; // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppPackage() { // return appPackage; // } // public void setAppPackage(String appPackage) { // this.appPackage = appPackage; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // // // // } // // Path: src/com/netty/push/pojo/DeviceInfo.java // public class DeviceInfo { // private String regId ; // private Long userId ; // private Long appId ; // private String appKey ; // private int isOnline ; // private String deviceId ; // private String imei ; // private String channel ; // private Date onlineTime ; // private Date offlineTime ; // public String getRegId() { // return regId; // } // public void setRegId(String regId) { // this.regId = regId; // } // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // public Long getAppId() { // return appId; // } // public void setAppId(Long appId) { // this.appId = appId; // } // public String getAppKey() { // return appKey; // } // public void setAppKey(String appKey) { // this.appKey = appKey; // } // public int getIsOnline() { // return isOnline; // } // public void setIsOnline(int isOnline) { // this.isOnline = isOnline; // } // public String getDeviceId() { // return deviceId; // } // public void setDeviceId(String deviceId) { // this.deviceId = deviceId; // } // public String getImei() { // return imei; // } // public void setImei(String imei) { // this.imei = imei; // } // public String getChannel() { // return channel; // } // public void setChannel(String channel) { // this.channel = channel; // } // public Date getOnlineTime() { // return onlineTime; // } // public void setOnlineTime(Date onlineTime) { // this.onlineTime = onlineTime; // } // public Date getOfflineTime() { // return offlineTime; // } // public void setOfflineTime(Date offlineTime) { // this.offlineTime = offlineTime; // } // // public String toString(){ // StringBuffer sb = new StringBuffer(); // sb.append("regId:"+regId); // sb.append("-userId:"+userId); // sb.append("-appId:"+appId); // sb.append("-appKey:"+appKey); // sb.append("-isOnline:"+(isOnline==1?"ONLINE":"OFFLINE")); // sb.append("-deviceId:"+deviceId); // sb.append("-imei:"+imei); // sb.append("-channel:"+channel); // sb.append("-onlineTime:"+((onlineTime==null)?"":onlineTime.toString())); // sb.append("-offlineTime:"+((offlineTime==null)?"":offlineTime.toString())); // return sb.toString(); // } // // } // Path: src/com/netty/push/handler/process/DeviceOfflineProcessor.java import io.netty.channel.ChannelHandlerContext; import com.netty.push.pojo.AppInfo; import com.netty.push.pojo.DeviceInfo; import com.xwtec.protoc.CommandProtoc; import com.xwtec.protoc.CommandProtoc.PushMessage; package com.netty.push.handler.process; /** * 设备下线消息处理 * * @author maofw * */ public class DeviceOfflineProcessor extends AbstractHandleProcessor<CommandProtoc.DeviceOffline> { @Override public PushMessage process(ChannelHandlerContext ctx) { CommandProtoc.DeviceOnoffResult.ResultCode resultCode = null; CommandProtoc.Message.UserStatus userStatus = CommandProtoc.Message.UserStatus.OFFLINE; // 获取设备id String deviceId = this.getProcessObject().getDeviceId(); DeviceInfo deviceInfo = this.applicationContext.getDeviceInfo(deviceId);
AppInfo appInfo = deviceInfo == null ? null : this.applicationContext.getAppInfo(deviceInfo.getAppKey());
flyhero/flyapi
src/main/java/cn/iflyapi/blog/annotation/OpLog.java
// Path: src/main/java/cn/iflyapi/blog/enums/OperationEnum.java // public enum OperationEnum { // // USER_REGISTER(1,"用户注册"), // USER_LOGIN(2,"用户登录"), // // ARTICLE_READ(10, "阅读文章"), // ARTICLE_WRITE(11, "发布文章"), // ARTICLE_COMMENT(12, "评论文章"), // // SUBJECT_READ(15, "查询小书"), // SUBJECT_WRITE(16, "创建小书"), // SUBJECT_EXPORT(17, "导出小书"), // ; // // private Integer code; // private String msg; // // OperationEnum(Integer code, String msg) { // this.code = code; // this.msg = msg; // } // // public Integer getCode() { // return code; // } // // public void setCode(Integer code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import cn.iflyapi.blog.enums.OperationEnum; import java.lang.annotation.*;
package cn.iflyapi.blog.annotation; /** * @author flyhero * @date 2018-12-21 2:42 PM */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface OpLog {
// Path: src/main/java/cn/iflyapi/blog/enums/OperationEnum.java // public enum OperationEnum { // // USER_REGISTER(1,"用户注册"), // USER_LOGIN(2,"用户登录"), // // ARTICLE_READ(10, "阅读文章"), // ARTICLE_WRITE(11, "发布文章"), // ARTICLE_COMMENT(12, "评论文章"), // // SUBJECT_READ(15, "查询小书"), // SUBJECT_WRITE(16, "创建小书"), // SUBJECT_EXPORT(17, "导出小书"), // ; // // private Integer code; // private String msg; // // OperationEnum(Integer code, String msg) { // this.code = code; // this.msg = msg; // } // // public Integer getCode() { // return code; // } // // public void setCode(Integer code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/cn/iflyapi/blog/annotation/OpLog.java import cn.iflyapi.blog.enums.OperationEnum; import java.lang.annotation.*; package cn.iflyapi.blog.annotation; /** * @author flyhero * @date 2018-12-21 2:42 PM */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface OpLog {
OperationEnum op() default OperationEnum.ARTICLE_READ;
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/SocialController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Social.java // public class Social { // private Long socialId; // // private Long userId; // // private Integer socialType; // // private String socialUrl; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getSocialId() { // return socialId; // } // // public void setSocialId(Long socialId) { // this.socialId = socialId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getSocialType() { // return socialType; // } // // public void setSocialType(Integer socialType) { // this.socialType = socialType; // } // // public String getSocialUrl() { // return socialUrl; // } // // public void setSocialUrl(String socialUrl) { // this.socialUrl = socialUrl; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/SocialService.java // @Service // public class SocialService { // // @Autowired // private SocialMapper socialMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Social> listSocial(Long userId){ // SocialExample socialExample = new SocialExample(); // socialExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // return socialMapper.selectByExample(socialExample); // } // // public void update(List<Social> socials){ // for (Social social : socials){ // update(social); // } // // } // // public void update(Social social){ // if (Objects.nonNull(social.getSocialId())) { // socialMapper.updateByPrimaryKeySelective(social); // }else { // social.setSocialId(idWorker.nextId()); // socialMapper.insertSelective(social); // } // } // // public void remove(Long socialId){ // Social social = new Social(); // social.setSocialId(socialId); // social.setIsDelete(true); // socialMapper.updateByPrimaryKeySelective(social); // } // }
import cn.iflyapi.blog.entity.Social; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.SocialService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 8:03 PM */ @Api(value = "SocialController", tags = "社交接口") @RestController public class SocialController extends BaseController { @Autowired
// Path: src/main/java/cn/iflyapi/blog/entity/Social.java // public class Social { // private Long socialId; // // private Long userId; // // private Integer socialType; // // private String socialUrl; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getSocialId() { // return socialId; // } // // public void setSocialId(Long socialId) { // this.socialId = socialId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getSocialType() { // return socialType; // } // // public void setSocialType(Integer socialType) { // this.socialType = socialType; // } // // public String getSocialUrl() { // return socialUrl; // } // // public void setSocialUrl(String socialUrl) { // this.socialUrl = socialUrl; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/SocialService.java // @Service // public class SocialService { // // @Autowired // private SocialMapper socialMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Social> listSocial(Long userId){ // SocialExample socialExample = new SocialExample(); // socialExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // return socialMapper.selectByExample(socialExample); // } // // public void update(List<Social> socials){ // for (Social social : socials){ // update(social); // } // // } // // public void update(Social social){ // if (Objects.nonNull(social.getSocialId())) { // socialMapper.updateByPrimaryKeySelective(social); // }else { // social.setSocialId(idWorker.nextId()); // socialMapper.insertSelective(social); // } // } // // public void remove(Long socialId){ // Social social = new Social(); // social.setSocialId(socialId); // social.setIsDelete(true); // socialMapper.updateByPrimaryKeySelective(social); // } // } // Path: src/main/java/cn/iflyapi/blog/controller/SocialController.java import cn.iflyapi.blog.entity.Social; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.SocialService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 8:03 PM */ @Api(value = "SocialController", tags = "社交接口") @RestController public class SocialController extends BaseController { @Autowired
private SocialService socialService;
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/SocialController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Social.java // public class Social { // private Long socialId; // // private Long userId; // // private Integer socialType; // // private String socialUrl; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getSocialId() { // return socialId; // } // // public void setSocialId(Long socialId) { // this.socialId = socialId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getSocialType() { // return socialType; // } // // public void setSocialType(Integer socialType) { // this.socialType = socialType; // } // // public String getSocialUrl() { // return socialUrl; // } // // public void setSocialUrl(String socialUrl) { // this.socialUrl = socialUrl; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/SocialService.java // @Service // public class SocialService { // // @Autowired // private SocialMapper socialMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Social> listSocial(Long userId){ // SocialExample socialExample = new SocialExample(); // socialExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // return socialMapper.selectByExample(socialExample); // } // // public void update(List<Social> socials){ // for (Social social : socials){ // update(social); // } // // } // // public void update(Social social){ // if (Objects.nonNull(social.getSocialId())) { // socialMapper.updateByPrimaryKeySelective(social); // }else { // social.setSocialId(idWorker.nextId()); // socialMapper.insertSelective(social); // } // } // // public void remove(Long socialId){ // Social social = new Social(); // social.setSocialId(socialId); // social.setIsDelete(true); // socialMapper.updateByPrimaryKeySelective(social); // } // }
import cn.iflyapi.blog.entity.Social; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.SocialService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 8:03 PM */ @Api(value = "SocialController", tags = "社交接口") @RestController public class SocialController extends BaseController { @Autowired private SocialService socialService; @ApiOperation("查询") @GetMapping("/socials")
// Path: src/main/java/cn/iflyapi/blog/entity/Social.java // public class Social { // private Long socialId; // // private Long userId; // // private Integer socialType; // // private String socialUrl; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getSocialId() { // return socialId; // } // // public void setSocialId(Long socialId) { // this.socialId = socialId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getSocialType() { // return socialType; // } // // public void setSocialType(Integer socialType) { // this.socialType = socialType; // } // // public String getSocialUrl() { // return socialUrl; // } // // public void setSocialUrl(String socialUrl) { // this.socialUrl = socialUrl; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/SocialService.java // @Service // public class SocialService { // // @Autowired // private SocialMapper socialMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Social> listSocial(Long userId){ // SocialExample socialExample = new SocialExample(); // socialExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // return socialMapper.selectByExample(socialExample); // } // // public void update(List<Social> socials){ // for (Social social : socials){ // update(social); // } // // } // // public void update(Social social){ // if (Objects.nonNull(social.getSocialId())) { // socialMapper.updateByPrimaryKeySelective(social); // }else { // social.setSocialId(idWorker.nextId()); // socialMapper.insertSelective(social); // } // } // // public void remove(Long socialId){ // Social social = new Social(); // social.setSocialId(socialId); // social.setIsDelete(true); // socialMapper.updateByPrimaryKeySelective(social); // } // } // Path: src/main/java/cn/iflyapi/blog/controller/SocialController.java import cn.iflyapi.blog.entity.Social; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.SocialService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 8:03 PM */ @Api(value = "SocialController", tags = "社交接口") @RestController public class SocialController extends BaseController { @Autowired private SocialService socialService; @ApiOperation("查询") @GetMapping("/socials")
public JSONResult find() {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/SocialController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Social.java // public class Social { // private Long socialId; // // private Long userId; // // private Integer socialType; // // private String socialUrl; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getSocialId() { // return socialId; // } // // public void setSocialId(Long socialId) { // this.socialId = socialId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getSocialType() { // return socialType; // } // // public void setSocialType(Integer socialType) { // this.socialType = socialType; // } // // public String getSocialUrl() { // return socialUrl; // } // // public void setSocialUrl(String socialUrl) { // this.socialUrl = socialUrl; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/SocialService.java // @Service // public class SocialService { // // @Autowired // private SocialMapper socialMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Social> listSocial(Long userId){ // SocialExample socialExample = new SocialExample(); // socialExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // return socialMapper.selectByExample(socialExample); // } // // public void update(List<Social> socials){ // for (Social social : socials){ // update(social); // } // // } // // public void update(Social social){ // if (Objects.nonNull(social.getSocialId())) { // socialMapper.updateByPrimaryKeySelective(social); // }else { // social.setSocialId(idWorker.nextId()); // socialMapper.insertSelective(social); // } // } // // public void remove(Long socialId){ // Social social = new Social(); // social.setSocialId(socialId); // social.setIsDelete(true); // socialMapper.updateByPrimaryKeySelective(social); // } // }
import cn.iflyapi.blog.entity.Social; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.SocialService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 8:03 PM */ @Api(value = "SocialController", tags = "社交接口") @RestController public class SocialController extends BaseController { @Autowired private SocialService socialService; @ApiOperation("查询") @GetMapping("/socials") public JSONResult find() { return JSONResult.ok(socialService.listSocial(getUserId())); } @ApiOperation("新增/修改") @PostMapping("/socials")
// Path: src/main/java/cn/iflyapi/blog/entity/Social.java // public class Social { // private Long socialId; // // private Long userId; // // private Integer socialType; // // private String socialUrl; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getSocialId() { // return socialId; // } // // public void setSocialId(Long socialId) { // this.socialId = socialId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getSocialType() { // return socialType; // } // // public void setSocialType(Integer socialType) { // this.socialType = socialType; // } // // public String getSocialUrl() { // return socialUrl; // } // // public void setSocialUrl(String socialUrl) { // this.socialUrl = socialUrl; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/SocialService.java // @Service // public class SocialService { // // @Autowired // private SocialMapper socialMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Social> listSocial(Long userId){ // SocialExample socialExample = new SocialExample(); // socialExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // return socialMapper.selectByExample(socialExample); // } // // public void update(List<Social> socials){ // for (Social social : socials){ // update(social); // } // // } // // public void update(Social social){ // if (Objects.nonNull(social.getSocialId())) { // socialMapper.updateByPrimaryKeySelective(social); // }else { // social.setSocialId(idWorker.nextId()); // socialMapper.insertSelective(social); // } // } // // public void remove(Long socialId){ // Social social = new Social(); // social.setSocialId(socialId); // social.setIsDelete(true); // socialMapper.updateByPrimaryKeySelective(social); // } // } // Path: src/main/java/cn/iflyapi/blog/controller/SocialController.java import cn.iflyapi.blog.entity.Social; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.SocialService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 8:03 PM */ @Api(value = "SocialController", tags = "社交接口") @RestController public class SocialController extends BaseController { @Autowired private SocialService socialService; @ApiOperation("查询") @GetMapping("/socials") public JSONResult find() { return JSONResult.ok(socialService.listSocial(getUserId())); } @ApiOperation("新增/修改") @PostMapping("/socials")
public JSONResult add(@RequestBody Social socials) {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/annotation/OpenApiScan.java
// Path: src/main/java/cn/iflyapi/blog/config/JwtInterceptor.java // public class JwtInterceptor implements HandlerInterceptor { // // private final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class); // // private List<String> excludedUrl = new ArrayList<>(); // // public void register(String url) { // excludedUrl.add(url); // } // // @Override // public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { // try { // //过滤 OPTIONS 请求 // if (HttpMethod.OPTIONS.name().equals(httpServletRequest.getMethod())) { // return true; // } // System.out.println(excludedUrl.toString()); // String currentPath = httpServletRequest.getMethod() + httpServletRequest.getRequestURI(); // for (String target : excludedUrl) { // if (pathMatch(currentPath, target)) { // return true; // } // } // // String token = httpServletRequest.getHeader("Authorization"); // // if (StringUtils.isEmpty(token)) { // logger.error("token validate failed, no auth info in http header"); // return setNoAuth(httpServletResponse); // } // // Map<String, Claim> map = JwtUtils.verify(token); // if (map != null) { // return true; // } // } catch (Exception e) { // logger.error("JWT验证失败 {}", e.getMessage()); // return setNoAuth(httpServletResponse); // } // // return setNoAuth(httpServletResponse); // } // // /** // * 设置response 返回需要登录的标识 // * // * @param response // */ // private boolean setNoAuth(HttpServletResponse response) throws IOException { // response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); // response.setHeader("Access-Control-Allow-Origin", "*"); // response.setHeader("Access-Control-Allow-Credentials", "true"); // response.getWriter().write(JSONObject.toJSONString(JSONResult.fail(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()), SerializerFeature.WriteMapNullValue)); // return false; // } // // /** // * 匹配路径 // * // * @param current 当前请求路径 // * @param target 目标开放路径 // * @return boolean // */ // private boolean pathMatch(String current, String target) { // if (current.equals(target)) { // return true; // } // if (!target.contains("*")) { // return false; // } // // int index = target.indexOf("*"); // if (target.contains("**")) { // String prefixPath = target.substring(0, index); // if (current.startsWith(prefixPath)) { // return true; // } // } else { // String[] targets = target.split("/"); // String[] currents = current.split("/"); // if (targets.length == currents.length) { // for (int i = 0; i < targets.length; i++) { // if (!targets[i].equals("*")) { // if (!targets[i].equals(currents[i])) { // return false; // } // } // } // return true; // } // // } // // return false; // } // // public static void main(String[] args) { // String s = "/users/*"; // System.out.println(s.indexOf("*")); // System.out.println(s.substring(0, s.indexOf("*"))); // System.out.println(s.substring(s.indexOf("*")+1).equals("")); // System.out.println(s.contains("**")); // System.out.println(s.split("/").length); // // String p = "users"; // System.out.println(p.split("/").length); // System.out.println(p.split("/")[0]); // // String m = "/users/*/subjects"; // System.out.println(); // } // // @Override // public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) { // // } // // @Override // public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { // // } // }
import cn.iflyapi.blog.config.JwtInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.*; import java.lang.reflect.Method; import java.util.Iterator; import java.util.Map; import java.util.Set;
package cn.iflyapi.blog.annotation; /** * @author flyhero * @date 2018-12-20 12:55 PM */ @Component public class OpenApiScan implements ApplicationListener<ApplicationReadyEvent> { @Autowired
// Path: src/main/java/cn/iflyapi/blog/config/JwtInterceptor.java // public class JwtInterceptor implements HandlerInterceptor { // // private final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class); // // private List<String> excludedUrl = new ArrayList<>(); // // public void register(String url) { // excludedUrl.add(url); // } // // @Override // public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { // try { // //过滤 OPTIONS 请求 // if (HttpMethod.OPTIONS.name().equals(httpServletRequest.getMethod())) { // return true; // } // System.out.println(excludedUrl.toString()); // String currentPath = httpServletRequest.getMethod() + httpServletRequest.getRequestURI(); // for (String target : excludedUrl) { // if (pathMatch(currentPath, target)) { // return true; // } // } // // String token = httpServletRequest.getHeader("Authorization"); // // if (StringUtils.isEmpty(token)) { // logger.error("token validate failed, no auth info in http header"); // return setNoAuth(httpServletResponse); // } // // Map<String, Claim> map = JwtUtils.verify(token); // if (map != null) { // return true; // } // } catch (Exception e) { // logger.error("JWT验证失败 {}", e.getMessage()); // return setNoAuth(httpServletResponse); // } // // return setNoAuth(httpServletResponse); // } // // /** // * 设置response 返回需要登录的标识 // * // * @param response // */ // private boolean setNoAuth(HttpServletResponse response) throws IOException { // response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); // response.setHeader("Access-Control-Allow-Origin", "*"); // response.setHeader("Access-Control-Allow-Credentials", "true"); // response.getWriter().write(JSONObject.toJSONString(JSONResult.fail(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()), SerializerFeature.WriteMapNullValue)); // return false; // } // // /** // * 匹配路径 // * // * @param current 当前请求路径 // * @param target 目标开放路径 // * @return boolean // */ // private boolean pathMatch(String current, String target) { // if (current.equals(target)) { // return true; // } // if (!target.contains("*")) { // return false; // } // // int index = target.indexOf("*"); // if (target.contains("**")) { // String prefixPath = target.substring(0, index); // if (current.startsWith(prefixPath)) { // return true; // } // } else { // String[] targets = target.split("/"); // String[] currents = current.split("/"); // if (targets.length == currents.length) { // for (int i = 0; i < targets.length; i++) { // if (!targets[i].equals("*")) { // if (!targets[i].equals(currents[i])) { // return false; // } // } // } // return true; // } // // } // // return false; // } // // public static void main(String[] args) { // String s = "/users/*"; // System.out.println(s.indexOf("*")); // System.out.println(s.substring(0, s.indexOf("*"))); // System.out.println(s.substring(s.indexOf("*")+1).equals("")); // System.out.println(s.contains("**")); // System.out.println(s.split("/").length); // // String p = "users"; // System.out.println(p.split("/").length); // System.out.println(p.split("/")[0]); // // String m = "/users/*/subjects"; // System.out.println(); // } // // @Override // public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) { // // } // // @Override // public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { // // } // } // Path: src/main/java/cn/iflyapi/blog/annotation/OpenApiScan.java import cn.iflyapi.blog.config.JwtInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.*; import java.lang.reflect.Method; import java.util.Iterator; import java.util.Map; import java.util.Set; package cn.iflyapi.blog.annotation; /** * @author flyhero * @date 2018-12-20 12:55 PM */ @Component public class OpenApiScan implements ApplicationListener<ApplicationReadyEvent> { @Autowired
private JwtInterceptor jwtInterceptor;
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/FileController.java
// Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/IFileService.java // public interface IFileService { // // String upload(MultipartFile file, Long userId); // }
import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.IFileService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-22 6:48 PM */ @Api(value = "FileController", tags = "文件接口") @RestController public class FileController extends BaseController { @Autowired @Qualifier("qiniu")
// Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/IFileService.java // public interface IFileService { // // String upload(MultipartFile file, Long userId); // } // Path: src/main/java/cn/iflyapi/blog/controller/FileController.java import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.IFileService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-22 6:48 PM */ @Api(value = "FileController", tags = "文件接口") @RestController public class FileController extends BaseController { @Autowired @Qualifier("qiniu")
private IFileService fileService;
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/FileController.java
// Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/IFileService.java // public interface IFileService { // // String upload(MultipartFile file, Long userId); // }
import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.IFileService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-22 6:48 PM */ @Api(value = "FileController", tags = "文件接口") @RestController public class FileController extends BaseController { @Autowired @Qualifier("qiniu") private IFileService fileService; @ApiOperation("文件上传") @PostMapping("files")
// Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/IFileService.java // public interface IFileService { // // String upload(MultipartFile file, Long userId); // } // Path: src/main/java/cn/iflyapi/blog/controller/FileController.java import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.IFileService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-22 6:48 PM */ @Api(value = "FileController", tags = "文件接口") @RestController public class FileController extends BaseController { @Autowired @Qualifier("qiniu") private IFileService fileService; @ApiOperation("文件上传") @PostMapping("files")
public JSONResult upload(MultipartFile file) {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/config/JwtInterceptor.java
// Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/util/JwtUtils.java // public class JwtUtils { // // private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class); // // //一个月 // private static long EXPIRED_TIME = 60 * 60 * 24 * 30; // // private static String key = "secret"; // // public static String getToken(Long userId, String nickName) throws Exception { // Map<String, Object> mapHeader = new HashMap<>(2); // mapHeader.put("alg", "HS256"); // mapHeader.put("typ", "JWT"); // long iat = System.currentTimeMillis(); // long exp = iat + EXPIRED_TIME * 1000L; // return JWT.create() // .withHeader(mapHeader) // .withIssuedAt(new Date(iat)) // .withExpiresAt(new Date(exp)) // .withClaim("userId", String.valueOf(userId)) // .withClaim("nickName", nickName) // .sign(Algorithm.HMAC256(key)); // } // // public static Map<String, Claim> verify(String token) { // DecodedJWT jwt; // try { // JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build(); // jwt = verifier.verify(token); // Map<String, Claim> claims = jwt.getClaims(); // return jwt.getClaims(); // } catch (Exception ex) { // logger.error("verify jwt token failed, token={}", token, ex); // return null; // } // // } // // // /* public static void main(String[] args) { // Map<String, Object> map = new HashMap<>(); // map.put("userName", "flyhero"); // try { // String t = getToken(map); // Thread.sleep(10000); // verify(t); // } catch (InvalidClaimException e) { // System.out.println("InvalidClaimException"); // } catch (SignatureVerificationException e) { // System.out.println("SignatureVerificationException"); // } catch (Exception e) { // // } // }*/ // }
import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.util.JwtUtils; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.auth0.jwt.interfaces.Claim; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map;
package cn.iflyapi.blog.config; public class JwtInterceptor implements HandlerInterceptor { private final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class); private List<String> excludedUrl = new ArrayList<>(); public void register(String url) { excludedUrl.add(url); } @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { try { //过滤 OPTIONS 请求 if (HttpMethod.OPTIONS.name().equals(httpServletRequest.getMethod())) { return true; } System.out.println(excludedUrl.toString()); String currentPath = httpServletRequest.getMethod() + httpServletRequest.getRequestURI(); for (String target : excludedUrl) { if (pathMatch(currentPath, target)) { return true; } } String token = httpServletRequest.getHeader("Authorization"); if (StringUtils.isEmpty(token)) { logger.error("token validate failed, no auth info in http header"); return setNoAuth(httpServletResponse); }
// Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/util/JwtUtils.java // public class JwtUtils { // // private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class); // // //一个月 // private static long EXPIRED_TIME = 60 * 60 * 24 * 30; // // private static String key = "secret"; // // public static String getToken(Long userId, String nickName) throws Exception { // Map<String, Object> mapHeader = new HashMap<>(2); // mapHeader.put("alg", "HS256"); // mapHeader.put("typ", "JWT"); // long iat = System.currentTimeMillis(); // long exp = iat + EXPIRED_TIME * 1000L; // return JWT.create() // .withHeader(mapHeader) // .withIssuedAt(new Date(iat)) // .withExpiresAt(new Date(exp)) // .withClaim("userId", String.valueOf(userId)) // .withClaim("nickName", nickName) // .sign(Algorithm.HMAC256(key)); // } // // public static Map<String, Claim> verify(String token) { // DecodedJWT jwt; // try { // JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build(); // jwt = verifier.verify(token); // Map<String, Claim> claims = jwt.getClaims(); // return jwt.getClaims(); // } catch (Exception ex) { // logger.error("verify jwt token failed, token={}", token, ex); // return null; // } // // } // // // /* public static void main(String[] args) { // Map<String, Object> map = new HashMap<>(); // map.put("userName", "flyhero"); // try { // String t = getToken(map); // Thread.sleep(10000); // verify(t); // } catch (InvalidClaimException e) { // System.out.println("InvalidClaimException"); // } catch (SignatureVerificationException e) { // System.out.println("SignatureVerificationException"); // } catch (Exception e) { // // } // }*/ // } // Path: src/main/java/cn/iflyapi/blog/config/JwtInterceptor.java import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.util.JwtUtils; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.auth0.jwt.interfaces.Claim; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; package cn.iflyapi.blog.config; public class JwtInterceptor implements HandlerInterceptor { private final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class); private List<String> excludedUrl = new ArrayList<>(); public void register(String url) { excludedUrl.add(url); } @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { try { //过滤 OPTIONS 请求 if (HttpMethod.OPTIONS.name().equals(httpServletRequest.getMethod())) { return true; } System.out.println(excludedUrl.toString()); String currentPath = httpServletRequest.getMethod() + httpServletRequest.getRequestURI(); for (String target : excludedUrl) { if (pathMatch(currentPath, target)) { return true; } } String token = httpServletRequest.getHeader("Authorization"); if (StringUtils.isEmpty(token)) { logger.error("token validate failed, no auth info in http header"); return setNoAuth(httpServletResponse); }
Map<String, Claim> map = JwtUtils.verify(token);
flyhero/flyapi
src/main/java/cn/iflyapi/blog/config/JwtInterceptor.java
// Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/util/JwtUtils.java // public class JwtUtils { // // private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class); // // //一个月 // private static long EXPIRED_TIME = 60 * 60 * 24 * 30; // // private static String key = "secret"; // // public static String getToken(Long userId, String nickName) throws Exception { // Map<String, Object> mapHeader = new HashMap<>(2); // mapHeader.put("alg", "HS256"); // mapHeader.put("typ", "JWT"); // long iat = System.currentTimeMillis(); // long exp = iat + EXPIRED_TIME * 1000L; // return JWT.create() // .withHeader(mapHeader) // .withIssuedAt(new Date(iat)) // .withExpiresAt(new Date(exp)) // .withClaim("userId", String.valueOf(userId)) // .withClaim("nickName", nickName) // .sign(Algorithm.HMAC256(key)); // } // // public static Map<String, Claim> verify(String token) { // DecodedJWT jwt; // try { // JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build(); // jwt = verifier.verify(token); // Map<String, Claim> claims = jwt.getClaims(); // return jwt.getClaims(); // } catch (Exception ex) { // logger.error("verify jwt token failed, token={}", token, ex); // return null; // } // // } // // // /* public static void main(String[] args) { // Map<String, Object> map = new HashMap<>(); // map.put("userName", "flyhero"); // try { // String t = getToken(map); // Thread.sleep(10000); // verify(t); // } catch (InvalidClaimException e) { // System.out.println("InvalidClaimException"); // } catch (SignatureVerificationException e) { // System.out.println("SignatureVerificationException"); // } catch (Exception e) { // // } // }*/ // }
import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.util.JwtUtils; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.auth0.jwt.interfaces.Claim; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map;
} String token = httpServletRequest.getHeader("Authorization"); if (StringUtils.isEmpty(token)) { logger.error("token validate failed, no auth info in http header"); return setNoAuth(httpServletResponse); } Map<String, Claim> map = JwtUtils.verify(token); if (map != null) { return true; } } catch (Exception e) { logger.error("JWT验证失败 {}", e.getMessage()); return setNoAuth(httpServletResponse); } return setNoAuth(httpServletResponse); } /** * 设置response 返回需要登录的标识 * * @param response */ private boolean setNoAuth(HttpServletResponse response) throws IOException { response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true");
// Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/util/JwtUtils.java // public class JwtUtils { // // private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class); // // //一个月 // private static long EXPIRED_TIME = 60 * 60 * 24 * 30; // // private static String key = "secret"; // // public static String getToken(Long userId, String nickName) throws Exception { // Map<String, Object> mapHeader = new HashMap<>(2); // mapHeader.put("alg", "HS256"); // mapHeader.put("typ", "JWT"); // long iat = System.currentTimeMillis(); // long exp = iat + EXPIRED_TIME * 1000L; // return JWT.create() // .withHeader(mapHeader) // .withIssuedAt(new Date(iat)) // .withExpiresAt(new Date(exp)) // .withClaim("userId", String.valueOf(userId)) // .withClaim("nickName", nickName) // .sign(Algorithm.HMAC256(key)); // } // // public static Map<String, Claim> verify(String token) { // DecodedJWT jwt; // try { // JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build(); // jwt = verifier.verify(token); // Map<String, Claim> claims = jwt.getClaims(); // return jwt.getClaims(); // } catch (Exception ex) { // logger.error("verify jwt token failed, token={}", token, ex); // return null; // } // // } // // // /* public static void main(String[] args) { // Map<String, Object> map = new HashMap<>(); // map.put("userName", "flyhero"); // try { // String t = getToken(map); // Thread.sleep(10000); // verify(t); // } catch (InvalidClaimException e) { // System.out.println("InvalidClaimException"); // } catch (SignatureVerificationException e) { // System.out.println("SignatureVerificationException"); // } catch (Exception e) { // // } // }*/ // } // Path: src/main/java/cn/iflyapi/blog/config/JwtInterceptor.java import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.util.JwtUtils; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.auth0.jwt.interfaces.Claim; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; } String token = httpServletRequest.getHeader("Authorization"); if (StringUtils.isEmpty(token)) { logger.error("token validate failed, no auth info in http header"); return setNoAuth(httpServletResponse); } Map<String, Claim> map = JwtUtils.verify(token); if (map != null) { return true; } } catch (Exception e) { logger.error("JWT验证失败 {}", e.getMessage()); return setNoAuth(httpServletResponse); } return setNoAuth(httpServletResponse); } /** * 设置response 返回需要登录的标识 * * @param response */ private boolean setNoAuth(HttpServletResponse response) throws IOException { response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true");
response.getWriter().write(JSONObject.toJSONString(JSONResult.fail(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()), SerializerFeature.WriteMapNullValue));
flyhero/flyapi
src/main/java/cn/iflyapi/blog/model/JSONResult.java
// Path: src/main/java/cn/iflyapi/blog/enums/CodeMsgEnum.java // public enum CodeMsgEnum { // OK(200, "Success"), // FAIL(-1, "Fail"), // USERNAME_OR_PASSWD_INVALID(40000, "用户名或密码不正确"), // USERNAME_EXIST(40001, "用户名已存在"), // USERNAME_MUST_MAIL_OR_PHONE(40002, "用户名必须是邮箱或手机号"), // USER_ALREADY_REGISTER(40003, "你已经注册过了"), // USER_NOT_LOGIN(40004, "你还没有登录"), // // IMG_BED_MUST_BE_SET(40010, "你必须设置你的图床或赞助使用我们提供的图床"), // IMG_FILE_ALREADY_100M(40010, "由于空间有限,目前仅能提供100M免费存储,你可自行设置图床或赞助我们继续使用"), // // RESOURCE_FORBIDDEN(40300, "你没有操作该资源的权限"), // // RESOURCE_NOT_EXIST(40400, "你查询的资源不存在"), // // USER_IS_DISABLED(50000, "用户已被禁用"); // // // private Integer code; // private String msg; // // CodeMsgEnum(Integer code, String msg) { // this.code = code; // this.msg = msg; // } // // public Integer getCode() { // return code; // } // // public void setCode(Integer code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import cn.iflyapi.blog.enums.CodeMsgEnum; import lombok.Getter; import lombok.Setter;
package cn.iflyapi.blog.model; /** * author: flyhero * date: 2018-12-13 9:56 AM */ @Getter @Setter public class JSONResult { private int code; private String msg; private boolean success; private Object data; private JSONResult(int code, String msg, boolean success, Object data) { this.code = code; this.msg = msg; this.success = success; this.data = data; } public static JSONResult ok(int code, String msg, Object data) { return new JSONResult(code, msg, true, data); }
// Path: src/main/java/cn/iflyapi/blog/enums/CodeMsgEnum.java // public enum CodeMsgEnum { // OK(200, "Success"), // FAIL(-1, "Fail"), // USERNAME_OR_PASSWD_INVALID(40000, "用户名或密码不正确"), // USERNAME_EXIST(40001, "用户名已存在"), // USERNAME_MUST_MAIL_OR_PHONE(40002, "用户名必须是邮箱或手机号"), // USER_ALREADY_REGISTER(40003, "你已经注册过了"), // USER_NOT_LOGIN(40004, "你还没有登录"), // // IMG_BED_MUST_BE_SET(40010, "你必须设置你的图床或赞助使用我们提供的图床"), // IMG_FILE_ALREADY_100M(40010, "由于空间有限,目前仅能提供100M免费存储,你可自行设置图床或赞助我们继续使用"), // // RESOURCE_FORBIDDEN(40300, "你没有操作该资源的权限"), // // RESOURCE_NOT_EXIST(40400, "你查询的资源不存在"), // // USER_IS_DISABLED(50000, "用户已被禁用"); // // // private Integer code; // private String msg; // // CodeMsgEnum(Integer code, String msg) { // this.code = code; // this.msg = msg; // } // // public Integer getCode() { // return code; // } // // public void setCode(Integer code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java import cn.iflyapi.blog.enums.CodeMsgEnum; import lombok.Getter; import lombok.Setter; package cn.iflyapi.blog.model; /** * author: flyhero * date: 2018-12-13 9:56 AM */ @Getter @Setter public class JSONResult { private int code; private String msg; private boolean success; private Object data; private JSONResult(int code, String msg, boolean success, Object data) { this.code = code; this.msg = msg; this.success = success; this.data = data; } public static JSONResult ok(int code, String msg, Object data) { return new JSONResult(code, msg, true, data); }
public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/CarouselController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Carousel.java // public class Carousel { // private Long id; // // private String title; // // private String imgUrl; // // private String detailUrl; // // private Integer sort; // // private Date createTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImgUrl() { // return imgUrl; // } // // public void setImgUrl(String imgUrl) { // this.imgUrl = imgUrl; // } // // public String getDetailUrl() { // return detailUrl; // } // // public void setDetailUrl(String detailUrl) { // this.detailUrl = detailUrl; // } // // public Integer getSort() { // return sort; // } // // public void setSort(Integer sort) { // this.sort = sort; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/CarouselService.java // @Service // public class CarouselService { // // @Autowired // private CarouselMapper carouselMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Carousel> listCarousel() { // CarouselExample carouselExample = new CarouselExample(); // carouselExample.createCriteria().andIsDeleteEqualTo(false); // carouselExample.setOrderByClause("sort desc"); // return carouselMapper.selectByExample(carouselExample); // } // // public void save(Carousel carousel) { // FastValidator.doit().notEmpty(carousel.getTitle(), "title"); // carousel.setId(idWorker.nextId()); // carouselMapper.insertSelective(carousel); // } // // public void update(Carousel carousel) { // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // public void remove(Long carouselId) { // Carousel carousel = new Carousel(); // carousel.setId(carouselId); // carousel.setIsDelete(true); // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // // }
import cn.iflyapi.blog.annotation.OpenApi; import cn.iflyapi.blog.entity.Carousel; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.CarouselService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 11:14 AM */ @Api(value = "CarouselController", tags = "轮播图接口") @RestController public class CarouselController { @Autowired
// Path: src/main/java/cn/iflyapi/blog/entity/Carousel.java // public class Carousel { // private Long id; // // private String title; // // private String imgUrl; // // private String detailUrl; // // private Integer sort; // // private Date createTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImgUrl() { // return imgUrl; // } // // public void setImgUrl(String imgUrl) { // this.imgUrl = imgUrl; // } // // public String getDetailUrl() { // return detailUrl; // } // // public void setDetailUrl(String detailUrl) { // this.detailUrl = detailUrl; // } // // public Integer getSort() { // return sort; // } // // public void setSort(Integer sort) { // this.sort = sort; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/CarouselService.java // @Service // public class CarouselService { // // @Autowired // private CarouselMapper carouselMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Carousel> listCarousel() { // CarouselExample carouselExample = new CarouselExample(); // carouselExample.createCriteria().andIsDeleteEqualTo(false); // carouselExample.setOrderByClause("sort desc"); // return carouselMapper.selectByExample(carouselExample); // } // // public void save(Carousel carousel) { // FastValidator.doit().notEmpty(carousel.getTitle(), "title"); // carousel.setId(idWorker.nextId()); // carouselMapper.insertSelective(carousel); // } // // public void update(Carousel carousel) { // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // public void remove(Long carouselId) { // Carousel carousel = new Carousel(); // carousel.setId(carouselId); // carousel.setIsDelete(true); // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // // } // Path: src/main/java/cn/iflyapi/blog/controller/CarouselController.java import cn.iflyapi.blog.annotation.OpenApi; import cn.iflyapi.blog.entity.Carousel; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.CarouselService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 11:14 AM */ @Api(value = "CarouselController", tags = "轮播图接口") @RestController public class CarouselController { @Autowired
private CarouselService carouselService;
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/CarouselController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Carousel.java // public class Carousel { // private Long id; // // private String title; // // private String imgUrl; // // private String detailUrl; // // private Integer sort; // // private Date createTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImgUrl() { // return imgUrl; // } // // public void setImgUrl(String imgUrl) { // this.imgUrl = imgUrl; // } // // public String getDetailUrl() { // return detailUrl; // } // // public void setDetailUrl(String detailUrl) { // this.detailUrl = detailUrl; // } // // public Integer getSort() { // return sort; // } // // public void setSort(Integer sort) { // this.sort = sort; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/CarouselService.java // @Service // public class CarouselService { // // @Autowired // private CarouselMapper carouselMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Carousel> listCarousel() { // CarouselExample carouselExample = new CarouselExample(); // carouselExample.createCriteria().andIsDeleteEqualTo(false); // carouselExample.setOrderByClause("sort desc"); // return carouselMapper.selectByExample(carouselExample); // } // // public void save(Carousel carousel) { // FastValidator.doit().notEmpty(carousel.getTitle(), "title"); // carousel.setId(idWorker.nextId()); // carouselMapper.insertSelective(carousel); // } // // public void update(Carousel carousel) { // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // public void remove(Long carouselId) { // Carousel carousel = new Carousel(); // carousel.setId(carouselId); // carousel.setIsDelete(true); // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // // }
import cn.iflyapi.blog.annotation.OpenApi; import cn.iflyapi.blog.entity.Carousel; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.CarouselService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 11:14 AM */ @Api(value = "CarouselController", tags = "轮播图接口") @RestController public class CarouselController { @Autowired private CarouselService carouselService; @ApiOperation("查询轮播图") @OpenApi("/carousels") @GetMapping("/carousels")
// Path: src/main/java/cn/iflyapi/blog/entity/Carousel.java // public class Carousel { // private Long id; // // private String title; // // private String imgUrl; // // private String detailUrl; // // private Integer sort; // // private Date createTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImgUrl() { // return imgUrl; // } // // public void setImgUrl(String imgUrl) { // this.imgUrl = imgUrl; // } // // public String getDetailUrl() { // return detailUrl; // } // // public void setDetailUrl(String detailUrl) { // this.detailUrl = detailUrl; // } // // public Integer getSort() { // return sort; // } // // public void setSort(Integer sort) { // this.sort = sort; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/CarouselService.java // @Service // public class CarouselService { // // @Autowired // private CarouselMapper carouselMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Carousel> listCarousel() { // CarouselExample carouselExample = new CarouselExample(); // carouselExample.createCriteria().andIsDeleteEqualTo(false); // carouselExample.setOrderByClause("sort desc"); // return carouselMapper.selectByExample(carouselExample); // } // // public void save(Carousel carousel) { // FastValidator.doit().notEmpty(carousel.getTitle(), "title"); // carousel.setId(idWorker.nextId()); // carouselMapper.insertSelective(carousel); // } // // public void update(Carousel carousel) { // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // public void remove(Long carouselId) { // Carousel carousel = new Carousel(); // carousel.setId(carouselId); // carousel.setIsDelete(true); // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // // } // Path: src/main/java/cn/iflyapi/blog/controller/CarouselController.java import cn.iflyapi.blog.annotation.OpenApi; import cn.iflyapi.blog.entity.Carousel; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.CarouselService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 11:14 AM */ @Api(value = "CarouselController", tags = "轮播图接口") @RestController public class CarouselController { @Autowired private CarouselService carouselService; @ApiOperation("查询轮播图") @OpenApi("/carousels") @GetMapping("/carousels")
public JSONResult find() {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/CarouselController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Carousel.java // public class Carousel { // private Long id; // // private String title; // // private String imgUrl; // // private String detailUrl; // // private Integer sort; // // private Date createTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImgUrl() { // return imgUrl; // } // // public void setImgUrl(String imgUrl) { // this.imgUrl = imgUrl; // } // // public String getDetailUrl() { // return detailUrl; // } // // public void setDetailUrl(String detailUrl) { // this.detailUrl = detailUrl; // } // // public Integer getSort() { // return sort; // } // // public void setSort(Integer sort) { // this.sort = sort; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/CarouselService.java // @Service // public class CarouselService { // // @Autowired // private CarouselMapper carouselMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Carousel> listCarousel() { // CarouselExample carouselExample = new CarouselExample(); // carouselExample.createCriteria().andIsDeleteEqualTo(false); // carouselExample.setOrderByClause("sort desc"); // return carouselMapper.selectByExample(carouselExample); // } // // public void save(Carousel carousel) { // FastValidator.doit().notEmpty(carousel.getTitle(), "title"); // carousel.setId(idWorker.nextId()); // carouselMapper.insertSelective(carousel); // } // // public void update(Carousel carousel) { // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // public void remove(Long carouselId) { // Carousel carousel = new Carousel(); // carousel.setId(carouselId); // carousel.setIsDelete(true); // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // // }
import cn.iflyapi.blog.annotation.OpenApi; import cn.iflyapi.blog.entity.Carousel; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.CarouselService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 11:14 AM */ @Api(value = "CarouselController", tags = "轮播图接口") @RestController public class CarouselController { @Autowired private CarouselService carouselService; @ApiOperation("查询轮播图") @OpenApi("/carousels") @GetMapping("/carousels") public JSONResult find() { return JSONResult.ok(carouselService.listCarousel()); } @ApiOperation("新增轮播图") @PostMapping("/carousels")
// Path: src/main/java/cn/iflyapi/blog/entity/Carousel.java // public class Carousel { // private Long id; // // private String title; // // private String imgUrl; // // private String detailUrl; // // private Integer sort; // // private Date createTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImgUrl() { // return imgUrl; // } // // public void setImgUrl(String imgUrl) { // this.imgUrl = imgUrl; // } // // public String getDetailUrl() { // return detailUrl; // } // // public void setDetailUrl(String detailUrl) { // this.detailUrl = detailUrl; // } // // public Integer getSort() { // return sort; // } // // public void setSort(Integer sort) { // this.sort = sort; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/CarouselService.java // @Service // public class CarouselService { // // @Autowired // private CarouselMapper carouselMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Carousel> listCarousel() { // CarouselExample carouselExample = new CarouselExample(); // carouselExample.createCriteria().andIsDeleteEqualTo(false); // carouselExample.setOrderByClause("sort desc"); // return carouselMapper.selectByExample(carouselExample); // } // // public void save(Carousel carousel) { // FastValidator.doit().notEmpty(carousel.getTitle(), "title"); // carousel.setId(idWorker.nextId()); // carouselMapper.insertSelective(carousel); // } // // public void update(Carousel carousel) { // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // public void remove(Long carouselId) { // Carousel carousel = new Carousel(); // carousel.setId(carouselId); // carousel.setIsDelete(true); // carouselMapper.updateByPrimaryKeySelective(carousel); // } // // // } // Path: src/main/java/cn/iflyapi/blog/controller/CarouselController.java import cn.iflyapi.blog.annotation.OpenApi; import cn.iflyapi.blog.entity.Carousel; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.CarouselService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 11:14 AM */ @Api(value = "CarouselController", tags = "轮播图接口") @RestController public class CarouselController { @Autowired private CarouselService carouselService; @ApiOperation("查询轮播图") @OpenApi("/carousels") @GetMapping("/carousels") public JSONResult find() { return JSONResult.ok(carouselService.listCarousel()); } @ApiOperation("新增轮播图") @PostMapping("/carousels")
public JSONResult add(@RequestBody Carousel carousel) {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/StoreController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Store.java // public class Store { // private Long id; // // private Long userId; // // private String ak; // // private String sk; // // private String bucket; // // private String domain; // // private Integer vip; // // private String storeType; // // private Boolean isTry; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getAk() { // return ak; // } // // public void setAk(String ak) { // this.ak = ak; // } // // public String getSk() { // return sk; // } // // public void setSk(String sk) { // this.sk = sk; // } // // public String getBucket() { // return bucket; // } // // public void setBucket(String bucket) { // this.bucket = bucket; // } // // public String getDomain() { // return domain; // } // // public void setDomain(String domain) { // this.domain = domain; // } // // public Integer getVip() { // return vip; // } // // public void setVip(Integer vip) { // this.vip = vip; // } // // public String getStoreType() { // return storeType; // } // // public void setStoreType(String storeType) { // this.storeType = storeType; // } // // public Boolean getIsTry() { // return isTry; // } // // public void setIsTry(Boolean isTry) { // this.isTry = isTry; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/StoreService.java // @Service // public class StoreService { // // @Autowired // private StoreMapper storeMapper; // // public Store get(Long userId) { // StoreExample storeExample = new StoreExample(); // storeExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // List<Store> storeList = storeMapper.selectByExample(storeExample); // if (CollectionUtils.isEmpty(storeList)) { // return null; // } // return storeList.get(0); // } // // public boolean save(Store store) { // store.setCreateTime(new Date()); // int num = storeMapper.insertSelective(store); // return num > 0; // } // // public boolean update(Store store) { // int num = storeMapper.updateByPrimaryKeySelective(store); // return num > 0; // } // }
import cn.iflyapi.blog.entity.Store; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.StoreService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 2:32 PM */ @Api(value = "StoreController", tags = "图床接口") @RestController public class StoreController extends BaseController { @Autowired
// Path: src/main/java/cn/iflyapi/blog/entity/Store.java // public class Store { // private Long id; // // private Long userId; // // private String ak; // // private String sk; // // private String bucket; // // private String domain; // // private Integer vip; // // private String storeType; // // private Boolean isTry; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getAk() { // return ak; // } // // public void setAk(String ak) { // this.ak = ak; // } // // public String getSk() { // return sk; // } // // public void setSk(String sk) { // this.sk = sk; // } // // public String getBucket() { // return bucket; // } // // public void setBucket(String bucket) { // this.bucket = bucket; // } // // public String getDomain() { // return domain; // } // // public void setDomain(String domain) { // this.domain = domain; // } // // public Integer getVip() { // return vip; // } // // public void setVip(Integer vip) { // this.vip = vip; // } // // public String getStoreType() { // return storeType; // } // // public void setStoreType(String storeType) { // this.storeType = storeType; // } // // public Boolean getIsTry() { // return isTry; // } // // public void setIsTry(Boolean isTry) { // this.isTry = isTry; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/StoreService.java // @Service // public class StoreService { // // @Autowired // private StoreMapper storeMapper; // // public Store get(Long userId) { // StoreExample storeExample = new StoreExample(); // storeExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // List<Store> storeList = storeMapper.selectByExample(storeExample); // if (CollectionUtils.isEmpty(storeList)) { // return null; // } // return storeList.get(0); // } // // public boolean save(Store store) { // store.setCreateTime(new Date()); // int num = storeMapper.insertSelective(store); // return num > 0; // } // // public boolean update(Store store) { // int num = storeMapper.updateByPrimaryKeySelective(store); // return num > 0; // } // } // Path: src/main/java/cn/iflyapi/blog/controller/StoreController.java import cn.iflyapi.blog.entity.Store; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.StoreService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 2:32 PM */ @Api(value = "StoreController", tags = "图床接口") @RestController public class StoreController extends BaseController { @Autowired
private StoreService storeService;
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/StoreController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Store.java // public class Store { // private Long id; // // private Long userId; // // private String ak; // // private String sk; // // private String bucket; // // private String domain; // // private Integer vip; // // private String storeType; // // private Boolean isTry; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getAk() { // return ak; // } // // public void setAk(String ak) { // this.ak = ak; // } // // public String getSk() { // return sk; // } // // public void setSk(String sk) { // this.sk = sk; // } // // public String getBucket() { // return bucket; // } // // public void setBucket(String bucket) { // this.bucket = bucket; // } // // public String getDomain() { // return domain; // } // // public void setDomain(String domain) { // this.domain = domain; // } // // public Integer getVip() { // return vip; // } // // public void setVip(Integer vip) { // this.vip = vip; // } // // public String getStoreType() { // return storeType; // } // // public void setStoreType(String storeType) { // this.storeType = storeType; // } // // public Boolean getIsTry() { // return isTry; // } // // public void setIsTry(Boolean isTry) { // this.isTry = isTry; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/StoreService.java // @Service // public class StoreService { // // @Autowired // private StoreMapper storeMapper; // // public Store get(Long userId) { // StoreExample storeExample = new StoreExample(); // storeExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // List<Store> storeList = storeMapper.selectByExample(storeExample); // if (CollectionUtils.isEmpty(storeList)) { // return null; // } // return storeList.get(0); // } // // public boolean save(Store store) { // store.setCreateTime(new Date()); // int num = storeMapper.insertSelective(store); // return num > 0; // } // // public boolean update(Store store) { // int num = storeMapper.updateByPrimaryKeySelective(store); // return num > 0; // } // }
import cn.iflyapi.blog.entity.Store; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.StoreService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 2:32 PM */ @Api(value = "StoreController", tags = "图床接口") @RestController public class StoreController extends BaseController { @Autowired private StoreService storeService; @ApiOperation("查询图床") @GetMapping("/stores")
// Path: src/main/java/cn/iflyapi/blog/entity/Store.java // public class Store { // private Long id; // // private Long userId; // // private String ak; // // private String sk; // // private String bucket; // // private String domain; // // private Integer vip; // // private String storeType; // // private Boolean isTry; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getAk() { // return ak; // } // // public void setAk(String ak) { // this.ak = ak; // } // // public String getSk() { // return sk; // } // // public void setSk(String sk) { // this.sk = sk; // } // // public String getBucket() { // return bucket; // } // // public void setBucket(String bucket) { // this.bucket = bucket; // } // // public String getDomain() { // return domain; // } // // public void setDomain(String domain) { // this.domain = domain; // } // // public Integer getVip() { // return vip; // } // // public void setVip(Integer vip) { // this.vip = vip; // } // // public String getStoreType() { // return storeType; // } // // public void setStoreType(String storeType) { // this.storeType = storeType; // } // // public Boolean getIsTry() { // return isTry; // } // // public void setIsTry(Boolean isTry) { // this.isTry = isTry; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/StoreService.java // @Service // public class StoreService { // // @Autowired // private StoreMapper storeMapper; // // public Store get(Long userId) { // StoreExample storeExample = new StoreExample(); // storeExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // List<Store> storeList = storeMapper.selectByExample(storeExample); // if (CollectionUtils.isEmpty(storeList)) { // return null; // } // return storeList.get(0); // } // // public boolean save(Store store) { // store.setCreateTime(new Date()); // int num = storeMapper.insertSelective(store); // return num > 0; // } // // public boolean update(Store store) { // int num = storeMapper.updateByPrimaryKeySelective(store); // return num > 0; // } // } // Path: src/main/java/cn/iflyapi/blog/controller/StoreController.java import cn.iflyapi.blog.entity.Store; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.StoreService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 2:32 PM */ @Api(value = "StoreController", tags = "图床接口") @RestController public class StoreController extends BaseController { @Autowired private StoreService storeService; @ApiOperation("查询图床") @GetMapping("/stores")
public JSONResult find() {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/StoreController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Store.java // public class Store { // private Long id; // // private Long userId; // // private String ak; // // private String sk; // // private String bucket; // // private String domain; // // private Integer vip; // // private String storeType; // // private Boolean isTry; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getAk() { // return ak; // } // // public void setAk(String ak) { // this.ak = ak; // } // // public String getSk() { // return sk; // } // // public void setSk(String sk) { // this.sk = sk; // } // // public String getBucket() { // return bucket; // } // // public void setBucket(String bucket) { // this.bucket = bucket; // } // // public String getDomain() { // return domain; // } // // public void setDomain(String domain) { // this.domain = domain; // } // // public Integer getVip() { // return vip; // } // // public void setVip(Integer vip) { // this.vip = vip; // } // // public String getStoreType() { // return storeType; // } // // public void setStoreType(String storeType) { // this.storeType = storeType; // } // // public Boolean getIsTry() { // return isTry; // } // // public void setIsTry(Boolean isTry) { // this.isTry = isTry; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/StoreService.java // @Service // public class StoreService { // // @Autowired // private StoreMapper storeMapper; // // public Store get(Long userId) { // StoreExample storeExample = new StoreExample(); // storeExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // List<Store> storeList = storeMapper.selectByExample(storeExample); // if (CollectionUtils.isEmpty(storeList)) { // return null; // } // return storeList.get(0); // } // // public boolean save(Store store) { // store.setCreateTime(new Date()); // int num = storeMapper.insertSelective(store); // return num > 0; // } // // public boolean update(Store store) { // int num = storeMapper.updateByPrimaryKeySelective(store); // return num > 0; // } // }
import cn.iflyapi.blog.entity.Store; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.StoreService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 2:32 PM */ @Api(value = "StoreController", tags = "图床接口") @RestController public class StoreController extends BaseController { @Autowired private StoreService storeService; @ApiOperation("查询图床") @GetMapping("/stores") public JSONResult find() { return JSONResult.ok(storeService.get(getUserId())); } @ApiOperation("修改图床") @PatchMapping("/stores/{storeId}")
// Path: src/main/java/cn/iflyapi/blog/entity/Store.java // public class Store { // private Long id; // // private Long userId; // // private String ak; // // private String sk; // // private String bucket; // // private String domain; // // private Integer vip; // // private String storeType; // // private Boolean isTry; // // private Date createTime; // // private Date updateTime; // // private Boolean isDelete; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getAk() { // return ak; // } // // public void setAk(String ak) { // this.ak = ak; // } // // public String getSk() { // return sk; // } // // public void setSk(String sk) { // this.sk = sk; // } // // public String getBucket() { // return bucket; // } // // public void setBucket(String bucket) { // this.bucket = bucket; // } // // public String getDomain() { // return domain; // } // // public void setDomain(String domain) { // this.domain = domain; // } // // public Integer getVip() { // return vip; // } // // public void setVip(Integer vip) { // this.vip = vip; // } // // public String getStoreType() { // return storeType; // } // // public void setStoreType(String storeType) { // this.storeType = storeType; // } // // public Boolean getIsTry() { // return isTry; // } // // public void setIsTry(Boolean isTry) { // this.isTry = isTry; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/StoreService.java // @Service // public class StoreService { // // @Autowired // private StoreMapper storeMapper; // // public Store get(Long userId) { // StoreExample storeExample = new StoreExample(); // storeExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // List<Store> storeList = storeMapper.selectByExample(storeExample); // if (CollectionUtils.isEmpty(storeList)) { // return null; // } // return storeList.get(0); // } // // public boolean save(Store store) { // store.setCreateTime(new Date()); // int num = storeMapper.insertSelective(store); // return num > 0; // } // // public boolean update(Store store) { // int num = storeMapper.updateByPrimaryKeySelective(store); // return num > 0; // } // } // Path: src/main/java/cn/iflyapi/blog/controller/StoreController.java import cn.iflyapi.blog.entity.Store; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.StoreService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018-12-31 2:32 PM */ @Api(value = "StoreController", tags = "图床接口") @RestController public class StoreController extends BaseController { @Autowired private StoreService storeService; @ApiOperation("查询图床") @GetMapping("/stores") public JSONResult find() { return JSONResult.ok(storeService.get(getUserId())); } @ApiOperation("修改图床") @PatchMapping("/stores/{storeId}")
public JSONResult update(@PathVariable Long storeId, @RequestBody Store store) {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/util/HtmlUtils.java
// Path: src/main/java/cn/iflyapi/blog/util/StrUtils.java // public static final String EMPTY_JSON = "{}";
import org.apache.ibatis.reflection.ArrayUtil; import org.springframework.util.StringUtils; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.regex.Pattern; import static cn.iflyapi.blog.util.StrUtils.EMPTY_JSON;
} return format(template.toString(), params); } /** * 格式化字符串<br> * 此方法只是简单将占位符 {} 按照顺序替换为参数<br> * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br> * 例:<br> * 通常使用:format("this is {} for {}", "a", "b") =》 this is a for b<br> * 转义{}: format("this is \\{} for {}", "a", "b") =》 this is \{} for a<br> * 转义\: format("this is \\\\{} for {}", "a", "b") =》 this is \a for b<br> * * @param strPattern 字符串模板 * @param argArray 参数列表 * @return 结果 */ public static String format(final String strPattern, final Object... argArray) { if (StringUtils.isEmpty(strPattern) || argArray == null || argArray.length == 0) { return strPattern; } final int strPatternLength = strPattern.length(); //初始化定义好的长度以获得更好的性能 StringBuilder sbuf = new StringBuilder(strPatternLength + 50); int handledPosition = 0;//记录已经处理到的位置 int delimIndex;//占位符所在位置 for (int argIndex = 0; argIndex < argArray.length; argIndex++) {
// Path: src/main/java/cn/iflyapi/blog/util/StrUtils.java // public static final String EMPTY_JSON = "{}"; // Path: src/main/java/cn/iflyapi/blog/util/HtmlUtils.java import org.apache.ibatis.reflection.ArrayUtil; import org.springframework.util.StringUtils; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.regex.Pattern; import static cn.iflyapi.blog.util.StrUtils.EMPTY_JSON; } return format(template.toString(), params); } /** * 格式化字符串<br> * 此方法只是简单将占位符 {} 按照顺序替换为参数<br> * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br> * 例:<br> * 通常使用:format("this is {} for {}", "a", "b") =》 this is a for b<br> * 转义{}: format("this is \\{} for {}", "a", "b") =》 this is \{} for a<br> * 转义\: format("this is \\\\{} for {}", "a", "b") =》 this is \a for b<br> * * @param strPattern 字符串模板 * @param argArray 参数列表 * @return 结果 */ public static String format(final String strPattern, final Object... argArray) { if (StringUtils.isEmpty(strPattern) || argArray == null || argArray.length == 0) { return strPattern; } final int strPatternLength = strPattern.length(); //初始化定义好的长度以获得更好的性能 StringBuilder sbuf = new StringBuilder(strPatternLength + 50); int handledPosition = 0;//记录已经处理到的位置 int delimIndex;//占位符所在位置 for (int argIndex = 0; argIndex < argArray.length; argIndex++) {
delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
flyhero/flyapi
src/main/java/cn/iflyapi/blog/config/ErrorHandler.java
// Path: src/main/java/cn/iflyapi/blog/exception/FlyapiException.java // public class FlyapiException extends RuntimeException { // // private int code = -1; // private String msg; // // public FlyapiException(CodeMsgEnum codeMsgEnum) { // this.code = codeMsgEnum.getCode(); // this.msg = codeMsgEnum.getMsg(); // } // // public FlyapiException(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public FlyapiException(String msg) { // this.msg = msg; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // }
import cn.iflyapi.blog.exception.FlyapiException; import cn.iflyapi.blog.model.JSONResult; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice;
package cn.iflyapi.blog.config; /** * author: flyhero * date: 2018-12-13 11:09 AM */ @Slf4j @RestControllerAdvice public class ErrorHandler {
// Path: src/main/java/cn/iflyapi/blog/exception/FlyapiException.java // public class FlyapiException extends RuntimeException { // // private int code = -1; // private String msg; // // public FlyapiException(CodeMsgEnum codeMsgEnum) { // this.code = codeMsgEnum.getCode(); // this.msg = codeMsgEnum.getMsg(); // } // // public FlyapiException(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public FlyapiException(String msg) { // this.msg = msg; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // Path: src/main/java/cn/iflyapi/blog/config/ErrorHandler.java import cn.iflyapi.blog.exception.FlyapiException; import cn.iflyapi.blog.model.JSONResult; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; package cn.iflyapi.blog.config; /** * author: flyhero * date: 2018-12-13 11:09 AM */ @Slf4j @RestControllerAdvice public class ErrorHandler {
@ExceptionHandler(FlyapiException.class)
flyhero/flyapi
src/main/java/cn/iflyapi/blog/config/ErrorHandler.java
// Path: src/main/java/cn/iflyapi/blog/exception/FlyapiException.java // public class FlyapiException extends RuntimeException { // // private int code = -1; // private String msg; // // public FlyapiException(CodeMsgEnum codeMsgEnum) { // this.code = codeMsgEnum.getCode(); // this.msg = codeMsgEnum.getMsg(); // } // // public FlyapiException(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public FlyapiException(String msg) { // this.msg = msg; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // }
import cn.iflyapi.blog.exception.FlyapiException; import cn.iflyapi.blog.model.JSONResult; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice;
package cn.iflyapi.blog.config; /** * author: flyhero * date: 2018-12-13 11:09 AM */ @Slf4j @RestControllerAdvice public class ErrorHandler { @ExceptionHandler(FlyapiException.class)
// Path: src/main/java/cn/iflyapi/blog/exception/FlyapiException.java // public class FlyapiException extends RuntimeException { // // private int code = -1; // private String msg; // // public FlyapiException(CodeMsgEnum codeMsgEnum) { // this.code = codeMsgEnum.getCode(); // this.msg = codeMsgEnum.getMsg(); // } // // public FlyapiException(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public FlyapiException(String msg) { // this.msg = msg; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // Path: src/main/java/cn/iflyapi/blog/config/ErrorHandler.java import cn.iflyapi.blog.exception.FlyapiException; import cn.iflyapi.blog.model.JSONResult; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; package cn.iflyapi.blog.config; /** * author: flyhero * date: 2018-12-13 11:09 AM */ @Slf4j @RestControllerAdvice public class ErrorHandler { @ExceptionHandler(FlyapiException.class)
public JSONResult handlerFlyapiException(FlyapiException ex) {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/BaseController.java
// Path: src/main/java/cn/iflyapi/blog/util/JwtUtils.java // public class JwtUtils { // // private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class); // // //一个月 // private static long EXPIRED_TIME = 60 * 60 * 24 * 30; // // private static String key = "secret"; // // public static String getToken(Long userId, String nickName) throws Exception { // Map<String, Object> mapHeader = new HashMap<>(2); // mapHeader.put("alg", "HS256"); // mapHeader.put("typ", "JWT"); // long iat = System.currentTimeMillis(); // long exp = iat + EXPIRED_TIME * 1000L; // return JWT.create() // .withHeader(mapHeader) // .withIssuedAt(new Date(iat)) // .withExpiresAt(new Date(exp)) // .withClaim("userId", String.valueOf(userId)) // .withClaim("nickName", nickName) // .sign(Algorithm.HMAC256(key)); // } // // public static Map<String, Claim> verify(String token) { // DecodedJWT jwt; // try { // JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build(); // jwt = verifier.verify(token); // Map<String, Claim> claims = jwt.getClaims(); // return jwt.getClaims(); // } catch (Exception ex) { // logger.error("verify jwt token failed, token={}", token, ex); // return null; // } // // } // // // /* public static void main(String[] args) { // Map<String, Object> map = new HashMap<>(); // map.put("userName", "flyhero"); // try { // String t = getToken(map); // Thread.sleep(10000); // verify(t); // } catch (InvalidClaimException e) { // System.out.println("InvalidClaimException"); // } catch (SignatureVerificationException e) { // System.out.println("SignatureVerificationException"); // } catch (Exception e) { // // } // }*/ // }
import cn.iflyapi.blog.util.JwtUtils; import com.auth0.jwt.interfaces.Claim; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map;
package cn.iflyapi.blog.controller; /** * author: flyhero * date: 2018-12-12 7:48 PM */ public abstract class BaseController { protected HttpServletRequest request; protected HttpServletResponse response; /** * ModelAttribute标注的方法会在Controller类的每个映射url的控制执行方法之前执行 * * @param request * @param response */ @ModelAttribute public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) { this.response = response; this.request = request; } /** * 获取当前用户id * * @return */ protected Long getUserId() { Map<String, Claim> map = getStringClaimMap(); if (CollectionUtils.isEmpty(map) || null == map.get("userId")) { return null; } return Long.valueOf(map.get("userId").asString()); } /** * 获取当前用户昵称 * * @return */ protected String getNickName() { Map<String, Claim> map = getStringClaimMap(); if (CollectionUtils.isEmpty(map) || null == map.get("nickName")) { return null; } return map.get("nickName").asString(); } private Map<String, Claim> getStringClaimMap() { String token = request.getHeader("Authorization"); if (StringUtils.isEmpty(token)) { return null; }
// Path: src/main/java/cn/iflyapi/blog/util/JwtUtils.java // public class JwtUtils { // // private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class); // // //一个月 // private static long EXPIRED_TIME = 60 * 60 * 24 * 30; // // private static String key = "secret"; // // public static String getToken(Long userId, String nickName) throws Exception { // Map<String, Object> mapHeader = new HashMap<>(2); // mapHeader.put("alg", "HS256"); // mapHeader.put("typ", "JWT"); // long iat = System.currentTimeMillis(); // long exp = iat + EXPIRED_TIME * 1000L; // return JWT.create() // .withHeader(mapHeader) // .withIssuedAt(new Date(iat)) // .withExpiresAt(new Date(exp)) // .withClaim("userId", String.valueOf(userId)) // .withClaim("nickName", nickName) // .sign(Algorithm.HMAC256(key)); // } // // public static Map<String, Claim> verify(String token) { // DecodedJWT jwt; // try { // JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build(); // jwt = verifier.verify(token); // Map<String, Claim> claims = jwt.getClaims(); // return jwt.getClaims(); // } catch (Exception ex) { // logger.error("verify jwt token failed, token={}", token, ex); // return null; // } // // } // // // /* public static void main(String[] args) { // Map<String, Object> map = new HashMap<>(); // map.put("userName", "flyhero"); // try { // String t = getToken(map); // Thread.sleep(10000); // verify(t); // } catch (InvalidClaimException e) { // System.out.println("InvalidClaimException"); // } catch (SignatureVerificationException e) { // System.out.println("SignatureVerificationException"); // } catch (Exception e) { // // } // }*/ // } // Path: src/main/java/cn/iflyapi/blog/controller/BaseController.java import cn.iflyapi.blog.util.JwtUtils; import com.auth0.jwt.interfaces.Claim; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; package cn.iflyapi.blog.controller; /** * author: flyhero * date: 2018-12-12 7:48 PM */ public abstract class BaseController { protected HttpServletRequest request; protected HttpServletResponse response; /** * ModelAttribute标注的方法会在Controller类的每个映射url的控制执行方法之前执行 * * @param request * @param response */ @ModelAttribute public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) { this.response = response; this.request = request; } /** * 获取当前用户id * * @return */ protected Long getUserId() { Map<String, Claim> map = getStringClaimMap(); if (CollectionUtils.isEmpty(map) || null == map.get("userId")) { return null; } return Long.valueOf(map.get("userId").asString()); } /** * 获取当前用户昵称 * * @return */ protected String getNickName() { Map<String, Claim> map = getStringClaimMap(); if (CollectionUtils.isEmpty(map) || null == map.get("nickName")) { return null; } return map.get("nickName").asString(); } private Map<String, Claim> getStringClaimMap() { String token = request.getHeader("Authorization"); if (StringUtils.isEmpty(token)) { return null; }
return JwtUtils.verify(token);
flyhero/flyapi
src/main/java/cn/iflyapi/blog/exception/FlyapiException.java
// Path: src/main/java/cn/iflyapi/blog/enums/CodeMsgEnum.java // public enum CodeMsgEnum { // OK(200, "Success"), // FAIL(-1, "Fail"), // USERNAME_OR_PASSWD_INVALID(40000, "用户名或密码不正确"), // USERNAME_EXIST(40001, "用户名已存在"), // USERNAME_MUST_MAIL_OR_PHONE(40002, "用户名必须是邮箱或手机号"), // USER_ALREADY_REGISTER(40003, "你已经注册过了"), // USER_NOT_LOGIN(40004, "你还没有登录"), // // IMG_BED_MUST_BE_SET(40010, "你必须设置你的图床或赞助使用我们提供的图床"), // IMG_FILE_ALREADY_100M(40010, "由于空间有限,目前仅能提供100M免费存储,你可自行设置图床或赞助我们继续使用"), // // RESOURCE_FORBIDDEN(40300, "你没有操作该资源的权限"), // // RESOURCE_NOT_EXIST(40400, "你查询的资源不存在"), // // USER_IS_DISABLED(50000, "用户已被禁用"); // // // private Integer code; // private String msg; // // CodeMsgEnum(Integer code, String msg) { // this.code = code; // this.msg = msg; // } // // public Integer getCode() { // return code; // } // // public void setCode(Integer code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import cn.iflyapi.blog.enums.CodeMsgEnum;
package cn.iflyapi.blog.exception; /** * author: flyhero * date: 2018-12-13 11:08 AM */ public class FlyapiException extends RuntimeException { private int code = -1; private String msg;
// Path: src/main/java/cn/iflyapi/blog/enums/CodeMsgEnum.java // public enum CodeMsgEnum { // OK(200, "Success"), // FAIL(-1, "Fail"), // USERNAME_OR_PASSWD_INVALID(40000, "用户名或密码不正确"), // USERNAME_EXIST(40001, "用户名已存在"), // USERNAME_MUST_MAIL_OR_PHONE(40002, "用户名必须是邮箱或手机号"), // USER_ALREADY_REGISTER(40003, "你已经注册过了"), // USER_NOT_LOGIN(40004, "你还没有登录"), // // IMG_BED_MUST_BE_SET(40010, "你必须设置你的图床或赞助使用我们提供的图床"), // IMG_FILE_ALREADY_100M(40010, "由于空间有限,目前仅能提供100M免费存储,你可自行设置图床或赞助我们继续使用"), // // RESOURCE_FORBIDDEN(40300, "你没有操作该资源的权限"), // // RESOURCE_NOT_EXIST(40400, "你查询的资源不存在"), // // USER_IS_DISABLED(50000, "用户已被禁用"); // // // private Integer code; // private String msg; // // CodeMsgEnum(Integer code, String msg) { // this.code = code; // this.msg = msg; // } // // public Integer getCode() { // return code; // } // // public void setCode(Integer code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/cn/iflyapi/blog/exception/FlyapiException.java import cn.iflyapi.blog.enums.CodeMsgEnum; package cn.iflyapi.blog.exception; /** * author: flyhero * date: 2018-12-13 11:08 AM */ public class FlyapiException extends RuntimeException { private int code = -1; private String msg;
public FlyapiException(CodeMsgEnum codeMsgEnum) {
flyhero/flyapi
src/main/java/cn/iflyapi/blog/controller/SubjectController.java
// Path: src/main/java/cn/iflyapi/blog/entity/Subject.java // public class Subject { // private Long subjectId; // // private Long userId; // // private String cover; // // private String subjectTitle; // // private String subjectDes; // // private Boolean isPrivate; // // private Date createTime; // // private Boolean isDelete; // // public Long getSubjectId() { // return subjectId; // } // // public void setSubjectId(Long subjectId) { // this.subjectId = subjectId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getCover() { // return cover; // } // // public void setCover(String cover) { // this.cover = cover; // } // // public String getSubjectTitle() { // return subjectTitle; // } // // public void setSubjectTitle(String subjectTitle) { // this.subjectTitle = subjectTitle; // } // // public String getSubjectDes() { // return subjectDes; // } // // public void setSubjectDes(String subjectDes) { // this.subjectDes = subjectDes; // } // // public Boolean getIsPrivate() { // return isPrivate; // } // // public void setIsPrivate(Boolean isPrivate) { // this.isPrivate = isPrivate; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/SubjectService.java // @Service // public class SubjectService { // // @Autowired // private SubjectMapper subjectMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Subject> listSubjects(Long userId, Long currentUserId) { // SubjectExample subjectExample = new SubjectExample(); // if (userId.equals(currentUserId)) { // subjectExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // return subjectMapper.selectByExample(subjectExample); // } // subjectExample.createCriteria().andIsDeleteEqualTo(false).andIsPrivateEqualTo(false).andUserIdEqualTo(userId); // return subjectMapper.selectByExample(subjectExample); // } // // // public Subject save(Subject subject) { // FastValidator.doit().notEmpty(subject.getUserId(), "userId") // .notEmpty(subject.getSubjectTitle(), "subjectTitle") // .onMax(subject.getSubjectTitle(), 20, "subjectTitle"); // // subject.setSubjectId(idWorker.nextId()); // subject.setSubjectDes(Objects.isNull(subject.getSubjectDes()) ? subject.getSubjectTitle() : subject.getSubjectDes()); // subject.setCreateTime(new Date()); // subjectMapper.insertSelective(subject); // return subjectMapper.selectByPrimaryKey(subject.getSubjectId()); // } // // public boolean update(Subject subject) { // FastValidator.doit().notEmpty(subject.getUserId(), "userId") // .notEmpty(subject.getSubjectTitle(), "subjectTitle") // .onMax(subject.getSubjectTitle(), 20, "subjectTitle"); // // return subjectMapper.updateByPrimaryKeySelective(subject) > 0; // } // // public boolean remove(Long subjectId) { // Subject subject = new Subject(); // subject.setSubjectId(subjectId); // int num = subjectMapper.updateByPrimaryKeySelective(subject); // if (num > 0) { // return true; // } // return false; // } // }
import cn.iflyapi.blog.annotation.OpenApi; import cn.iflyapi.blog.entity.Subject; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.SubjectService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;
package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018/12/16 7:39 PM */ @Api(value = "SubjectController", tags = "小书接口") @RestController public class SubjectController extends BaseController { @Autowired
// Path: src/main/java/cn/iflyapi/blog/entity/Subject.java // public class Subject { // private Long subjectId; // // private Long userId; // // private String cover; // // private String subjectTitle; // // private String subjectDes; // // private Boolean isPrivate; // // private Date createTime; // // private Boolean isDelete; // // public Long getSubjectId() { // return subjectId; // } // // public void setSubjectId(Long subjectId) { // this.subjectId = subjectId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getCover() { // return cover; // } // // public void setCover(String cover) { // this.cover = cover; // } // // public String getSubjectTitle() { // return subjectTitle; // } // // public void setSubjectTitle(String subjectTitle) { // this.subjectTitle = subjectTitle; // } // // public String getSubjectDes() { // return subjectDes; // } // // public void setSubjectDes(String subjectDes) { // this.subjectDes = subjectDes; // } // // public Boolean getIsPrivate() { // return isPrivate; // } // // public void setIsPrivate(Boolean isPrivate) { // this.isPrivate = isPrivate; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Boolean getIsDelete() { // return isDelete; // } // // public void setIsDelete(Boolean isDelete) { // this.isDelete = isDelete; // } // } // // Path: src/main/java/cn/iflyapi/blog/model/JSONResult.java // @Getter // @Setter // public class JSONResult { // // private int code; // private String msg; // private boolean success; // private Object data; // // private JSONResult(int code, String msg, boolean success, Object data) { // this.code = code; // this.msg = msg; // this.success = success; // this.data = data; // } // // public static JSONResult ok(int code, String msg, Object data) { // return new JSONResult(code, msg, true, data); // } // // public static JSONResult ok(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult ok(Object data) { // return ok(CodeMsgEnum.OK, data); // } // // public static JSONResult ok() { // return ok(CodeMsgEnum.OK, null); // } // // public static JSONResult fail(int code, String msg) { // return new JSONResult(code, msg, false, null); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum, Object data) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), data); // } // // public static JSONResult fail(CodeMsgEnum codeMsgEnum) { // return ok(codeMsgEnum.getCode(), codeMsgEnum.getMsg(), null); // } // // public static JSONResult fail(Object data) { // return ok(CodeMsgEnum.FAIL, data); // } // // public static JSONResult fail() { // return ok(CodeMsgEnum.FAIL, null); // } // } // // Path: src/main/java/cn/iflyapi/blog/service/SubjectService.java // @Service // public class SubjectService { // // @Autowired // private SubjectMapper subjectMapper; // // @Autowired // private SnowflakeIdWorker idWorker; // // public List<Subject> listSubjects(Long userId, Long currentUserId) { // SubjectExample subjectExample = new SubjectExample(); // if (userId.equals(currentUserId)) { // subjectExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(false); // return subjectMapper.selectByExample(subjectExample); // } // subjectExample.createCriteria().andIsDeleteEqualTo(false).andIsPrivateEqualTo(false).andUserIdEqualTo(userId); // return subjectMapper.selectByExample(subjectExample); // } // // // public Subject save(Subject subject) { // FastValidator.doit().notEmpty(subject.getUserId(), "userId") // .notEmpty(subject.getSubjectTitle(), "subjectTitle") // .onMax(subject.getSubjectTitle(), 20, "subjectTitle"); // // subject.setSubjectId(idWorker.nextId()); // subject.setSubjectDes(Objects.isNull(subject.getSubjectDes()) ? subject.getSubjectTitle() : subject.getSubjectDes()); // subject.setCreateTime(new Date()); // subjectMapper.insertSelective(subject); // return subjectMapper.selectByPrimaryKey(subject.getSubjectId()); // } // // public boolean update(Subject subject) { // FastValidator.doit().notEmpty(subject.getUserId(), "userId") // .notEmpty(subject.getSubjectTitle(), "subjectTitle") // .onMax(subject.getSubjectTitle(), 20, "subjectTitle"); // // return subjectMapper.updateByPrimaryKeySelective(subject) > 0; // } // // public boolean remove(Long subjectId) { // Subject subject = new Subject(); // subject.setSubjectId(subjectId); // int num = subjectMapper.updateByPrimaryKeySelective(subject); // if (num > 0) { // return true; // } // return false; // } // } // Path: src/main/java/cn/iflyapi/blog/controller/SubjectController.java import cn.iflyapi.blog.annotation.OpenApi; import cn.iflyapi.blog.entity.Subject; import cn.iflyapi.blog.model.JSONResult; import cn.iflyapi.blog.service.SubjectService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; package cn.iflyapi.blog.controller; /** * @author flyhero * @date 2018/12/16 7:39 PM */ @Api(value = "SubjectController", tags = "小书接口") @RestController public class SubjectController extends BaseController { @Autowired
private SubjectService subjectService;
flyhero/flyapi
src/main/java/cn/iflyapi/blog/util/FastValidator.java
// Path: src/main/java/cn/iflyapi/blog/exception/FlyapiException.java // public class FlyapiException extends RuntimeException { // // private int code = -1; // private String msg; // // public FlyapiException(CodeMsgEnum codeMsgEnum) { // this.code = codeMsgEnum.getCode(); // this.msg = codeMsgEnum.getMsg(); // } // // public FlyapiException(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public FlyapiException(String msg) { // this.msg = msg; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import cn.iflyapi.blog.exception.FlyapiException;
package cn.iflyapi.blog.util; /** * author: flyhero * date: 2018-12-15 10:49 AM */ public class FastValidator { public static FastValidator doit() { return new FastValidator(); } /** * 校验参数不为空 * * @param o * @param paramName * @return */ public FastValidator notEmpty(Object o, String paramName) { if (null == o) {
// Path: src/main/java/cn/iflyapi/blog/exception/FlyapiException.java // public class FlyapiException extends RuntimeException { // // private int code = -1; // private String msg; // // public FlyapiException(CodeMsgEnum codeMsgEnum) { // this.code = codeMsgEnum.getCode(); // this.msg = codeMsgEnum.getMsg(); // } // // public FlyapiException(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public FlyapiException(String msg) { // this.msg = msg; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/cn/iflyapi/blog/util/FastValidator.java import cn.iflyapi.blog.exception.FlyapiException; package cn.iflyapi.blog.util; /** * author: flyhero * date: 2018-12-15 10:49 AM */ public class FastValidator { public static FastValidator doit() { return new FastValidator(); } /** * 校验参数不为空 * * @param o * @param paramName * @return */ public FastValidator notEmpty(Object o, String paramName) { if (null == o) {
throw new FlyapiException("参数[" + paramName + "]不能为空");
flyhero/flyapi
src/main/java/cn/iflyapi/blog/dao/custom/UserCustomMapper.java
// Path: src/main/java/cn/iflyapi/blog/pojo/po/UserFame.java // @Data // public class UserFame { // private Long userId; // private int score; // } // // Path: src/main/java/cn/iflyapi/blog/pojo/vo/RankFameVo.java // @Data // public class RankFameVo { // // private String userId; // private String nickName; // private String avatar; // private Integer total; // }
import cn.iflyapi.blog.pojo.po.UserFame; import cn.iflyapi.blog.pojo.vo.RankFameVo; import java.util.List;
package cn.iflyapi.blog.dao.custom; public interface UserCustomMapper { int countUserFameVal(UserFame userFame); int viewHomePage(Long userId);
// Path: src/main/java/cn/iflyapi/blog/pojo/po/UserFame.java // @Data // public class UserFame { // private Long userId; // private int score; // } // // Path: src/main/java/cn/iflyapi/blog/pojo/vo/RankFameVo.java // @Data // public class RankFameVo { // // private String userId; // private String nickName; // private String avatar; // private Integer total; // } // Path: src/main/java/cn/iflyapi/blog/dao/custom/UserCustomMapper.java import cn.iflyapi.blog.pojo.po.UserFame; import cn.iflyapi.blog.pojo.vo.RankFameVo; import java.util.List; package cn.iflyapi.blog.dao.custom; public interface UserCustomMapper { int countUserFameVal(UserFame userFame); int viewHomePage(Long userId);
List<RankFameVo> rankDay();
shevek/spring-rich-client
spring-richclient-sandbox/src/main/java/org/springframework/richclient/settings/jdbc/JdbcSettings.java
// Path: spring-richclient-sandbox/src/main/java/org/springframework/richclient/settings/Settings.java // public interface Settings { // void setString(String key, String value); // // String getString(String key); // // void setDefaultString(String key, String value); // // String getDefaultString(String key); // // void setInt(String key, int value); // // int getInt(String key); // // void setLong(String key, long value); // // long getLong(String key); // // void setDefaultInt(String key, int value); // // int getDefaultInt(String key); // // void setDefaultLong(String key, long value); // // long getDefaultLong(String key); // // void setFloat(String key, float value); // // float getFloat(String key); // // void setDefaultFloat(String key, float value); // // float getDefaultFloat(String key); // // void setDouble(String key, double value); // // double getDouble(String key); // // void setDefaultDouble(String key, double value); // // double getDefaultDouble(String key); // // void setBoolean(String key, boolean value); // // boolean getBoolean(String key); // // void setDefaultBoolean(String key, boolean value); // // boolean getDefaultBoolean(String key); // // void setLabeledEnum(String key, LabeledEnum value); // // LabeledEnum getLabeledEnum(String key); // // void setDefaultLabeledEnum(String key, LabeledEnum value); // // LabeledEnum getDefaultLabeledEnum(String key); // // boolean isDefault(String key); // // /** // * Returns the keys in this <code>Settings</code>. // * // * @return the keys // */ // String[] getKeys(); // // /** // * Returns the registered default keys in this <code>Settings</code>. // * // * @return the keys // */ // String[] getDefaultKeys(); // // /** // * Returns the "sum" of {link #getKeys()} and {link #getDefaultKeys()}. // * // * @return all keys // */ // String[] getAllKeys(); // // void save() throws IOException; // // void load() throws IOException; // // Settings getSettings(String name); // // /** // * Removes this <code>Settings</code> from the backing store. // */ // void removeSettings(); // // String getName(); // // Settings getParent(); // // void addPropertyChangeListener(PropertyChangeListener l); // // void addPropertyChangeListener(String key, PropertyChangeListener l); // // void removePropertyChangeListener(PropertyChangeListener l); // // void removePropertyChangeListener(String key, PropertyChangeListener l); // // boolean contains(String key); // // void remove(String key); // // boolean isRoot(); // // String[] getChildSettings(); // }
import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.richclient.settings.AbstractSettings; import org.springframework.richclient.settings.Settings;
/* * Copyright 2002-2006 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 org.springframework.richclient.settings.jdbc; /** * * @author Peter De Bruycker */ public class JdbcSettings extends AbstractSettings { private DataSource dataSource; private Integer id; private String user; private Map values = new HashMap(); private Set remove = new HashSet(); private Set add = new HashSet(); private Set update = new HashSet(); private String[] childKeys; public JdbcSettings( DataSource ds, String user, Integer id, String key ) { this( null, ds, user, id, key ); } public JdbcSettings( JdbcSettings parent, DataSource ds, String user, Integer id, String key ) { super( parent, key ); this.id = id; // TODO assert dataSource not null dataSource = ds; // TODO assert user not empty this.user = user; } protected boolean internalContains( String key ) { return values.containsKey( key ); } protected String[] internalGetChildSettings() { if( childKeys == null ) { loadChildKeys(); } return childKeys; }
// Path: spring-richclient-sandbox/src/main/java/org/springframework/richclient/settings/Settings.java // public interface Settings { // void setString(String key, String value); // // String getString(String key); // // void setDefaultString(String key, String value); // // String getDefaultString(String key); // // void setInt(String key, int value); // // int getInt(String key); // // void setLong(String key, long value); // // long getLong(String key); // // void setDefaultInt(String key, int value); // // int getDefaultInt(String key); // // void setDefaultLong(String key, long value); // // long getDefaultLong(String key); // // void setFloat(String key, float value); // // float getFloat(String key); // // void setDefaultFloat(String key, float value); // // float getDefaultFloat(String key); // // void setDouble(String key, double value); // // double getDouble(String key); // // void setDefaultDouble(String key, double value); // // double getDefaultDouble(String key); // // void setBoolean(String key, boolean value); // // boolean getBoolean(String key); // // void setDefaultBoolean(String key, boolean value); // // boolean getDefaultBoolean(String key); // // void setLabeledEnum(String key, LabeledEnum value); // // LabeledEnum getLabeledEnum(String key); // // void setDefaultLabeledEnum(String key, LabeledEnum value); // // LabeledEnum getDefaultLabeledEnum(String key); // // boolean isDefault(String key); // // /** // * Returns the keys in this <code>Settings</code>. // * // * @return the keys // */ // String[] getKeys(); // // /** // * Returns the registered default keys in this <code>Settings</code>. // * // * @return the keys // */ // String[] getDefaultKeys(); // // /** // * Returns the "sum" of {link #getKeys()} and {link #getDefaultKeys()}. // * // * @return all keys // */ // String[] getAllKeys(); // // void save() throws IOException; // // void load() throws IOException; // // Settings getSettings(String name); // // /** // * Removes this <code>Settings</code> from the backing store. // */ // void removeSettings(); // // String getName(); // // Settings getParent(); // // void addPropertyChangeListener(PropertyChangeListener l); // // void addPropertyChangeListener(String key, PropertyChangeListener l); // // void removePropertyChangeListener(PropertyChangeListener l); // // void removePropertyChangeListener(String key, PropertyChangeListener l); // // boolean contains(String key); // // void remove(String key); // // boolean isRoot(); // // String[] getChildSettings(); // } // Path: spring-richclient-sandbox/src/main/java/org/springframework/richclient/settings/jdbc/JdbcSettings.java import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.richclient.settings.AbstractSettings; import org.springframework.richclient.settings.Settings; /* * Copyright 2002-2006 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 org.springframework.richclient.settings.jdbc; /** * * @author Peter De Bruycker */ public class JdbcSettings extends AbstractSettings { private DataSource dataSource; private Integer id; private String user; private Map values = new HashMap(); private Set remove = new HashSet(); private Set add = new HashSet(); private Set update = new HashSet(); private String[] childKeys; public JdbcSettings( DataSource ds, String user, Integer id, String key ) { this( null, ds, user, id, key ); } public JdbcSettings( JdbcSettings parent, DataSource ds, String user, Integer id, String key ) { super( parent, key ); this.id = id; // TODO assert dataSource not null dataSource = ds; // TODO assert user not empty this.user = user; } protected boolean internalContains( String key ) { return values.containsKey( key ); } protected String[] internalGetChildSettings() { if( childKeys == null ) { loadChildKeys(); } return childKeys; }
protected Settings internalCreateChild( String key ) {
shevek/spring-rich-client
spring-richclient-core/src/main/java/org/springframework/richclient/form/binding/swing/FormattedTextFieldBinding.java
// Path: spring-richclient-core/src/main/java/org/springframework/binding/value/swing/ValueCommitPolicy.java // public abstract class ValueCommitPolicy extends ShortCodedLabeledEnum { // public static final ValueCommitPolicy AS_YOU_TYPE = new ValueCommitPolicy(0, "as_you_type") { // public void configure(JFormattedTextField textField, DefaultFormatter formatter) { // textField.setFocusLostBehavior(JFormattedTextField.PERSIST); // formatter.setOverwriteMode(false); // formatter.setAllowsInvalid(true); // formatter.setCommitsOnValidEdit(true); // } // }; // // public static final ValueCommitPolicy FOCUS_LOST = new ValueCommitPolicy(1, "focus_lost") { // public void configure(JFormattedTextField textField, DefaultFormatter formatter) { // textField.setFocusLostBehavior(JFormattedTextField.COMMIT); // formatter.setOverwriteMode(false); // formatter.setAllowsInvalid(true); // formatter.setCommitsOnValidEdit(false); // } // }; // // public static final ValueCommitPolicy ON_SUBMIT = new ValueCommitPolicy(2, "on_submit") { // public void configure(JFormattedTextField textField, DefaultFormatter formatter) { // textField.setFocusLostBehavior(JFormattedTextField.PERSIST); // formatter.setOverwriteMode(false); // formatter.setAllowsInvalid(true); // formatter.setCommitsOnValidEdit(false); // } // }; // // private ValueCommitPolicy(int code, String label) { // super(code, label); // } // // public abstract void configure(JFormattedTextField textField, DefaultFormatter formatter); // }
import javax.swing.JComponent; import javax.swing.JFormattedTextField; import org.springframework.binding.form.FormModel; import org.springframework.binding.value.ValueModel; import org.springframework.binding.value.swing.FormattedTextFieldAdapter; import org.springframework.binding.value.swing.ValueCommitPolicy; import org.springframework.richclient.form.binding.support.AbstractBinding;
/* * Copyright 2002-2004 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 org.springframework.richclient.form.binding.swing; /** * TODO: this is probably very broken. Need to do extensive testing. * * @author Oliver Hutchison */ public class FormattedTextFieldBinding extends AbstractBinding { private final JFormattedTextField formattedTextField; public FormattedTextFieldBinding(JFormattedTextField formattedTextField, FormModel formModel, String formPropertyPath, Class requiredSourceClass) { super(formModel, formPropertyPath, requiredSourceClass); this.formattedTextField = formattedTextField; } protected JComponent doBindControl() { final ValueModel valueModel = getValueModel(); formattedTextField.setValue(valueModel.getValue()); // TODO: implement ValueCommitPolicies
// Path: spring-richclient-core/src/main/java/org/springframework/binding/value/swing/ValueCommitPolicy.java // public abstract class ValueCommitPolicy extends ShortCodedLabeledEnum { // public static final ValueCommitPolicy AS_YOU_TYPE = new ValueCommitPolicy(0, "as_you_type") { // public void configure(JFormattedTextField textField, DefaultFormatter formatter) { // textField.setFocusLostBehavior(JFormattedTextField.PERSIST); // formatter.setOverwriteMode(false); // formatter.setAllowsInvalid(true); // formatter.setCommitsOnValidEdit(true); // } // }; // // public static final ValueCommitPolicy FOCUS_LOST = new ValueCommitPolicy(1, "focus_lost") { // public void configure(JFormattedTextField textField, DefaultFormatter formatter) { // textField.setFocusLostBehavior(JFormattedTextField.COMMIT); // formatter.setOverwriteMode(false); // formatter.setAllowsInvalid(true); // formatter.setCommitsOnValidEdit(false); // } // }; // // public static final ValueCommitPolicy ON_SUBMIT = new ValueCommitPolicy(2, "on_submit") { // public void configure(JFormattedTextField textField, DefaultFormatter formatter) { // textField.setFocusLostBehavior(JFormattedTextField.PERSIST); // formatter.setOverwriteMode(false); // formatter.setAllowsInvalid(true); // formatter.setCommitsOnValidEdit(false); // } // }; // // private ValueCommitPolicy(int code, String label) { // super(code, label); // } // // public abstract void configure(JFormattedTextField textField, DefaultFormatter formatter); // } // Path: spring-richclient-core/src/main/java/org/springframework/richclient/form/binding/swing/FormattedTextFieldBinding.java import javax.swing.JComponent; import javax.swing.JFormattedTextField; import org.springframework.binding.form.FormModel; import org.springframework.binding.value.ValueModel; import org.springframework.binding.value.swing.FormattedTextFieldAdapter; import org.springframework.binding.value.swing.ValueCommitPolicy; import org.springframework.richclient.form.binding.support.AbstractBinding; /* * Copyright 2002-2004 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 org.springframework.richclient.form.binding.swing; /** * TODO: this is probably very broken. Need to do extensive testing. * * @author Oliver Hutchison */ public class FormattedTextFieldBinding extends AbstractBinding { private final JFormattedTextField formattedTextField; public FormattedTextFieldBinding(JFormattedTextField formattedTextField, FormModel formModel, String formPropertyPath, Class requiredSourceClass) { super(formModel, formPropertyPath, requiredSourceClass); this.formattedTextField = formattedTextField; } protected JComponent doBindControl() { final ValueModel valueModel = getValueModel(); formattedTextField.setValue(valueModel.getValue()); // TODO: implement ValueCommitPolicies
new FormattedTextFieldAdapter(formattedTextField, valueModel, ValueCommitPolicy.AS_YOU_TYPE);
ncjones/juzidian
org.juzidian.cli/src/main/java/org/juzidian/cli/DictionaryDbInitializer.java
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloader.java // public class DictionaryResourceDownloader { // // /** // * Download a compressed dictionary resource, verify its SHA1 hash code and // * uncompress it into the given output stream. // * // * @param resource a {@link DictionaryResource} to download. // * @param out the output stream to write the downloaded data to. // * @param handler the {@link DownloadProgressHandler} to receive events for // * download progress. // * @throws DictionaryResourceDownloaderException if download fails or a hash // * code does not match. // */ // public void download(final DictionaryResource resource, final OutputStream out, final DownloadProgressHandler handler) throws DictionaryResourceDownloaderException { // final URL url = createUrl(resource); // try { // final int contentLength = url.openConnection().getContentLength(); // final InputStream rawInputStream = url.openStream(); // final InputStream progressMonitoringInputStream = new ProgressMonitoringInputStream(rawInputStream, contentLength, handler); // final MessageDigest messageDigest = getSha1Digest(); // final InputStream digestInputStream = new DigestInputStream(progressMonitoringInputStream, messageDigest); // final InputStream gzipInputStream = new GZIPInputStream(digestInputStream); // IoUtil.copy(gzipInputStream, out); // this.verifyChecksum(resource, messageDigest.digest()); // } catch (final IOException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private void verifyChecksum(final DictionaryResource resource, final byte[] digest) throws DictionaryResourceDownloaderException { // final String digestHex = HexUtil.bytesToHex(digest); // if (!digestHex.equals(resource.getSha1())) { // throw new DictionaryResourceDownloaderException("Checksum mismatch. Expected " + resource.getSha1() + " but was " + digestHex); // } // } // // private static MessageDigest getSha1Digest() throws DictionaryResourceDownloaderException { // try { // return MessageDigest.getInstance("SHA1"); // } catch (final NoSuchAlgorithmException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private static URL createUrl(final DictionaryResource resource) throws DictionaryResourceDownloaderException { // try { // return new URL(resource.getUrl()); // } catch (final MalformedURLException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // }
import org.juzidian.util.IoUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.inject.Inject; import org.juzidian.core.DictionaryDataStore; import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceDownloader; import org.juzidian.dataload.DictionaryResourceRegistry; import org.juzidian.dataload.DictionaryResourceRegistryService; import org.juzidian.dataload.DictonaryResourceRegistryServiceException;
/* * Copyright Nathan Jones 2013 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.cli; class DictionaryDbInitializer { private static final Logger LOGGER = LoggerFactory.getLogger(DictionaryDbInitializer.class); final DictionaryDataStore dictionaryDataStore; final DictionaryResourceRegistryService dictionaryRegistryService;
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloader.java // public class DictionaryResourceDownloader { // // /** // * Download a compressed dictionary resource, verify its SHA1 hash code and // * uncompress it into the given output stream. // * // * @param resource a {@link DictionaryResource} to download. // * @param out the output stream to write the downloaded data to. // * @param handler the {@link DownloadProgressHandler} to receive events for // * download progress. // * @throws DictionaryResourceDownloaderException if download fails or a hash // * code does not match. // */ // public void download(final DictionaryResource resource, final OutputStream out, final DownloadProgressHandler handler) throws DictionaryResourceDownloaderException { // final URL url = createUrl(resource); // try { // final int contentLength = url.openConnection().getContentLength(); // final InputStream rawInputStream = url.openStream(); // final InputStream progressMonitoringInputStream = new ProgressMonitoringInputStream(rawInputStream, contentLength, handler); // final MessageDigest messageDigest = getSha1Digest(); // final InputStream digestInputStream = new DigestInputStream(progressMonitoringInputStream, messageDigest); // final InputStream gzipInputStream = new GZIPInputStream(digestInputStream); // IoUtil.copy(gzipInputStream, out); // this.verifyChecksum(resource, messageDigest.digest()); // } catch (final IOException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private void verifyChecksum(final DictionaryResource resource, final byte[] digest) throws DictionaryResourceDownloaderException { // final String digestHex = HexUtil.bytesToHex(digest); // if (!digestHex.equals(resource.getSha1())) { // throw new DictionaryResourceDownloaderException("Checksum mismatch. Expected " + resource.getSha1() + " but was " + digestHex); // } // } // // private static MessageDigest getSha1Digest() throws DictionaryResourceDownloaderException { // try { // return MessageDigest.getInstance("SHA1"); // } catch (final NoSuchAlgorithmException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private static URL createUrl(final DictionaryResource resource) throws DictionaryResourceDownloaderException { // try { // return new URL(resource.getUrl()); // } catch (final MalformedURLException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // } // Path: org.juzidian.cli/src/main/java/org/juzidian/cli/DictionaryDbInitializer.java import org.juzidian.util.IoUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.inject.Inject; import org.juzidian.core.DictionaryDataStore; import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceDownloader; import org.juzidian.dataload.DictionaryResourceRegistry; import org.juzidian.dataload.DictionaryResourceRegistryService; import org.juzidian.dataload.DictonaryResourceRegistryServiceException; /* * Copyright Nathan Jones 2013 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.cli; class DictionaryDbInitializer { private static final Logger LOGGER = LoggerFactory.getLogger(DictionaryDbInitializer.class); final DictionaryDataStore dictionaryDataStore; final DictionaryResourceRegistryService dictionaryRegistryService;
final DictionaryResourceDownloader dictionaryDownloader;
ncjones/juzidian
org.juzidian.cli/src/main/java/org/juzidian/cli/DictionaryDbInitializer.java
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloader.java // public class DictionaryResourceDownloader { // // /** // * Download a compressed dictionary resource, verify its SHA1 hash code and // * uncompress it into the given output stream. // * // * @param resource a {@link DictionaryResource} to download. // * @param out the output stream to write the downloaded data to. // * @param handler the {@link DownloadProgressHandler} to receive events for // * download progress. // * @throws DictionaryResourceDownloaderException if download fails or a hash // * code does not match. // */ // public void download(final DictionaryResource resource, final OutputStream out, final DownloadProgressHandler handler) throws DictionaryResourceDownloaderException { // final URL url = createUrl(resource); // try { // final int contentLength = url.openConnection().getContentLength(); // final InputStream rawInputStream = url.openStream(); // final InputStream progressMonitoringInputStream = new ProgressMonitoringInputStream(rawInputStream, contentLength, handler); // final MessageDigest messageDigest = getSha1Digest(); // final InputStream digestInputStream = new DigestInputStream(progressMonitoringInputStream, messageDigest); // final InputStream gzipInputStream = new GZIPInputStream(digestInputStream); // IoUtil.copy(gzipInputStream, out); // this.verifyChecksum(resource, messageDigest.digest()); // } catch (final IOException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private void verifyChecksum(final DictionaryResource resource, final byte[] digest) throws DictionaryResourceDownloaderException { // final String digestHex = HexUtil.bytesToHex(digest); // if (!digestHex.equals(resource.getSha1())) { // throw new DictionaryResourceDownloaderException("Checksum mismatch. Expected " + resource.getSha1() + " but was " + digestHex); // } // } // // private static MessageDigest getSha1Digest() throws DictionaryResourceDownloaderException { // try { // return MessageDigest.getInstance("SHA1"); // } catch (final NoSuchAlgorithmException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private static URL createUrl(final DictionaryResource resource) throws DictionaryResourceDownloaderException { // try { // return new URL(resource.getUrl()); // } catch (final MalformedURLException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // }
import org.juzidian.util.IoUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.inject.Inject; import org.juzidian.core.DictionaryDataStore; import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceDownloader; import org.juzidian.dataload.DictionaryResourceRegistry; import org.juzidian.dataload.DictionaryResourceRegistryService; import org.juzidian.dataload.DictonaryResourceRegistryServiceException;
/* * Copyright Nathan Jones 2013 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.cli; class DictionaryDbInitializer { private static final Logger LOGGER = LoggerFactory.getLogger(DictionaryDbInitializer.class); final DictionaryDataStore dictionaryDataStore; final DictionaryResourceRegistryService dictionaryRegistryService; final DictionaryResourceDownloader dictionaryDownloader; final File dictionaryDbFile; @Inject public DictionaryDbInitializer(final DictionaryDataStore dataStore, final DictionaryResourceRegistryService registryService, final DictionaryResourceDownloader dictionaryDownloader, @DictionaryDbPath final File dictionaryDbFile) { this.dictionaryDataStore = dataStore; this.dictionaryRegistryService = registryService; this.dictionaryDownloader = dictionaryDownloader; this.dictionaryDbFile = dictionaryDbFile; } public void initializeDb() throws Exception { if (!this.dictionaryDbFile.exists()) { LOGGER.info("Dictionary DB missing."); this.downloadDb(); } else { if (this.dictionaryDataStore.getCurrentDataFormatVersion() != DictionaryDataStore.DATA_FORMAT_VERSION) { LOGGER.info("Dictionary DB incompatible."); this.downloadDb(); } else { LOGGER.debug("Dictionary DB compatible."); } } } private void downloadDb() throws Exception { this.dictionaryDbFile.getParentFile().mkdirs();
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloader.java // public class DictionaryResourceDownloader { // // /** // * Download a compressed dictionary resource, verify its SHA1 hash code and // * uncompress it into the given output stream. // * // * @param resource a {@link DictionaryResource} to download. // * @param out the output stream to write the downloaded data to. // * @param handler the {@link DownloadProgressHandler} to receive events for // * download progress. // * @throws DictionaryResourceDownloaderException if download fails or a hash // * code does not match. // */ // public void download(final DictionaryResource resource, final OutputStream out, final DownloadProgressHandler handler) throws DictionaryResourceDownloaderException { // final URL url = createUrl(resource); // try { // final int contentLength = url.openConnection().getContentLength(); // final InputStream rawInputStream = url.openStream(); // final InputStream progressMonitoringInputStream = new ProgressMonitoringInputStream(rawInputStream, contentLength, handler); // final MessageDigest messageDigest = getSha1Digest(); // final InputStream digestInputStream = new DigestInputStream(progressMonitoringInputStream, messageDigest); // final InputStream gzipInputStream = new GZIPInputStream(digestInputStream); // IoUtil.copy(gzipInputStream, out); // this.verifyChecksum(resource, messageDigest.digest()); // } catch (final IOException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private void verifyChecksum(final DictionaryResource resource, final byte[] digest) throws DictionaryResourceDownloaderException { // final String digestHex = HexUtil.bytesToHex(digest); // if (!digestHex.equals(resource.getSha1())) { // throw new DictionaryResourceDownloaderException("Checksum mismatch. Expected " + resource.getSha1() + " but was " + digestHex); // } // } // // private static MessageDigest getSha1Digest() throws DictionaryResourceDownloaderException { // try { // return MessageDigest.getInstance("SHA1"); // } catch (final NoSuchAlgorithmException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private static URL createUrl(final DictionaryResource resource) throws DictionaryResourceDownloaderException { // try { // return new URL(resource.getUrl()); // } catch (final MalformedURLException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // } // Path: org.juzidian.cli/src/main/java/org/juzidian/cli/DictionaryDbInitializer.java import org.juzidian.util.IoUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.inject.Inject; import org.juzidian.core.DictionaryDataStore; import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceDownloader; import org.juzidian.dataload.DictionaryResourceRegistry; import org.juzidian.dataload.DictionaryResourceRegistryService; import org.juzidian.dataload.DictonaryResourceRegistryServiceException; /* * Copyright Nathan Jones 2013 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.cli; class DictionaryDbInitializer { private static final Logger LOGGER = LoggerFactory.getLogger(DictionaryDbInitializer.class); final DictionaryDataStore dictionaryDataStore; final DictionaryResourceRegistryService dictionaryRegistryService; final DictionaryResourceDownloader dictionaryDownloader; final File dictionaryDbFile; @Inject public DictionaryDbInitializer(final DictionaryDataStore dataStore, final DictionaryResourceRegistryService registryService, final DictionaryResourceDownloader dictionaryDownloader, @DictionaryDbPath final File dictionaryDbFile) { this.dictionaryDataStore = dataStore; this.dictionaryRegistryService = registryService; this.dictionaryDownloader = dictionaryDownloader; this.dictionaryDbFile = dictionaryDbFile; } public void initializeDb() throws Exception { if (!this.dictionaryDbFile.exists()) { LOGGER.info("Dictionary DB missing."); this.downloadDb(); } else { if (this.dictionaryDataStore.getCurrentDataFormatVersion() != DictionaryDataStore.DATA_FORMAT_VERSION) { LOGGER.info("Dictionary DB incompatible."); this.downloadDb(); } else { LOGGER.debug("Dictionary DB compatible."); } } } private void downloadDb() throws Exception { this.dictionaryDbFile.getParentFile().mkdirs();
final DictionaryResource resource = this.getDictionaryResource();
ncjones/juzidian
org.juzidian.pinyin/src/test/java/org/juzidian/pinyin/ToneDiacriticCharacterTest.java
// Path: org.juzidian.pinyin/src/main/java/org/juzidian/pinyin/Tone.java // public enum Tone { // // FIRST(1, "ĀāĒēĪīŌōŪūǕǖ"), // // SECOND(2, "ÁáÉéÍíÓóÚúǗǘ"), // // THIRD(3, "ǍǎĚĕǏǐǑǒǓǔǙǚ"), // // FOURTH(4, "ÀàÈèÌìÒòÙùǛǜ"), // // NEUTRAL(5, "AaEeIiOoUuÜü"), // // ANY(null, "AaEeIiOoUuÜü"); // // private static final String NON_DIACRITIC_VOWELS = "AaEeIiOoUuÜü"; // // private final Integer number; // // /** // * Stores the mapping between non-diacritical Pinyin vowels and the // * diacritical vowels for this tone. // * <p> // * We use an array for slightly faster lookups than a hash map and use the // * integer value of the non-diacritical vowels as indices. Despite being // * initialised for capacity of 253 the array will only contain entries for // * each of the non-diacritical vowels &ndash; the entries are spread // * throughout the array with the last at index 252 (the int value of 'ü'). // */ // private final char[] diacritics = new char[253]; // // private Tone(final Integer number, final String diacriticVowelsForTone) { // this.number = number; // for (int i = 0; i < diacriticVowelsForTone.length(); i++) { // final char nonDiacriticVowel = NON_DIACRITIC_VOWELS.charAt(i); // final char diacritic = diacriticVowelsForTone.charAt(i); // this.diacritics[nonDiacriticVowel] = diacritic; // } // } // // /** // * @return the numeric representation of the tone. // */ // public Integer getNumber() { // return this.number; // } // // public String getDisplayValue() { // return ANY.equals(this) ? "" : this.getNumber().toString(); // } // // /** // * Get the character that uses a diacritical mark to represent this tone on // * the given Pinyin vowel. // * // * @param vowel a lower-case Pinyin vowel (a, e, i, o, u, ü) without a // * diacritic tone mark. // * @return a character with the diacritic tone mark for this tone. // * @throws IllegalArgumentException if the character is not a non-diacritic, // * lower case Pinyin vowel. // */ // public char getDiacriticCharacter(final char vowel) { // if (NON_DIACRITIC_VOWELS.indexOf(vowel) == -1) { // throw new IllegalArgumentException("character is not a valid pinyin vowel: " + vowel); // } // return this.diacritics[vowel]; // } // // /** // * @param toneNumber the number (1-5) that represents a tone. // * @return the tone with the given tone number. // */ // public static Tone valueOf(final Integer toneNumber) { // if (toneNumber == null) { // return Tone.ANY; // } // for (final Tone tone : Tone.values()) { // if (toneNumber.equals(tone.number)) { // return tone; // } // } // throw new IllegalArgumentException("Invalid tone number: " + toneNumber); // } // // /** // * @param tone another tone. // * @return <code>true</code> if the given tone is this tone or this tone is // * ANY. // * @throws IllegalArgumentException if tone is <code>null</code>. // */ // public boolean matches(final Tone tone) { // if (tone == null) { // throw new IllegalArgumentException("tone is null"); // } // return tone.equals(this) || this.equals(ANY); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.juzidian.pinyin.Tone; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.juzidian.pinyin.Tone.ANY; import static org.juzidian.pinyin.Tone.FIRST; import static org.juzidian.pinyin.Tone.FOURTH; import static org.juzidian.pinyin.Tone.NEUTRAL; import static org.juzidian.pinyin.Tone.SECOND; import static org.juzidian.pinyin.Tone.THIRD; import java.util.Arrays; import java.util.Collection;
/* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.pinyin; @RunWith(Parameterized.class) public class ToneDiacriticCharacterTest {
// Path: org.juzidian.pinyin/src/main/java/org/juzidian/pinyin/Tone.java // public enum Tone { // // FIRST(1, "ĀāĒēĪīŌōŪūǕǖ"), // // SECOND(2, "ÁáÉéÍíÓóÚúǗǘ"), // // THIRD(3, "ǍǎĚĕǏǐǑǒǓǔǙǚ"), // // FOURTH(4, "ÀàÈèÌìÒòÙùǛǜ"), // // NEUTRAL(5, "AaEeIiOoUuÜü"), // // ANY(null, "AaEeIiOoUuÜü"); // // private static final String NON_DIACRITIC_VOWELS = "AaEeIiOoUuÜü"; // // private final Integer number; // // /** // * Stores the mapping between non-diacritical Pinyin vowels and the // * diacritical vowels for this tone. // * <p> // * We use an array for slightly faster lookups than a hash map and use the // * integer value of the non-diacritical vowels as indices. Despite being // * initialised for capacity of 253 the array will only contain entries for // * each of the non-diacritical vowels &ndash; the entries are spread // * throughout the array with the last at index 252 (the int value of 'ü'). // */ // private final char[] diacritics = new char[253]; // // private Tone(final Integer number, final String diacriticVowelsForTone) { // this.number = number; // for (int i = 0; i < diacriticVowelsForTone.length(); i++) { // final char nonDiacriticVowel = NON_DIACRITIC_VOWELS.charAt(i); // final char diacritic = diacriticVowelsForTone.charAt(i); // this.diacritics[nonDiacriticVowel] = diacritic; // } // } // // /** // * @return the numeric representation of the tone. // */ // public Integer getNumber() { // return this.number; // } // // public String getDisplayValue() { // return ANY.equals(this) ? "" : this.getNumber().toString(); // } // // /** // * Get the character that uses a diacritical mark to represent this tone on // * the given Pinyin vowel. // * // * @param vowel a lower-case Pinyin vowel (a, e, i, o, u, ü) without a // * diacritic tone mark. // * @return a character with the diacritic tone mark for this tone. // * @throws IllegalArgumentException if the character is not a non-diacritic, // * lower case Pinyin vowel. // */ // public char getDiacriticCharacter(final char vowel) { // if (NON_DIACRITIC_VOWELS.indexOf(vowel) == -1) { // throw new IllegalArgumentException("character is not a valid pinyin vowel: " + vowel); // } // return this.diacritics[vowel]; // } // // /** // * @param toneNumber the number (1-5) that represents a tone. // * @return the tone with the given tone number. // */ // public static Tone valueOf(final Integer toneNumber) { // if (toneNumber == null) { // return Tone.ANY; // } // for (final Tone tone : Tone.values()) { // if (toneNumber.equals(tone.number)) { // return tone; // } // } // throw new IllegalArgumentException("Invalid tone number: " + toneNumber); // } // // /** // * @param tone another tone. // * @return <code>true</code> if the given tone is this tone or this tone is // * ANY. // * @throws IllegalArgumentException if tone is <code>null</code>. // */ // public boolean matches(final Tone tone) { // if (tone == null) { // throw new IllegalArgumentException("tone is null"); // } // return tone.equals(this) || this.equals(ANY); // } // // } // Path: org.juzidian.pinyin/src/test/java/org/juzidian/pinyin/ToneDiacriticCharacterTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.juzidian.pinyin.Tone; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.juzidian.pinyin.Tone.ANY; import static org.juzidian.pinyin.Tone.FIRST; import static org.juzidian.pinyin.Tone.FOURTH; import static org.juzidian.pinyin.Tone.NEUTRAL; import static org.juzidian.pinyin.Tone.SECOND; import static org.juzidian.pinyin.Tone.THIRD; import java.util.Arrays; import java.util.Collection; /* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.pinyin; @RunWith(Parameterized.class) public class ToneDiacriticCharacterTest {
private final Tone tone;
ncjones/juzidian
org.juzidian.dataload/src/test/java/org/juzidian/dataload/DictionaryResourceRegistryDeserializerTest.java
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // }
import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceRegistry; import org.juzidian.dataload.DictionaryResourceRegistryDeserializer; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import java.io.ByteArrayInputStream; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.junit.Before; import org.junit.Test;
/* * Copyright Nathan Jones 2013 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.dataload; public class DictionaryResourceRegistryDeserializerTest { private DictionaryResourceRegistryDeserializer deserializer; @Before public void setUp() throws Exception { final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser saxParser = factory.newSAXParser(); this.deserializer = new DictionaryResourceRegistryDeserializer(saxParser); } @Test public void test() throws Exception { final String xml = "<juzidianDictionaries>\n" + " <dictionary formatVersion='0'>\n" + " <size>12345678</size>\n" + " <sha1>1234abcd</sha1>\n" + " <url>http://test/dict1</url>\n" + " </dictionary>\n" + " </juzidianDictionaries>\n"; final DictionaryResourceRegistry registry = this.deserializer.deserialize(new ByteArrayInputStream(xml.getBytes()));
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // Path: org.juzidian.dataload/src/test/java/org/juzidian/dataload/DictionaryResourceRegistryDeserializerTest.java import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceRegistry; import org.juzidian.dataload.DictionaryResourceRegistryDeserializer; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import java.io.ByteArrayInputStream; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.junit.Before; import org.junit.Test; /* * Copyright Nathan Jones 2013 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.dataload; public class DictionaryResourceRegistryDeserializerTest { private DictionaryResourceRegistryDeserializer deserializer; @Before public void setUp() throws Exception { final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser saxParser = factory.newSAXParser(); this.deserializer = new DictionaryResourceRegistryDeserializer(saxParser); } @Test public void test() throws Exception { final String xml = "<juzidianDictionaries>\n" + " <dictionary formatVersion='0'>\n" + " <size>12345678</size>\n" + " <sha1>1234abcd</sha1>\n" + " <url>http://test/dict1</url>\n" + " </dictionary>\n" + " </juzidianDictionaries>\n"; final DictionaryResourceRegistry registry = this.deserializer.deserialize(new ByteArrayInputStream(xml.getBytes()));
final List<DictionaryResource> dictionaryResources = registry.getDictionaryResources();
ncjones/juzidian
org.juzidian.dataload/src/test/java/org/juzidian/dataload/DictionaryResourceDownloaderTest.java
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloader.java // public class DictionaryResourceDownloader { // // /** // * Download a compressed dictionary resource, verify its SHA1 hash code and // * uncompress it into the given output stream. // * // * @param resource a {@link DictionaryResource} to download. // * @param out the output stream to write the downloaded data to. // * @param handler the {@link DownloadProgressHandler} to receive events for // * download progress. // * @throws DictionaryResourceDownloaderException if download fails or a hash // * code does not match. // */ // public void download(final DictionaryResource resource, final OutputStream out, final DownloadProgressHandler handler) throws DictionaryResourceDownloaderException { // final URL url = createUrl(resource); // try { // final int contentLength = url.openConnection().getContentLength(); // final InputStream rawInputStream = url.openStream(); // final InputStream progressMonitoringInputStream = new ProgressMonitoringInputStream(rawInputStream, contentLength, handler); // final MessageDigest messageDigest = getSha1Digest(); // final InputStream digestInputStream = new DigestInputStream(progressMonitoringInputStream, messageDigest); // final InputStream gzipInputStream = new GZIPInputStream(digestInputStream); // IoUtil.copy(gzipInputStream, out); // this.verifyChecksum(resource, messageDigest.digest()); // } catch (final IOException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private void verifyChecksum(final DictionaryResource resource, final byte[] digest) throws DictionaryResourceDownloaderException { // final String digestHex = HexUtil.bytesToHex(digest); // if (!digestHex.equals(resource.getSha1())) { // throw new DictionaryResourceDownloaderException("Checksum mismatch. Expected " + resource.getSha1() + " but was " + digestHex); // } // } // // private static MessageDigest getSha1Digest() throws DictionaryResourceDownloaderException { // try { // return MessageDigest.getInstance("SHA1"); // } catch (final NoSuchAlgorithmException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private static URL createUrl(final DictionaryResource resource) throws DictionaryResourceDownloaderException { // try { // return new URL(resource.getUrl()); // } catch (final MalformedURLException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloaderException.java // public class DictionaryResourceDownloaderException extends Exception { // // private static final long serialVersionUID = 1L; // // public DictionaryResourceDownloaderException(final String message) { // super(message); // } // // public DictionaryResourceDownloaderException(final Throwable cause) { // super(cause); // } // // }
import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.zip.GZIPOutputStream; import org.junit.Before; import org.junit.Test; import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceDownloader; import org.juzidian.dataload.DictionaryResourceDownloaderException; import org.juzidian.dataload.DownloadProgressHandler; import org.juzidian.util.HexUtil; import org.mockito.Matchers; import org.mockito.Mockito;
/* * Copyright Nathan Jones 2013 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.dataload; public class DictionaryResourceDownloaderTest { private DictionaryResourceDownloader downloader; private DownloadProgressHandler mockProgressHandler;
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloader.java // public class DictionaryResourceDownloader { // // /** // * Download a compressed dictionary resource, verify its SHA1 hash code and // * uncompress it into the given output stream. // * // * @param resource a {@link DictionaryResource} to download. // * @param out the output stream to write the downloaded data to. // * @param handler the {@link DownloadProgressHandler} to receive events for // * download progress. // * @throws DictionaryResourceDownloaderException if download fails or a hash // * code does not match. // */ // public void download(final DictionaryResource resource, final OutputStream out, final DownloadProgressHandler handler) throws DictionaryResourceDownloaderException { // final URL url = createUrl(resource); // try { // final int contentLength = url.openConnection().getContentLength(); // final InputStream rawInputStream = url.openStream(); // final InputStream progressMonitoringInputStream = new ProgressMonitoringInputStream(rawInputStream, contentLength, handler); // final MessageDigest messageDigest = getSha1Digest(); // final InputStream digestInputStream = new DigestInputStream(progressMonitoringInputStream, messageDigest); // final InputStream gzipInputStream = new GZIPInputStream(digestInputStream); // IoUtil.copy(gzipInputStream, out); // this.verifyChecksum(resource, messageDigest.digest()); // } catch (final IOException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private void verifyChecksum(final DictionaryResource resource, final byte[] digest) throws DictionaryResourceDownloaderException { // final String digestHex = HexUtil.bytesToHex(digest); // if (!digestHex.equals(resource.getSha1())) { // throw new DictionaryResourceDownloaderException("Checksum mismatch. Expected " + resource.getSha1() + " but was " + digestHex); // } // } // // private static MessageDigest getSha1Digest() throws DictionaryResourceDownloaderException { // try { // return MessageDigest.getInstance("SHA1"); // } catch (final NoSuchAlgorithmException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private static URL createUrl(final DictionaryResource resource) throws DictionaryResourceDownloaderException { // try { // return new URL(resource.getUrl()); // } catch (final MalformedURLException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloaderException.java // public class DictionaryResourceDownloaderException extends Exception { // // private static final long serialVersionUID = 1L; // // public DictionaryResourceDownloaderException(final String message) { // super(message); // } // // public DictionaryResourceDownloaderException(final Throwable cause) { // super(cause); // } // // } // Path: org.juzidian.dataload/src/test/java/org/juzidian/dataload/DictionaryResourceDownloaderTest.java import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.zip.GZIPOutputStream; import org.junit.Before; import org.junit.Test; import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceDownloader; import org.juzidian.dataload.DictionaryResourceDownloaderException; import org.juzidian.dataload.DownloadProgressHandler; import org.juzidian.util.HexUtil; import org.mockito.Matchers; import org.mockito.Mockito; /* * Copyright Nathan Jones 2013 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.dataload; public class DictionaryResourceDownloaderTest { private DictionaryResourceDownloader downloader; private DownloadProgressHandler mockProgressHandler;
private DictionaryResource mockResource;
ncjones/juzidian
org.juzidian.dataload/src/test/java/org/juzidian/dataload/DictionaryResourceDownloaderTest.java
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloader.java // public class DictionaryResourceDownloader { // // /** // * Download a compressed dictionary resource, verify its SHA1 hash code and // * uncompress it into the given output stream. // * // * @param resource a {@link DictionaryResource} to download. // * @param out the output stream to write the downloaded data to. // * @param handler the {@link DownloadProgressHandler} to receive events for // * download progress. // * @throws DictionaryResourceDownloaderException if download fails or a hash // * code does not match. // */ // public void download(final DictionaryResource resource, final OutputStream out, final DownloadProgressHandler handler) throws DictionaryResourceDownloaderException { // final URL url = createUrl(resource); // try { // final int contentLength = url.openConnection().getContentLength(); // final InputStream rawInputStream = url.openStream(); // final InputStream progressMonitoringInputStream = new ProgressMonitoringInputStream(rawInputStream, contentLength, handler); // final MessageDigest messageDigest = getSha1Digest(); // final InputStream digestInputStream = new DigestInputStream(progressMonitoringInputStream, messageDigest); // final InputStream gzipInputStream = new GZIPInputStream(digestInputStream); // IoUtil.copy(gzipInputStream, out); // this.verifyChecksum(resource, messageDigest.digest()); // } catch (final IOException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private void verifyChecksum(final DictionaryResource resource, final byte[] digest) throws DictionaryResourceDownloaderException { // final String digestHex = HexUtil.bytesToHex(digest); // if (!digestHex.equals(resource.getSha1())) { // throw new DictionaryResourceDownloaderException("Checksum mismatch. Expected " + resource.getSha1() + " but was " + digestHex); // } // } // // private static MessageDigest getSha1Digest() throws DictionaryResourceDownloaderException { // try { // return MessageDigest.getInstance("SHA1"); // } catch (final NoSuchAlgorithmException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private static URL createUrl(final DictionaryResource resource) throws DictionaryResourceDownloaderException { // try { // return new URL(resource.getUrl()); // } catch (final MalformedURLException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloaderException.java // public class DictionaryResourceDownloaderException extends Exception { // // private static final long serialVersionUID = 1L; // // public DictionaryResourceDownloaderException(final String message) { // super(message); // } // // public DictionaryResourceDownloaderException(final Throwable cause) { // super(cause); // } // // }
import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.zip.GZIPOutputStream; import org.junit.Before; import org.junit.Test; import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceDownloader; import org.juzidian.dataload.DictionaryResourceDownloaderException; import org.juzidian.dataload.DownloadProgressHandler; import org.juzidian.util.HexUtil; import org.mockito.Matchers; import org.mockito.Mockito;
final byte[] gzipContent = gzip(content); final String sha1 = sha1(gzipContent); MockUrlHandler.delegate = Mockito.mock(MockUrlHandler.class); when(MockUrlHandler.delegate.openConnection(Matchers.any(URL.class))).thenReturn(new MockUrlConnection(gzipContent)); this.mockResource = createMockDictionaryResource("mock://localhost/foo", sha1, gzipContent.length); } private static DictionaryResource createMockDictionaryResource(final String url, final String hash, final int size) { final DictionaryResource mock = Mockito.mock(DictionaryResource.class); when(mock.getUrl()).thenReturn(url); when(mock.getSha1()).thenReturn(hash); when(mock.getSize()).thenReturn(size); return mock; } @Test public void downloadShouldUnzipContentIntoOutputStream() throws Exception { this.initMockDictionaryResource("foo"); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.downloader.download(this.mockResource, baos, this.mockProgressHandler); assertThat(baos.toString(), equalTo("foo")); } @Test public void downloadShouldNotifyProgress() throws Exception { this.initMockDictionaryResource("foo"); this.downloader.download(this.mockResource, new ByteArrayOutputStream(), this.mockProgressHandler); verify(this.mockProgressHandler, atLeastOnce()).handleProgress(anyInt(), anyInt()); }
// Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResource.java // public interface DictionaryResource { // // /** // * @return the URL for downloading the remote dictionary resource. // */ // String getUrl(); // // /** // * @return the size of the dictionary resource in bytes. // */ // int getSize(); // // /** // * @return the SHA-1 hash of the dictionary resource. // */ // String getSha1(); // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloader.java // public class DictionaryResourceDownloader { // // /** // * Download a compressed dictionary resource, verify its SHA1 hash code and // * uncompress it into the given output stream. // * // * @param resource a {@link DictionaryResource} to download. // * @param out the output stream to write the downloaded data to. // * @param handler the {@link DownloadProgressHandler} to receive events for // * download progress. // * @throws DictionaryResourceDownloaderException if download fails or a hash // * code does not match. // */ // public void download(final DictionaryResource resource, final OutputStream out, final DownloadProgressHandler handler) throws DictionaryResourceDownloaderException { // final URL url = createUrl(resource); // try { // final int contentLength = url.openConnection().getContentLength(); // final InputStream rawInputStream = url.openStream(); // final InputStream progressMonitoringInputStream = new ProgressMonitoringInputStream(rawInputStream, contentLength, handler); // final MessageDigest messageDigest = getSha1Digest(); // final InputStream digestInputStream = new DigestInputStream(progressMonitoringInputStream, messageDigest); // final InputStream gzipInputStream = new GZIPInputStream(digestInputStream); // IoUtil.copy(gzipInputStream, out); // this.verifyChecksum(resource, messageDigest.digest()); // } catch (final IOException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private void verifyChecksum(final DictionaryResource resource, final byte[] digest) throws DictionaryResourceDownloaderException { // final String digestHex = HexUtil.bytesToHex(digest); // if (!digestHex.equals(resource.getSha1())) { // throw new DictionaryResourceDownloaderException("Checksum mismatch. Expected " + resource.getSha1() + " but was " + digestHex); // } // } // // private static MessageDigest getSha1Digest() throws DictionaryResourceDownloaderException { // try { // return MessageDigest.getInstance("SHA1"); // } catch (final NoSuchAlgorithmException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // private static URL createUrl(final DictionaryResource resource) throws DictionaryResourceDownloaderException { // try { // return new URL(resource.getUrl()); // } catch (final MalformedURLException e) { // throw new DictionaryResourceDownloaderException(e); // } // } // // } // // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/DictionaryResourceDownloaderException.java // public class DictionaryResourceDownloaderException extends Exception { // // private static final long serialVersionUID = 1L; // // public DictionaryResourceDownloaderException(final String message) { // super(message); // } // // public DictionaryResourceDownloaderException(final Throwable cause) { // super(cause); // } // // } // Path: org.juzidian.dataload/src/test/java/org/juzidian/dataload/DictionaryResourceDownloaderTest.java import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.zip.GZIPOutputStream; import org.junit.Before; import org.junit.Test; import org.juzidian.dataload.DictionaryResource; import org.juzidian.dataload.DictionaryResourceDownloader; import org.juzidian.dataload.DictionaryResourceDownloaderException; import org.juzidian.dataload.DownloadProgressHandler; import org.juzidian.util.HexUtil; import org.mockito.Matchers; import org.mockito.Mockito; final byte[] gzipContent = gzip(content); final String sha1 = sha1(gzipContent); MockUrlHandler.delegate = Mockito.mock(MockUrlHandler.class); when(MockUrlHandler.delegate.openConnection(Matchers.any(URL.class))).thenReturn(new MockUrlConnection(gzipContent)); this.mockResource = createMockDictionaryResource("mock://localhost/foo", sha1, gzipContent.length); } private static DictionaryResource createMockDictionaryResource(final String url, final String hash, final int size) { final DictionaryResource mock = Mockito.mock(DictionaryResource.class); when(mock.getUrl()).thenReturn(url); when(mock.getSha1()).thenReturn(hash); when(mock.getSize()).thenReturn(size); return mock; } @Test public void downloadShouldUnzipContentIntoOutputStream() throws Exception { this.initMockDictionaryResource("foo"); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.downloader.download(this.mockResource, baos, this.mockProgressHandler); assertThat(baos.toString(), equalTo("foo")); } @Test public void downloadShouldNotifyProgress() throws Exception { this.initMockDictionaryResource("foo"); this.downloader.download(this.mockResource, new ByteArrayOutputStream(), this.mockProgressHandler); verify(this.mockProgressHandler, atLeastOnce()).handleProgress(anyInt(), anyInt()); }
@Test(expected = DictionaryResourceDownloaderException.class)
ncjones/juzidian
org.juzidian.android/src/main/java/org/juzidian/android/SearchResultItemView.java
// Path: org.juzidian.core/src/main/java/org/juzidian/core/DictionaryEntry.java // public class DictionaryEntry { // // private final String traditional; // // private final String simplified; // // private final List<PinyinSyllable> pinyin; // // private final List<String> definitions; // // public DictionaryEntry(final String traditional, final String simplified, final List<PinyinSyllable> pinyin, // final List<String> definitions) { // this.traditional = traditional; // this.simplified = simplified; // this.pinyin = pinyin; // this.definitions = definitions; // } // // /** // * @return the traditional Chinese representation of the word. // */ // public String getTraditional() { // return this.traditional; // } // // /** // * @return the simplified Chinese representation of the word. // */ // public String getSimplified() { // return this.simplified; // } // // /** // * @return the Pinyin phonetic representation of the word. // */ // public List<PinyinSyllable> getPinyin() { // return Collections.unmodifiableList(this.pinyin); // } // // /** // * @return a list of English definitions for the word. // */ // public List<String> getDefinitions() { // return Collections.unmodifiableList(this.definitions); // } // // /** // * @param pinyinSyllables a list of {@link PinyinSyllable}. // * @return <code>true</code> if this word starts with the given syllables. // */ // public boolean pinyinStartsWith(final Collection<PinyinSyllable> pinyinSyllables) { // final List<PinyinSyllable> actualPinyinSyllables = this.getPinyin(); // int index = 0; // for (final PinyinSyllable pinyinSyllable : pinyinSyllables) { // if (index >= actualPinyinSyllables.size()) { // return false; // } // final PinyinSyllable actualPinyinSyllable = actualPinyinSyllables.get(index); // if (!pinyinSyllable.matches(actualPinyinSyllable)) { // return false; // } // index += 1; // } // return true; // } // // @Override // public String toString() { // return this.getClass().getSimpleName() + " [" + this.getTraditional() + ", " + this.getSimplified() + ", " + this.getPinyinString() // + ", " + this.getDefinitions() + "]"; // } // // private String getPinyinString() { // final StringBuilder stringBuilder = new StringBuilder(); // for (final PinyinSyllable pinyinSyllable : this.getPinyin()) { // stringBuilder.append(pinyinSyllable.getDisplayValue()).append(" "); // } // return stringBuilder.toString().trim(); // } // // }
import android.widget.TextView.BufferType; import java.util.List; import org.juzidian.core.DictionaryEntry; import org.juzidian.pinyin.PinyinSyllable; import android.content.Context; import android.text.Spannable; import android.text.Spanned; import android.text.style.RelativeSizeSpan; import android.view.LayoutInflater; import android.widget.RelativeLayout; import android.widget.TextView;
/* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.android; /** * Display a dictionary entry as a search result. */ public class SearchResultItemView extends RelativeLayout { private static final RelativeSizeSpan SPAN_SIZE_HANZI = new RelativeSizeSpan(1.2f); private final TextView chineseTextView; private final TextView definitionTextView;
// Path: org.juzidian.core/src/main/java/org/juzidian/core/DictionaryEntry.java // public class DictionaryEntry { // // private final String traditional; // // private final String simplified; // // private final List<PinyinSyllable> pinyin; // // private final List<String> definitions; // // public DictionaryEntry(final String traditional, final String simplified, final List<PinyinSyllable> pinyin, // final List<String> definitions) { // this.traditional = traditional; // this.simplified = simplified; // this.pinyin = pinyin; // this.definitions = definitions; // } // // /** // * @return the traditional Chinese representation of the word. // */ // public String getTraditional() { // return this.traditional; // } // // /** // * @return the simplified Chinese representation of the word. // */ // public String getSimplified() { // return this.simplified; // } // // /** // * @return the Pinyin phonetic representation of the word. // */ // public List<PinyinSyllable> getPinyin() { // return Collections.unmodifiableList(this.pinyin); // } // // /** // * @return a list of English definitions for the word. // */ // public List<String> getDefinitions() { // return Collections.unmodifiableList(this.definitions); // } // // /** // * @param pinyinSyllables a list of {@link PinyinSyllable}. // * @return <code>true</code> if this word starts with the given syllables. // */ // public boolean pinyinStartsWith(final Collection<PinyinSyllable> pinyinSyllables) { // final List<PinyinSyllable> actualPinyinSyllables = this.getPinyin(); // int index = 0; // for (final PinyinSyllable pinyinSyllable : pinyinSyllables) { // if (index >= actualPinyinSyllables.size()) { // return false; // } // final PinyinSyllable actualPinyinSyllable = actualPinyinSyllables.get(index); // if (!pinyinSyllable.matches(actualPinyinSyllable)) { // return false; // } // index += 1; // } // return true; // } // // @Override // public String toString() { // return this.getClass().getSimpleName() + " [" + this.getTraditional() + ", " + this.getSimplified() + ", " + this.getPinyinString() // + ", " + this.getDefinitions() + "]"; // } // // private String getPinyinString() { // final StringBuilder stringBuilder = new StringBuilder(); // for (final PinyinSyllable pinyinSyllable : this.getPinyin()) { // stringBuilder.append(pinyinSyllable.getDisplayValue()).append(" "); // } // return stringBuilder.toString().trim(); // } // // } // Path: org.juzidian.android/src/main/java/org/juzidian/android/SearchResultItemView.java import android.widget.TextView.BufferType; import java.util.List; import org.juzidian.core.DictionaryEntry; import org.juzidian.pinyin.PinyinSyllable; import android.content.Context; import android.text.Spannable; import android.text.Spanned; import android.text.style.RelativeSizeSpan; import android.view.LayoutInflater; import android.widget.RelativeLayout; import android.widget.TextView; /* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.android; /** * Display a dictionary entry as a search result. */ public class SearchResultItemView extends RelativeLayout { private static final RelativeSizeSpan SPAN_SIZE_HANZI = new RelativeSizeSpan(1.2f); private final TextView chineseTextView; private final TextView definitionTextView;
public SearchResultItemView(final Context context, final DictionaryEntry entry) {
ncjones/juzidian
org.juzidian.dataload/src/main/java/org/juzidian/dataload/EntryCollector.java
// Path: org.juzidian.cedict/src/main/java/org/juzidian/cedict/CedictEntry.java // public interface CedictEntry { // // String getTraditionalCharacters(); // // String getSimplifiedCharacters(); // // List<CedictPinyinSyllable> getPinyinSyllables(); // // List<String> getDefinitions(); // // } // // Path: org.juzidian.core/src/main/java/org/juzidian/core/DictionaryEntry.java // public class DictionaryEntry { // // private final String traditional; // // private final String simplified; // // private final List<PinyinSyllable> pinyin; // // private final List<String> definitions; // // public DictionaryEntry(final String traditional, final String simplified, final List<PinyinSyllable> pinyin, // final List<String> definitions) { // this.traditional = traditional; // this.simplified = simplified; // this.pinyin = pinyin; // this.definitions = definitions; // } // // /** // * @return the traditional Chinese representation of the word. // */ // public String getTraditional() { // return this.traditional; // } // // /** // * @return the simplified Chinese representation of the word. // */ // public String getSimplified() { // return this.simplified; // } // // /** // * @return the Pinyin phonetic representation of the word. // */ // public List<PinyinSyllable> getPinyin() { // return Collections.unmodifiableList(this.pinyin); // } // // /** // * @return a list of English definitions for the word. // */ // public List<String> getDefinitions() { // return Collections.unmodifiableList(this.definitions); // } // // /** // * @param pinyinSyllables a list of {@link PinyinSyllable}. // * @return <code>true</code> if this word starts with the given syllables. // */ // public boolean pinyinStartsWith(final Collection<PinyinSyllable> pinyinSyllables) { // final List<PinyinSyllable> actualPinyinSyllables = this.getPinyin(); // int index = 0; // for (final PinyinSyllable pinyinSyllable : pinyinSyllables) { // if (index >= actualPinyinSyllables.size()) { // return false; // } // final PinyinSyllable actualPinyinSyllable = actualPinyinSyllables.get(index); // if (!pinyinSyllable.matches(actualPinyinSyllable)) { // return false; // } // index += 1; // } // return true; // } // // @Override // public String toString() { // return this.getClass().getSimpleName() + " [" + this.getTraditional() + ", " + this.getSimplified() + ", " + this.getPinyinString() // + ", " + this.getDefinitions() + "]"; // } // // private String getPinyinString() { // final StringBuilder stringBuilder = new StringBuilder(); // for (final PinyinSyllable pinyinSyllable : this.getPinyin()) { // stringBuilder.append(pinyinSyllable.getDisplayValue()).append(" "); // } // return stringBuilder.toString().trim(); // } // // }
import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.inject.Inject; import org.juzidian.cedict.CedictEntry; import org.juzidian.cedict.CedictLoadHandler; import org.juzidian.core.DictionaryEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.dataload; class EntryCollector implements CedictLoadHandler { private static final Logger LOGGER = LoggerFactory.getLogger(EntryCollector.class); private final CedictEntryToDictionaryEntryConverter entryConverter;
// Path: org.juzidian.cedict/src/main/java/org/juzidian/cedict/CedictEntry.java // public interface CedictEntry { // // String getTraditionalCharacters(); // // String getSimplifiedCharacters(); // // List<CedictPinyinSyllable> getPinyinSyllables(); // // List<String> getDefinitions(); // // } // // Path: org.juzidian.core/src/main/java/org/juzidian/core/DictionaryEntry.java // public class DictionaryEntry { // // private final String traditional; // // private final String simplified; // // private final List<PinyinSyllable> pinyin; // // private final List<String> definitions; // // public DictionaryEntry(final String traditional, final String simplified, final List<PinyinSyllable> pinyin, // final List<String> definitions) { // this.traditional = traditional; // this.simplified = simplified; // this.pinyin = pinyin; // this.definitions = definitions; // } // // /** // * @return the traditional Chinese representation of the word. // */ // public String getTraditional() { // return this.traditional; // } // // /** // * @return the simplified Chinese representation of the word. // */ // public String getSimplified() { // return this.simplified; // } // // /** // * @return the Pinyin phonetic representation of the word. // */ // public List<PinyinSyllable> getPinyin() { // return Collections.unmodifiableList(this.pinyin); // } // // /** // * @return a list of English definitions for the word. // */ // public List<String> getDefinitions() { // return Collections.unmodifiableList(this.definitions); // } // // /** // * @param pinyinSyllables a list of {@link PinyinSyllable}. // * @return <code>true</code> if this word starts with the given syllables. // */ // public boolean pinyinStartsWith(final Collection<PinyinSyllable> pinyinSyllables) { // final List<PinyinSyllable> actualPinyinSyllables = this.getPinyin(); // int index = 0; // for (final PinyinSyllable pinyinSyllable : pinyinSyllables) { // if (index >= actualPinyinSyllables.size()) { // return false; // } // final PinyinSyllable actualPinyinSyllable = actualPinyinSyllables.get(index); // if (!pinyinSyllable.matches(actualPinyinSyllable)) { // return false; // } // index += 1; // } // return true; // } // // @Override // public String toString() { // return this.getClass().getSimpleName() + " [" + this.getTraditional() + ", " + this.getSimplified() + ", " + this.getPinyinString() // + ", " + this.getDefinitions() + "]"; // } // // private String getPinyinString() { // final StringBuilder stringBuilder = new StringBuilder(); // for (final PinyinSyllable pinyinSyllable : this.getPinyin()) { // stringBuilder.append(pinyinSyllable.getDisplayValue()).append(" "); // } // return stringBuilder.toString().trim(); // } // // } // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/EntryCollector.java import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.inject.Inject; import org.juzidian.cedict.CedictEntry; import org.juzidian.cedict.CedictLoadHandler; import org.juzidian.core.DictionaryEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.dataload; class EntryCollector implements CedictLoadHandler { private static final Logger LOGGER = LoggerFactory.getLogger(EntryCollector.class); private final CedictEntryToDictionaryEntryConverter entryConverter;
private final List<DictionaryEntry> entries = new LinkedList<DictionaryEntry>();
ncjones/juzidian
org.juzidian.dataload/src/main/java/org/juzidian/dataload/EntryCollector.java
// Path: org.juzidian.cedict/src/main/java/org/juzidian/cedict/CedictEntry.java // public interface CedictEntry { // // String getTraditionalCharacters(); // // String getSimplifiedCharacters(); // // List<CedictPinyinSyllable> getPinyinSyllables(); // // List<String> getDefinitions(); // // } // // Path: org.juzidian.core/src/main/java/org/juzidian/core/DictionaryEntry.java // public class DictionaryEntry { // // private final String traditional; // // private final String simplified; // // private final List<PinyinSyllable> pinyin; // // private final List<String> definitions; // // public DictionaryEntry(final String traditional, final String simplified, final List<PinyinSyllable> pinyin, // final List<String> definitions) { // this.traditional = traditional; // this.simplified = simplified; // this.pinyin = pinyin; // this.definitions = definitions; // } // // /** // * @return the traditional Chinese representation of the word. // */ // public String getTraditional() { // return this.traditional; // } // // /** // * @return the simplified Chinese representation of the word. // */ // public String getSimplified() { // return this.simplified; // } // // /** // * @return the Pinyin phonetic representation of the word. // */ // public List<PinyinSyllable> getPinyin() { // return Collections.unmodifiableList(this.pinyin); // } // // /** // * @return a list of English definitions for the word. // */ // public List<String> getDefinitions() { // return Collections.unmodifiableList(this.definitions); // } // // /** // * @param pinyinSyllables a list of {@link PinyinSyllable}. // * @return <code>true</code> if this word starts with the given syllables. // */ // public boolean pinyinStartsWith(final Collection<PinyinSyllable> pinyinSyllables) { // final List<PinyinSyllable> actualPinyinSyllables = this.getPinyin(); // int index = 0; // for (final PinyinSyllable pinyinSyllable : pinyinSyllables) { // if (index >= actualPinyinSyllables.size()) { // return false; // } // final PinyinSyllable actualPinyinSyllable = actualPinyinSyllables.get(index); // if (!pinyinSyllable.matches(actualPinyinSyllable)) { // return false; // } // index += 1; // } // return true; // } // // @Override // public String toString() { // return this.getClass().getSimpleName() + " [" + this.getTraditional() + ", " + this.getSimplified() + ", " + this.getPinyinString() // + ", " + this.getDefinitions() + "]"; // } // // private String getPinyinString() { // final StringBuilder stringBuilder = new StringBuilder(); // for (final PinyinSyllable pinyinSyllable : this.getPinyin()) { // stringBuilder.append(pinyinSyllable.getDisplayValue()).append(" "); // } // return stringBuilder.toString().trim(); // } // // }
import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.inject.Inject; import org.juzidian.cedict.CedictEntry; import org.juzidian.cedict.CedictLoadHandler; import org.juzidian.core.DictionaryEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.dataload; class EntryCollector implements CedictLoadHandler { private static final Logger LOGGER = LoggerFactory.getLogger(EntryCollector.class); private final CedictEntryToDictionaryEntryConverter entryConverter; private final List<DictionaryEntry> entries = new LinkedList<DictionaryEntry>(); @Inject public EntryCollector(final CedictEntryToDictionaryEntryConverter entryConverter) { this.entryConverter = entryConverter; } public Collection<DictionaryEntry> getEntries() { return this.entries; } @Override public void loadingStarted() { } @Override
// Path: org.juzidian.cedict/src/main/java/org/juzidian/cedict/CedictEntry.java // public interface CedictEntry { // // String getTraditionalCharacters(); // // String getSimplifiedCharacters(); // // List<CedictPinyinSyllable> getPinyinSyllables(); // // List<String> getDefinitions(); // // } // // Path: org.juzidian.core/src/main/java/org/juzidian/core/DictionaryEntry.java // public class DictionaryEntry { // // private final String traditional; // // private final String simplified; // // private final List<PinyinSyllable> pinyin; // // private final List<String> definitions; // // public DictionaryEntry(final String traditional, final String simplified, final List<PinyinSyllable> pinyin, // final List<String> definitions) { // this.traditional = traditional; // this.simplified = simplified; // this.pinyin = pinyin; // this.definitions = definitions; // } // // /** // * @return the traditional Chinese representation of the word. // */ // public String getTraditional() { // return this.traditional; // } // // /** // * @return the simplified Chinese representation of the word. // */ // public String getSimplified() { // return this.simplified; // } // // /** // * @return the Pinyin phonetic representation of the word. // */ // public List<PinyinSyllable> getPinyin() { // return Collections.unmodifiableList(this.pinyin); // } // // /** // * @return a list of English definitions for the word. // */ // public List<String> getDefinitions() { // return Collections.unmodifiableList(this.definitions); // } // // /** // * @param pinyinSyllables a list of {@link PinyinSyllable}. // * @return <code>true</code> if this word starts with the given syllables. // */ // public boolean pinyinStartsWith(final Collection<PinyinSyllable> pinyinSyllables) { // final List<PinyinSyllable> actualPinyinSyllables = this.getPinyin(); // int index = 0; // for (final PinyinSyllable pinyinSyllable : pinyinSyllables) { // if (index >= actualPinyinSyllables.size()) { // return false; // } // final PinyinSyllable actualPinyinSyllable = actualPinyinSyllables.get(index); // if (!pinyinSyllable.matches(actualPinyinSyllable)) { // return false; // } // index += 1; // } // return true; // } // // @Override // public String toString() { // return this.getClass().getSimpleName() + " [" + this.getTraditional() + ", " + this.getSimplified() + ", " + this.getPinyinString() // + ", " + this.getDefinitions() + "]"; // } // // private String getPinyinString() { // final StringBuilder stringBuilder = new StringBuilder(); // for (final PinyinSyllable pinyinSyllable : this.getPinyin()) { // stringBuilder.append(pinyinSyllable.getDisplayValue()).append(" "); // } // return stringBuilder.toString().trim(); // } // // } // Path: org.juzidian.dataload/src/main/java/org/juzidian/dataload/EntryCollector.java import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.inject.Inject; import org.juzidian.cedict.CedictEntry; import org.juzidian.cedict.CedictLoadHandler; import org.juzidian.core.DictionaryEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.dataload; class EntryCollector implements CedictLoadHandler { private static final Logger LOGGER = LoggerFactory.getLogger(EntryCollector.class); private final CedictEntryToDictionaryEntryConverter entryConverter; private final List<DictionaryEntry> entries = new LinkedList<DictionaryEntry>(); @Inject public EntryCollector(final CedictEntryToDictionaryEntryConverter entryConverter) { this.entryConverter = entryConverter; } public Collection<DictionaryEntry> getEntries() { return this.entries; } @Override public void loadingStarted() { } @Override
public void entryLoaded(final CedictEntry cedictEntry) {
ncjones/juzidian
org.juzidian.core/src/test/java/org/juzidian/core/DictionaryEntryTest.java
// Path: org.juzidian.pinyin/src/main/java/org/juzidian/pinyin/Tone.java // public enum Tone { // // FIRST(1, "ĀāĒēĪīŌōŪūǕǖ"), // // SECOND(2, "ÁáÉéÍíÓóÚúǗǘ"), // // THIRD(3, "ǍǎĚĕǏǐǑǒǓǔǙǚ"), // // FOURTH(4, "ÀàÈèÌìÒòÙùǛǜ"), // // NEUTRAL(5, "AaEeIiOoUuÜü"), // // ANY(null, "AaEeIiOoUuÜü"); // // private static final String NON_DIACRITIC_VOWELS = "AaEeIiOoUuÜü"; // // private final Integer number; // // /** // * Stores the mapping between non-diacritical Pinyin vowels and the // * diacritical vowels for this tone. // * <p> // * We use an array for slightly faster lookups than a hash map and use the // * integer value of the non-diacritical vowels as indices. Despite being // * initialised for capacity of 253 the array will only contain entries for // * each of the non-diacritical vowels &ndash; the entries are spread // * throughout the array with the last at index 252 (the int value of 'ü'). // */ // private final char[] diacritics = new char[253]; // // private Tone(final Integer number, final String diacriticVowelsForTone) { // this.number = number; // for (int i = 0; i < diacriticVowelsForTone.length(); i++) { // final char nonDiacriticVowel = NON_DIACRITIC_VOWELS.charAt(i); // final char diacritic = diacriticVowelsForTone.charAt(i); // this.diacritics[nonDiacriticVowel] = diacritic; // } // } // // /** // * @return the numeric representation of the tone. // */ // public Integer getNumber() { // return this.number; // } // // public String getDisplayValue() { // return ANY.equals(this) ? "" : this.getNumber().toString(); // } // // /** // * Get the character that uses a diacritical mark to represent this tone on // * the given Pinyin vowel. // * // * @param vowel a lower-case Pinyin vowel (a, e, i, o, u, ü) without a // * diacritic tone mark. // * @return a character with the diacritic tone mark for this tone. // * @throws IllegalArgumentException if the character is not a non-diacritic, // * lower case Pinyin vowel. // */ // public char getDiacriticCharacter(final char vowel) { // if (NON_DIACRITIC_VOWELS.indexOf(vowel) == -1) { // throw new IllegalArgumentException("character is not a valid pinyin vowel: " + vowel); // } // return this.diacritics[vowel]; // } // // /** // * @param toneNumber the number (1-5) that represents a tone. // * @return the tone with the given tone number. // */ // public static Tone valueOf(final Integer toneNumber) { // if (toneNumber == null) { // return Tone.ANY; // } // for (final Tone tone : Tone.values()) { // if (toneNumber.equals(tone.number)) { // return tone; // } // } // throw new IllegalArgumentException("Invalid tone number: " + toneNumber); // } // // /** // * @param tone another tone. // * @return <code>true</code> if the given tone is this tone or this tone is // * ANY. // * @throws IllegalArgumentException if tone is <code>null</code>. // */ // public boolean matches(final Tone tone) { // if (tone == null) { // throw new IllegalArgumentException("tone is null"); // } // return tone.equals(this) || this.equals(ANY); // } // // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.juzidian.pinyin.PinyinSyllable; import org.juzidian.pinyin.Tone;
/* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.core; public abstract class DictionaryEntryTest { @Test public void pinyinStartsWithShouldMatchTonedSyllable() {
// Path: org.juzidian.pinyin/src/main/java/org/juzidian/pinyin/Tone.java // public enum Tone { // // FIRST(1, "ĀāĒēĪīŌōŪūǕǖ"), // // SECOND(2, "ÁáÉéÍíÓóÚúǗǘ"), // // THIRD(3, "ǍǎĚĕǏǐǑǒǓǔǙǚ"), // // FOURTH(4, "ÀàÈèÌìÒòÙùǛǜ"), // // NEUTRAL(5, "AaEeIiOoUuÜü"), // // ANY(null, "AaEeIiOoUuÜü"); // // private static final String NON_DIACRITIC_VOWELS = "AaEeIiOoUuÜü"; // // private final Integer number; // // /** // * Stores the mapping between non-diacritical Pinyin vowels and the // * diacritical vowels for this tone. // * <p> // * We use an array for slightly faster lookups than a hash map and use the // * integer value of the non-diacritical vowels as indices. Despite being // * initialised for capacity of 253 the array will only contain entries for // * each of the non-diacritical vowels &ndash; the entries are spread // * throughout the array with the last at index 252 (the int value of 'ü'). // */ // private final char[] diacritics = new char[253]; // // private Tone(final Integer number, final String diacriticVowelsForTone) { // this.number = number; // for (int i = 0; i < diacriticVowelsForTone.length(); i++) { // final char nonDiacriticVowel = NON_DIACRITIC_VOWELS.charAt(i); // final char diacritic = diacriticVowelsForTone.charAt(i); // this.diacritics[nonDiacriticVowel] = diacritic; // } // } // // /** // * @return the numeric representation of the tone. // */ // public Integer getNumber() { // return this.number; // } // // public String getDisplayValue() { // return ANY.equals(this) ? "" : this.getNumber().toString(); // } // // /** // * Get the character that uses a diacritical mark to represent this tone on // * the given Pinyin vowel. // * // * @param vowel a lower-case Pinyin vowel (a, e, i, o, u, ü) without a // * diacritic tone mark. // * @return a character with the diacritic tone mark for this tone. // * @throws IllegalArgumentException if the character is not a non-diacritic, // * lower case Pinyin vowel. // */ // public char getDiacriticCharacter(final char vowel) { // if (NON_DIACRITIC_VOWELS.indexOf(vowel) == -1) { // throw new IllegalArgumentException("character is not a valid pinyin vowel: " + vowel); // } // return this.diacritics[vowel]; // } // // /** // * @param toneNumber the number (1-5) that represents a tone. // * @return the tone with the given tone number. // */ // public static Tone valueOf(final Integer toneNumber) { // if (toneNumber == null) { // return Tone.ANY; // } // for (final Tone tone : Tone.values()) { // if (toneNumber.equals(tone.number)) { // return tone; // } // } // throw new IllegalArgumentException("Invalid tone number: " + toneNumber); // } // // /** // * @param tone another tone. // * @return <code>true</code> if the given tone is this tone or this tone is // * ANY. // * @throws IllegalArgumentException if tone is <code>null</code>. // */ // public boolean matches(final Tone tone) { // if (tone == null) { // throw new IllegalArgumentException("tone is null"); // } // return tone.equals(this) || this.equals(ANY); // } // // } // Path: org.juzidian.core/src/test/java/org/juzidian/core/DictionaryEntryTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.juzidian.pinyin.PinyinSyllable; import org.juzidian.pinyin.Tone; /* * Copyright Nathan Jones 2012 * * This file is part of Juzidian. * * Juzidian is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Juzidian 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 Juzidian. If not, see <http://www.gnu.org/licenses/>. */ package org.juzidian.core; public abstract class DictionaryEntryTest { @Test public void pinyinStartsWithShouldMatchTonedSyllable() {
final DictionaryEntry entry = this.createChineseWord(new PinyinSyllable("hao", Tone.THIRD));
punkbrwstr/pinto
src/main/java/tech/pinto/time/PeriodicRange.java
// Path: src/main/java/tech/pinto/tools/ID.java // public class ID { // // private static final AtomicInteger current = new AtomicInteger(); // // public static String getId() { // return toBase26(current.getAndIncrement()); // } // // private static String toBase26(int i){ // String s = ""; // while(i > 25) { // int r = i % 26; // i = i / 26; // s = (char)(r + 65) + s;//26 + 64 = 100 // } // s = (char)(i + 65) + s; // return s.toLowerCase(); // } // // }
import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import tech.pinto.tools.ID;
package tech.pinto.time; public final class PeriodicRange<P extends Period<P>> { private final Periodicity<P> periodicity; private final P startInclusive; private final P endInclusive;
// Path: src/main/java/tech/pinto/tools/ID.java // public class ID { // // private static final AtomicInteger current = new AtomicInteger(); // // public static String getId() { // return toBase26(current.getAndIncrement()); // } // // private static String toBase26(int i){ // String s = ""; // while(i > 25) { // int r = i % 26; // i = i / 26; // s = (char)(r + 65) + s;//26 + 64 = 100 // } // s = (char)(i + 65) + s; // return s.toLowerCase(); // } // // } // Path: src/main/java/tech/pinto/time/PeriodicRange.java import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import tech.pinto.tools.ID; package tech.pinto.time; public final class PeriodicRange<P extends Period<P>> { private final Periodicity<P> periodicity; private final P startInclusive; private final P endInclusive;
private final String id = ID.getId();
punkbrwstr/pinto
src/main/java/tech/pinto/Namespace.java
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {}
import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import javax.inject.Inject; import com.google.common.base.Joiner; import jline.console.completer.Completer; import tech.pinto.Pinto.Expression; import tech.pinto.Pinto.TableFunction;
package tech.pinto; public class Namespace implements Completer { private final String DELIMITER = "::"; private final TreeMap<String,Name> names = new TreeMap<>(); private final TreeSet<String> dependencyGraph = new TreeSet<>(); @Inject public Namespace(Vocabulary vocabulary) { if(names.isEmpty()) { for(Name name : vocabulary.getNames()) { names.put(name.toString(), name); } } } public synchronized boolean contains(String name) { return names.containsKey(name); }
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // Path: src/main/java/tech/pinto/Namespace.java import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import javax.inject.Inject; import com.google.common.base.Joiner; import jline.console.completer.Completer; import tech.pinto.Pinto.Expression; import tech.pinto.Pinto.TableFunction; package tech.pinto; public class Namespace implements Completer { private final String DELIMITER = "::"; private final TreeMap<String,Name> names = new TreeMap<>(); private final TreeSet<String> dependencyGraph = new TreeSet<>(); @Inject public Namespace(Vocabulary vocabulary) { if(names.isEmpty()) { for(Name name : vocabulary.getNames()) { names.put(name.toString(), name); } } } public synchronized boolean contains(String name) { return names.containsKey(name); }
public synchronized String define(Pinto pinto, Expression expression, boolean onlyIfUndefined) {
punkbrwstr/pinto
src/main/java/tech/pinto/Namespace.java
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {}
import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import javax.inject.Inject; import com.google.common.base.Joiner; import jline.console.completer.Completer; import tech.pinto.Pinto.Expression; import tech.pinto.Pinto.TableFunction;
} public synchronized boolean contains(String name) { return names.containsKey(name); } public synchronized String define(Pinto pinto, Expression expression, boolean onlyIfUndefined) { String name = expression.getNameLiteral() .orElseThrow(() -> new PintoSyntaxException("A name literal is required to define a name.")); if(names.containsKey(name)) { if(onlyIfUndefined) { return name; } if(names.get(name).isBuiltIn()) { throw new IllegalArgumentException("Cannot redefine built-in name " + name + "."); } clearCache(name); for(String dependencyCode : getDependsOn(name)) { dependencyGraph.remove(join(name, "dependsOn", dependencyCode)); dependencyGraph.remove(join(dependencyCode, "dependedOnBy", name)); } } for(String dependencyName : expression.getDependencies()) { dependencyGraph.add(join(name, "dependsOn", dependencyName)); dependencyGraph.add(join(dependencyName, "dependedOnBy", name)); } if(expression.isNullary()) { names.put(name, Name.nameBuilder(name,Cache.cacheNullaryFunction(name, expression)) .defined().description(expression.getText()).build()); } else {
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // Path: src/main/java/tech/pinto/Namespace.java import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import javax.inject.Inject; import com.google.common.base.Joiner; import jline.console.completer.Completer; import tech.pinto.Pinto.Expression; import tech.pinto.Pinto.TableFunction; } public synchronized boolean contains(String name) { return names.containsKey(name); } public synchronized String define(Pinto pinto, Expression expression, boolean onlyIfUndefined) { String name = expression.getNameLiteral() .orElseThrow(() -> new PintoSyntaxException("A name literal is required to define a name.")); if(names.containsKey(name)) { if(onlyIfUndefined) { return name; } if(names.get(name).isBuiltIn()) { throw new IllegalArgumentException("Cannot redefine built-in name " + name + "."); } clearCache(name); for(String dependencyCode : getDependsOn(name)) { dependencyGraph.remove(join(name, "dependsOn", dependencyCode)); dependencyGraph.remove(join(dependencyCode, "dependedOnBy", name)); } } for(String dependencyName : expression.getDependencies()) { dependencyGraph.add(join(name, "dependsOn", dependencyName)); dependencyGraph.add(join(dependencyName, "dependedOnBy", name)); } if(expression.isNullary()) { names.put(name, Name.nameBuilder(name,Cache.cacheNullaryFunction(name, expression)) .defined().description(expression.getText()).build()); } else {
names.put(name, Name.nameBuilder(name, (TableFunction) (p,t) -> expression.accept(p, t))
punkbrwstr/pinto
src/main/java/tech/pinto/Console.java
// Path: src/main/java/tech/pinto/tools/LogAppender.java // public class LogAppender extends AppenderBase<ILoggingEvent> { // public static ArrayBlockingQueue<String> LOG = new ArrayBlockingQueue<String>(1000); // static int DEFAULT_LIMIT = 100000; // int counter = 0; // int limit = DEFAULT_LIMIT; // // PatternLayoutEncoder encoder; // // public void setLimit(int limit) { // this.limit = limit; // } // // public int getLimit() { // return limit; // } // // @Override // public void start() { // if (this.encoder == null) { // addError("No encoder set for the appender named ["+ name +"]."); // return; // } // // try { // encoder.init(new OutputStream() // { // private StringBuilder string = new StringBuilder(); // @Override // public void write(int b) throws IOException { // if(((char)b) == '\n') { // if(LOG.remainingCapacity() == 0) { // LOG.remove(); // } else { // LOG.add(string.toString()); // string.setLength(0); // } // } else { // this.string.append((char) b ); // } // } // // public String toString(){ // return this.string.toString(); // } // }); // } catch (IOException e) { // e.printStackTrace(); // } // super.start(); // } // // public void append(ILoggingEvent event) { // if (counter >= limit) { // return; // } // try { // this.encoder.doEncode(event); // } catch (IOException e) { // e.printStackTrace(); // } // // counter++; // } // // public PatternLayoutEncoder getEncoder() { // return encoder; // } // // public void setEncoder(PatternLayoutEncoder encoder) { // this.encoder = encoder; // } // }
import java.io.IOException; import java.io.PrintWriter; import java.text.NumberFormat; import java.util.Arrays; import java.util.List; import jline.console.ConsoleReader; import tech.pinto.tools.LogAppender;
private boolean trace = false; public Console(Pinto pinto, int port, String build, Runnable...shutdownCommands) { this.pinto = pinto; this.port = port; this.build = build; this.shutdownCommands = shutdownCommands; } @Override public void run() { try { NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(4); nf.setMaximumFractionDigits(8); ConsoleReader reader = new ConsoleReader(); reader.setPrompt("pinto> "); reader.addCompleter(pinto.getNamespace()); String line; PrintWriter out = new PrintWriter(reader.getOutput()); out.println("Pinto (build: " + build + ")"); out.println("Server started on http://127.0.0.1:" + port); out.println("For pinto help type \"help\". To quit type \"\\q\". To show other console options type \"\\help\"."); while ((line = reader.readLine()) != null) { if (line.indexOf("\\") == 0) { if(line.startsWith("\\q")) { Arrays.stream(shutdownCommands).forEach(r -> r.run()); return; } else if(line.startsWith("\\log")) {
// Path: src/main/java/tech/pinto/tools/LogAppender.java // public class LogAppender extends AppenderBase<ILoggingEvent> { // public static ArrayBlockingQueue<String> LOG = new ArrayBlockingQueue<String>(1000); // static int DEFAULT_LIMIT = 100000; // int counter = 0; // int limit = DEFAULT_LIMIT; // // PatternLayoutEncoder encoder; // // public void setLimit(int limit) { // this.limit = limit; // } // // public int getLimit() { // return limit; // } // // @Override // public void start() { // if (this.encoder == null) { // addError("No encoder set for the appender named ["+ name +"]."); // return; // } // // try { // encoder.init(new OutputStream() // { // private StringBuilder string = new StringBuilder(); // @Override // public void write(int b) throws IOException { // if(((char)b) == '\n') { // if(LOG.remainingCapacity() == 0) { // LOG.remove(); // } else { // LOG.add(string.toString()); // string.setLength(0); // } // } else { // this.string.append((char) b ); // } // } // // public String toString(){ // return this.string.toString(); // } // }); // } catch (IOException e) { // e.printStackTrace(); // } // super.start(); // } // // public void append(ILoggingEvent event) { // if (counter >= limit) { // return; // } // try { // this.encoder.doEncode(event); // } catch (IOException e) { // e.printStackTrace(); // } // // counter++; // } // // public PatternLayoutEncoder getEncoder() { // return encoder; // } // // public void setEncoder(PatternLayoutEncoder encoder) { // this.encoder = encoder; // } // } // Path: src/main/java/tech/pinto/Console.java import java.io.IOException; import java.io.PrintWriter; import java.text.NumberFormat; import java.util.Arrays; import java.util.List; import jline.console.ConsoleReader; import tech.pinto.tools.LogAppender; private boolean trace = false; public Console(Pinto pinto, int port, String build, Runnable...shutdownCommands) { this.pinto = pinto; this.port = port; this.build = build; this.shutdownCommands = shutdownCommands; } @Override public void run() { try { NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(4); nf.setMaximumFractionDigits(8); ConsoleReader reader = new ConsoleReader(); reader.setPrompt("pinto> "); reader.addCompleter(pinto.getNamespace()); String line; PrintWriter out = new PrintWriter(reader.getOutput()); out.println("Pinto (build: " + build + ")"); out.println("Server started on http://127.0.0.1:" + port); out.println("For pinto help type \"help\". To quit type \"\\q\". To show other console options type \"\\help\"."); while ((line = reader.readLine()) != null) { if (line.indexOf("\\") == 0) { if(line.startsWith("\\q")) { Arrays.stream(shutdownCommands).forEach(r -> r.run()); return; } else if(line.startsWith("\\log")) {
while(!LogAppender.LOG.isEmpty()) {
punkbrwstr/pinto
src/main/java/tech/pinto/Indexer.java
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import tech.pinto.Pinto.Expression; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.Stack;
sb.append(this.indexString.charAt(i)); } else { if (this.indexString.charAt(i) == ',') { indexes.add(new Index(pinto, dependencies, sb.toString().trim())); sb = new StringBuilder(); Arrays.setAll(open, x -> 0); } else { sb.append(this.indexString.charAt(i)); } } } if (Arrays.stream(open).sum() == 0) { indexes.add(new Index(pinto, dependencies, sb.toString().trim())); } else { String unmatched = IntStream.range(0, 4) .mapToObj(i -> open[i] == 0 ? "" : new String[] { "\"", "$", "{", "[" }[i]) .filter(s -> !s.equals("")).collect(Collectors.joining(",")); throw new IllegalArgumentException("Unmatched \"" + unmatched + "\" in Index: \"[" + indexString + "]\""); } } public boolean isNone() { return indexes.size() == 1 && indexes.get(0).isNone(); } public void setIndexForExpression() { this.indexForExpression = true; } public void accept(Pinto pinto, Table t) {
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // } // Path: src/main/java/tech/pinto/Indexer.java import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import tech.pinto.Pinto.Expression; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.Stack; sb.append(this.indexString.charAt(i)); } else { if (this.indexString.charAt(i) == ',') { indexes.add(new Index(pinto, dependencies, sb.toString().trim())); sb = new StringBuilder(); Arrays.setAll(open, x -> 0); } else { sb.append(this.indexString.charAt(i)); } } } if (Arrays.stream(open).sum() == 0) { indexes.add(new Index(pinto, dependencies, sb.toString().trim())); } else { String unmatched = IntStream.range(0, 4) .mapToObj(i -> open[i] == 0 ? "" : new String[] { "\"", "$", "{", "[" }[i]) .filter(s -> !s.equals("")).collect(Collectors.joining(",")); throw new IllegalArgumentException("Unmatched \"" + unmatched + "\" in Index: \"[" + indexString + "]\""); } } public boolean isNone() { return indexes.size() == 1 && indexes.get(0).isNone(); } public void setIndexForExpression() { this.indexForExpression = true; } public void accept(Pinto pinto, Table t) {
LinkedList<Stack> unused = new LinkedList<>();
punkbrwstr/pinto
src/main/java/tech/pinto/Indexer.java
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import tech.pinto.Pinto.Expression; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.Stack;
} unused.addLast(thisUnused); } t.insertAtTop(unused); t.push(indexForExpression, indexedStacks); } public String toString() { return "[" + indexString + "]"; } public Indexer clone() { try { Indexer clone = (Indexer) super.clone(); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } private class Index { private final String string; private boolean copy = false; private boolean not = false; private int repeat = 0; private Optional<String> header = Optional.empty(); private Optional<Integer> sliceStart = Optional.empty(); private Optional<Integer> sliceEnd = Optional.empty();
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // } // Path: src/main/java/tech/pinto/Indexer.java import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import tech.pinto.Pinto.Expression; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.Stack; } unused.addLast(thisUnused); } t.insertAtTop(unused); t.push(indexForExpression, indexedStacks); } public String toString() { return "[" + indexString + "]"; } public Indexer clone() { try { Indexer clone = (Indexer) super.clone(); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } private class Index { private final String string; private boolean copy = false; private boolean not = false; private int repeat = 0; private Optional<String> header = Optional.empty(); private Optional<Integer> sliceStart = Optional.empty(); private Optional<Integer> sliceEnd = Optional.empty();
private Optional<Expression> orFunction = Optional.empty();
punkbrwstr/pinto
src/main/java/tech/pinto/Window.java
// Path: src/main/java/tech/pinto/time/PeriodicRange.java // public final class PeriodicRange<P extends Period<P>> { // // private final Periodicity<P> periodicity; // private final P startInclusive; // private final P endInclusive; // private final String id = ID.getId(); // // PeriodicRange(Periodicity<P> periodcity, P startInclusive, P endInclusive) { // if(endInclusive.isBefore(startInclusive)) { // throw new IllegalArgumentException("Range end must be >= range start"); // } // this.periodicity = periodcity; // this.startInclusive = startInclusive; // this.endInclusive = endInclusive; // } // // public String getId() { // return id; // } // // public List<P> values() { // List<P> l = new ArrayList<>(); // P p = start(); // do { // l.add(p); // p = (P) p.next(); // } while(!p.isAfter(end())); // return l; // } // // public List<LocalDate> dates() { // List<LocalDate> l = new ArrayList<>(); // P p = start(); // do { // l.add(p.endDate()); // p = p.next(); // } while(!p.isAfter(end())); // return l; // } // // public long[] datesInMillis() { // var zone = ZoneId.of("GMT"); // long[] d = new long[(int)size()]; // int i = 0; // P p = start(); // do { // d[i++] = p.endDate().atStartOfDay(zone).toInstant().toEpochMilli(); // p = p.next(); // } while(!p.isAfter(end())); // return d; // } // // public long size() { // return periodicity.distance(startInclusive, endInclusive) + 1; // } // // public long indexOf(P period) { // return periodicity.distance(startInclusive, (P) period); // } // // public long indexOf(LocalDate d) { // return periodicity.distance(startInclusive, periodicity.from(d)); // } // // public P start() { // return startInclusive; // } // // public P end() { // return endInclusive; // } // // public PeriodicRange<P> expand(long offset) { // P start = periodicity.offset(Math.min(offset, 0), start()); // P end = periodicity.offset(Math.max(offset, 0), end()); // return periodicity.range(start, end); // } // // public Periodicity<P> periodicity() { // return periodicity; // } // // public Map<String,String> asStringMap() { // return new ImmutableMap.Builder<String, String>() // .put("start", start().endDate().toString()) // .put("end", end().endDate().toString()) // .put("freq", periodicity().code()).build(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // final PeriodicRange<?> other = (PeriodicRange<?>) obj; // return Objects.equals(this.periodicity, other.periodicity) // && Objects.equals(this.startInclusive, other.startInclusive) // && Objects.equals(this.endInclusive, other.endInclusive); // } // // @Override // public String toString() { // return Joiner.on(":").join(periodicity.code(),start().toString(),end().toString()); // } // // @Override // public int hashCode() { // return Objects.hash(periodicity.code(),startInclusive.hashCode(),endInclusive.hashCode()); // } // }
import java.time.LocalDate; import java.util.List; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleUnaryOperator; import org.ejml.data.DMatrix; import org.ejml.data.DMatrixRMaj; import org.ejml.data.Matrix; import org.ejml.data.MatrixType; import tech.pinto.time.PeriodicRange;
@Override public void apply(DoubleUnaryOperator duo) { for(int i = 0; i < d.length; i++) { for(int j = 0; i < d.length; i++) { d[i][j] = duo.applyAsDouble(d[i][j]); } } } @Override public void apply(DoubleBinaryOperator duo, Window other) { if(!other.getClass().equals(Cross.class)) { throw new IllegalArgumentException("Incompatible window types."); } else if (((Cross) other).d.length != d.length || (d.length > 0 && ((Cross) other).d[0].length != d[0].length)) { throw new IllegalArgumentException("Incompatible window dimensions."); } for(int i = 0; i < d.length; i++) { for(int j = 0; i < d.length; i++) { d[i][j] = duo.applyAsDouble(d[i][j], ((Cross)other).d[i][j]); } } } } public static class Downsample implements Window { final double[] data; final List<LocalDate> dates;
// Path: src/main/java/tech/pinto/time/PeriodicRange.java // public final class PeriodicRange<P extends Period<P>> { // // private final Periodicity<P> periodicity; // private final P startInclusive; // private final P endInclusive; // private final String id = ID.getId(); // // PeriodicRange(Periodicity<P> periodcity, P startInclusive, P endInclusive) { // if(endInclusive.isBefore(startInclusive)) { // throw new IllegalArgumentException("Range end must be >= range start"); // } // this.periodicity = periodcity; // this.startInclusive = startInclusive; // this.endInclusive = endInclusive; // } // // public String getId() { // return id; // } // // public List<P> values() { // List<P> l = new ArrayList<>(); // P p = start(); // do { // l.add(p); // p = (P) p.next(); // } while(!p.isAfter(end())); // return l; // } // // public List<LocalDate> dates() { // List<LocalDate> l = new ArrayList<>(); // P p = start(); // do { // l.add(p.endDate()); // p = p.next(); // } while(!p.isAfter(end())); // return l; // } // // public long[] datesInMillis() { // var zone = ZoneId.of("GMT"); // long[] d = new long[(int)size()]; // int i = 0; // P p = start(); // do { // d[i++] = p.endDate().atStartOfDay(zone).toInstant().toEpochMilli(); // p = p.next(); // } while(!p.isAfter(end())); // return d; // } // // public long size() { // return periodicity.distance(startInclusive, endInclusive) + 1; // } // // public long indexOf(P period) { // return periodicity.distance(startInclusive, (P) period); // } // // public long indexOf(LocalDate d) { // return periodicity.distance(startInclusive, periodicity.from(d)); // } // // public P start() { // return startInclusive; // } // // public P end() { // return endInclusive; // } // // public PeriodicRange<P> expand(long offset) { // P start = periodicity.offset(Math.min(offset, 0), start()); // P end = periodicity.offset(Math.max(offset, 0), end()); // return periodicity.range(start, end); // } // // public Periodicity<P> periodicity() { // return periodicity; // } // // public Map<String,String> asStringMap() { // return new ImmutableMap.Builder<String, String>() // .put("start", start().endDate().toString()) // .put("end", end().endDate().toString()) // .put("freq", periodicity().code()).build(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // final PeriodicRange<?> other = (PeriodicRange<?>) obj; // return Objects.equals(this.periodicity, other.periodicity) // && Objects.equals(this.startInclusive, other.startInclusive) // && Objects.equals(this.endInclusive, other.endInclusive); // } // // @Override // public String toString() { // return Joiner.on(":").join(periodicity.code(),start().toString(),end().toString()); // } // // @Override // public int hashCode() { // return Objects.hash(periodicity.code(),startInclusive.hashCode(),endInclusive.hashCode()); // } // } // Path: src/main/java/tech/pinto/Window.java import java.time.LocalDate; import java.util.List; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleUnaryOperator; import org.ejml.data.DMatrix; import org.ejml.data.DMatrixRMaj; import org.ejml.data.Matrix; import org.ejml.data.MatrixType; import tech.pinto.time.PeriodicRange; @Override public void apply(DoubleUnaryOperator duo) { for(int i = 0; i < d.length; i++) { for(int j = 0; i < d.length; i++) { d[i][j] = duo.applyAsDouble(d[i][j]); } } } @Override public void apply(DoubleBinaryOperator duo, Window other) { if(!other.getClass().equals(Cross.class)) { throw new IllegalArgumentException("Incompatible window types."); } else if (((Cross) other).d.length != d.length || (d.length > 0 && ((Cross) other).d[0].length != d[0].length)) { throw new IllegalArgumentException("Incompatible window dimensions."); } for(int i = 0; i < d.length; i++) { for(int j = 0; i < d.length; i++) { d[i][j] = duo.applyAsDouble(d[i][j], ((Cross)other).d[i][j]); } } } } public static class Downsample implements Window { final double[] data; final List<LocalDate> dates;
final PeriodicRange<?> dataRange;
punkbrwstr/pinto
src/main/java/tech/pinto/Servlet.java
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // }
import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import java.util.StringTokenizer; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import tech.pinto.Pinto.Expression;
getReport(pinto, request, response); } } private void getCSV(Pinto pinto, HttpServletRequest request, HttpServletResponse response) throws IOException { getCSV(pinto,request,response,"NA", 10); } private void getSas(Pinto pinto, HttpServletRequest request, HttpServletResponse response) throws IOException { getCSV(pinto,request,response,".", 10); } private void getCSV(Pinto pinto, HttpServletRequest request, HttpServletResponse response, String naLiteral, int digits ) throws IOException { try { response.setContentType("text/csv"); response.setCharacterEncoding("UTF-8"); if(!request.getParameterMap().containsKey("p")) { throw new Exception("Empty request."); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setNaN(naLiteral); dfs.setInfinity(naLiteral); DecimalFormat nf = new DecimalFormat(); nf.setDecimalFormatSymbols(dfs); nf.setGroupingUsed(false); nf.setMinimumFractionDigits(1); nf.setMaximumFractionDigits(8); //List<Table> l = pinto.evaluate(request.getParameter("p")); Table t = null; var lines = request.getParameter("p").split("\n");
// Path: src/main/java/tech/pinto/Pinto.java // public static class Expression implements TableFunction { // // private final boolean isSubExpression; // private ArrayList<TableFunction> functions = new ArrayList<>(); // private Optional<Indexer> indexer = null; // private Optional<TerminalFunction> terminalFunction = Optional.empty(); // private Set<String> dependencies = new HashSet<>(); // private StringBuilder text = new StringBuilder(); // private Optional<String> nameLiteral = Optional.empty(); // // public Expression(boolean isSubExpression) { // this.isSubExpression = isSubExpression; // } // // public Table evaluate(Pinto pinto) { // if(!terminalFunction.isPresent()) { // throw new PintoSyntaxException("Need terminal to evaluate expression."); // } // return terminalFunction.get().apply(pinto, this); // } // // @Override // public void accept(Pinto pinto, Table table) { // try { // this.indexer.orElse(new Indexer(true)).accept(pinto, table); // for(int i = 0; i < functions.size(); i++) { // functions.get(i).accept(pinto, table); // } // table.collapseFunction(); // } catch(RuntimeException e) { // throw new PintoSyntaxException("Error in expression: \"" + getText().trim() + "\": " + e.getLocalizedMessage() + "\n",e); // } // } // // public void addIndexer(Indexer indexer) { // if(this.indexer == null) { // indexer.setIndexForExpression(); // this.indexer = Optional.of(indexer); // } else { // functions.add(indexer); // } // } // // public void addFunction(Column<?> col) { // addFunction((StackFunction) (p, s) -> s.addFirst(col)); // } // // public void addFunction(TableFunction function) { // if(this.indexer == null) { // this.indexer = Optional.empty(); // } // functions.add(function); // } // // public void setTerminal(TerminalFunction function) { // if(isSubExpression) { // throw new PintoSyntaxException("Sub-expressions cannot include terminal functions"); // } // this.terminalFunction = Optional.of(function); // } // // public ArrayList<TableFunction> getFunctions() { // return functions; // } // // public boolean isExpressionStart() { // return functions.size() == 0; // } // // public boolean isNullary() { // return (!indexer.isPresent()) || indexer.get().isNone(); // } // // public Set<String> getDependencies() { // return dependencies; // } // // public String getText() { // return text.toString(); // } // // public void addText(String expression) { // this.text.append(" ").append(expression); // } // // public Optional<String> getNameLiteral() { // return nameLiteral; // } // // public void setNameLiteral(String nameLiteral) { // this.nameLiteral = Optional.of(nameLiteral); // } // // public boolean hasTerminal() { // return terminalFunction.isPresent(); // } // // } // Path: src/main/java/tech/pinto/Servlet.java import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import java.util.StringTokenizer; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import tech.pinto.Pinto.Expression; getReport(pinto, request, response); } } private void getCSV(Pinto pinto, HttpServletRequest request, HttpServletResponse response) throws IOException { getCSV(pinto,request,response,"NA", 10); } private void getSas(Pinto pinto, HttpServletRequest request, HttpServletResponse response) throws IOException { getCSV(pinto,request,response,".", 10); } private void getCSV(Pinto pinto, HttpServletRequest request, HttpServletResponse response, String naLiteral, int digits ) throws IOException { try { response.setContentType("text/csv"); response.setCharacterEncoding("UTF-8"); if(!request.getParameterMap().containsKey("p")) { throw new Exception("Empty request."); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setNaN(naLiteral); dfs.setInfinity(naLiteral); DecimalFormat nf = new DecimalFormat(); nf.setDecimalFormatSymbols(dfs); nf.setGroupingUsed(false); nf.setMinimumFractionDigits(1); nf.setMaximumFractionDigits(8); //List<Table> l = pinto.evaluate(request.getParameter("p")); Table t = null; var lines = request.getParameter("p").split("\n");
var e = new Pinto.Expression(false);
punkbrwstr/pinto
src/main/java/tech/pinto/HeaderLiteral.java
// Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface StackFunction extends TableFunction { // void accept(Pinto p, Stack s); // // default void accept(Pinto p, Table t) { // List<Stack> inputs = t.takeTop(); // for(int i = 0; i < inputs.size(); i++) { // accept(p, inputs.get(i)); // } // t.insertAtTop(inputs); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import tech.pinto.Pinto.StackFunction; import tech.pinto.Pinto.Stack;
} // don't count colons of commas if anything's open if(Arrays.stream(open).sum() > 0) { h[position].append(header.charAt(i)); } else { if(header.charAt(i) == ':') { position = 1; } else if(header.charAt(i) == ',') { this.headers.add(new Header(pinto, dependencies, h[0].toString(),h[1].length() == 0 ? Optional.empty() : Optional.of(h[1].toString()))); h = new StringBuilder[] {new StringBuilder(), new StringBuilder()}; Arrays.setAll(open, x -> 0); position = 0; } else { h[position].append(header.charAt(i)); } } } if(Arrays.stream(open).sum() == 0) { this.headers.add(new Header(pinto, dependencies, h[0].toString(),h[1].length() == 0 ? Optional.empty() : Optional.of(h[1].toString()))); } else { String unmatched = IntStream.range(0, 4).mapToObj(i -> open[i] == 0 ? "" : new String[]{"\"","$","{","["}[i]) .filter(s -> !s.equals("")).collect(Collectors.joining(",")); throw new IllegalArgumentException("Unmatched \"" + unmatched + "\" in header literal: \"[" + header + "]\""); } } @Override
// Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface StackFunction extends TableFunction { // void accept(Pinto p, Stack s); // // default void accept(Pinto p, Table t) { // List<Stack> inputs = t.takeTop(); // for(int i = 0; i < inputs.size(); i++) { // accept(p, inputs.get(i)); // } // t.insertAtTop(inputs); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // } // Path: src/main/java/tech/pinto/HeaderLiteral.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import tech.pinto.Pinto.StackFunction; import tech.pinto.Pinto.Stack; } // don't count colons of commas if anything's open if(Arrays.stream(open).sum() > 0) { h[position].append(header.charAt(i)); } else { if(header.charAt(i) == ':') { position = 1; } else if(header.charAt(i) == ',') { this.headers.add(new Header(pinto, dependencies, h[0].toString(),h[1].length() == 0 ? Optional.empty() : Optional.of(h[1].toString()))); h = new StringBuilder[] {new StringBuilder(), new StringBuilder()}; Arrays.setAll(open, x -> 0); position = 0; } else { h[position].append(header.charAt(i)); } } } if(Arrays.stream(open).sum() == 0) { this.headers.add(new Header(pinto, dependencies, h[0].toString(),h[1].length() == 0 ? Optional.empty() : Optional.of(h[1].toString()))); } else { String unmatched = IntStream.range(0, 4).mapToObj(i -> open[i] == 0 ? "" : new String[]{"\"","$","{","["}[i]) .filter(s -> !s.equals("")).collect(Collectors.joining(",")); throw new IllegalArgumentException("Unmatched \"" + unmatched + "\" in header literal: \"[" + header + "]\""); } } @Override
public void accept(Pinto pinto, Stack stack) {
punkbrwstr/pinto
src/main/java/tech/pinto/Name.java
// Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface StackFunction extends TableFunction { // void accept(Pinto p, Stack s); // // default void accept(Pinto p, Table t) { // List<Stack> inputs = t.takeTop(); // for(int i = 0; i < inputs.size(); i++) { // accept(p, inputs.get(i)); // } // t.insertAtTop(inputs); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TerminalFunction extends BiFunction<Pinto,Expression,Table> {}
import java.util.HashSet; import java.util.Optional; import tech.pinto.Pinto.StackFunction; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.TerminalFunction;
package tech.pinto; public class Name { final private String name;
// Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface StackFunction extends TableFunction { // void accept(Pinto p, Stack s); // // default void accept(Pinto p, Table t) { // List<Stack> inputs = t.takeTop(); // for(int i = 0; i < inputs.size(); i++) { // accept(p, inputs.get(i)); // } // t.insertAtTop(inputs); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TerminalFunction extends BiFunction<Pinto,Expression,Table> {} // Path: src/main/java/tech/pinto/Name.java import java.util.HashSet; import java.util.Optional; import tech.pinto.Pinto.StackFunction; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.TerminalFunction; package tech.pinto; public class Name { final private String name;
final private Optional<TableFunction> tableFunction;
punkbrwstr/pinto
src/main/java/tech/pinto/Name.java
// Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface StackFunction extends TableFunction { // void accept(Pinto p, Stack s); // // default void accept(Pinto p, Table t) { // List<Stack> inputs = t.takeTop(); // for(int i = 0; i < inputs.size(); i++) { // accept(p, inputs.get(i)); // } // t.insertAtTop(inputs); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TerminalFunction extends BiFunction<Pinto,Expression,Table> {}
import java.util.HashSet; import java.util.Optional; import tech.pinto.Pinto.StackFunction; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.TerminalFunction;
package tech.pinto; public class Name { final private String name; final private Optional<TableFunction> tableFunction;
// Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface StackFunction extends TableFunction { // void accept(Pinto p, Stack s); // // default void accept(Pinto p, Table t) { // List<Stack> inputs = t.takeTop(); // for(int i = 0; i < inputs.size(); i++) { // accept(p, inputs.get(i)); // } // t.insertAtTop(inputs); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TerminalFunction extends BiFunction<Pinto,Expression,Table> {} // Path: src/main/java/tech/pinto/Name.java import java.util.HashSet; import java.util.Optional; import tech.pinto.Pinto.StackFunction; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.TerminalFunction; package tech.pinto; public class Name { final private String name; final private Optional<TableFunction> tableFunction;
final private Optional<TerminalFunction> terminalFunction;
punkbrwstr/pinto
src/main/java/tech/pinto/Name.java
// Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface StackFunction extends TableFunction { // void accept(Pinto p, Stack s); // // default void accept(Pinto p, Table t) { // List<Stack> inputs = t.takeTop(); // for(int i = 0; i < inputs.size(); i++) { // accept(p, inputs.get(i)); // } // t.insertAtTop(inputs); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TerminalFunction extends BiFunction<Pinto,Expression,Table> {}
import java.util.HashSet; import java.util.Optional; import tech.pinto.Pinto.StackFunction; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.TerminalFunction;
} public boolean isBuiltIn() { return isBuiltIn; } public String getDescription() { return description; } public String getIndexString() { return indexString.orElse("[:]"); } public String getHelp(String name) { StringBuilder sb = new StringBuilder(); String crlf = System.getProperty("line.separator"); sb.append(name).append(" help").append(crlf); if(indexString.isPresent()) { sb.append("\t").append("Default indexer: ").append(indexString).append(crlf); } sb.append("\t").append(description).append(crlf); return sb.toString(); } @Override public String toString() { return name; }
// Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface StackFunction extends TableFunction { // void accept(Pinto p, Stack s); // // default void accept(Pinto p, Table t) { // List<Stack> inputs = t.takeTop(); // for(int i = 0; i < inputs.size(); i++) { // accept(p, inputs.get(i)); // } // t.insertAtTop(inputs); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TableFunction extends BiConsumer<Pinto,Table> {} // // Path: src/main/java/tech/pinto/Pinto.java // @FunctionalInterface // public static interface TerminalFunction extends BiFunction<Pinto,Expression,Table> {} // Path: src/main/java/tech/pinto/Name.java import java.util.HashSet; import java.util.Optional; import tech.pinto.Pinto.StackFunction; import tech.pinto.Pinto.TableFunction; import tech.pinto.Pinto.TerminalFunction; } public boolean isBuiltIn() { return isBuiltIn; } public String getDescription() { return description; } public String getIndexString() { return indexString.orElse("[:]"); } public String getHelp(String name) { StringBuilder sb = new StringBuilder(); String crlf = System.getProperty("line.separator"); sb.append(name).append(" help").append(crlf); if(indexString.isPresent()) { sb.append("\t").append("Default indexer: ").append(indexString).append(crlf); } sb.append("\t").append(description).append(crlf); return sb.toString(); } @Override public String toString() { return name; }
public static Builder nameBuilder(String name, StackFunction function) {
punkbrwstr/pinto
src/main/java/tech/pinto/Table.java
// Path: src/main/java/tech/pinto/time/PeriodicRange.java // public final class PeriodicRange<P extends Period<P>> { // // private final Periodicity<P> periodicity; // private final P startInclusive; // private final P endInclusive; // private final String id = ID.getId(); // // PeriodicRange(Periodicity<P> periodcity, P startInclusive, P endInclusive) { // if(endInclusive.isBefore(startInclusive)) { // throw new IllegalArgumentException("Range end must be >= range start"); // } // this.periodicity = periodcity; // this.startInclusive = startInclusive; // this.endInclusive = endInclusive; // } // // public String getId() { // return id; // } // // public List<P> values() { // List<P> l = new ArrayList<>(); // P p = start(); // do { // l.add(p); // p = (P) p.next(); // } while(!p.isAfter(end())); // return l; // } // // public List<LocalDate> dates() { // List<LocalDate> l = new ArrayList<>(); // P p = start(); // do { // l.add(p.endDate()); // p = p.next(); // } while(!p.isAfter(end())); // return l; // } // // public long[] datesInMillis() { // var zone = ZoneId.of("GMT"); // long[] d = new long[(int)size()]; // int i = 0; // P p = start(); // do { // d[i++] = p.endDate().atStartOfDay(zone).toInstant().toEpochMilli(); // p = p.next(); // } while(!p.isAfter(end())); // return d; // } // // public long size() { // return periodicity.distance(startInclusive, endInclusive) + 1; // } // // public long indexOf(P period) { // return periodicity.distance(startInclusive, (P) period); // } // // public long indexOf(LocalDate d) { // return periodicity.distance(startInclusive, periodicity.from(d)); // } // // public P start() { // return startInclusive; // } // // public P end() { // return endInclusive; // } // // public PeriodicRange<P> expand(long offset) { // P start = periodicity.offset(Math.min(offset, 0), start()); // P end = periodicity.offset(Math.max(offset, 0), end()); // return periodicity.range(start, end); // } // // public Periodicity<P> periodicity() { // return periodicity; // } // // public Map<String,String> asStringMap() { // return new ImmutableMap.Builder<String, String>() // .put("start", start().endDate().toString()) // .put("end", end().endDate().toString()) // .put("freq", periodicity().code()).build(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // final PeriodicRange<?> other = (PeriodicRange<?>) obj; // return Objects.equals(this.periodicity, other.periodicity) // && Objects.equals(this.startInclusive, other.startInclusive) // && Objects.equals(this.endInclusive, other.endInclusive); // } // // @Override // public String toString() { // return Joiner.on(":").join(periodicity.code(),start().toString(),end().toString()); // } // // @Override // public int hashCode() { // return Objects.hash(periodicity.code(),startInclusive.hashCode(),endInclusive.hashCode()); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // }
import static java.util.stream.Collectors.toList; import java.text.NumberFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import com.google.common.collect.ImmutableMap; import com.jakewharton.fliptables.FlipTable; import tech.pinto.time.PeriodicRange; import tech.pinto.Pinto.Stack;
package tech.pinto; public class Table { private final LinkedList<Level> levels = new LinkedList<>(); private Optional<String> status = Optional.empty();
// Path: src/main/java/tech/pinto/time/PeriodicRange.java // public final class PeriodicRange<P extends Period<P>> { // // private final Periodicity<P> periodicity; // private final P startInclusive; // private final P endInclusive; // private final String id = ID.getId(); // // PeriodicRange(Periodicity<P> periodcity, P startInclusive, P endInclusive) { // if(endInclusive.isBefore(startInclusive)) { // throw new IllegalArgumentException("Range end must be >= range start"); // } // this.periodicity = periodcity; // this.startInclusive = startInclusive; // this.endInclusive = endInclusive; // } // // public String getId() { // return id; // } // // public List<P> values() { // List<P> l = new ArrayList<>(); // P p = start(); // do { // l.add(p); // p = (P) p.next(); // } while(!p.isAfter(end())); // return l; // } // // public List<LocalDate> dates() { // List<LocalDate> l = new ArrayList<>(); // P p = start(); // do { // l.add(p.endDate()); // p = p.next(); // } while(!p.isAfter(end())); // return l; // } // // public long[] datesInMillis() { // var zone = ZoneId.of("GMT"); // long[] d = new long[(int)size()]; // int i = 0; // P p = start(); // do { // d[i++] = p.endDate().atStartOfDay(zone).toInstant().toEpochMilli(); // p = p.next(); // } while(!p.isAfter(end())); // return d; // } // // public long size() { // return periodicity.distance(startInclusive, endInclusive) + 1; // } // // public long indexOf(P period) { // return periodicity.distance(startInclusive, (P) period); // } // // public long indexOf(LocalDate d) { // return periodicity.distance(startInclusive, periodicity.from(d)); // } // // public P start() { // return startInclusive; // } // // public P end() { // return endInclusive; // } // // public PeriodicRange<P> expand(long offset) { // P start = periodicity.offset(Math.min(offset, 0), start()); // P end = periodicity.offset(Math.max(offset, 0), end()); // return periodicity.range(start, end); // } // // public Periodicity<P> periodicity() { // return periodicity; // } // // public Map<String,String> asStringMap() { // return new ImmutableMap.Builder<String, String>() // .put("start", start().endDate().toString()) // .put("end", end().endDate().toString()) // .put("freq", periodicity().code()).build(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // final PeriodicRange<?> other = (PeriodicRange<?>) obj; // return Objects.equals(this.periodicity, other.periodicity) // && Objects.equals(this.startInclusive, other.startInclusive) // && Objects.equals(this.endInclusive, other.endInclusive); // } // // @Override // public String toString() { // return Joiner.on(":").join(periodicity.code(),start().toString(),end().toString()); // } // // @Override // public int hashCode() { // return Objects.hash(periodicity.code(),startInclusive.hashCode(),endInclusive.hashCode()); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // } // Path: src/main/java/tech/pinto/Table.java import static java.util.stream.Collectors.toList; import java.text.NumberFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import com.google.common.collect.ImmutableMap; import com.jakewharton.fliptables.FlipTable; import tech.pinto.time.PeriodicRange; import tech.pinto.Pinto.Stack; package tech.pinto; public class Table { private final LinkedList<Level> levels = new LinkedList<>(); private Optional<String> status = Optional.empty();
private Optional<PeriodicRange<?>> range = Optional.empty();
punkbrwstr/pinto
src/main/java/tech/pinto/Table.java
// Path: src/main/java/tech/pinto/time/PeriodicRange.java // public final class PeriodicRange<P extends Period<P>> { // // private final Periodicity<P> periodicity; // private final P startInclusive; // private final P endInclusive; // private final String id = ID.getId(); // // PeriodicRange(Periodicity<P> periodcity, P startInclusive, P endInclusive) { // if(endInclusive.isBefore(startInclusive)) { // throw new IllegalArgumentException("Range end must be >= range start"); // } // this.periodicity = periodcity; // this.startInclusive = startInclusive; // this.endInclusive = endInclusive; // } // // public String getId() { // return id; // } // // public List<P> values() { // List<P> l = new ArrayList<>(); // P p = start(); // do { // l.add(p); // p = (P) p.next(); // } while(!p.isAfter(end())); // return l; // } // // public List<LocalDate> dates() { // List<LocalDate> l = new ArrayList<>(); // P p = start(); // do { // l.add(p.endDate()); // p = p.next(); // } while(!p.isAfter(end())); // return l; // } // // public long[] datesInMillis() { // var zone = ZoneId.of("GMT"); // long[] d = new long[(int)size()]; // int i = 0; // P p = start(); // do { // d[i++] = p.endDate().atStartOfDay(zone).toInstant().toEpochMilli(); // p = p.next(); // } while(!p.isAfter(end())); // return d; // } // // public long size() { // return periodicity.distance(startInclusive, endInclusive) + 1; // } // // public long indexOf(P period) { // return periodicity.distance(startInclusive, (P) period); // } // // public long indexOf(LocalDate d) { // return periodicity.distance(startInclusive, periodicity.from(d)); // } // // public P start() { // return startInclusive; // } // // public P end() { // return endInclusive; // } // // public PeriodicRange<P> expand(long offset) { // P start = periodicity.offset(Math.min(offset, 0), start()); // P end = periodicity.offset(Math.max(offset, 0), end()); // return periodicity.range(start, end); // } // // public Periodicity<P> periodicity() { // return periodicity; // } // // public Map<String,String> asStringMap() { // return new ImmutableMap.Builder<String, String>() // .put("start", start().endDate().toString()) // .put("end", end().endDate().toString()) // .put("freq", periodicity().code()).build(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // final PeriodicRange<?> other = (PeriodicRange<?>) obj; // return Objects.equals(this.periodicity, other.periodicity) // && Objects.equals(this.startInclusive, other.startInclusive) // && Objects.equals(this.endInclusive, other.endInclusive); // } // // @Override // public String toString() { // return Joiner.on(":").join(periodicity.code(),start().toString(),end().toString()); // } // // @Override // public int hashCode() { // return Objects.hash(periodicity.code(),startInclusive.hashCode(),endInclusive.hashCode()); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // }
import static java.util.stream.Collectors.toList; import java.text.NumberFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import com.google.common.collect.ImmutableMap; import com.jakewharton.fliptables.FlipTable; import tech.pinto.time.PeriodicRange; import tech.pinto.Pinto.Stack;
package tech.pinto; public class Table { private final LinkedList<Level> levels = new LinkedList<>(); private Optional<String> status = Optional.empty(); private Optional<PeriodicRange<?>> range = Optional.empty();
// Path: src/main/java/tech/pinto/time/PeriodicRange.java // public final class PeriodicRange<P extends Period<P>> { // // private final Periodicity<P> periodicity; // private final P startInclusive; // private final P endInclusive; // private final String id = ID.getId(); // // PeriodicRange(Periodicity<P> periodcity, P startInclusive, P endInclusive) { // if(endInclusive.isBefore(startInclusive)) { // throw new IllegalArgumentException("Range end must be >= range start"); // } // this.periodicity = periodcity; // this.startInclusive = startInclusive; // this.endInclusive = endInclusive; // } // // public String getId() { // return id; // } // // public List<P> values() { // List<P> l = new ArrayList<>(); // P p = start(); // do { // l.add(p); // p = (P) p.next(); // } while(!p.isAfter(end())); // return l; // } // // public List<LocalDate> dates() { // List<LocalDate> l = new ArrayList<>(); // P p = start(); // do { // l.add(p.endDate()); // p = p.next(); // } while(!p.isAfter(end())); // return l; // } // // public long[] datesInMillis() { // var zone = ZoneId.of("GMT"); // long[] d = new long[(int)size()]; // int i = 0; // P p = start(); // do { // d[i++] = p.endDate().atStartOfDay(zone).toInstant().toEpochMilli(); // p = p.next(); // } while(!p.isAfter(end())); // return d; // } // // public long size() { // return periodicity.distance(startInclusive, endInclusive) + 1; // } // // public long indexOf(P period) { // return periodicity.distance(startInclusive, (P) period); // } // // public long indexOf(LocalDate d) { // return periodicity.distance(startInclusive, periodicity.from(d)); // } // // public P start() { // return startInclusive; // } // // public P end() { // return endInclusive; // } // // public PeriodicRange<P> expand(long offset) { // P start = periodicity.offset(Math.min(offset, 0), start()); // P end = periodicity.offset(Math.max(offset, 0), end()); // return periodicity.range(start, end); // } // // public Periodicity<P> periodicity() { // return periodicity; // } // // public Map<String,String> asStringMap() { // return new ImmutableMap.Builder<String, String>() // .put("start", start().endDate().toString()) // .put("end", end().endDate().toString()) // .put("freq", periodicity().code()).build(); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // final PeriodicRange<?> other = (PeriodicRange<?>) obj; // return Objects.equals(this.periodicity, other.periodicity) // && Objects.equals(this.startInclusive, other.startInclusive) // && Objects.equals(this.endInclusive, other.endInclusive); // } // // @Override // public String toString() { // return Joiner.on(":").join(periodicity.code(),start().toString(),end().toString()); // } // // @Override // public int hashCode() { // return Objects.hash(periodicity.code(),startInclusive.hashCode(),endInclusive.hashCode()); // } // } // // Path: src/main/java/tech/pinto/Pinto.java // public static class Stack extends LinkedList<Column<?>> { // private static final long serialVersionUID = 1L; // // public Stack() { // super(); // } // // public Stack(Collection<? extends Column<?>> c) { // super(c); // } // // } // Path: src/main/java/tech/pinto/Table.java import static java.util.stream.Collectors.toList; import java.text.NumberFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import com.google.common.collect.ImmutableMap; import com.jakewharton.fliptables.FlipTable; import tech.pinto.time.PeriodicRange; import tech.pinto.Pinto.Stack; package tech.pinto; public class Table { private final LinkedList<Level> levels = new LinkedList<>(); private Optional<String> status = Optional.empty(); private Optional<PeriodicRange<?>> range = Optional.empty();
private Optional<Stack> flattenedStack = Optional.empty();
f2prateek/device-frame-generator
src/main/java/com/f2prateek/dfg/Events.java
// Path: src/main/java/com/f2prateek/dfg/model/Device.java // @AutoValue public abstract class Device implements Parcelable { // // // Unique identifier for each device, also used to identify resources. // public abstract String id(); // // // Device name to display // public abstract String name(); // // // Device product URL // public abstract String url(); // // // Physical size of device, just for displaying to user // public abstract float physicalSize(); // // // DPI; just for displaying to user // public abstract String density(); // // // offset of screenshot from edges when in landscape // public abstract Bounds landOffset(); // // // offset of screenshot from edges when in portrait // public abstract Bounds portOffset(); // // // Screen resolution in portrait for the device frame // public abstract Bounds portSize(); // // // Screen resolution in portrait, that will be displayed to the user. // // This may or may not be same as portSize // public abstract Bounds realSize(); // // // A list of product ids that match {@link android.os.Build#PRODUCT} for this device // public abstract Collection<String> productIds(); // // private static Device create(String id, String name, String url, float physicalSize, // String density, Bounds landOffset, Bounds portOffset, Bounds portSize, Bounds realSize, // Set<String> productIds) { // return new AutoValue_Device(id, name, url, physicalSize, density, landOffset, portOffset, // portSize, realSize, productIds); // } // // // Get the name of the shadow resource // public String getShadowStringResourceName(String orientation) { // return id() + "_" + orientation + "_shadow"; // } // // // Get the name of the glare resource // public String getGlareStringResourceName(String orientation) { // return id() + "_" + orientation + "_glare"; // } // // // Get the name of the background resource // public String getBackgroundStringResourceName(String orientation) { // return id() + "_" + orientation + "_back"; // } // // // Get the name of the thumbnail resource // public String getThumbnailResourceName() { // return id() + "_thumb"; // } // // // Put all relevant values into the given container object and return it // public void into(Map<String, Object> container) { // container.put("device_id", id()); // container.put("device_name", name()); // container.put("device_bounds_x", portSize().x()); // container.put("device_bounds_y", portSize().y()); // } // // public static class Builder { // // private String id; // private String name; // private String url; // private float physicalSize; // private String density; // private Bounds landOffset; // private Bounds portOffset; // private Bounds portSize; // private Bounds realSize; // private Set<String> productIds = new LinkedHashSet<>(); // // public Builder setId(String id) { // this.id = id; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setUrl(String url) { // this.url = url; // return this; // } // // public Builder setPhysicalSize(float physicalSize) { // this.physicalSize = physicalSize; // return this; // } // // public Builder setDensity(String density) { // this.density = density; // return this; // } // // public Builder setLandOffset(int landOffsetX, int landOffsetY) { // this.landOffset = Bounds.create(landOffsetX, landOffsetY); // return this; // } // // public Builder setPortOffset(int portOffsetX, int portOffsetY) { // this.portOffset = Bounds.create(portOffsetX, portOffsetY); // return this; // } // // public Builder setPortSize(int portSizeX, int portSizeY) { // this.portSize = Bounds.create(portSizeX, portSizeY); // return this; // } // // public Builder setRealSize(int realSizeX, int realSizeY) { // this.realSize = Bounds.create(realSizeX, realSizeY); // return this; // } // // public Builder addProductId(String id) { // productIds.add(id); // return this; // } // // public Device build() { // return create(id, name, url, physicalSize, density, landOffset, portOffset, portSize, // realSize, productIds); // } // } // }
import android.net.Uri; import com.f2prateek.dfg.model.Device; import java.util.List;
/* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg; public class Events { private Events() { // no instances } public static class GlareSettingUpdated { public final boolean isEnabled; public GlareSettingUpdated(boolean isEnabled) { this.isEnabled = isEnabled; } } public static class ShadowSettingUpdated { public final boolean isEnabled; public ShadowSettingUpdated(boolean isEnabled) { this.isEnabled = isEnabled; } } public static class DefaultDeviceUpdated {
// Path: src/main/java/com/f2prateek/dfg/model/Device.java // @AutoValue public abstract class Device implements Parcelable { // // // Unique identifier for each device, also used to identify resources. // public abstract String id(); // // // Device name to display // public abstract String name(); // // // Device product URL // public abstract String url(); // // // Physical size of device, just for displaying to user // public abstract float physicalSize(); // // // DPI; just for displaying to user // public abstract String density(); // // // offset of screenshot from edges when in landscape // public abstract Bounds landOffset(); // // // offset of screenshot from edges when in portrait // public abstract Bounds portOffset(); // // // Screen resolution in portrait for the device frame // public abstract Bounds portSize(); // // // Screen resolution in portrait, that will be displayed to the user. // // This may or may not be same as portSize // public abstract Bounds realSize(); // // // A list of product ids that match {@link android.os.Build#PRODUCT} for this device // public abstract Collection<String> productIds(); // // private static Device create(String id, String name, String url, float physicalSize, // String density, Bounds landOffset, Bounds portOffset, Bounds portSize, Bounds realSize, // Set<String> productIds) { // return new AutoValue_Device(id, name, url, physicalSize, density, landOffset, portOffset, // portSize, realSize, productIds); // } // // // Get the name of the shadow resource // public String getShadowStringResourceName(String orientation) { // return id() + "_" + orientation + "_shadow"; // } // // // Get the name of the glare resource // public String getGlareStringResourceName(String orientation) { // return id() + "_" + orientation + "_glare"; // } // // // Get the name of the background resource // public String getBackgroundStringResourceName(String orientation) { // return id() + "_" + orientation + "_back"; // } // // // Get the name of the thumbnail resource // public String getThumbnailResourceName() { // return id() + "_thumb"; // } // // // Put all relevant values into the given container object and return it // public void into(Map<String, Object> container) { // container.put("device_id", id()); // container.put("device_name", name()); // container.put("device_bounds_x", portSize().x()); // container.put("device_bounds_y", portSize().y()); // } // // public static class Builder { // // private String id; // private String name; // private String url; // private float physicalSize; // private String density; // private Bounds landOffset; // private Bounds portOffset; // private Bounds portSize; // private Bounds realSize; // private Set<String> productIds = new LinkedHashSet<>(); // // public Builder setId(String id) { // this.id = id; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setUrl(String url) { // this.url = url; // return this; // } // // public Builder setPhysicalSize(float physicalSize) { // this.physicalSize = physicalSize; // return this; // } // // public Builder setDensity(String density) { // this.density = density; // return this; // } // // public Builder setLandOffset(int landOffsetX, int landOffsetY) { // this.landOffset = Bounds.create(landOffsetX, landOffsetY); // return this; // } // // public Builder setPortOffset(int portOffsetX, int portOffsetY) { // this.portOffset = Bounds.create(portOffsetX, portOffsetY); // return this; // } // // public Builder setPortSize(int portSizeX, int portSizeY) { // this.portSize = Bounds.create(portSizeX, portSizeY); // return this; // } // // public Builder setRealSize(int realSizeX, int realSizeY) { // this.realSize = Bounds.create(realSizeX, realSizeY); // return this; // } // // public Builder addProductId(String id) { // productIds.add(id); // return this; // } // // public Device build() { // return create(id, name, url, physicalSize, density, landOffset, portOffset, portSize, // realSize, productIds); // } // } // } // Path: src/main/java/com/f2prateek/dfg/Events.java import android.net.Uri; import com.f2prateek.dfg.model.Device; import java.util.List; /* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg; public class Events { private Events() { // no instances } public static class GlareSettingUpdated { public final boolean isEnabled; public GlareSettingUpdated(boolean isEnabled) { this.isEnabled = isEnabled; } } public static class ShadowSettingUpdated { public final boolean isEnabled; public ShadowSettingUpdated(boolean isEnabled) { this.isEnabled = isEnabled; } } public static class DefaultDeviceUpdated {
public final Device newDevice;
f2prateek/device-frame-generator
src/main/java/com/f2prateek/dfg/ui/activities/BaseActivity.java
// Path: src/main/java/com/f2prateek/dfg/DFGApplication.java // public class DFGApplication extends Application { // ObjectGraph applicationGraph; // @Inject ActivityHierarchyServer activityHierarchyServer; // @Inject Bus bus; // // @Inject WindowManager windowManager; // @Inject DeviceProvider deviceProvider; // @Inject @FirstRun Preference<Boolean> firstRun; // @Inject Analytics analytics; // // @Override public void onCreate() { // super.onCreate(); // // // Perform Injection // buildApplicationGraphAndInject(); // // registerActivityLifecycleCallbacks(activityHierarchyServer); // // if (BuildConfig.DEBUG) { // Ln.set(DebugLn.from(this)); // } // // if (!isStorageAvailable()) { // Toast.makeText(this, R.string.storage_unavailable, Toast.LENGTH_SHORT).show(); // Ln.w("storage unavailable"); // } // // if (firstRun.get()) { // analytics.track("First Launch"); // Device device = deviceProvider.find(windowManager); // if (device != null) { // deviceProvider.saveDefaultDevice(device); // bus.post(new Events.DefaultDeviceUpdated(device)); // } // firstRun.set(false); // } // } // // @DebugLog public void buildApplicationGraphAndInject() { // applicationGraph = ObjectGraph.create(Modules.list(this)); // applicationGraph.inject(this); // } // // public static DFGApplication get(Context context) { // return (DFGApplication) context.getApplicationContext(); // } // // public void inject(Object object) { // applicationGraph.inject(object); // } // } // // Path: src/main/java/com/f2prateek/dfg/ui/AppContainer.java // public interface AppContainer { // /** The root {@link android.view.ViewGroup} into which the activity should place its contents. */ // ViewGroup get(Activity activity, DFGApplication app); // // /** An {@link AppContainer} which returns the normal activity content view. */ // AppContainer DEFAULT = new AppContainer() { // @Override public ViewGroup get(Activity activity, DFGApplication app) { // return findById(activity, android.R.id.content); // } // }; // }
import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import butterknife.ButterKnife; import com.f2prateek.dart.Dart; import com.f2prateek.dfg.DFGApplication; import com.f2prateek.dfg.ui.AppContainer; import com.squareup.otto.Bus; import javax.inject.Inject;
/* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg.ui.activities; @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { @Inject Bus bus;
// Path: src/main/java/com/f2prateek/dfg/DFGApplication.java // public class DFGApplication extends Application { // ObjectGraph applicationGraph; // @Inject ActivityHierarchyServer activityHierarchyServer; // @Inject Bus bus; // // @Inject WindowManager windowManager; // @Inject DeviceProvider deviceProvider; // @Inject @FirstRun Preference<Boolean> firstRun; // @Inject Analytics analytics; // // @Override public void onCreate() { // super.onCreate(); // // // Perform Injection // buildApplicationGraphAndInject(); // // registerActivityLifecycleCallbacks(activityHierarchyServer); // // if (BuildConfig.DEBUG) { // Ln.set(DebugLn.from(this)); // } // // if (!isStorageAvailable()) { // Toast.makeText(this, R.string.storage_unavailable, Toast.LENGTH_SHORT).show(); // Ln.w("storage unavailable"); // } // // if (firstRun.get()) { // analytics.track("First Launch"); // Device device = deviceProvider.find(windowManager); // if (device != null) { // deviceProvider.saveDefaultDevice(device); // bus.post(new Events.DefaultDeviceUpdated(device)); // } // firstRun.set(false); // } // } // // @DebugLog public void buildApplicationGraphAndInject() { // applicationGraph = ObjectGraph.create(Modules.list(this)); // applicationGraph.inject(this); // } // // public static DFGApplication get(Context context) { // return (DFGApplication) context.getApplicationContext(); // } // // public void inject(Object object) { // applicationGraph.inject(object); // } // } // // Path: src/main/java/com/f2prateek/dfg/ui/AppContainer.java // public interface AppContainer { // /** The root {@link android.view.ViewGroup} into which the activity should place its contents. */ // ViewGroup get(Activity activity, DFGApplication app); // // /** An {@link AppContainer} which returns the normal activity content view. */ // AppContainer DEFAULT = new AppContainer() { // @Override public ViewGroup get(Activity activity, DFGApplication app) { // return findById(activity, android.R.id.content); // } // }; // } // Path: src/main/java/com/f2prateek/dfg/ui/activities/BaseActivity.java import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import butterknife.ButterKnife; import com.f2prateek.dart.Dart; import com.f2prateek.dfg.DFGApplication; import com.f2prateek.dfg.ui.AppContainer; import com.squareup.otto.Bus; import javax.inject.Inject; /* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg.ui.activities; @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { @Inject Bus bus;
@Inject AppContainer appContainer;
f2prateek/device-frame-generator
src/main/java/com/f2prateek/dfg/ui/activities/BaseActivity.java
// Path: src/main/java/com/f2prateek/dfg/DFGApplication.java // public class DFGApplication extends Application { // ObjectGraph applicationGraph; // @Inject ActivityHierarchyServer activityHierarchyServer; // @Inject Bus bus; // // @Inject WindowManager windowManager; // @Inject DeviceProvider deviceProvider; // @Inject @FirstRun Preference<Boolean> firstRun; // @Inject Analytics analytics; // // @Override public void onCreate() { // super.onCreate(); // // // Perform Injection // buildApplicationGraphAndInject(); // // registerActivityLifecycleCallbacks(activityHierarchyServer); // // if (BuildConfig.DEBUG) { // Ln.set(DebugLn.from(this)); // } // // if (!isStorageAvailable()) { // Toast.makeText(this, R.string.storage_unavailable, Toast.LENGTH_SHORT).show(); // Ln.w("storage unavailable"); // } // // if (firstRun.get()) { // analytics.track("First Launch"); // Device device = deviceProvider.find(windowManager); // if (device != null) { // deviceProvider.saveDefaultDevice(device); // bus.post(new Events.DefaultDeviceUpdated(device)); // } // firstRun.set(false); // } // } // // @DebugLog public void buildApplicationGraphAndInject() { // applicationGraph = ObjectGraph.create(Modules.list(this)); // applicationGraph.inject(this); // } // // public static DFGApplication get(Context context) { // return (DFGApplication) context.getApplicationContext(); // } // // public void inject(Object object) { // applicationGraph.inject(object); // } // } // // Path: src/main/java/com/f2prateek/dfg/ui/AppContainer.java // public interface AppContainer { // /** The root {@link android.view.ViewGroup} into which the activity should place its contents. */ // ViewGroup get(Activity activity, DFGApplication app); // // /** An {@link AppContainer} which returns the normal activity content view. */ // AppContainer DEFAULT = new AppContainer() { // @Override public ViewGroup get(Activity activity, DFGApplication app) { // return findById(activity, android.R.id.content); // } // }; // }
import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import butterknife.ButterKnife; import com.f2prateek.dart.Dart; import com.f2prateek.dfg.DFGApplication; import com.f2prateek.dfg.ui.AppContainer; import com.squareup.otto.Bus; import javax.inject.Inject;
/* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg.ui.activities; @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { @Inject Bus bus; @Inject AppContainer appContainer; private ViewGroup container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: src/main/java/com/f2prateek/dfg/DFGApplication.java // public class DFGApplication extends Application { // ObjectGraph applicationGraph; // @Inject ActivityHierarchyServer activityHierarchyServer; // @Inject Bus bus; // // @Inject WindowManager windowManager; // @Inject DeviceProvider deviceProvider; // @Inject @FirstRun Preference<Boolean> firstRun; // @Inject Analytics analytics; // // @Override public void onCreate() { // super.onCreate(); // // // Perform Injection // buildApplicationGraphAndInject(); // // registerActivityLifecycleCallbacks(activityHierarchyServer); // // if (BuildConfig.DEBUG) { // Ln.set(DebugLn.from(this)); // } // // if (!isStorageAvailable()) { // Toast.makeText(this, R.string.storage_unavailable, Toast.LENGTH_SHORT).show(); // Ln.w("storage unavailable"); // } // // if (firstRun.get()) { // analytics.track("First Launch"); // Device device = deviceProvider.find(windowManager); // if (device != null) { // deviceProvider.saveDefaultDevice(device); // bus.post(new Events.DefaultDeviceUpdated(device)); // } // firstRun.set(false); // } // } // // @DebugLog public void buildApplicationGraphAndInject() { // applicationGraph = ObjectGraph.create(Modules.list(this)); // applicationGraph.inject(this); // } // // public static DFGApplication get(Context context) { // return (DFGApplication) context.getApplicationContext(); // } // // public void inject(Object object) { // applicationGraph.inject(object); // } // } // // Path: src/main/java/com/f2prateek/dfg/ui/AppContainer.java // public interface AppContainer { // /** The root {@link android.view.ViewGroup} into which the activity should place its contents. */ // ViewGroup get(Activity activity, DFGApplication app); // // /** An {@link AppContainer} which returns the normal activity content view. */ // AppContainer DEFAULT = new AppContainer() { // @Override public ViewGroup get(Activity activity, DFGApplication app) { // return findById(activity, android.R.id.content); // } // }; // } // Path: src/main/java/com/f2prateek/dfg/ui/activities/BaseActivity.java import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import butterknife.ButterKnife; import com.f2prateek.dart.Dart; import com.f2prateek.dfg.DFGApplication; import com.f2prateek.dfg.ui.AppContainer; import com.squareup.otto.Bus; import javax.inject.Inject; /* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg.ui.activities; @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { @Inject Bus bus; @Inject AppContainer appContainer; private ViewGroup container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
DFGApplication app = DFGApplication.get(this);
f2prateek/device-frame-generator
src/main/java/com/f2prateek/dfg/DeviceModule.java
// Path: src/main/java/com/f2prateek/dfg/model/Device.java // @AutoValue public abstract class Device implements Parcelable { // // // Unique identifier for each device, also used to identify resources. // public abstract String id(); // // // Device name to display // public abstract String name(); // // // Device product URL // public abstract String url(); // // // Physical size of device, just for displaying to user // public abstract float physicalSize(); // // // DPI; just for displaying to user // public abstract String density(); // // // offset of screenshot from edges when in landscape // public abstract Bounds landOffset(); // // // offset of screenshot from edges when in portrait // public abstract Bounds portOffset(); // // // Screen resolution in portrait for the device frame // public abstract Bounds portSize(); // // // Screen resolution in portrait, that will be displayed to the user. // // This may or may not be same as portSize // public abstract Bounds realSize(); // // // A list of product ids that match {@link android.os.Build#PRODUCT} for this device // public abstract Collection<String> productIds(); // // private static Device create(String id, String name, String url, float physicalSize, // String density, Bounds landOffset, Bounds portOffset, Bounds portSize, Bounds realSize, // Set<String> productIds) { // return new AutoValue_Device(id, name, url, physicalSize, density, landOffset, portOffset, // portSize, realSize, productIds); // } // // // Get the name of the shadow resource // public String getShadowStringResourceName(String orientation) { // return id() + "_" + orientation + "_shadow"; // } // // // Get the name of the glare resource // public String getGlareStringResourceName(String orientation) { // return id() + "_" + orientation + "_glare"; // } // // // Get the name of the background resource // public String getBackgroundStringResourceName(String orientation) { // return id() + "_" + orientation + "_back"; // } // // // Get the name of the thumbnail resource // public String getThumbnailResourceName() { // return id() + "_thumb"; // } // // // Put all relevant values into the given container object and return it // public void into(Map<String, Object> container) { // container.put("device_id", id()); // container.put("device_name", name()); // container.put("device_bounds_x", portSize().x()); // container.put("device_bounds_y", portSize().y()); // } // // public static class Builder { // // private String id; // private String name; // private String url; // private float physicalSize; // private String density; // private Bounds landOffset; // private Bounds portOffset; // private Bounds portSize; // private Bounds realSize; // private Set<String> productIds = new LinkedHashSet<>(); // // public Builder setId(String id) { // this.id = id; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setUrl(String url) { // this.url = url; // return this; // } // // public Builder setPhysicalSize(float physicalSize) { // this.physicalSize = physicalSize; // return this; // } // // public Builder setDensity(String density) { // this.density = density; // return this; // } // // public Builder setLandOffset(int landOffsetX, int landOffsetY) { // this.landOffset = Bounds.create(landOffsetX, landOffsetY); // return this; // } // // public Builder setPortOffset(int portOffsetX, int portOffsetY) { // this.portOffset = Bounds.create(portOffsetX, portOffsetY); // return this; // } // // public Builder setPortSize(int portSizeX, int portSizeY) { // this.portSize = Bounds.create(portSizeX, portSizeY); // return this; // } // // public Builder setRealSize(int realSizeX, int realSizeY) { // this.realSize = Bounds.create(realSizeX, realSizeY); // return this; // } // // public Builder addProductId(String id) { // productIds.add(id); // return this; // } // // public Device build() { // return create(id, name, url, physicalSize, density, landOffset, portOffset, portSize, // realSize, productIds); // } // } // }
import com.f2prateek.dfg.model.Device; import dagger.Module; import dagger.Provides; import static dagger.Provides.Type.SET;
/* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg; @Module(library = true) public class DeviceModule {
// Path: src/main/java/com/f2prateek/dfg/model/Device.java // @AutoValue public abstract class Device implements Parcelable { // // // Unique identifier for each device, also used to identify resources. // public abstract String id(); // // // Device name to display // public abstract String name(); // // // Device product URL // public abstract String url(); // // // Physical size of device, just for displaying to user // public abstract float physicalSize(); // // // DPI; just for displaying to user // public abstract String density(); // // // offset of screenshot from edges when in landscape // public abstract Bounds landOffset(); // // // offset of screenshot from edges when in portrait // public abstract Bounds portOffset(); // // // Screen resolution in portrait for the device frame // public abstract Bounds portSize(); // // // Screen resolution in portrait, that will be displayed to the user. // // This may or may not be same as portSize // public abstract Bounds realSize(); // // // A list of product ids that match {@link android.os.Build#PRODUCT} for this device // public abstract Collection<String> productIds(); // // private static Device create(String id, String name, String url, float physicalSize, // String density, Bounds landOffset, Bounds portOffset, Bounds portSize, Bounds realSize, // Set<String> productIds) { // return new AutoValue_Device(id, name, url, physicalSize, density, landOffset, portOffset, // portSize, realSize, productIds); // } // // // Get the name of the shadow resource // public String getShadowStringResourceName(String orientation) { // return id() + "_" + orientation + "_shadow"; // } // // // Get the name of the glare resource // public String getGlareStringResourceName(String orientation) { // return id() + "_" + orientation + "_glare"; // } // // // Get the name of the background resource // public String getBackgroundStringResourceName(String orientation) { // return id() + "_" + orientation + "_back"; // } // // // Get the name of the thumbnail resource // public String getThumbnailResourceName() { // return id() + "_thumb"; // } // // // Put all relevant values into the given container object and return it // public void into(Map<String, Object> container) { // container.put("device_id", id()); // container.put("device_name", name()); // container.put("device_bounds_x", portSize().x()); // container.put("device_bounds_y", portSize().y()); // } // // public static class Builder { // // private String id; // private String name; // private String url; // private float physicalSize; // private String density; // private Bounds landOffset; // private Bounds portOffset; // private Bounds portSize; // private Bounds realSize; // private Set<String> productIds = new LinkedHashSet<>(); // // public Builder setId(String id) { // this.id = id; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setUrl(String url) { // this.url = url; // return this; // } // // public Builder setPhysicalSize(float physicalSize) { // this.physicalSize = physicalSize; // return this; // } // // public Builder setDensity(String density) { // this.density = density; // return this; // } // // public Builder setLandOffset(int landOffsetX, int landOffsetY) { // this.landOffset = Bounds.create(landOffsetX, landOffsetY); // return this; // } // // public Builder setPortOffset(int portOffsetX, int portOffsetY) { // this.portOffset = Bounds.create(portOffsetX, portOffsetY); // return this; // } // // public Builder setPortSize(int portSizeX, int portSizeY) { // this.portSize = Bounds.create(portSizeX, portSizeY); // return this; // } // // public Builder setRealSize(int realSizeX, int realSizeY) { // this.realSize = Bounds.create(realSizeX, realSizeY); // return this; // } // // public Builder addProductId(String id) { // productIds.add(id); // return this; // } // // public Device build() { // return create(id, name, url, physicalSize, density, landOffset, portOffset, portSize, // realSize, productIds); // } // } // } // Path: src/main/java/com/f2prateek/dfg/DeviceModule.java import com.f2prateek.dfg.model.Device; import dagger.Module; import dagger.Provides; import static dagger.Provides.Type.SET; /* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg; @Module(library = true) public class DeviceModule {
@Provides(type = SET) Device provideNexusS() {
f2prateek/device-frame-generator
src/debug/java/com/f2prateek/dfg/DebugDFGApplicationModule.java
// Path: src/debug/java/com/f2prateek/dfg/prefs/DebugPreferencesModule.java // @Module(complete = false, library = true) public class DebugPreferencesModule { // private static final int DEFAULT_ANIMATION_SPEED = 1; // 1x (normal) speed. // private static final boolean DEFAULT_PICASSO_DEBUGGING = false; // Debug indicators displayed // private static final boolean DEFAULT_PIXEL_GRID_ENABLED = false; // No pixel grid overlay. // private static final boolean DEFAULT_PIXEL_RATIO_ENABLED = false; // No pixel ratio overlay. // private static final boolean DEFAULT_SCALPEL_ENABLED = false; // No crazy 3D view tree. // private static final boolean DEFAULT_SCALPEL_WIREFRAME_ENABLED = false; // Draw views by default. // private static final boolean DEFAULT_SEEN_DEBUG_DRAWER = false; // Show debug drawer first time. // // @Provides @Singleton @AnimationSpeed // // Preference<Integer> provideAnimationSpeed(RxSharedPreferences preferences) { // return preferences.getInteger("debug_animation_speed", DEFAULT_ANIMATION_SPEED); // } // // @Provides @Singleton @PicassoDebugging // // Preference<Boolean> providePicassoDebugging(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_picasso_debugging", DEFAULT_PICASSO_DEBUGGING); // } // // @Provides @Singleton @PixelGridEnabled // // Preference<Boolean> providePixelGridEnabled(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_pixel_grid_enabled", DEFAULT_PIXEL_GRID_ENABLED); // } // // @Provides @Singleton @PixelRatioEnabled // // Preference<Boolean> providePixelRatioEnabled(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_pixel_ratio_enabled", DEFAULT_PIXEL_RATIO_ENABLED); // } // // @Provides @Singleton @SeenDebugDrawer // // Preference<Boolean> provideSeenDebugDrawer(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_seen_debug_drawer", DEFAULT_SEEN_DEBUG_DRAWER); // } // // @Provides @Singleton @ScalpelEnabled // // Preference<Boolean> provideScalpelEnabled(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_scalpel_enabled", DEFAULT_SCALPEL_ENABLED); // } // // @Provides @Singleton @ScalpelWireframeEnabled // // Preference<Boolean> provideScalpelWireframeEnabled(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_scalpel_wireframe_drawer", // DEFAULT_SCALPEL_WIREFRAME_ENABLED); // } // }
import android.content.Context; import com.f2prateek.dfg.prefs.DebugPreferencesModule; import com.f2prateek.dfg.ui.DebugUiModule; import com.segment.analytics.Analytics; import dagger.Module; import dagger.Provides; import javax.inject.Singleton;
/* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg; @Module( addsTo = DFGApplicationModule.class, includes = {
// Path: src/debug/java/com/f2prateek/dfg/prefs/DebugPreferencesModule.java // @Module(complete = false, library = true) public class DebugPreferencesModule { // private static final int DEFAULT_ANIMATION_SPEED = 1; // 1x (normal) speed. // private static final boolean DEFAULT_PICASSO_DEBUGGING = false; // Debug indicators displayed // private static final boolean DEFAULT_PIXEL_GRID_ENABLED = false; // No pixel grid overlay. // private static final boolean DEFAULT_PIXEL_RATIO_ENABLED = false; // No pixel ratio overlay. // private static final boolean DEFAULT_SCALPEL_ENABLED = false; // No crazy 3D view tree. // private static final boolean DEFAULT_SCALPEL_WIREFRAME_ENABLED = false; // Draw views by default. // private static final boolean DEFAULT_SEEN_DEBUG_DRAWER = false; // Show debug drawer first time. // // @Provides @Singleton @AnimationSpeed // // Preference<Integer> provideAnimationSpeed(RxSharedPreferences preferences) { // return preferences.getInteger("debug_animation_speed", DEFAULT_ANIMATION_SPEED); // } // // @Provides @Singleton @PicassoDebugging // // Preference<Boolean> providePicassoDebugging(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_picasso_debugging", DEFAULT_PICASSO_DEBUGGING); // } // // @Provides @Singleton @PixelGridEnabled // // Preference<Boolean> providePixelGridEnabled(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_pixel_grid_enabled", DEFAULT_PIXEL_GRID_ENABLED); // } // // @Provides @Singleton @PixelRatioEnabled // // Preference<Boolean> providePixelRatioEnabled(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_pixel_ratio_enabled", DEFAULT_PIXEL_RATIO_ENABLED); // } // // @Provides @Singleton @SeenDebugDrawer // // Preference<Boolean> provideSeenDebugDrawer(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_seen_debug_drawer", DEFAULT_SEEN_DEBUG_DRAWER); // } // // @Provides @Singleton @ScalpelEnabled // // Preference<Boolean> provideScalpelEnabled(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_scalpel_enabled", DEFAULT_SCALPEL_ENABLED); // } // // @Provides @Singleton @ScalpelWireframeEnabled // // Preference<Boolean> provideScalpelWireframeEnabled(RxSharedPreferences preferences) { // return preferences.getBoolean("debug_scalpel_wireframe_drawer", // DEFAULT_SCALPEL_WIREFRAME_ENABLED); // } // } // Path: src/debug/java/com/f2prateek/dfg/DebugDFGApplicationModule.java import android.content.Context; import com.f2prateek.dfg.prefs.DebugPreferencesModule; import com.f2prateek.dfg.ui.DebugUiModule; import com.segment.analytics.Analytics; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; /* * Copyright 2014 Prateek Srivastava (@f2prateek) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.f2prateek.dfg; @Module( addsTo = DFGApplicationModule.class, includes = {
DebugUiModule.class, DebugPreferencesModule.class
pentaho/pentaho-mongodb-plugin
pentaho-mongodb-plugin/src/test/java/org/pentaho/di/trans/steps/mongodboutput/MongoDbOutputDataTest.java
// Path: pentaho-mongodb-plugin/src/main/java/org/pentaho/di/trans/steps/mongodboutput/MongoDbOutputMeta.java // public static class MongoIndex { // // /** // * Dot notation for accessing a fields - e.g. person.address.street. Can also specify entire embedded documents as // * an index (rather than a primitive key) - e.g. person.address. // * // * Multiple fields are comma-separated followed by an optional "direction" indicator for the index (1 or -1). If // * omitted, direction is assumed to be 1. // */ // @Injection( name = "INDEX_FIELD", group = "INDEXES" ) // public String m_pathToFields = ""; //$NON-NLS-1$ // // /** whether to drop this index - default is create */ // @Injection( name = "DROP", group = "INDEXES" ) // public boolean m_drop; // // // other options unique, sparse // @Injection( name = "UNIQUE", group = "INDEXES" ) // public boolean m_unique; // @Injection( name = "SPARSE", group = "INDEXES" ) // public boolean m_sparse; // // @Override // public String toString() { // StringBuffer buff = new StringBuffer(); // buff.append( m_pathToFields + " (unique = " //$NON-NLS-1$ // + new Boolean( m_unique ).toString() + " sparse = " //$NON-NLS-1$ // + new Boolean( m_sparse ).toString() + ")" ); //$NON-NLS-1$ // // return buff.toString(); // } // }
import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.util.JSON; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.trans.steps.mongodboutput.MongoDbOutputMeta.MongoIndex; import org.pentaho.mongo.MongoDbException; import org.pentaho.mongo.wrapper.MongoClientWrapper; import org.pentaho.mongo.wrapper.collection.DefaultMongoCollectionWrapper; import org.pentaho.mongo.wrapper.collection.MongoCollectionWrapper; import java.util.Arrays; import java.util.List; import static junit.framework.TestCase.fail; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*;
.thenAnswer( new Answer<String>() { @Override public String answer( InvocationOnMock invocationOnMock ) throws Throwable { return (String) invocationOnMock.getArguments()[0]; } } ); when( space.environmentSubstitute( any( String.class ), anyBoolean() ) ) .thenAnswer( new Answer<String>() { @Override public String answer( InvocationOnMock invocationOnMock ) throws Throwable { return (String) invocationOnMock.getArguments()[0]; } } ); } @BeforeClass public static void setUpBeforeClass() throws KettleException { KettleEnvironment.init( false ); } @Test public void testApplyIndexesOptions() throws KettleException, MongoDbException { MongoDbOutputData data = new MongoDbOutputData(); LogChannelInterface log = new LogChannel( data ); DBCollection collection = mock( DBCollection.class ); MongoCollectionWrapper collectionWrapper = spy( new DefaultMongoCollectionWrapper( collection ) ); data.setCollection( collectionWrapper ); ArgumentCaptor<BasicDBObject> captorIndexes = ArgumentCaptor.forClass( BasicDBObject.class ); ArgumentCaptor<BasicDBObject> captorOptions = ArgumentCaptor.forClass( BasicDBObject.class ); doNothing().when( collectionWrapper ).createIndex( captorIndexes.capture(), captorOptions.capture() );
// Path: pentaho-mongodb-plugin/src/main/java/org/pentaho/di/trans/steps/mongodboutput/MongoDbOutputMeta.java // public static class MongoIndex { // // /** // * Dot notation for accessing a fields - e.g. person.address.street. Can also specify entire embedded documents as // * an index (rather than a primitive key) - e.g. person.address. // * // * Multiple fields are comma-separated followed by an optional "direction" indicator for the index (1 or -1). If // * omitted, direction is assumed to be 1. // */ // @Injection( name = "INDEX_FIELD", group = "INDEXES" ) // public String m_pathToFields = ""; //$NON-NLS-1$ // // /** whether to drop this index - default is create */ // @Injection( name = "DROP", group = "INDEXES" ) // public boolean m_drop; // // // other options unique, sparse // @Injection( name = "UNIQUE", group = "INDEXES" ) // public boolean m_unique; // @Injection( name = "SPARSE", group = "INDEXES" ) // public boolean m_sparse; // // @Override // public String toString() { // StringBuffer buff = new StringBuffer(); // buff.append( m_pathToFields + " (unique = " //$NON-NLS-1$ // + new Boolean( m_unique ).toString() + " sparse = " //$NON-NLS-1$ // + new Boolean( m_sparse ).toString() + ")" ); //$NON-NLS-1$ // // return buff.toString(); // } // } // Path: pentaho-mongodb-plugin/src/test/java/org/pentaho/di/trans/steps/mongodboutput/MongoDbOutputDataTest.java import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.util.JSON; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.trans.steps.mongodboutput.MongoDbOutputMeta.MongoIndex; import org.pentaho.mongo.MongoDbException; import org.pentaho.mongo.wrapper.MongoClientWrapper; import org.pentaho.mongo.wrapper.collection.DefaultMongoCollectionWrapper; import org.pentaho.mongo.wrapper.collection.MongoCollectionWrapper; import java.util.Arrays; import java.util.List; import static junit.framework.TestCase.fail; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; .thenAnswer( new Answer<String>() { @Override public String answer( InvocationOnMock invocationOnMock ) throws Throwable { return (String) invocationOnMock.getArguments()[0]; } } ); when( space.environmentSubstitute( any( String.class ), anyBoolean() ) ) .thenAnswer( new Answer<String>() { @Override public String answer( InvocationOnMock invocationOnMock ) throws Throwable { return (String) invocationOnMock.getArguments()[0]; } } ); } @BeforeClass public static void setUpBeforeClass() throws KettleException { KettleEnvironment.init( false ); } @Test public void testApplyIndexesOptions() throws KettleException, MongoDbException { MongoDbOutputData data = new MongoDbOutputData(); LogChannelInterface log = new LogChannel( data ); DBCollection collection = mock( DBCollection.class ); MongoCollectionWrapper collectionWrapper = spy( new DefaultMongoCollectionWrapper( collection ) ); data.setCollection( collectionWrapper ); ArgumentCaptor<BasicDBObject> captorIndexes = ArgumentCaptor.forClass( BasicDBObject.class ); ArgumentCaptor<BasicDBObject> captorOptions = ArgumentCaptor.forClass( BasicDBObject.class ); doNothing().when( collectionWrapper ).createIndex( captorIndexes.capture(), captorOptions.capture() );
MongoIndex index = new MongoDbOutputMeta.MongoIndex();
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/source/DigitalAssetLinksDataSource.java
// Path: afservice/src/main/java/com/example/android/autofill/service/data/DataCallback.java // public interface DataCallback<T> { // void onLoaded(T object); // // void onDataNotAvailable(String msg, Object... params); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalCheck.java // public class DalCheck { // public boolean linked; // public String maxAge; // public String debugString; // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalInfo.java // public class DalInfo { // private final String mWebDomain; // private final String mPackageName; // // public DalInfo(String webDomain, String packageName) { // String canonicalDomain = getCanonicalDomain(webDomain); // final String fullDomain; // if (!webDomain.startsWith("http:") && !webDomain.startsWith("https:")) { // // Unfortunately AssistStructure.ViewNode does not tell what the domain is, so let's // // assume it's https // fullDomain = "https://" + canonicalDomain; // } else { // fullDomain = canonicalDomain; // } // mWebDomain = fullDomain; // mPackageName = packageName; // } // // public String getWebDomain() { // return mWebDomain; // } // // public String getPackageName() { // return mPackageName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DalInfo dalInfo = (DalInfo) o; // // if (mWebDomain != null ? !mWebDomain.equals(dalInfo.mWebDomain) : // dalInfo.mWebDomain != null) // return false; // return mPackageName != null ? mPackageName.equals(dalInfo.mPackageName) : // dalInfo.mPackageName == null; // } // // @Override // public int hashCode() { // int result = mWebDomain != null ? mWebDomain.hashCode() : 0; // result = 31 * result + (mPackageName != null ? mPackageName.hashCode() : 0); // return result; // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public enum DalCheckRequirement {Disabled, LoginOnly, AllUrls}
import com.example.android.autofill.service.data.DataCallback; import com.example.android.autofill.service.model.DalCheck; import com.example.android.autofill.service.model.DalInfo; import static com.example.android.autofill.service.util.Util.DalCheckRequirement;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source; /** * Data source for * <a href="https://developers.google.com/digital-asset-links/">Digital Asset Links</a>. */ public interface DigitalAssetLinksDataSource { /** * Checks if the association between a web domain and a package is valid. */ void checkValid(DalCheckRequirement dalCheckRequirement, DalInfo dalInfo,
// Path: afservice/src/main/java/com/example/android/autofill/service/data/DataCallback.java // public interface DataCallback<T> { // void onLoaded(T object); // // void onDataNotAvailable(String msg, Object... params); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalCheck.java // public class DalCheck { // public boolean linked; // public String maxAge; // public String debugString; // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalInfo.java // public class DalInfo { // private final String mWebDomain; // private final String mPackageName; // // public DalInfo(String webDomain, String packageName) { // String canonicalDomain = getCanonicalDomain(webDomain); // final String fullDomain; // if (!webDomain.startsWith("http:") && !webDomain.startsWith("https:")) { // // Unfortunately AssistStructure.ViewNode does not tell what the domain is, so let's // // assume it's https // fullDomain = "https://" + canonicalDomain; // } else { // fullDomain = canonicalDomain; // } // mWebDomain = fullDomain; // mPackageName = packageName; // } // // public String getWebDomain() { // return mWebDomain; // } // // public String getPackageName() { // return mPackageName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DalInfo dalInfo = (DalInfo) o; // // if (mWebDomain != null ? !mWebDomain.equals(dalInfo.mWebDomain) : // dalInfo.mWebDomain != null) // return false; // return mPackageName != null ? mPackageName.equals(dalInfo.mPackageName) : // dalInfo.mPackageName == null; // } // // @Override // public int hashCode() { // int result = mWebDomain != null ? mWebDomain.hashCode() : 0; // result = 31 * result + (mPackageName != null ? mPackageName.hashCode() : 0); // return result; // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public enum DalCheckRequirement {Disabled, LoginOnly, AllUrls} // Path: afservice/src/main/java/com/example/android/autofill/service/data/source/DigitalAssetLinksDataSource.java import com.example.android.autofill.service.data.DataCallback; import com.example.android.autofill.service.model.DalCheck; import com.example.android.autofill.service.model.DalInfo; import static com.example.android.autofill.service.util.Util.DalCheckRequirement; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source; /** * Data source for * <a href="https://developers.google.com/digital-asset-links/">Digital Asset Links</a>. */ public interface DigitalAssetLinksDataSource { /** * Checks if the association between a web domain and a package is valid. */ void checkValid(DalCheckRequirement dalCheckRequirement, DalInfo dalInfo,
DataCallback<DalCheck> dalCheckCallback);
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/source/DigitalAssetLinksDataSource.java
// Path: afservice/src/main/java/com/example/android/autofill/service/data/DataCallback.java // public interface DataCallback<T> { // void onLoaded(T object); // // void onDataNotAvailable(String msg, Object... params); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalCheck.java // public class DalCheck { // public boolean linked; // public String maxAge; // public String debugString; // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalInfo.java // public class DalInfo { // private final String mWebDomain; // private final String mPackageName; // // public DalInfo(String webDomain, String packageName) { // String canonicalDomain = getCanonicalDomain(webDomain); // final String fullDomain; // if (!webDomain.startsWith("http:") && !webDomain.startsWith("https:")) { // // Unfortunately AssistStructure.ViewNode does not tell what the domain is, so let's // // assume it's https // fullDomain = "https://" + canonicalDomain; // } else { // fullDomain = canonicalDomain; // } // mWebDomain = fullDomain; // mPackageName = packageName; // } // // public String getWebDomain() { // return mWebDomain; // } // // public String getPackageName() { // return mPackageName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DalInfo dalInfo = (DalInfo) o; // // if (mWebDomain != null ? !mWebDomain.equals(dalInfo.mWebDomain) : // dalInfo.mWebDomain != null) // return false; // return mPackageName != null ? mPackageName.equals(dalInfo.mPackageName) : // dalInfo.mPackageName == null; // } // // @Override // public int hashCode() { // int result = mWebDomain != null ? mWebDomain.hashCode() : 0; // result = 31 * result + (mPackageName != null ? mPackageName.hashCode() : 0); // return result; // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public enum DalCheckRequirement {Disabled, LoginOnly, AllUrls}
import com.example.android.autofill.service.data.DataCallback; import com.example.android.autofill.service.model.DalCheck; import com.example.android.autofill.service.model.DalInfo; import static com.example.android.autofill.service.util.Util.DalCheckRequirement;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source; /** * Data source for * <a href="https://developers.google.com/digital-asset-links/">Digital Asset Links</a>. */ public interface DigitalAssetLinksDataSource { /** * Checks if the association between a web domain and a package is valid. */ void checkValid(DalCheckRequirement dalCheckRequirement, DalInfo dalInfo,
// Path: afservice/src/main/java/com/example/android/autofill/service/data/DataCallback.java // public interface DataCallback<T> { // void onLoaded(T object); // // void onDataNotAvailable(String msg, Object... params); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalCheck.java // public class DalCheck { // public boolean linked; // public String maxAge; // public String debugString; // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalInfo.java // public class DalInfo { // private final String mWebDomain; // private final String mPackageName; // // public DalInfo(String webDomain, String packageName) { // String canonicalDomain = getCanonicalDomain(webDomain); // final String fullDomain; // if (!webDomain.startsWith("http:") && !webDomain.startsWith("https:")) { // // Unfortunately AssistStructure.ViewNode does not tell what the domain is, so let's // // assume it's https // fullDomain = "https://" + canonicalDomain; // } else { // fullDomain = canonicalDomain; // } // mWebDomain = fullDomain; // mPackageName = packageName; // } // // public String getWebDomain() { // return mWebDomain; // } // // public String getPackageName() { // return mPackageName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // DalInfo dalInfo = (DalInfo) o; // // if (mWebDomain != null ? !mWebDomain.equals(dalInfo.mWebDomain) : // dalInfo.mWebDomain != null) // return false; // return mPackageName != null ? mPackageName.equals(dalInfo.mPackageName) : // dalInfo.mPackageName == null; // } // // @Override // public int hashCode() { // int result = mWebDomain != null ? mWebDomain.hashCode() : 0; // result = 31 * result + (mPackageName != null ? mPackageName.hashCode() : 0); // return result; // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public enum DalCheckRequirement {Disabled, LoginOnly, AllUrls} // Path: afservice/src/main/java/com/example/android/autofill/service/data/source/DigitalAssetLinksDataSource.java import com.example.android.autofill.service.data.DataCallback; import com.example.android.autofill.service.model.DalCheck; import com.example.android.autofill.service.model.DalInfo; import static com.example.android.autofill.service.util.Util.DalCheckRequirement; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source; /** * Data source for * <a href="https://developers.google.com/digital-asset-links/">Digital Asset Links</a>. */ public interface DigitalAssetLinksDataSource { /** * Checks if the association between a web domain and a package is valid. */ void checkValid(DalCheckRequirement dalCheckRequirement, DalInfo dalInfo,
DataCallback<DalCheck> dalCheckCallback);
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/source/local/SharedPrefsPackageVerificationRepository.java
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/PackageVerificationDataSource.java // public interface PackageVerificationDataSource { // // /** // * Verifies that the signatures in the passed {@code Context} match what is currently in // * storage. If there are no current signatures in storage for this packageName, it will store // * the signatures from the passed {@code Context}. // * // * @return {@code true} if signatures for this packageName are not currently in storage // * or if the signatures in the passed {@code Context} match what is currently in storage; // * {@code false} if the signatures in the passed {@code Context} do not match what is // * currently in storage or if an {@code Exception} was thrown while generating the signatures. // */ // boolean putPackageSignatures(String packageName); // // /** // * Clears all signature data currently in storage. // */ // void clear(); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/SecurityHelper.java // public final class SecurityHelper { // // private SecurityHelper() { // throw new UnsupportedOperationException("Provides static methods only."); // } // // /** // * Gets the fingerprint of the signed certificate of a package. // */ // public static String getFingerprint(PackageInfo packageInfo, String packageName) throws // PackageManager.NameNotFoundException, IOException, NoSuchAlgorithmException, // CertificateException { // Signature[] signatures = packageInfo.signatures; // if (signatures.length != 1) { // throw new SecurityException(packageName + " has " + signatures.length + " signatures"); // } // byte[] cert = signatures[0].toByteArray(); // try (InputStream input = new ByteArrayInputStream(cert)) { // CertificateFactory factory = CertificateFactory.getInstance("X509"); // X509Certificate x509 = (X509Certificate) factory.generateCertificate(input); // MessageDigest md = MessageDigest.getInstance("SHA256"); // byte[] publicKey = md.digest(x509.getEncoded()); // return toHexFormat(publicKey); // } // } // // private static String toHexFormat(byte[] bytes) { // StringBuilder builder = new StringBuilder(bytes.length * 2); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(bytes[i]); // int length = hex.length(); // if (length == 1) { // hex = "0" + hex; // } // if (length > 2) { // hex = hex.substring(length - 2, length); // } // builder.append(hex.toUpperCase()); // if (i < (bytes.length - 1)) { // builder.append(':'); // } // } // return builder.toString(); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logd(String message, Object... params) { // if (logDebugEnabled()) { // Log.d(TAG, String.format(message, params)); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logw(String message, Object... params) { // Log.w(TAG, String.format(message, params)); // }
import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.example.android.autofill.service.data.source.PackageVerificationDataSource; import com.example.android.autofill.service.util.SecurityHelper; import static com.example.android.autofill.service.util.Util.logd; import static com.example.android.autofill.service.util.Util.logw;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source.local; public class SharedPrefsPackageVerificationRepository implements PackageVerificationDataSource { private static final String SHARED_PREF_KEY = "com.example.android.autofill.service" + ".datasource.PackageVerificationDataSource"; private static PackageVerificationDataSource sInstance; private final SharedPreferences mSharedPrefs; private final Context mContext; private SharedPrefsPackageVerificationRepository(Context context) { mSharedPrefs = context.getApplicationContext() .getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE); mContext = context.getApplicationContext(); } public static PackageVerificationDataSource getInstance(Context context) { if (sInstance == null) { sInstance = new SharedPrefsPackageVerificationRepository( context.getApplicationContext()); } return sInstance; } @Override public void clear() { mSharedPrefs.edit().clear().apply(); } @Override public boolean putPackageSignatures(String packageName) { String hash; try { PackageManager pm = mContext.getPackageManager(); PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/PackageVerificationDataSource.java // public interface PackageVerificationDataSource { // // /** // * Verifies that the signatures in the passed {@code Context} match what is currently in // * storage. If there are no current signatures in storage for this packageName, it will store // * the signatures from the passed {@code Context}. // * // * @return {@code true} if signatures for this packageName are not currently in storage // * or if the signatures in the passed {@code Context} match what is currently in storage; // * {@code false} if the signatures in the passed {@code Context} do not match what is // * currently in storage or if an {@code Exception} was thrown while generating the signatures. // */ // boolean putPackageSignatures(String packageName); // // /** // * Clears all signature data currently in storage. // */ // void clear(); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/SecurityHelper.java // public final class SecurityHelper { // // private SecurityHelper() { // throw new UnsupportedOperationException("Provides static methods only."); // } // // /** // * Gets the fingerprint of the signed certificate of a package. // */ // public static String getFingerprint(PackageInfo packageInfo, String packageName) throws // PackageManager.NameNotFoundException, IOException, NoSuchAlgorithmException, // CertificateException { // Signature[] signatures = packageInfo.signatures; // if (signatures.length != 1) { // throw new SecurityException(packageName + " has " + signatures.length + " signatures"); // } // byte[] cert = signatures[0].toByteArray(); // try (InputStream input = new ByteArrayInputStream(cert)) { // CertificateFactory factory = CertificateFactory.getInstance("X509"); // X509Certificate x509 = (X509Certificate) factory.generateCertificate(input); // MessageDigest md = MessageDigest.getInstance("SHA256"); // byte[] publicKey = md.digest(x509.getEncoded()); // return toHexFormat(publicKey); // } // } // // private static String toHexFormat(byte[] bytes) { // StringBuilder builder = new StringBuilder(bytes.length * 2); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(bytes[i]); // int length = hex.length(); // if (length == 1) { // hex = "0" + hex; // } // if (length > 2) { // hex = hex.substring(length - 2, length); // } // builder.append(hex.toUpperCase()); // if (i < (bytes.length - 1)) { // builder.append(':'); // } // } // return builder.toString(); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logd(String message, Object... params) { // if (logDebugEnabled()) { // Log.d(TAG, String.format(message, params)); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logw(String message, Object... params) { // Log.w(TAG, String.format(message, params)); // } // Path: afservice/src/main/java/com/example/android/autofill/service/data/source/local/SharedPrefsPackageVerificationRepository.java import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.example.android.autofill.service.data.source.PackageVerificationDataSource; import com.example.android.autofill.service.util.SecurityHelper; import static com.example.android.autofill.service.util.Util.logd; import static com.example.android.autofill.service.util.Util.logw; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source.local; public class SharedPrefsPackageVerificationRepository implements PackageVerificationDataSource { private static final String SHARED_PREF_KEY = "com.example.android.autofill.service" + ".datasource.PackageVerificationDataSource"; private static PackageVerificationDataSource sInstance; private final SharedPreferences mSharedPrefs; private final Context mContext; private SharedPrefsPackageVerificationRepository(Context context) { mSharedPrefs = context.getApplicationContext() .getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE); mContext = context.getApplicationContext(); } public static PackageVerificationDataSource getInstance(Context context) { if (sInstance == null) { sInstance = new SharedPrefsPackageVerificationRepository( context.getApplicationContext()); } return sInstance; } @Override public void clear() { mSharedPrefs.edit().clear().apply(); } @Override public boolean putPackageSignatures(String packageName) { String hash; try { PackageManager pm = mContext.getPackageManager(); PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
hash = SecurityHelper.getFingerprint(packageInfo, packageName);
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/source/local/SharedPrefsPackageVerificationRepository.java
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/PackageVerificationDataSource.java // public interface PackageVerificationDataSource { // // /** // * Verifies that the signatures in the passed {@code Context} match what is currently in // * storage. If there are no current signatures in storage for this packageName, it will store // * the signatures from the passed {@code Context}. // * // * @return {@code true} if signatures for this packageName are not currently in storage // * or if the signatures in the passed {@code Context} match what is currently in storage; // * {@code false} if the signatures in the passed {@code Context} do not match what is // * currently in storage or if an {@code Exception} was thrown while generating the signatures. // */ // boolean putPackageSignatures(String packageName); // // /** // * Clears all signature data currently in storage. // */ // void clear(); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/SecurityHelper.java // public final class SecurityHelper { // // private SecurityHelper() { // throw new UnsupportedOperationException("Provides static methods only."); // } // // /** // * Gets the fingerprint of the signed certificate of a package. // */ // public static String getFingerprint(PackageInfo packageInfo, String packageName) throws // PackageManager.NameNotFoundException, IOException, NoSuchAlgorithmException, // CertificateException { // Signature[] signatures = packageInfo.signatures; // if (signatures.length != 1) { // throw new SecurityException(packageName + " has " + signatures.length + " signatures"); // } // byte[] cert = signatures[0].toByteArray(); // try (InputStream input = new ByteArrayInputStream(cert)) { // CertificateFactory factory = CertificateFactory.getInstance("X509"); // X509Certificate x509 = (X509Certificate) factory.generateCertificate(input); // MessageDigest md = MessageDigest.getInstance("SHA256"); // byte[] publicKey = md.digest(x509.getEncoded()); // return toHexFormat(publicKey); // } // } // // private static String toHexFormat(byte[] bytes) { // StringBuilder builder = new StringBuilder(bytes.length * 2); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(bytes[i]); // int length = hex.length(); // if (length == 1) { // hex = "0" + hex; // } // if (length > 2) { // hex = hex.substring(length - 2, length); // } // builder.append(hex.toUpperCase()); // if (i < (bytes.length - 1)) { // builder.append(':'); // } // } // return builder.toString(); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logd(String message, Object... params) { // if (logDebugEnabled()) { // Log.d(TAG, String.format(message, params)); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logw(String message, Object... params) { // Log.w(TAG, String.format(message, params)); // }
import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.example.android.autofill.service.data.source.PackageVerificationDataSource; import com.example.android.autofill.service.util.SecurityHelper; import static com.example.android.autofill.service.util.Util.logd; import static com.example.android.autofill.service.util.Util.logw;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source.local; public class SharedPrefsPackageVerificationRepository implements PackageVerificationDataSource { private static final String SHARED_PREF_KEY = "com.example.android.autofill.service" + ".datasource.PackageVerificationDataSource"; private static PackageVerificationDataSource sInstance; private final SharedPreferences mSharedPrefs; private final Context mContext; private SharedPrefsPackageVerificationRepository(Context context) { mSharedPrefs = context.getApplicationContext() .getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE); mContext = context.getApplicationContext(); } public static PackageVerificationDataSource getInstance(Context context) { if (sInstance == null) { sInstance = new SharedPrefsPackageVerificationRepository( context.getApplicationContext()); } return sInstance; } @Override public void clear() { mSharedPrefs.edit().clear().apply(); } @Override public boolean putPackageSignatures(String packageName) { String hash; try { PackageManager pm = mContext.getPackageManager(); PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); hash = SecurityHelper.getFingerprint(packageInfo, packageName);
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/PackageVerificationDataSource.java // public interface PackageVerificationDataSource { // // /** // * Verifies that the signatures in the passed {@code Context} match what is currently in // * storage. If there are no current signatures in storage for this packageName, it will store // * the signatures from the passed {@code Context}. // * // * @return {@code true} if signatures for this packageName are not currently in storage // * or if the signatures in the passed {@code Context} match what is currently in storage; // * {@code false} if the signatures in the passed {@code Context} do not match what is // * currently in storage or if an {@code Exception} was thrown while generating the signatures. // */ // boolean putPackageSignatures(String packageName); // // /** // * Clears all signature data currently in storage. // */ // void clear(); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/SecurityHelper.java // public final class SecurityHelper { // // private SecurityHelper() { // throw new UnsupportedOperationException("Provides static methods only."); // } // // /** // * Gets the fingerprint of the signed certificate of a package. // */ // public static String getFingerprint(PackageInfo packageInfo, String packageName) throws // PackageManager.NameNotFoundException, IOException, NoSuchAlgorithmException, // CertificateException { // Signature[] signatures = packageInfo.signatures; // if (signatures.length != 1) { // throw new SecurityException(packageName + " has " + signatures.length + " signatures"); // } // byte[] cert = signatures[0].toByteArray(); // try (InputStream input = new ByteArrayInputStream(cert)) { // CertificateFactory factory = CertificateFactory.getInstance("X509"); // X509Certificate x509 = (X509Certificate) factory.generateCertificate(input); // MessageDigest md = MessageDigest.getInstance("SHA256"); // byte[] publicKey = md.digest(x509.getEncoded()); // return toHexFormat(publicKey); // } // } // // private static String toHexFormat(byte[] bytes) { // StringBuilder builder = new StringBuilder(bytes.length * 2); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(bytes[i]); // int length = hex.length(); // if (length == 1) { // hex = "0" + hex; // } // if (length > 2) { // hex = hex.substring(length - 2, length); // } // builder.append(hex.toUpperCase()); // if (i < (bytes.length - 1)) { // builder.append(':'); // } // } // return builder.toString(); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logd(String message, Object... params) { // if (logDebugEnabled()) { // Log.d(TAG, String.format(message, params)); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logw(String message, Object... params) { // Log.w(TAG, String.format(message, params)); // } // Path: afservice/src/main/java/com/example/android/autofill/service/data/source/local/SharedPrefsPackageVerificationRepository.java import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.example.android.autofill.service.data.source.PackageVerificationDataSource; import com.example.android.autofill.service.util.SecurityHelper; import static com.example.android.autofill.service.util.Util.logd; import static com.example.android.autofill.service.util.Util.logw; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source.local; public class SharedPrefsPackageVerificationRepository implements PackageVerificationDataSource { private static final String SHARED_PREF_KEY = "com.example.android.autofill.service" + ".datasource.PackageVerificationDataSource"; private static PackageVerificationDataSource sInstance; private final SharedPreferences mSharedPrefs; private final Context mContext; private SharedPrefsPackageVerificationRepository(Context context) { mSharedPrefs = context.getApplicationContext() .getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE); mContext = context.getApplicationContext(); } public static PackageVerificationDataSource getInstance(Context context) { if (sInstance == null) { sInstance = new SharedPrefsPackageVerificationRepository( context.getApplicationContext()); } return sInstance; } @Override public void clear() { mSharedPrefs.edit().clear().apply(); } @Override public boolean putPackageSignatures(String packageName) { String hash; try { PackageManager pm = mContext.getPackageManager(); PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); hash = SecurityHelper.getFingerprint(packageInfo, packageName);
logd("Hash for %s: %s", packageName, hash);
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/source/local/SharedPrefsPackageVerificationRepository.java
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/PackageVerificationDataSource.java // public interface PackageVerificationDataSource { // // /** // * Verifies that the signatures in the passed {@code Context} match what is currently in // * storage. If there are no current signatures in storage for this packageName, it will store // * the signatures from the passed {@code Context}. // * // * @return {@code true} if signatures for this packageName are not currently in storage // * or if the signatures in the passed {@code Context} match what is currently in storage; // * {@code false} if the signatures in the passed {@code Context} do not match what is // * currently in storage or if an {@code Exception} was thrown while generating the signatures. // */ // boolean putPackageSignatures(String packageName); // // /** // * Clears all signature data currently in storage. // */ // void clear(); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/SecurityHelper.java // public final class SecurityHelper { // // private SecurityHelper() { // throw new UnsupportedOperationException("Provides static methods only."); // } // // /** // * Gets the fingerprint of the signed certificate of a package. // */ // public static String getFingerprint(PackageInfo packageInfo, String packageName) throws // PackageManager.NameNotFoundException, IOException, NoSuchAlgorithmException, // CertificateException { // Signature[] signatures = packageInfo.signatures; // if (signatures.length != 1) { // throw new SecurityException(packageName + " has " + signatures.length + " signatures"); // } // byte[] cert = signatures[0].toByteArray(); // try (InputStream input = new ByteArrayInputStream(cert)) { // CertificateFactory factory = CertificateFactory.getInstance("X509"); // X509Certificate x509 = (X509Certificate) factory.generateCertificate(input); // MessageDigest md = MessageDigest.getInstance("SHA256"); // byte[] publicKey = md.digest(x509.getEncoded()); // return toHexFormat(publicKey); // } // } // // private static String toHexFormat(byte[] bytes) { // StringBuilder builder = new StringBuilder(bytes.length * 2); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(bytes[i]); // int length = hex.length(); // if (length == 1) { // hex = "0" + hex; // } // if (length > 2) { // hex = hex.substring(length - 2, length); // } // builder.append(hex.toUpperCase()); // if (i < (bytes.length - 1)) { // builder.append(':'); // } // } // return builder.toString(); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logd(String message, Object... params) { // if (logDebugEnabled()) { // Log.d(TAG, String.format(message, params)); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logw(String message, Object... params) { // Log.w(TAG, String.format(message, params)); // }
import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.example.android.autofill.service.data.source.PackageVerificationDataSource; import com.example.android.autofill.service.util.SecurityHelper; import static com.example.android.autofill.service.util.Util.logd; import static com.example.android.autofill.service.util.Util.logw;
private final Context mContext; private SharedPrefsPackageVerificationRepository(Context context) { mSharedPrefs = context.getApplicationContext() .getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE); mContext = context.getApplicationContext(); } public static PackageVerificationDataSource getInstance(Context context) { if (sInstance == null) { sInstance = new SharedPrefsPackageVerificationRepository( context.getApplicationContext()); } return sInstance; } @Override public void clear() { mSharedPrefs.edit().clear().apply(); } @Override public boolean putPackageSignatures(String packageName) { String hash; try { PackageManager pm = mContext.getPackageManager(); PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); hash = SecurityHelper.getFingerprint(packageInfo, packageName); logd("Hash for %s: %s", packageName, hash); } catch (Exception e) {
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/PackageVerificationDataSource.java // public interface PackageVerificationDataSource { // // /** // * Verifies that the signatures in the passed {@code Context} match what is currently in // * storage. If there are no current signatures in storage for this packageName, it will store // * the signatures from the passed {@code Context}. // * // * @return {@code true} if signatures for this packageName are not currently in storage // * or if the signatures in the passed {@code Context} match what is currently in storage; // * {@code false} if the signatures in the passed {@code Context} do not match what is // * currently in storage or if an {@code Exception} was thrown while generating the signatures. // */ // boolean putPackageSignatures(String packageName); // // /** // * Clears all signature data currently in storage. // */ // void clear(); // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/SecurityHelper.java // public final class SecurityHelper { // // private SecurityHelper() { // throw new UnsupportedOperationException("Provides static methods only."); // } // // /** // * Gets the fingerprint of the signed certificate of a package. // */ // public static String getFingerprint(PackageInfo packageInfo, String packageName) throws // PackageManager.NameNotFoundException, IOException, NoSuchAlgorithmException, // CertificateException { // Signature[] signatures = packageInfo.signatures; // if (signatures.length != 1) { // throw new SecurityException(packageName + " has " + signatures.length + " signatures"); // } // byte[] cert = signatures[0].toByteArray(); // try (InputStream input = new ByteArrayInputStream(cert)) { // CertificateFactory factory = CertificateFactory.getInstance("X509"); // X509Certificate x509 = (X509Certificate) factory.generateCertificate(input); // MessageDigest md = MessageDigest.getInstance("SHA256"); // byte[] publicKey = md.digest(x509.getEncoded()); // return toHexFormat(publicKey); // } // } // // private static String toHexFormat(byte[] bytes) { // StringBuilder builder = new StringBuilder(bytes.length * 2); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(bytes[i]); // int length = hex.length(); // if (length == 1) { // hex = "0" + hex; // } // if (length > 2) { // hex = hex.substring(length - 2, length); // } // builder.append(hex.toUpperCase()); // if (i < (bytes.length - 1)) { // builder.append(':'); // } // } // return builder.toString(); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logd(String message, Object... params) { // if (logDebugEnabled()) { // Log.d(TAG, String.format(message, params)); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logw(String message, Object... params) { // Log.w(TAG, String.format(message, params)); // } // Path: afservice/src/main/java/com/example/android/autofill/service/data/source/local/SharedPrefsPackageVerificationRepository.java import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.example.android.autofill.service.data.source.PackageVerificationDataSource; import com.example.android.autofill.service.util.SecurityHelper; import static com.example.android.autofill.service.util.Util.logd; import static com.example.android.autofill.service.util.Util.logw; private final Context mContext; private SharedPrefsPackageVerificationRepository(Context context) { mSharedPrefs = context.getApplicationContext() .getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE); mContext = context.getApplicationContext(); } public static PackageVerificationDataSource getInstance(Context context) { if (sInstance == null) { sInstance = new SharedPrefsPackageVerificationRepository( context.getApplicationContext()); } return sInstance; } @Override public void clear() { mSharedPrefs.edit().clear().apply(); } @Override public boolean putPackageSignatures(String packageName) { String hash; try { PackageManager pm = mContext.getPackageManager(); PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); hash = SecurityHelper.getFingerprint(packageInfo, packageName); logd("Hash for %s: %s", packageName, hash); } catch (Exception e) {
logw(e, "Error getting hash for %s.", packageName);
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/model/DalInfo.java
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/local/DigitalAssetLinksRepository.java // public static String getCanonicalDomain(String domain) { // InternetDomainName idn = InternetDomainName.from(domain); // while (idn != null && !idn.isTopPrivateDomain()) { // idn = idn.parent(); // } // return idn == null ? null : idn.toString(); // }
import static com.example.android.autofill.service.data.source.local.DigitalAssetLinksRepository.getCanonicalDomain;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.model; public class DalInfo { private final String mWebDomain; private final String mPackageName; public DalInfo(String webDomain, String packageName) {
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/local/DigitalAssetLinksRepository.java // public static String getCanonicalDomain(String domain) { // InternetDomainName idn = InternetDomainName.from(domain); // while (idn != null && !idn.isTopPrivateDomain()) { // idn = idn.parent(); // } // return idn == null ? null : idn.toString(); // } // Path: afservice/src/main/java/com/example/android/autofill/service/model/DalInfo.java import static com.example.android.autofill.service.data.source.local.DigitalAssetLinksRepository.getCanonicalDomain; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.model; public class DalInfo { private final String mWebDomain; private final String mPackageName; public DalInfo(String webDomain, String packageName) {
String canonicalDomain = getCanonicalDomain(webDomain);
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/source/DalService.java
// Path: afservice/src/main/java/com/example/android/autofill/service/model/DalCheck.java // public class DalCheck { // public boolean linked; // public String maxAge; // public String debugString; // }
import com.example.android.autofill.service.model.DalCheck; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source; public interface DalService { @GET("/v1/assetlinks:check")
// Path: afservice/src/main/java/com/example/android/autofill/service/model/DalCheck.java // public class DalCheck { // public boolean linked; // public String maxAge; // public String debugString; // } // Path: afservice/src/main/java/com/example/android/autofill/service/data/source/DalService.java import com.example.android.autofill.service.model.DalCheck; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.source; public interface DalService { @GET("/v1/assetlinks:check")
Call<DalCheck> check(@Query("source.web.site") String webDomain,
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/AutofillHintProperties.java
// Path: afservice/src/main/java/com/example/android/autofill/service/model/FilledAutofillField.java // @Entity(primaryKeys = {"datasetId", "fieldTypeName"}, foreignKeys = { // @ForeignKey(entity = AutofillDataset.class, parentColumns = "id", // childColumns = "datasetId", onDelete = ForeignKey.CASCADE), // @ForeignKey(entity = FieldType.class, parentColumns = "typeName", // childColumns = "fieldTypeName", onDelete = ForeignKey.CASCADE) // }) // public class FilledAutofillField { // // @NonNull // @ColumnInfo(name = "datasetId") // private final String mDatasetId; // // @Nullable // @ColumnInfo(name = "textValue") // private final String mTextValue; // // @Nullable // @ColumnInfo(name = "dateValue") // private final Long mDateValue; // // @Nullable // @ColumnInfo(name = "toggleValue") // private final Boolean mToggleValue; // // @NonNull // @ColumnInfo(name = "fieldTypeName") // private final String mFieldTypeName; // // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName, // @Nullable String textValue, @Nullable Long dateValue, // @Nullable Boolean toggleValue) { // mDatasetId = datasetId; // mFieldTypeName = fieldTypeName; // mTextValue = textValue; // mDateValue = dateValue; // mToggleValue = toggleValue; // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, // @NonNull String fieldTypeName, @Nullable String textValue, @Nullable Long dateValue) { // this(datasetId, fieldTypeName, textValue, dateValue, null); // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName, // @Nullable String textValue) { // this(datasetId, fieldTypeName, textValue, null, null); // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName, // @Nullable Long dateValue) { // this(datasetId, fieldTypeName, null, dateValue, null); // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName, // @Nullable Boolean toggleValue) { // this(datasetId, fieldTypeName, null, null, toggleValue); // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName) { // this(datasetId, fieldTypeName, null, null, null); // } // // @NonNull // public String getDatasetId() { // return mDatasetId; // } // // @Nullable // public String getTextValue() { // return mTextValue; // } // // @Nullable // public Long getDateValue() { // return mDateValue; // } // // @Nullable // public Boolean getToggleValue() { // return mToggleValue; // } // // @NonNull // public String getFieldTypeName() { // return mFieldTypeName; // } // // public boolean isNull() { // return mTextValue == null && mDateValue == null && mToggleValue == null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // FilledAutofillField that = (FilledAutofillField) o; // // if (mTextValue != null ? !mTextValue.equals(that.mTextValue) : that.mTextValue != null) // return false; // if (mDateValue != null ? !mDateValue.equals(that.mDateValue) : that.mDateValue != null) // return false; // if (mToggleValue != null ? !mToggleValue.equals(that.mToggleValue) : that.mToggleValue != null) // return false; // return mFieldTypeName.equals(that.mFieldTypeName); // } // // @Override // public int hashCode() { // int result = mTextValue != null ? mTextValue.hashCode() : 0; // result = 31 * result + (mDateValue != null ? mDateValue.hashCode() : 0); // result = 31 * result + (mToggleValue != null ? mToggleValue.hashCode() : 0); // result = 31 * result + mFieldTypeName.hashCode(); // return result; // } // }
import android.view.View; import com.example.android.autofill.service.model.FilledAutofillField; import java.util.Arrays; import java.util.HashSet; import java.util.Set;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service; /** * Holds the properties associated with an autofill hint in this Autofill Service. */ public final class AutofillHintProperties { private String mAutofillHint; private FakeFieldGenerator mFakeFieldGenerator; private Set<Integer> mValidTypes; private int mSaveType; private int mPartition; public AutofillHintProperties(String autofillHint, int saveType, int partitionNumber, FakeFieldGenerator fakeFieldGenerator, Integer... validTypes) { mAutofillHint = autofillHint; mSaveType = saveType; mPartition = partitionNumber; mFakeFieldGenerator = fakeFieldGenerator; mValidTypes = new HashSet<>(Arrays.asList(validTypes)); } /** * Generates dummy autofill field data that is relevant to the autofill hint. */
// Path: afservice/src/main/java/com/example/android/autofill/service/model/FilledAutofillField.java // @Entity(primaryKeys = {"datasetId", "fieldTypeName"}, foreignKeys = { // @ForeignKey(entity = AutofillDataset.class, parentColumns = "id", // childColumns = "datasetId", onDelete = ForeignKey.CASCADE), // @ForeignKey(entity = FieldType.class, parentColumns = "typeName", // childColumns = "fieldTypeName", onDelete = ForeignKey.CASCADE) // }) // public class FilledAutofillField { // // @NonNull // @ColumnInfo(name = "datasetId") // private final String mDatasetId; // // @Nullable // @ColumnInfo(name = "textValue") // private final String mTextValue; // // @Nullable // @ColumnInfo(name = "dateValue") // private final Long mDateValue; // // @Nullable // @ColumnInfo(name = "toggleValue") // private final Boolean mToggleValue; // // @NonNull // @ColumnInfo(name = "fieldTypeName") // private final String mFieldTypeName; // // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName, // @Nullable String textValue, @Nullable Long dateValue, // @Nullable Boolean toggleValue) { // mDatasetId = datasetId; // mFieldTypeName = fieldTypeName; // mTextValue = textValue; // mDateValue = dateValue; // mToggleValue = toggleValue; // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, // @NonNull String fieldTypeName, @Nullable String textValue, @Nullable Long dateValue) { // this(datasetId, fieldTypeName, textValue, dateValue, null); // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName, // @Nullable String textValue) { // this(datasetId, fieldTypeName, textValue, null, null); // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName, // @Nullable Long dateValue) { // this(datasetId, fieldTypeName, null, dateValue, null); // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName, // @Nullable Boolean toggleValue) { // this(datasetId, fieldTypeName, null, null, toggleValue); // } // // @Ignore // public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName) { // this(datasetId, fieldTypeName, null, null, null); // } // // @NonNull // public String getDatasetId() { // return mDatasetId; // } // // @Nullable // public String getTextValue() { // return mTextValue; // } // // @Nullable // public Long getDateValue() { // return mDateValue; // } // // @Nullable // public Boolean getToggleValue() { // return mToggleValue; // } // // @NonNull // public String getFieldTypeName() { // return mFieldTypeName; // } // // public boolean isNull() { // return mTextValue == null && mDateValue == null && mToggleValue == null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // FilledAutofillField that = (FilledAutofillField) o; // // if (mTextValue != null ? !mTextValue.equals(that.mTextValue) : that.mTextValue != null) // return false; // if (mDateValue != null ? !mDateValue.equals(that.mDateValue) : that.mDateValue != null) // return false; // if (mToggleValue != null ? !mToggleValue.equals(that.mToggleValue) : that.mToggleValue != null) // return false; // return mFieldTypeName.equals(that.mFieldTypeName); // } // // @Override // public int hashCode() { // int result = mTextValue != null ? mTextValue.hashCode() : 0; // result = 31 * result + (mDateValue != null ? mDateValue.hashCode() : 0); // result = 31 * result + (mToggleValue != null ? mToggleValue.hashCode() : 0); // result = 31 * result + mFieldTypeName.hashCode(); // return result; // } // } // Path: afservice/src/main/java/com/example/android/autofill/service/AutofillHintProperties.java import android.view.View; import com.example.android.autofill.service.model.FilledAutofillField; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service; /** * Holds the properties associated with an autofill hint in this Autofill Service. */ public final class AutofillHintProperties { private String mAutofillHint; private FakeFieldGenerator mFakeFieldGenerator; private Set<Integer> mValidTypes; private int mSaveType; private int mPartition; public AutofillHintProperties(String autofillHint, int saveType, int partitionNumber, FakeFieldGenerator fakeFieldGenerator, Integer... validTypes) { mAutofillHint = autofillHint; mSaveType = saveType; mPartition = partitionNumber; mFakeFieldGenerator = fakeFieldGenerator; mValidTypes = new HashSet<>(Arrays.asList(validTypes)); } /** * Generates dummy autofill field data that is relevant to the autofill hint. */
public FilledAutofillField generateFakeField(int seed, String datasetId) {
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/model/FieldType.java
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/local/db/Converters.java // public static class IntList { // public final List<Integer> ints; // // public IntList(List<Integer> ints) { // this.ints = ints; // } // }
import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Embedded; import android.arch.persistence.room.Entity; import android.support.annotation.NonNull; import static com.example.android.autofill.service.data.source.local.db.Converters.IntList;
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.model; @Entity(primaryKeys = {"typeName"}) public class FieldType { @NonNull @ColumnInfo(name = "typeName") private final String mTypeName; @NonNull @ColumnInfo(name = "autofillTypes")
// Path: afservice/src/main/java/com/example/android/autofill/service/data/source/local/db/Converters.java // public static class IntList { // public final List<Integer> ints; // // public IntList(List<Integer> ints) { // this.ints = ints; // } // } // Path: afservice/src/main/java/com/example/android/autofill/service/model/FieldType.java import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Embedded; import android.arch.persistence.room.Entity; import android.support.annotation.NonNull; import static com.example.android.autofill.service.data.source.local.db.Converters.IntList; /* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.model; @Entity(primaryKeys = {"typeName"}) public class FieldType { @NonNull @ColumnInfo(name = "typeName") private final String mTypeName; @NonNull @ColumnInfo(name = "autofillTypes")
private final IntList mAutofillTypes;
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/ClientViewMetadataBuilder.java
// Path: afservice/src/main/java/com/example/android/autofill/service/ClientParser.java // public final class ClientParser { // private final List<AssistStructure> mStructures; // // public ClientParser(@NonNull List<AssistStructure> structures) { // Preconditions.checkNotNull(structures); // mStructures = structures; // } // // public ClientParser(@NonNull AssistStructure structure) { // this(ImmutableList.of(structure)); // } // // /** // * Traverses through the {@link AssistStructure} and does something at each {@link ViewNode}. // * // * @param processor contains action to be performed on each {@link ViewNode}. // */ // public void parse(NodeProcessor processor) { // for (AssistStructure structure : mStructures) { // int nodes = structure.getWindowNodeCount(); // for (int i = 0; i < nodes; i++) { // AssistStructure.ViewNode viewNode = structure.getWindowNodeAt(i).getRootViewNode(); // traverseRoot(viewNode, processor); // } // } // } // // private void traverseRoot(AssistStructure.ViewNode viewNode, NodeProcessor processor) { // processor.processNode(viewNode); // int childrenSize = viewNode.getChildCount(); // if (childrenSize > 0) { // for (int i = 0; i < childrenSize; i++) { // traverseRoot(viewNode.getChildAt(i), processor); // } // } // } // // public interface NodeProcessor { // void processNode(ViewNode node); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/FieldType.java // @Entity(primaryKeys = {"typeName"}) // public class FieldType { // @NonNull // @ColumnInfo(name = "typeName") // private final String mTypeName; // // @NonNull // @ColumnInfo(name = "autofillTypes") // private final IntList mAutofillTypes; // // @NonNull // @ColumnInfo(name = "saveInfo") // private final Integer mSaveInfo; // // @NonNull // @ColumnInfo(name = "partition") // private final Integer mPartition; // // @NonNull // @Embedded // private final FakeData mFakeData; // // public FieldType(@NonNull String typeName, @NonNull IntList autofillTypes, // @NonNull Integer saveInfo, @NonNull Integer partition, @NonNull FakeData fakeData) { // mTypeName = typeName; // mAutofillTypes = autofillTypes; // mSaveInfo = saveInfo; // mPartition = partition; // mFakeData = fakeData; // } // // @NonNull // public String getTypeName() { // return mTypeName; // } // // @NonNull // public IntList getAutofillTypes() { // return mAutofillTypes; // } // // @NonNull // public Integer getSaveInfo() { // return mSaveInfo; // } // // @NonNull // public Integer getPartition() { // return mPartition; // } // // @NonNull // public FakeData getFakeData() { // return mFakeData; // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/FieldTypeWithHeuristics.java // public class FieldTypeWithHeuristics { // @Embedded // public FieldType fieldType; // // @Relation(parentColumn = "typeName", entityColumn = "fieldTypeName", entity = AutofillHint.class) // public List<AutofillHint> autofillHints; // // @Relation(parentColumn = "typeName", entityColumn = "fieldTypeName", entity = ResourceIdHeuristic.class) // public List<ResourceIdHeuristic> resourceIdHeuristics; // // public FieldType getFieldType() { // return fieldType; // } // // public List<AutofillHint> getAutofillHints() { // return autofillHints; // } // // public List<ResourceIdHeuristic> getResourceIdHeuristics() { // return resourceIdHeuristics; // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logd(String message, Object... params) { // if (logDebugEnabled()) { // Log.d(TAG, String.format(message, params)); // } // }
import android.app.assist.AssistStructure; import android.util.MutableInt; import android.view.autofill.AutofillId; import com.example.android.autofill.service.ClientParser; import com.example.android.autofill.service.model.FieldType; import com.example.android.autofill.service.model.FieldTypeWithHeuristics; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.example.android.autofill.service.util.Util.logd;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data; public class ClientViewMetadataBuilder { private ClientParser mClientParser;
// Path: afservice/src/main/java/com/example/android/autofill/service/ClientParser.java // public final class ClientParser { // private final List<AssistStructure> mStructures; // // public ClientParser(@NonNull List<AssistStructure> structures) { // Preconditions.checkNotNull(structures); // mStructures = structures; // } // // public ClientParser(@NonNull AssistStructure structure) { // this(ImmutableList.of(structure)); // } // // /** // * Traverses through the {@link AssistStructure} and does something at each {@link ViewNode}. // * // * @param processor contains action to be performed on each {@link ViewNode}. // */ // public void parse(NodeProcessor processor) { // for (AssistStructure structure : mStructures) { // int nodes = structure.getWindowNodeCount(); // for (int i = 0; i < nodes; i++) { // AssistStructure.ViewNode viewNode = structure.getWindowNodeAt(i).getRootViewNode(); // traverseRoot(viewNode, processor); // } // } // } // // private void traverseRoot(AssistStructure.ViewNode viewNode, NodeProcessor processor) { // processor.processNode(viewNode); // int childrenSize = viewNode.getChildCount(); // if (childrenSize > 0) { // for (int i = 0; i < childrenSize; i++) { // traverseRoot(viewNode.getChildAt(i), processor); // } // } // } // // public interface NodeProcessor { // void processNode(ViewNode node); // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/FieldType.java // @Entity(primaryKeys = {"typeName"}) // public class FieldType { // @NonNull // @ColumnInfo(name = "typeName") // private final String mTypeName; // // @NonNull // @ColumnInfo(name = "autofillTypes") // private final IntList mAutofillTypes; // // @NonNull // @ColumnInfo(name = "saveInfo") // private final Integer mSaveInfo; // // @NonNull // @ColumnInfo(name = "partition") // private final Integer mPartition; // // @NonNull // @Embedded // private final FakeData mFakeData; // // public FieldType(@NonNull String typeName, @NonNull IntList autofillTypes, // @NonNull Integer saveInfo, @NonNull Integer partition, @NonNull FakeData fakeData) { // mTypeName = typeName; // mAutofillTypes = autofillTypes; // mSaveInfo = saveInfo; // mPartition = partition; // mFakeData = fakeData; // } // // @NonNull // public String getTypeName() { // return mTypeName; // } // // @NonNull // public IntList getAutofillTypes() { // return mAutofillTypes; // } // // @NonNull // public Integer getSaveInfo() { // return mSaveInfo; // } // // @NonNull // public Integer getPartition() { // return mPartition; // } // // @NonNull // public FakeData getFakeData() { // return mFakeData; // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/model/FieldTypeWithHeuristics.java // public class FieldTypeWithHeuristics { // @Embedded // public FieldType fieldType; // // @Relation(parentColumn = "typeName", entityColumn = "fieldTypeName", entity = AutofillHint.class) // public List<AutofillHint> autofillHints; // // @Relation(parentColumn = "typeName", entityColumn = "fieldTypeName", entity = ResourceIdHeuristic.class) // public List<ResourceIdHeuristic> resourceIdHeuristics; // // public FieldType getFieldType() { // return fieldType; // } // // public List<AutofillHint> getAutofillHints() { // return autofillHints; // } // // public List<ResourceIdHeuristic> getResourceIdHeuristics() { // return resourceIdHeuristics; // } // } // // Path: afservice/src/main/java/com/example/android/autofill/service/util/Util.java // public static void logd(String message, Object... params) { // if (logDebugEnabled()) { // Log.d(TAG, String.format(message, params)); // } // } // Path: afservice/src/main/java/com/example/android/autofill/service/data/ClientViewMetadataBuilder.java import android.app.assist.AssistStructure; import android.util.MutableInt; import android.view.autofill.AutofillId; import com.example.android.autofill.service.ClientParser; import com.example.android.autofill.service.model.FieldType; import com.example.android.autofill.service.model.FieldTypeWithHeuristics; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.example.android.autofill.service.util.Util.logd; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data; public class ClientViewMetadataBuilder { private ClientParser mClientParser;
private HashMap<String, FieldTypeWithHeuristics> mFieldTypesByAutofillHint;
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/item/IPv4CIDRACLItem.java
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemMethod.java // public enum ACLItemMethod { // DIRECT, // PROXY, // REJECT // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemType.java // public enum ACLItemType { // DOMAIN, // DOMAIN_SUFFIX, // IPv4, // IPv4_CIDR, // IPv6, // IPv6_CIDR // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // }
import com.vecsight.dragonite.proxy.acl.ACLItemMethod; import com.vecsight.dragonite.proxy.acl.ACLItemType; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.net.InetAddress; import java.net.UnknownHostException;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.acl.item; public class IPv4CIDRACLItem implements ACLItem { private final int lowest; private final int highest;
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemMethod.java // public enum ACLItemMethod { // DIRECT, // PROXY, // REJECT // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemType.java // public enum ACLItemType { // DOMAIN, // DOMAIN_SUFFIX, // IPv4, // IPv4_CIDR, // IPv6, // IPv6_CIDR // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // } // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/item/IPv4CIDRACLItem.java import com.vecsight.dragonite.proxy.acl.ACLItemMethod; import com.vecsight.dragonite.proxy.acl.ACLItemType; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.net.InetAddress; import java.net.UnknownHostException; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.acl.item; public class IPv4CIDRACLItem implements ACLItem { private final int lowest; private final int highest;
private final ACLItemMethod method;
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/item/IPv4CIDRACLItem.java
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemMethod.java // public enum ACLItemMethod { // DIRECT, // PROXY, // REJECT // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemType.java // public enum ACLItemType { // DOMAIN, // DOMAIN_SUFFIX, // IPv4, // IPv4_CIDR, // IPv6, // IPv6_CIDR // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // }
import com.vecsight.dragonite.proxy.acl.ACLItemMethod; import com.vecsight.dragonite.proxy.acl.ACLItemType; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.net.InetAddress; import java.net.UnknownHostException;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.acl.item; public class IPv4CIDRACLItem implements ACLItem { private final int lowest; private final int highest; private final ACLItemMethod method;
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemMethod.java // public enum ACLItemMethod { // DIRECT, // PROXY, // REJECT // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemType.java // public enum ACLItemType { // DOMAIN, // DOMAIN_SUFFIX, // IPv4, // IPv4_CIDR, // IPv6, // IPv6_CIDR // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // } // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/item/IPv4CIDRACLItem.java import com.vecsight.dragonite.proxy.acl.ACLItemMethod; import com.vecsight.dragonite.proxy.acl.ACLItemType; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.net.InetAddress; import java.net.UnknownHostException; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.acl.item; public class IPv4CIDRACLItem implements ACLItem { private final int lowest; private final int highest; private final ACLItemMethod method;
public IPv4CIDRACLItem(final String string, final ACLItemMethod method) throws InvalidAddressException {
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/item/IPv4CIDRACLItem.java
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemMethod.java // public enum ACLItemMethod { // DIRECT, // PROXY, // REJECT // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemType.java // public enum ACLItemType { // DOMAIN, // DOMAIN_SUFFIX, // IPv4, // IPv4_CIDR, // IPv6, // IPv6_CIDR // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // }
import com.vecsight.dragonite.proxy.acl.ACLItemMethod; import com.vecsight.dragonite.proxy.acl.ACLItemType; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.net.InetAddress; import java.net.UnknownHostException;
} final int mask; try { final int shift = Integer.parseInt(stringSplit[1]); if (shift < 1 || shift > 32) throw new InvalidAddressException(string + " is not a valid IPv4 CIDR address"); mask = (-1) << (32 - shift); } catch (final NumberFormatException e) { throw new InvalidAddressException(string + " is not a valid IPv4 CIDR address"); } final int addr = ipv4ToInt(bytes); lowest = addr & mask; highest = lowest + (~mask); } private int ipv4ToInt(final byte[] bytes) { return ((bytes[0] << 24) & 0xFF000000) | ((bytes[1] << 16) & 0xFF0000) | ((bytes[2] << 8) & 0xFF00) | (bytes[3] & 0xFF); } @Override
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemMethod.java // public enum ACLItemMethod { // DIRECT, // PROXY, // REJECT // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLItemType.java // public enum ACLItemType { // DOMAIN, // DOMAIN_SUFFIX, // IPv4, // IPv4_CIDR, // IPv6, // IPv6_CIDR // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // } // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/item/IPv4CIDRACLItem.java import com.vecsight.dragonite.proxy.acl.ACLItemMethod; import com.vecsight.dragonite.proxy.acl.ACLItemType; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.net.InetAddress; import java.net.UnknownHostException; } final int mask; try { final int shift = Integer.parseInt(stringSplit[1]); if (shift < 1 || shift > 32) throw new InvalidAddressException(string + " is not a valid IPv4 CIDR address"); mask = (-1) << (32 - shift); } catch (final NumberFormatException e) { throw new InvalidAddressException(string + " is not a valid IPv4 CIDR address"); } final int addr = ipv4ToInt(bytes); lowest = addr & mask; highest = lowest + (~mask); } private int ipv4ToInt(final byte[] bytes) { return ((bytes[0] << 24) & 0xFF000000) | ((bytes[1] << 16) & 0xFF0000) | ((bytes[2] << 8) & 0xFF00) | (bytes[3] & 0xFF); } @Override
public ACLItemType getType() {
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/mux/MuxConnectionRequestHeader.java
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/IncorrectHeaderException.java // public class IncorrectHeaderException extends Exception { // // public IncorrectHeaderException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/AddressType.java // public enum AddressType { // IPv4((byte) 0), // IPv6((byte) 1), // DOMAIN((byte) 2); // // private final byte value; // // AddressType(final byte value) { // this.value = value; // } // // public byte getValue() { // return value; // } // // private static final AddressType[] types = AddressType.values(); // // public static AddressType fromByte(final byte type) { // try { // return types[type]; // } catch (final ArrayIndexOutOfBoundsException e) { // throw new IllegalArgumentException("Type byte " + type + " not found"); // } // } // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryReader.java // public class BinaryReader { // // private final ByteBuffer byteBuffer; // // public BinaryReader(final byte[] bytes) { // byteBuffer = ByteBuffer.wrap(bytes); // } // // public byte getSignedByte() { // return byteBuffer.get(); // } // // public short getUnsignedByte() { // return (short) (byteBuffer.get() & (short) 0xff); // } // // public short getSignedShort() { // return byteBuffer.getShort(); // } // // public int getUnsignedShort() { // return byteBuffer.getShort() & 0xffff; // } // // public int getSignedInt() { // return byteBuffer.getInt(); // } // // public long getUnsignedInt() { // return (long) byteBuffer.getInt() & 0xffffffffL; // } // // public void getBytes(final byte[] bytes) { // byteBuffer.get(bytes); // } // // public byte[] getBytesGroupWithByteLength() { // final short len = getUnsignedByte(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public byte[] getBytesGroupWithShortLength() { // final int len = getUnsignedShort(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public boolean getBoolean() { // return byteBuffer.get() != 0; // } // // public int remaining() { // return byteBuffer.remaining(); // } // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryWriter.java // public class BinaryWriter { // // private final ByteBuffer byteBuffer; // // public BinaryWriter(final int capacity) { // byteBuffer = ByteBuffer.allocate(capacity); // } // // public BinaryWriter putSignedByte(final byte sb) { // byteBuffer.put(sb); // return this; // } // // public BinaryWriter putUnsignedByte(final short ub) { // byteBuffer.put((byte) (ub & 0xff)); // return this; // } // // public BinaryWriter putSignedShort(final short ss) { // byteBuffer.putShort(ss); // return this; // } // // public BinaryWriter putUnsignedShort(final int us) { // byteBuffer.putShort((short) (us & 0xffff)); // return this; // } // // public BinaryWriter putSignedInt(final int si) { // byteBuffer.putInt(si); // return this; // } // // public BinaryWriter putUnsignedInt(final long ui) { // byteBuffer.putInt((int) (ui & 0xffffffffL)); // return this; // } // // public BinaryWriter putBytes(final byte[] bytes) { // byteBuffer.put(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithByteLength(final byte[] bytes) { // putUnsignedByte((short) bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithShortLength(final byte[] bytes) { // putUnsignedShort(bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBoolean(final boolean b) { // byteBuffer.put((byte) (b ? 1 : 0)); // return this; // } // // public byte[] toBytes() { // return byteBuffer.array(); // } // // }
import com.vecsight.dragonite.proxy.exception.IncorrectHeaderException; import com.vecsight.dragonite.proxy.header.AddressType; import com.vecsight.dragonite.utils.binary.BinaryReader; import com.vecsight.dragonite.utils.binary.BinaryWriter; import java.nio.BufferUnderflowException;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.header.mux; /* * addrType 1 SB * addr [4B/16B/1+length] * port 2 US * UDP mode 1 BOOL */ public class MuxConnectionRequestHeader { private AddressType type; private byte[] addr; private int port; private boolean udpMode; public MuxConnectionRequestHeader(final AddressType type, final byte[] addr, final int port, final boolean udpMode) { this.type = type; this.addr = addr; this.port = port; this.udpMode = udpMode; }
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/IncorrectHeaderException.java // public class IncorrectHeaderException extends Exception { // // public IncorrectHeaderException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/AddressType.java // public enum AddressType { // IPv4((byte) 0), // IPv6((byte) 1), // DOMAIN((byte) 2); // // private final byte value; // // AddressType(final byte value) { // this.value = value; // } // // public byte getValue() { // return value; // } // // private static final AddressType[] types = AddressType.values(); // // public static AddressType fromByte(final byte type) { // try { // return types[type]; // } catch (final ArrayIndexOutOfBoundsException e) { // throw new IllegalArgumentException("Type byte " + type + " not found"); // } // } // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryReader.java // public class BinaryReader { // // private final ByteBuffer byteBuffer; // // public BinaryReader(final byte[] bytes) { // byteBuffer = ByteBuffer.wrap(bytes); // } // // public byte getSignedByte() { // return byteBuffer.get(); // } // // public short getUnsignedByte() { // return (short) (byteBuffer.get() & (short) 0xff); // } // // public short getSignedShort() { // return byteBuffer.getShort(); // } // // public int getUnsignedShort() { // return byteBuffer.getShort() & 0xffff; // } // // public int getSignedInt() { // return byteBuffer.getInt(); // } // // public long getUnsignedInt() { // return (long) byteBuffer.getInt() & 0xffffffffL; // } // // public void getBytes(final byte[] bytes) { // byteBuffer.get(bytes); // } // // public byte[] getBytesGroupWithByteLength() { // final short len = getUnsignedByte(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public byte[] getBytesGroupWithShortLength() { // final int len = getUnsignedShort(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public boolean getBoolean() { // return byteBuffer.get() != 0; // } // // public int remaining() { // return byteBuffer.remaining(); // } // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryWriter.java // public class BinaryWriter { // // private final ByteBuffer byteBuffer; // // public BinaryWriter(final int capacity) { // byteBuffer = ByteBuffer.allocate(capacity); // } // // public BinaryWriter putSignedByte(final byte sb) { // byteBuffer.put(sb); // return this; // } // // public BinaryWriter putUnsignedByte(final short ub) { // byteBuffer.put((byte) (ub & 0xff)); // return this; // } // // public BinaryWriter putSignedShort(final short ss) { // byteBuffer.putShort(ss); // return this; // } // // public BinaryWriter putUnsignedShort(final int us) { // byteBuffer.putShort((short) (us & 0xffff)); // return this; // } // // public BinaryWriter putSignedInt(final int si) { // byteBuffer.putInt(si); // return this; // } // // public BinaryWriter putUnsignedInt(final long ui) { // byteBuffer.putInt((int) (ui & 0xffffffffL)); // return this; // } // // public BinaryWriter putBytes(final byte[] bytes) { // byteBuffer.put(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithByteLength(final byte[] bytes) { // putUnsignedByte((short) bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithShortLength(final byte[] bytes) { // putUnsignedShort(bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBoolean(final boolean b) { // byteBuffer.put((byte) (b ? 1 : 0)); // return this; // } // // public byte[] toBytes() { // return byteBuffer.array(); // } // // } // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/mux/MuxConnectionRequestHeader.java import com.vecsight.dragonite.proxy.exception.IncorrectHeaderException; import com.vecsight.dragonite.proxy.header.AddressType; import com.vecsight.dragonite.utils.binary.BinaryReader; import com.vecsight.dragonite.utils.binary.BinaryWriter; import java.nio.BufferUnderflowException; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.header.mux; /* * addrType 1 SB * addr [4B/16B/1+length] * port 2 US * UDP mode 1 BOOL */ public class MuxConnectionRequestHeader { private AddressType type; private byte[] addr; private int port; private boolean udpMode; public MuxConnectionRequestHeader(final AddressType type, final byte[] addr, final int port, final boolean udpMode) { this.type = type; this.addr = addr; this.port = port; this.udpMode = udpMode; }
public MuxConnectionRequestHeader(final byte[] header) throws IncorrectHeaderException {
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/mux/MuxConnectionRequestHeader.java
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/IncorrectHeaderException.java // public class IncorrectHeaderException extends Exception { // // public IncorrectHeaderException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/AddressType.java // public enum AddressType { // IPv4((byte) 0), // IPv6((byte) 1), // DOMAIN((byte) 2); // // private final byte value; // // AddressType(final byte value) { // this.value = value; // } // // public byte getValue() { // return value; // } // // private static final AddressType[] types = AddressType.values(); // // public static AddressType fromByte(final byte type) { // try { // return types[type]; // } catch (final ArrayIndexOutOfBoundsException e) { // throw new IllegalArgumentException("Type byte " + type + " not found"); // } // } // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryReader.java // public class BinaryReader { // // private final ByteBuffer byteBuffer; // // public BinaryReader(final byte[] bytes) { // byteBuffer = ByteBuffer.wrap(bytes); // } // // public byte getSignedByte() { // return byteBuffer.get(); // } // // public short getUnsignedByte() { // return (short) (byteBuffer.get() & (short) 0xff); // } // // public short getSignedShort() { // return byteBuffer.getShort(); // } // // public int getUnsignedShort() { // return byteBuffer.getShort() & 0xffff; // } // // public int getSignedInt() { // return byteBuffer.getInt(); // } // // public long getUnsignedInt() { // return (long) byteBuffer.getInt() & 0xffffffffL; // } // // public void getBytes(final byte[] bytes) { // byteBuffer.get(bytes); // } // // public byte[] getBytesGroupWithByteLength() { // final short len = getUnsignedByte(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public byte[] getBytesGroupWithShortLength() { // final int len = getUnsignedShort(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public boolean getBoolean() { // return byteBuffer.get() != 0; // } // // public int remaining() { // return byteBuffer.remaining(); // } // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryWriter.java // public class BinaryWriter { // // private final ByteBuffer byteBuffer; // // public BinaryWriter(final int capacity) { // byteBuffer = ByteBuffer.allocate(capacity); // } // // public BinaryWriter putSignedByte(final byte sb) { // byteBuffer.put(sb); // return this; // } // // public BinaryWriter putUnsignedByte(final short ub) { // byteBuffer.put((byte) (ub & 0xff)); // return this; // } // // public BinaryWriter putSignedShort(final short ss) { // byteBuffer.putShort(ss); // return this; // } // // public BinaryWriter putUnsignedShort(final int us) { // byteBuffer.putShort((short) (us & 0xffff)); // return this; // } // // public BinaryWriter putSignedInt(final int si) { // byteBuffer.putInt(si); // return this; // } // // public BinaryWriter putUnsignedInt(final long ui) { // byteBuffer.putInt((int) (ui & 0xffffffffL)); // return this; // } // // public BinaryWriter putBytes(final byte[] bytes) { // byteBuffer.put(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithByteLength(final byte[] bytes) { // putUnsignedByte((short) bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithShortLength(final byte[] bytes) { // putUnsignedShort(bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBoolean(final boolean b) { // byteBuffer.put((byte) (b ? 1 : 0)); // return this; // } // // public byte[] toBytes() { // return byteBuffer.array(); // } // // }
import com.vecsight.dragonite.proxy.exception.IncorrectHeaderException; import com.vecsight.dragonite.proxy.header.AddressType; import com.vecsight.dragonite.utils.binary.BinaryReader; import com.vecsight.dragonite.utils.binary.BinaryWriter; import java.nio.BufferUnderflowException;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.header.mux; /* * addrType 1 SB * addr [4B/16B/1+length] * port 2 US * UDP mode 1 BOOL */ public class MuxConnectionRequestHeader { private AddressType type; private byte[] addr; private int port; private boolean udpMode; public MuxConnectionRequestHeader(final AddressType type, final byte[] addr, final int port, final boolean udpMode) { this.type = type; this.addr = addr; this.port = port; this.udpMode = udpMode; } public MuxConnectionRequestHeader(final byte[] header) throws IncorrectHeaderException {
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/IncorrectHeaderException.java // public class IncorrectHeaderException extends Exception { // // public IncorrectHeaderException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/AddressType.java // public enum AddressType { // IPv4((byte) 0), // IPv6((byte) 1), // DOMAIN((byte) 2); // // private final byte value; // // AddressType(final byte value) { // this.value = value; // } // // public byte getValue() { // return value; // } // // private static final AddressType[] types = AddressType.values(); // // public static AddressType fromByte(final byte type) { // try { // return types[type]; // } catch (final ArrayIndexOutOfBoundsException e) { // throw new IllegalArgumentException("Type byte " + type + " not found"); // } // } // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryReader.java // public class BinaryReader { // // private final ByteBuffer byteBuffer; // // public BinaryReader(final byte[] bytes) { // byteBuffer = ByteBuffer.wrap(bytes); // } // // public byte getSignedByte() { // return byteBuffer.get(); // } // // public short getUnsignedByte() { // return (short) (byteBuffer.get() & (short) 0xff); // } // // public short getSignedShort() { // return byteBuffer.getShort(); // } // // public int getUnsignedShort() { // return byteBuffer.getShort() & 0xffff; // } // // public int getSignedInt() { // return byteBuffer.getInt(); // } // // public long getUnsignedInt() { // return (long) byteBuffer.getInt() & 0xffffffffL; // } // // public void getBytes(final byte[] bytes) { // byteBuffer.get(bytes); // } // // public byte[] getBytesGroupWithByteLength() { // final short len = getUnsignedByte(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public byte[] getBytesGroupWithShortLength() { // final int len = getUnsignedShort(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public boolean getBoolean() { // return byteBuffer.get() != 0; // } // // public int remaining() { // return byteBuffer.remaining(); // } // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryWriter.java // public class BinaryWriter { // // private final ByteBuffer byteBuffer; // // public BinaryWriter(final int capacity) { // byteBuffer = ByteBuffer.allocate(capacity); // } // // public BinaryWriter putSignedByte(final byte sb) { // byteBuffer.put(sb); // return this; // } // // public BinaryWriter putUnsignedByte(final short ub) { // byteBuffer.put((byte) (ub & 0xff)); // return this; // } // // public BinaryWriter putSignedShort(final short ss) { // byteBuffer.putShort(ss); // return this; // } // // public BinaryWriter putUnsignedShort(final int us) { // byteBuffer.putShort((short) (us & 0xffff)); // return this; // } // // public BinaryWriter putSignedInt(final int si) { // byteBuffer.putInt(si); // return this; // } // // public BinaryWriter putUnsignedInt(final long ui) { // byteBuffer.putInt((int) (ui & 0xffffffffL)); // return this; // } // // public BinaryWriter putBytes(final byte[] bytes) { // byteBuffer.put(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithByteLength(final byte[] bytes) { // putUnsignedByte((short) bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithShortLength(final byte[] bytes) { // putUnsignedShort(bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBoolean(final boolean b) { // byteBuffer.put((byte) (b ? 1 : 0)); // return this; // } // // public byte[] toBytes() { // return byteBuffer.array(); // } // // } // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/mux/MuxConnectionRequestHeader.java import com.vecsight.dragonite.proxy.exception.IncorrectHeaderException; import com.vecsight.dragonite.proxy.header.AddressType; import com.vecsight.dragonite.utils.binary.BinaryReader; import com.vecsight.dragonite.utils.binary.BinaryWriter; import java.nio.BufferUnderflowException; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.header.mux; /* * addrType 1 SB * addr [4B/16B/1+length] * port 2 US * UDP mode 1 BOOL */ public class MuxConnectionRequestHeader { private AddressType type; private byte[] addr; private int port; private boolean udpMode; public MuxConnectionRequestHeader(final AddressType type, final byte[] addr, final int port, final boolean udpMode) { this.type = type; this.addr = addr; this.port = port; this.udpMode = udpMode; } public MuxConnectionRequestHeader(final byte[] header) throws IncorrectHeaderException {
final BinaryReader reader = new BinaryReader(header);
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/mux/MuxConnectionRequestHeader.java
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/IncorrectHeaderException.java // public class IncorrectHeaderException extends Exception { // // public IncorrectHeaderException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/AddressType.java // public enum AddressType { // IPv4((byte) 0), // IPv6((byte) 1), // DOMAIN((byte) 2); // // private final byte value; // // AddressType(final byte value) { // this.value = value; // } // // public byte getValue() { // return value; // } // // private static final AddressType[] types = AddressType.values(); // // public static AddressType fromByte(final byte type) { // try { // return types[type]; // } catch (final ArrayIndexOutOfBoundsException e) { // throw new IllegalArgumentException("Type byte " + type + " not found"); // } // } // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryReader.java // public class BinaryReader { // // private final ByteBuffer byteBuffer; // // public BinaryReader(final byte[] bytes) { // byteBuffer = ByteBuffer.wrap(bytes); // } // // public byte getSignedByte() { // return byteBuffer.get(); // } // // public short getUnsignedByte() { // return (short) (byteBuffer.get() & (short) 0xff); // } // // public short getSignedShort() { // return byteBuffer.getShort(); // } // // public int getUnsignedShort() { // return byteBuffer.getShort() & 0xffff; // } // // public int getSignedInt() { // return byteBuffer.getInt(); // } // // public long getUnsignedInt() { // return (long) byteBuffer.getInt() & 0xffffffffL; // } // // public void getBytes(final byte[] bytes) { // byteBuffer.get(bytes); // } // // public byte[] getBytesGroupWithByteLength() { // final short len = getUnsignedByte(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public byte[] getBytesGroupWithShortLength() { // final int len = getUnsignedShort(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public boolean getBoolean() { // return byteBuffer.get() != 0; // } // // public int remaining() { // return byteBuffer.remaining(); // } // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryWriter.java // public class BinaryWriter { // // private final ByteBuffer byteBuffer; // // public BinaryWriter(final int capacity) { // byteBuffer = ByteBuffer.allocate(capacity); // } // // public BinaryWriter putSignedByte(final byte sb) { // byteBuffer.put(sb); // return this; // } // // public BinaryWriter putUnsignedByte(final short ub) { // byteBuffer.put((byte) (ub & 0xff)); // return this; // } // // public BinaryWriter putSignedShort(final short ss) { // byteBuffer.putShort(ss); // return this; // } // // public BinaryWriter putUnsignedShort(final int us) { // byteBuffer.putShort((short) (us & 0xffff)); // return this; // } // // public BinaryWriter putSignedInt(final int si) { // byteBuffer.putInt(si); // return this; // } // // public BinaryWriter putUnsignedInt(final long ui) { // byteBuffer.putInt((int) (ui & 0xffffffffL)); // return this; // } // // public BinaryWriter putBytes(final byte[] bytes) { // byteBuffer.put(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithByteLength(final byte[] bytes) { // putUnsignedByte((short) bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithShortLength(final byte[] bytes) { // putUnsignedShort(bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBoolean(final boolean b) { // byteBuffer.put((byte) (b ? 1 : 0)); // return this; // } // // public byte[] toBytes() { // return byteBuffer.array(); // } // // }
import com.vecsight.dragonite.proxy.exception.IncorrectHeaderException; import com.vecsight.dragonite.proxy.header.AddressType; import com.vecsight.dragonite.utils.binary.BinaryReader; import com.vecsight.dragonite.utils.binary.BinaryWriter; import java.nio.BufferUnderflowException;
this.type = type; } public byte[] getAddr() { return addr; } public void setAddr(final byte[] addr) { this.addr = addr; } public int getPort() { return port; } public void setPort(final int port) { this.port = port; } public boolean isUdpMode() { return udpMode; } public void setUdpMode(final boolean udpMode) { this.udpMode = udpMode; } public byte[] toBytes() { final int addrTotalLength = (type == AddressType.IPv4 ? 4 : (type == AddressType.IPv6 ? 16 : 1 + addr.length));
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/IncorrectHeaderException.java // public class IncorrectHeaderException extends Exception { // // public IncorrectHeaderException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/AddressType.java // public enum AddressType { // IPv4((byte) 0), // IPv6((byte) 1), // DOMAIN((byte) 2); // // private final byte value; // // AddressType(final byte value) { // this.value = value; // } // // public byte getValue() { // return value; // } // // private static final AddressType[] types = AddressType.values(); // // public static AddressType fromByte(final byte type) { // try { // return types[type]; // } catch (final ArrayIndexOutOfBoundsException e) { // throw new IllegalArgumentException("Type byte " + type + " not found"); // } // } // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryReader.java // public class BinaryReader { // // private final ByteBuffer byteBuffer; // // public BinaryReader(final byte[] bytes) { // byteBuffer = ByteBuffer.wrap(bytes); // } // // public byte getSignedByte() { // return byteBuffer.get(); // } // // public short getUnsignedByte() { // return (short) (byteBuffer.get() & (short) 0xff); // } // // public short getSignedShort() { // return byteBuffer.getShort(); // } // // public int getUnsignedShort() { // return byteBuffer.getShort() & 0xffff; // } // // public int getSignedInt() { // return byteBuffer.getInt(); // } // // public long getUnsignedInt() { // return (long) byteBuffer.getInt() & 0xffffffffL; // } // // public void getBytes(final byte[] bytes) { // byteBuffer.get(bytes); // } // // public byte[] getBytesGroupWithByteLength() { // final short len = getUnsignedByte(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public byte[] getBytesGroupWithShortLength() { // final int len = getUnsignedShort(); // final byte[] bytes = new byte[len]; // byteBuffer.get(bytes); // return bytes; // } // // public boolean getBoolean() { // return byteBuffer.get() != 0; // } // // public int remaining() { // return byteBuffer.remaining(); // } // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/binary/BinaryWriter.java // public class BinaryWriter { // // private final ByteBuffer byteBuffer; // // public BinaryWriter(final int capacity) { // byteBuffer = ByteBuffer.allocate(capacity); // } // // public BinaryWriter putSignedByte(final byte sb) { // byteBuffer.put(sb); // return this; // } // // public BinaryWriter putUnsignedByte(final short ub) { // byteBuffer.put((byte) (ub & 0xff)); // return this; // } // // public BinaryWriter putSignedShort(final short ss) { // byteBuffer.putShort(ss); // return this; // } // // public BinaryWriter putUnsignedShort(final int us) { // byteBuffer.putShort((short) (us & 0xffff)); // return this; // } // // public BinaryWriter putSignedInt(final int si) { // byteBuffer.putInt(si); // return this; // } // // public BinaryWriter putUnsignedInt(final long ui) { // byteBuffer.putInt((int) (ui & 0xffffffffL)); // return this; // } // // public BinaryWriter putBytes(final byte[] bytes) { // byteBuffer.put(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithByteLength(final byte[] bytes) { // putUnsignedByte((short) bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBytesGroupWithShortLength(final byte[] bytes) { // putUnsignedShort(bytes.length); // putBytes(bytes); // return this; // } // // public BinaryWriter putBoolean(final boolean b) { // byteBuffer.put((byte) (b ? 1 : 0)); // return this; // } // // public byte[] toBytes() { // return byteBuffer.array(); // } // // } // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/header/mux/MuxConnectionRequestHeader.java import com.vecsight.dragonite.proxy.exception.IncorrectHeaderException; import com.vecsight.dragonite.proxy.header.AddressType; import com.vecsight.dragonite.utils.binary.BinaryReader; import com.vecsight.dragonite.utils.binary.BinaryWriter; import java.nio.BufferUnderflowException; this.type = type; } public byte[] getAddr() { return addr; } public void setAddr(final byte[] addr) { this.addr = addr; } public int getPort() { return port; } public void setPort(final int port) { this.port = port; } public boolean isUdpMode() { return udpMode; } public void setUdpMode(final boolean udpMode) { this.udpMode = udpMode; } public byte[] toBytes() { final int addrTotalLength = (type == AddressType.IPv4 ? 4 : (type == AddressType.IPv6 ? 16 : 1 + addr.length));
final BinaryWriter writer = new BinaryWriter(4 + addrTotalLength);
dragonite-network/dragonite-java
dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/socket/ACKSender.java
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/msg/types/ACKMessage.java // public class ACKMessage implements Message { // // private static final byte VERSION = DragoniteGlobalConstants.PROTOCOL_VERSION; // // private static final MessageType TYPE = MessageType.ACK; // // public static final int FIXED_LENGTH = 8; // // private int[] sequenceList; // // private int consumedSeq; // // public ACKMessage(final int[] sequenceList, final int consumedSeq) { // this.sequenceList = sequenceList; // this.consumedSeq = consumedSeq; // } // // public ACKMessage(final byte[] msg) throws IncorrectMessageException { // final BinaryReader reader = new BinaryReader(msg); // // try { // // final byte remoteVersion = reader.getSignedByte(); // final byte remoteType = reader.getSignedByte(); // // if (remoteVersion != VERSION) { // throw new IncorrectMessageException("Incorrect version (" + remoteVersion + ", should be " + VERSION + ")"); // } // if (remoteType != TYPE.getValue()) { // throw new IncorrectMessageException("Incorrect type (" + remoteType + ", should be " + TYPE + ")"); // } // // consumedSeq = reader.getSignedInt(); // // final int seqCount = reader.getUnsignedShort(); // // sequenceList = new int[seqCount]; // for (int i = 0; i < seqCount; i++) { // sequenceList[i] = reader.getSignedInt(); // } // // } catch (final BufferUnderflowException e) { // throw new IncorrectMessageException("Incorrect message length"); // } // } // // @Override // public byte getVersion() { // return VERSION; // } // // @Override // public MessageType getType() { // return TYPE; // } // // @Override // public byte[] toBytes() { // final BinaryWriter writer = new BinaryWriter(getFixedLength() + sequenceList.length * Integer.BYTES); // // writer.putSignedByte(VERSION) // .putSignedByte(TYPE.getValue()) // .putSignedInt(consumedSeq) // .putUnsignedShort(sequenceList.length); // // for (final int seq : sequenceList) { // writer.putSignedInt(seq); // } // // return writer.toBytes(); // } // // @Override // public int getFixedLength() { // return FIXED_LENGTH; // } // // public int[] getSequenceList() { // return sequenceList; // } // // public void setSequenceList(final int[] sequenceList) { // this.sequenceList = sequenceList; // } // // public int getConsumedSeq() { // return consumedSeq; // } // // public void setConsumedSeq(final int consumedSeq) { // this.consumedSeq = consumedSeq; // } // }
import com.vecsight.dragonite.sdk.msg.types.ACKMessage; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.socket; public class ACKSender { private final DragoniteSocket socket; private final int MTU; private final PacketSender action; private final Thread sendThread; private final int delayMS; private final Set<Integer> ackList = new HashSet<>(); private volatile int receivedSeq = 0; private volatile boolean receivedSeqChanged = false; private volatile boolean running = true; private volatile boolean enableLoopLock = false; private final Object ackLoopLock = new Object(); protected ACKSender(final DragoniteSocket socket, final PacketSender action, final int delayMS, final int MTU) { this.socket = socket; this.MTU = MTU; this.action = action; this.delayMS = delayMS; sendThread = new Thread(() -> { try { while (running && socket.isAlive()) { int[] ackarray = null; synchronized (ackList) { if (ackList.size() > 0) { ackarray = toIntArray(ackList); ackList.clear(); } } if (ackarray != null && ackarray.length > 0) { receivedSeqChanged = false;
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/msg/types/ACKMessage.java // public class ACKMessage implements Message { // // private static final byte VERSION = DragoniteGlobalConstants.PROTOCOL_VERSION; // // private static final MessageType TYPE = MessageType.ACK; // // public static final int FIXED_LENGTH = 8; // // private int[] sequenceList; // // private int consumedSeq; // // public ACKMessage(final int[] sequenceList, final int consumedSeq) { // this.sequenceList = sequenceList; // this.consumedSeq = consumedSeq; // } // // public ACKMessage(final byte[] msg) throws IncorrectMessageException { // final BinaryReader reader = new BinaryReader(msg); // // try { // // final byte remoteVersion = reader.getSignedByte(); // final byte remoteType = reader.getSignedByte(); // // if (remoteVersion != VERSION) { // throw new IncorrectMessageException("Incorrect version (" + remoteVersion + ", should be " + VERSION + ")"); // } // if (remoteType != TYPE.getValue()) { // throw new IncorrectMessageException("Incorrect type (" + remoteType + ", should be " + TYPE + ")"); // } // // consumedSeq = reader.getSignedInt(); // // final int seqCount = reader.getUnsignedShort(); // // sequenceList = new int[seqCount]; // for (int i = 0; i < seqCount; i++) { // sequenceList[i] = reader.getSignedInt(); // } // // } catch (final BufferUnderflowException e) { // throw new IncorrectMessageException("Incorrect message length"); // } // } // // @Override // public byte getVersion() { // return VERSION; // } // // @Override // public MessageType getType() { // return TYPE; // } // // @Override // public byte[] toBytes() { // final BinaryWriter writer = new BinaryWriter(getFixedLength() + sequenceList.length * Integer.BYTES); // // writer.putSignedByte(VERSION) // .putSignedByte(TYPE.getValue()) // .putSignedInt(consumedSeq) // .putUnsignedShort(sequenceList.length); // // for (final int seq : sequenceList) { // writer.putSignedInt(seq); // } // // return writer.toBytes(); // } // // @Override // public int getFixedLength() { // return FIXED_LENGTH; // } // // public int[] getSequenceList() { // return sequenceList; // } // // public void setSequenceList(final int[] sequenceList) { // this.sequenceList = sequenceList; // } // // public int getConsumedSeq() { // return consumedSeq; // } // // public void setConsumedSeq(final int consumedSeq) { // this.consumedSeq = consumedSeq; // } // } // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/socket/ACKSender.java import com.vecsight.dragonite.sdk.msg.types.ACKMessage; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.socket; public class ACKSender { private final DragoniteSocket socket; private final int MTU; private final PacketSender action; private final Thread sendThread; private final int delayMS; private final Set<Integer> ackList = new HashSet<>(); private volatile int receivedSeq = 0; private volatile boolean receivedSeqChanged = false; private volatile boolean running = true; private volatile boolean enableLoopLock = false; private final Object ackLoopLock = new Object(); protected ACKSender(final DragoniteSocket socket, final PacketSender action, final int delayMS, final int MTU) { this.socket = socket; this.MTU = MTU; this.action = action; this.delayMS = delayMS; sendThread = new Thread(() -> { try { while (running && socket.isAlive()) { int[] ackarray = null; synchronized (ackList) { if (ackList.size() > 0) { ackarray = toIntArray(ackList); ackList.clear(); } } if (ackarray != null && ackarray.length > 0) { receivedSeqChanged = false;
if (ACKMessage.FIXED_LENGTH + ackarray.length * Integer.BYTES > MTU) {
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLFileParser.java
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/ACLException.java // public class ACLException extends Exception { // // public ACLException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // }
import com.vecsight.dragonite.proxy.acl.item.*; import com.vecsight.dragonite.proxy.exception.ACLException; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.acl; public final class ACLFileParser { private static final Pattern INFO_PATTERN = Pattern.compile("(\\w+?):(.+)"); private static final Pattern RULE_PATTERN = Pattern.compile("([a-zA-Z0-9\\-]+?),([a-zA-Z0-9\\-.:/]+),([a-zA-Z]+)");
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/ACLException.java // public class ACLException extends Exception { // // public ACLException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // } // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLFileParser.java import com.vecsight.dragonite.proxy.acl.item.*; import com.vecsight.dragonite.proxy.exception.ACLException; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.acl; public final class ACLFileParser { private static final Pattern INFO_PATTERN = Pattern.compile("(\\w+?):(.+)"); private static final Pattern RULE_PATTERN = Pattern.compile("([a-zA-Z0-9\\-]+?),([a-zA-Z0-9\\-.:/]+),([a-zA-Z]+)");
public static ParsedACL parse(final Reader reader) throws IOException, ACLException {
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLFileParser.java
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/ACLException.java // public class ACLException extends Exception { // // public ACLException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // }
import com.vecsight.dragonite.proxy.acl.item.*; import com.vecsight.dragonite.proxy.exception.ACLException; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
final ACLItemType aclItemType; try { aclItemType = typeFromString(type); } catch (final ACLException e) { throw new ACLException("Line " + lineCount + " - " + e.getMessage()); } final ACLItemMethod aclItemMethod; aclItemMethod = methodFromString(method); try { switch (aclItemType) { case IPv4: aclItemList.add(new IPv4ACLItem(address, aclItemMethod)); break; case IPv4_CIDR: aclItemList.add(new IPv4CIDRACLItem(address, aclItemMethod)); break; case IPv6: aclItemList.add(new IPv6ACLItem(address, aclItemMethod)); break; case IPv6_CIDR: aclItemList.add(new IPv6CIDRACLItem(address, aclItemMethod)); break; case DOMAIN: aclItemList.add(new DomainACLItem(address, aclItemMethod)); break; case DOMAIN_SUFFIX: aclItemList.add(new DomainSuffixACLItem(address, aclItemMethod)); break; }
// Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/ACLException.java // public class ACLException extends Exception { // // public ACLException(final String msg) { // super(msg); // } // // } // // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/exception/InvalidAddressException.java // public class InvalidAddressException extends Exception { // // public InvalidAddressException(final String msg) { // super(msg); // } // // } // Path: dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/acl/ACLFileParser.java import com.vecsight.dragonite.proxy.acl.item.*; import com.vecsight.dragonite.proxy.exception.ACLException; import com.vecsight.dragonite.proxy.exception.InvalidAddressException; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; final ACLItemType aclItemType; try { aclItemType = typeFromString(type); } catch (final ACLException e) { throw new ACLException("Line " + lineCount + " - " + e.getMessage()); } final ACLItemMethod aclItemMethod; aclItemMethod = methodFromString(method); try { switch (aclItemType) { case IPv4: aclItemList.add(new IPv4ACLItem(address, aclItemMethod)); break; case IPv4_CIDR: aclItemList.add(new IPv4CIDRACLItem(address, aclItemMethod)); break; case IPv6: aclItemList.add(new IPv6ACLItem(address, aclItemMethod)); break; case IPv6_CIDR: aclItemList.add(new IPv6CIDRACLItem(address, aclItemMethod)); break; case DOMAIN: aclItemList.add(new DomainACLItem(address, aclItemMethod)); break; case DOMAIN_SUFFIX: aclItemList.add(new DomainSuffixACLItem(address, aclItemMethod)); break; }
} catch (final InvalidAddressException e) {
dragonite-network/dragonite-java
dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/socket/RTTEstimator.java
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/NumUtils.java // public final class NumUtils { // // public static long min(final long l1, final long l2) { // return l1 < l2 ? l1 : l2; // } // // public static long max(final long l1, final long l2) { // return l1 > l2 ? l1 : l2; // } // // public static int min(final int i1, final int i2) { // return i1 < i2 ? i1 : i2; // } // // public static int max(final int i1, final int i2) { // return i1 > i2 ? i1 : i2; // } // // }
import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import com.vecsight.dragonite.sdk.misc.NumUtils;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.socket; public class RTTEstimator { private final static float estimatedRTTUpdateFactor = 0.125f, devRTTUpdateFactor = 0.25f; private final ConnectionState state;
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/NumUtils.java // public final class NumUtils { // // public static long min(final long l1, final long l2) { // return l1 < l2 ? l1 : l2; // } // // public static long max(final long l1, final long l2) { // return l1 > l2 ? l1 : l2; // } // // public static int min(final int i1, final int i2) { // return i1 < i2 ? i1 : i2; // } // // public static int max(final int i1, final int i2) { // return i1 > i2 ? i1 : i2; // } // // } // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/socket/RTTEstimator.java import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import com.vecsight.dragonite.sdk.misc.NumUtils; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.socket; public class RTTEstimator { private final static float estimatedRTTUpdateFactor = 0.125f, devRTTUpdateFactor = 0.25f; private final ConnectionState state;
private long estimatedRTT = DragoniteGlobalConstants.INIT_RTT_MS, devRTT;
dragonite-network/dragonite-java
dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/socket/RTTEstimator.java
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/NumUtils.java // public final class NumUtils { // // public static long min(final long l1, final long l2) { // return l1 < l2 ? l1 : l2; // } // // public static long max(final long l1, final long l2) { // return l1 > l2 ? l1 : l2; // } // // public static int min(final int i1, final int i2) { // return i1 < i2 ? i1 : i2; // } // // public static int max(final int i1, final int i2) { // return i1 > i2 ? i1 : i2; // } // // }
import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import com.vecsight.dragonite.sdk.misc.NumUtils;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.socket; public class RTTEstimator { private final static float estimatedRTTUpdateFactor = 0.125f, devRTTUpdateFactor = 0.25f; private final ConnectionState state; private long estimatedRTT = DragoniteGlobalConstants.INIT_RTT_MS, devRTT; private long lastUpdate = 0; private int continuousResendCount = 0; public RTTEstimator(final ConnectionState state) { this.state = state; } public void pushStat(final MessageStat stat) { //System.out.println(stat); if (stat.isExist()) { final long currentTime = System.currentTimeMillis(); /*if (currentTime - lastRefresh >= DragoniteGlobalConstants.rttRefreshIntervalMS) { lastRefresh = System.currentTimeMillis(); if (stat.isResended()) { long maxCRTT = (long) (estimatedRTT * DragoniteGlobalConstants.RTT_RESENDED_REFRESH_MAX_MULT); setRTT(NumUtils.min(stat.getRTT(), maxCRTT), 0); } }*/ if (currentTime - lastUpdate >= DragoniteGlobalConstants.RTT_UPDATE_INTERVAL_MS) { lastUpdate = currentTime; //System.out.println(stat.toString()); if (!stat.isResended()) { continuousResendCount = 0; clampSetRTT((long) ((1 - estimatedRTTUpdateFactor) * estimatedRTT + estimatedRTTUpdateFactor * stat.getRTT()), (long) ((1 - devRTTUpdateFactor) * devRTT + devRTTUpdateFactor * Math.abs(stat.getRTT() - estimatedRTT))); } else { continuousResendCount++; if (continuousResendCount > (DragoniteGlobalConstants.RTT_RESEND_CORRECTION_INTERVAL_MS / DragoniteGlobalConstants.RTT_UPDATE_INTERVAL_MS)) { final long maxCRTT = (long) (estimatedRTT * DragoniteGlobalConstants.RTT_RESENDED_REFRESH_MAX_MULT);
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/NumUtils.java // public final class NumUtils { // // public static long min(final long l1, final long l2) { // return l1 < l2 ? l1 : l2; // } // // public static long max(final long l1, final long l2) { // return l1 > l2 ? l1 : l2; // } // // public static int min(final int i1, final int i2) { // return i1 < i2 ? i1 : i2; // } // // public static int max(final int i1, final int i2) { // return i1 > i2 ? i1 : i2; // } // // } // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/socket/RTTEstimator.java import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import com.vecsight.dragonite.sdk.misc.NumUtils; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.socket; public class RTTEstimator { private final static float estimatedRTTUpdateFactor = 0.125f, devRTTUpdateFactor = 0.25f; private final ConnectionState state; private long estimatedRTT = DragoniteGlobalConstants.INIT_RTT_MS, devRTT; private long lastUpdate = 0; private int continuousResendCount = 0; public RTTEstimator(final ConnectionState state) { this.state = state; } public void pushStat(final MessageStat stat) { //System.out.println(stat); if (stat.isExist()) { final long currentTime = System.currentTimeMillis(); /*if (currentTime - lastRefresh >= DragoniteGlobalConstants.rttRefreshIntervalMS) { lastRefresh = System.currentTimeMillis(); if (stat.isResended()) { long maxCRTT = (long) (estimatedRTT * DragoniteGlobalConstants.RTT_RESENDED_REFRESH_MAX_MULT); setRTT(NumUtils.min(stat.getRTT(), maxCRTT), 0); } }*/ if (currentTime - lastUpdate >= DragoniteGlobalConstants.RTT_UPDATE_INTERVAL_MS) { lastUpdate = currentTime; //System.out.println(stat.toString()); if (!stat.isResended()) { continuousResendCount = 0; clampSetRTT((long) ((1 - estimatedRTTUpdateFactor) * estimatedRTT + estimatedRTTUpdateFactor * stat.getRTT()), (long) ((1 - devRTTUpdateFactor) * devRTT + devRTTUpdateFactor * Math.abs(stat.getRTT() - estimatedRTT))); } else { continuousResendCount++; if (continuousResendCount > (DragoniteGlobalConstants.RTT_RESEND_CORRECTION_INTERVAL_MS / DragoniteGlobalConstants.RTT_UPDATE_INTERVAL_MS)) { final long maxCRTT = (long) (estimatedRTT * DragoniteGlobalConstants.RTT_RESENDED_REFRESH_MAX_MULT);
final long tmpRTT = NumUtils.min(stat.getRTT(), maxCRTT);
dragonite-network/dragonite-java
dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/config/DragoniteSocketParameters.java
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/cryptor/PacketCryptor.java // public interface PacketCryptor { // // /** // * Encrypt the message and return the ciphertext. // * This function may be called by multiple threads at the same time. // * // * @param rawData Content to be encrypted // * @return Encrypted content // */ // byte[] encrypt(final byte[] rawData); // // /** // * Decrypt the ciphertext and return the message. // * This function may be called by multiple threads at the same time. // * // * @param encryptedData Content to be decrypted // * @return Decrypted content // */ // byte[] decrypt(final byte[] encryptedData); // // /** // * Many encryption methods need to add additional bytes to the original message. // * Please specify the maximum length of additional bytes that the encryption might cause. // * // * @return Length of additional bytes // */ // int getMaxAdditionalBytesLength(); // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static void checkArgument(final boolean ok, final String message) { // if (!ok) throw new IllegalArgumentException(message); // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static boolean inTrafficClassRange(final int trafficClass) { // return trafficClass >= 0 && trafficClass <= 255; // }
import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import static com.vecsight.dragonite.utils.flow.Preconditions.checkArgument; import static com.vecsight.dragonite.utils.flow.Preconditions.inTrafficClassRange;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.config; public class DragoniteSocketParameters { private int packetSize = 1300; private boolean autoSplit = true; private int maxPacketBufferSize = 0; private int windowMultiplier = 4; private int resendMinDelayMS = 50; private int heartbeatIntervalSec = 5; private int receiveTimeoutSec = 10; private boolean enableWebPanel = false;
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/cryptor/PacketCryptor.java // public interface PacketCryptor { // // /** // * Encrypt the message and return the ciphertext. // * This function may be called by multiple threads at the same time. // * // * @param rawData Content to be encrypted // * @return Encrypted content // */ // byte[] encrypt(final byte[] rawData); // // /** // * Decrypt the ciphertext and return the message. // * This function may be called by multiple threads at the same time. // * // * @param encryptedData Content to be decrypted // * @return Decrypted content // */ // byte[] decrypt(final byte[] encryptedData); // // /** // * Many encryption methods need to add additional bytes to the original message. // * Please specify the maximum length of additional bytes that the encryption might cause. // * // * @return Length of additional bytes // */ // int getMaxAdditionalBytesLength(); // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static void checkArgument(final boolean ok, final String message) { // if (!ok) throw new IllegalArgumentException(message); // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static boolean inTrafficClassRange(final int trafficClass) { // return trafficClass >= 0 && trafficClass <= 255; // } // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/config/DragoniteSocketParameters.java import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import static com.vecsight.dragonite.utils.flow.Preconditions.checkArgument; import static com.vecsight.dragonite.utils.flow.Preconditions.inTrafficClassRange; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.config; public class DragoniteSocketParameters { private int packetSize = 1300; private boolean autoSplit = true; private int maxPacketBufferSize = 0; private int windowMultiplier = 4; private int resendMinDelayMS = 50; private int heartbeatIntervalSec = 5; private int receiveTimeoutSec = 10; private boolean enableWebPanel = false;
private InetSocketAddress webPanelBindAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), DragoniteGlobalConstants.WEB_PANEL_PORT);
dragonite-network/dragonite-java
dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/config/DragoniteSocketParameters.java
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/cryptor/PacketCryptor.java // public interface PacketCryptor { // // /** // * Encrypt the message and return the ciphertext. // * This function may be called by multiple threads at the same time. // * // * @param rawData Content to be encrypted // * @return Encrypted content // */ // byte[] encrypt(final byte[] rawData); // // /** // * Decrypt the ciphertext and return the message. // * This function may be called by multiple threads at the same time. // * // * @param encryptedData Content to be decrypted // * @return Decrypted content // */ // byte[] decrypt(final byte[] encryptedData); // // /** // * Many encryption methods need to add additional bytes to the original message. // * Please specify the maximum length of additional bytes that the encryption might cause. // * // * @return Length of additional bytes // */ // int getMaxAdditionalBytesLength(); // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static void checkArgument(final boolean ok, final String message) { // if (!ok) throw new IllegalArgumentException(message); // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static boolean inTrafficClassRange(final int trafficClass) { // return trafficClass >= 0 && trafficClass <= 255; // }
import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import static com.vecsight.dragonite.utils.flow.Preconditions.checkArgument; import static com.vecsight.dragonite.utils.flow.Preconditions.inTrafficClassRange;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.config; public class DragoniteSocketParameters { private int packetSize = 1300; private boolean autoSplit = true; private int maxPacketBufferSize = 0; private int windowMultiplier = 4; private int resendMinDelayMS = 50; private int heartbeatIntervalSec = 5; private int receiveTimeoutSec = 10; private boolean enableWebPanel = false; private InetSocketAddress webPanelBindAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), DragoniteGlobalConstants.WEB_PANEL_PORT);
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/cryptor/PacketCryptor.java // public interface PacketCryptor { // // /** // * Encrypt the message and return the ciphertext. // * This function may be called by multiple threads at the same time. // * // * @param rawData Content to be encrypted // * @return Encrypted content // */ // byte[] encrypt(final byte[] rawData); // // /** // * Decrypt the ciphertext and return the message. // * This function may be called by multiple threads at the same time. // * // * @param encryptedData Content to be decrypted // * @return Decrypted content // */ // byte[] decrypt(final byte[] encryptedData); // // /** // * Many encryption methods need to add additional bytes to the original message. // * Please specify the maximum length of additional bytes that the encryption might cause. // * // * @return Length of additional bytes // */ // int getMaxAdditionalBytesLength(); // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static void checkArgument(final boolean ok, final String message) { // if (!ok) throw new IllegalArgumentException(message); // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static boolean inTrafficClassRange(final int trafficClass) { // return trafficClass >= 0 && trafficClass <= 255; // } // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/config/DragoniteSocketParameters.java import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import static com.vecsight.dragonite.utils.flow.Preconditions.checkArgument; import static com.vecsight.dragonite.utils.flow.Preconditions.inTrafficClassRange; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.config; public class DragoniteSocketParameters { private int packetSize = 1300; private boolean autoSplit = true; private int maxPacketBufferSize = 0; private int windowMultiplier = 4; private int resendMinDelayMS = 50; private int heartbeatIntervalSec = 5; private int receiveTimeoutSec = 10; private boolean enableWebPanel = false; private InetSocketAddress webPanelBindAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), DragoniteGlobalConstants.WEB_PANEL_PORT);
private PacketCryptor packetCryptor = null;
dragonite-network/dragonite-java
dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/config/DragoniteSocketParameters.java
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/cryptor/PacketCryptor.java // public interface PacketCryptor { // // /** // * Encrypt the message and return the ciphertext. // * This function may be called by multiple threads at the same time. // * // * @param rawData Content to be encrypted // * @return Encrypted content // */ // byte[] encrypt(final byte[] rawData); // // /** // * Decrypt the ciphertext and return the message. // * This function may be called by multiple threads at the same time. // * // * @param encryptedData Content to be decrypted // * @return Decrypted content // */ // byte[] decrypt(final byte[] encryptedData); // // /** // * Many encryption methods need to add additional bytes to the original message. // * Please specify the maximum length of additional bytes that the encryption might cause. // * // * @return Length of additional bytes // */ // int getMaxAdditionalBytesLength(); // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static void checkArgument(final boolean ok, final String message) { // if (!ok) throw new IllegalArgumentException(message); // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static boolean inTrafficClassRange(final int trafficClass) { // return trafficClass >= 0 && trafficClass <= 255; // }
import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import static com.vecsight.dragonite.utils.flow.Preconditions.checkArgument; import static com.vecsight.dragonite.utils.flow.Preconditions.inTrafficClassRange;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.config; public class DragoniteSocketParameters { private int packetSize = 1300; private boolean autoSplit = true; private int maxPacketBufferSize = 0; private int windowMultiplier = 4; private int resendMinDelayMS = 50; private int heartbeatIntervalSec = 5; private int receiveTimeoutSec = 10; private boolean enableWebPanel = false; private InetSocketAddress webPanelBindAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), DragoniteGlobalConstants.WEB_PANEL_PORT); private PacketCryptor packetCryptor = null; private int trafficClass = 0; public int getPacketSize() { return packetSize; } public void setPacketSize(final int packetSize) {
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/cryptor/PacketCryptor.java // public interface PacketCryptor { // // /** // * Encrypt the message and return the ciphertext. // * This function may be called by multiple threads at the same time. // * // * @param rawData Content to be encrypted // * @return Encrypted content // */ // byte[] encrypt(final byte[] rawData); // // /** // * Decrypt the ciphertext and return the message. // * This function may be called by multiple threads at the same time. // * // * @param encryptedData Content to be decrypted // * @return Decrypted content // */ // byte[] decrypt(final byte[] encryptedData); // // /** // * Many encryption methods need to add additional bytes to the original message. // * Please specify the maximum length of additional bytes that the encryption might cause. // * // * @return Length of additional bytes // */ // int getMaxAdditionalBytesLength(); // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static void checkArgument(final boolean ok, final String message) { // if (!ok) throw new IllegalArgumentException(message); // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static boolean inTrafficClassRange(final int trafficClass) { // return trafficClass >= 0 && trafficClass <= 255; // } // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/config/DragoniteSocketParameters.java import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import static com.vecsight.dragonite.utils.flow.Preconditions.checkArgument; import static com.vecsight.dragonite.utils.flow.Preconditions.inTrafficClassRange; /* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.sdk.config; public class DragoniteSocketParameters { private int packetSize = 1300; private boolean autoSplit = true; private int maxPacketBufferSize = 0; private int windowMultiplier = 4; private int resendMinDelayMS = 50; private int heartbeatIntervalSec = 5; private int receiveTimeoutSec = 10; private boolean enableWebPanel = false; private InetSocketAddress webPanelBindAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), DragoniteGlobalConstants.WEB_PANEL_PORT); private PacketCryptor packetCryptor = null; private int trafficClass = 0; public int getPacketSize() { return packetSize; } public void setPacketSize(final int packetSize) {
checkArgument(packetSize >= 500, "Packet size is too small");
dragonite-network/dragonite-java
dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/config/DragoniteSocketParameters.java
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/cryptor/PacketCryptor.java // public interface PacketCryptor { // // /** // * Encrypt the message and return the ciphertext. // * This function may be called by multiple threads at the same time. // * // * @param rawData Content to be encrypted // * @return Encrypted content // */ // byte[] encrypt(final byte[] rawData); // // /** // * Decrypt the ciphertext and return the message. // * This function may be called by multiple threads at the same time. // * // * @param encryptedData Content to be decrypted // * @return Decrypted content // */ // byte[] decrypt(final byte[] encryptedData); // // /** // * Many encryption methods need to add additional bytes to the original message. // * Please specify the maximum length of additional bytes that the encryption might cause. // * // * @return Length of additional bytes // */ // int getMaxAdditionalBytesLength(); // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static void checkArgument(final boolean ok, final String message) { // if (!ok) throw new IllegalArgumentException(message); // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static boolean inTrafficClassRange(final int trafficClass) { // return trafficClass >= 0 && trafficClass <= 255; // }
import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import static com.vecsight.dragonite.utils.flow.Preconditions.checkArgument; import static com.vecsight.dragonite.utils.flow.Preconditions.inTrafficClassRange;
public boolean isEnableWebPanel() { return enableWebPanel; } public void setEnableWebPanel(final boolean enableWebPanel) { this.enableWebPanel = enableWebPanel; } public InetSocketAddress getWebPanelBindAddress() { return webPanelBindAddress; } public void setWebPanelBindAddress(final InetSocketAddress webPanelBindAddress) { checkArgument(webPanelBindAddress != null, "Bind address cannot be null"); this.webPanelBindAddress = webPanelBindAddress; } public PacketCryptor getPacketCryptor() { return packetCryptor; } public void setPacketCryptor(final PacketCryptor packetCryptor) { this.packetCryptor = packetCryptor; } public int getTrafficClass() { return trafficClass; } public void setTrafficClass(final int trafficClass) {
// Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/cryptor/PacketCryptor.java // public interface PacketCryptor { // // /** // * Encrypt the message and return the ciphertext. // * This function may be called by multiple threads at the same time. // * // * @param rawData Content to be encrypted // * @return Encrypted content // */ // byte[] encrypt(final byte[] rawData); // // /** // * Decrypt the ciphertext and return the message. // * This function may be called by multiple threads at the same time. // * // * @param encryptedData Content to be decrypted // * @return Decrypted content // */ // byte[] decrypt(final byte[] encryptedData); // // /** // * Many encryption methods need to add additional bytes to the original message. // * Please specify the maximum length of additional bytes that the encryption might cause. // * // * @return Length of additional bytes // */ // int getMaxAdditionalBytesLength(); // // } // // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/misc/DragoniteGlobalConstants.java // public final class DragoniteGlobalConstants { // // public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION; // // public static final byte PROTOCOL_VERSION = 2; // // public static final int MIN_SEND_WINDOW_SIZE = 20; // // public static final int ACK_INTERVAL_MS = 10; // // public static final int MAX_FAST_RESEND_COUNT = 3; // // public static final int MAX_SLOW_RESEND_MULT = 4; // // public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000; // // public static final int DEV_RTT_MULT = 4; // // public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f; // // public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4; // // public static final int WEB_PANEL_PORT = 8000; // // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static void checkArgument(final boolean ok, final String message) { // if (!ok) throw new IllegalArgumentException(message); // } // // Path: dragonite-utils/src/main/java/com/vecsight/dragonite/utils/flow/Preconditions.java // public static boolean inTrafficClassRange(final int trafficClass) { // return trafficClass >= 0 && trafficClass <= 255; // } // Path: dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/config/DragoniteSocketParameters.java import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import static com.vecsight.dragonite.utils.flow.Preconditions.checkArgument; import static com.vecsight.dragonite.utils.flow.Preconditions.inTrafficClassRange; public boolean isEnableWebPanel() { return enableWebPanel; } public void setEnableWebPanel(final boolean enableWebPanel) { this.enableWebPanel = enableWebPanel; } public InetSocketAddress getWebPanelBindAddress() { return webPanelBindAddress; } public void setWebPanelBindAddress(final InetSocketAddress webPanelBindAddress) { checkArgument(webPanelBindAddress != null, "Bind address cannot be null"); this.webPanelBindAddress = webPanelBindAddress; } public PacketCryptor getPacketCryptor() { return packetCryptor; } public void setPacketCryptor(final PacketCryptor packetCryptor) { this.packetCryptor = packetCryptor; } public int getTrafficClass() { return trafficClass; } public void setTrafficClass(final int trafficClass) {
checkArgument(inTrafficClassRange(trafficClass), "TC must be in the range 0 <= tc <= 255");