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
roncoo/roncoo-adminlte-springmvc
src/test/java/com/roncoo/adminlte/test/EamilAccountInfoTest/CacheTest.java
// Path: src/main/java/com/roncoo/adminlte/bean/entity/RcEmailAccountInfo.java // public class RcEmailAccountInfo implements Serializable { // private Long id; // // private String statusId; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date createTime; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date updateTime; // // private String fromUser; // // private String passwd; // // private String host; // // private String remark; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getStatusId() { // return statusId; // } // // public void setStatusId(String statusId) { // this.statusId = statusId == null ? null : statusId.trim(); // } // // 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 String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser == null ? null : fromUser.trim(); // } // // public String getPasswd() { // return passwd; // } // // public void setPasswd(String passwd) { // this.passwd = passwd == null ? null : passwd.trim(); // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host == null ? null : host.trim(); // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark == null ? null : remark.trim(); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(getClass().getSimpleName()); // sb.append(" ["); // sb.append("Hash = ").append(hashCode()); // sb.append(", id=").append(id); // sb.append(", statusId=").append(statusId); // sb.append(", createTime=").append(createTime); // sb.append(", updateTime=").append(updateTime); // sb.append(", fromUser=").append(fromUser); // sb.append(", passwd=").append(passwd); // sb.append(", host=").append(host); // sb.append(", remark=").append(remark); // sb.append(", serialVersionUID=").append(serialVersionUID); // sb.append("]"); // return sb.toString(); // } // } // // Path: src/main/java/com/roncoo/adminlte/cache/EmailAccountInfoCache.java // @Component // public class EmailAccountInfoCache extends CachedImpl<String, RcEmailAccountInfo> { // // @Autowired // private EmailAccountInfoService emailAccountInfoService; // // private final static Long INITIALDELAY = 300L; // private final static Long PERIOD = 300L; // // @PostConstruct // public void init() { // super.init(INITIALDELAY, PERIOD); // } // // @Override // public void reloadFromDb(ConcurrentMap<String, RcEmailAccountInfo> cached) { // Result<List<RcEmailAccountInfo>> result = emailAccountInfoService.list(); // if (result.isStatus()) { // for (RcEmailAccountInfo bean : result.getResultData()) { // cached.putIfAbsent(String.valueOf(bean.getId()), bean); // } // } // } // // }
import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.roncoo.adminlte.bean.entity.RcEmailAccountInfo; import com.roncoo.adminlte.cache.EmailAccountInfoCache;
/* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.test.EamilAccountInfoTest; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext-core.xml") public class CacheTest { @Autowired private EmailAccountInfoCache emailAcountInfoCache; @Test public void testCache(){ System.out.println(emailAcountInfoCache); emailAcountInfoCache.init();
// Path: src/main/java/com/roncoo/adminlte/bean/entity/RcEmailAccountInfo.java // public class RcEmailAccountInfo implements Serializable { // private Long id; // // private String statusId; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date createTime; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date updateTime; // // private String fromUser; // // private String passwd; // // private String host; // // private String remark; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getStatusId() { // return statusId; // } // // public void setStatusId(String statusId) { // this.statusId = statusId == null ? null : statusId.trim(); // } // // 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 String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser == null ? null : fromUser.trim(); // } // // public String getPasswd() { // return passwd; // } // // public void setPasswd(String passwd) { // this.passwd = passwd == null ? null : passwd.trim(); // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host == null ? null : host.trim(); // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark == null ? null : remark.trim(); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(getClass().getSimpleName()); // sb.append(" ["); // sb.append("Hash = ").append(hashCode()); // sb.append(", id=").append(id); // sb.append(", statusId=").append(statusId); // sb.append(", createTime=").append(createTime); // sb.append(", updateTime=").append(updateTime); // sb.append(", fromUser=").append(fromUser); // sb.append(", passwd=").append(passwd); // sb.append(", host=").append(host); // sb.append(", remark=").append(remark); // sb.append(", serialVersionUID=").append(serialVersionUID); // sb.append("]"); // return sb.toString(); // } // } // // Path: src/main/java/com/roncoo/adminlte/cache/EmailAccountInfoCache.java // @Component // public class EmailAccountInfoCache extends CachedImpl<String, RcEmailAccountInfo> { // // @Autowired // private EmailAccountInfoService emailAccountInfoService; // // private final static Long INITIALDELAY = 300L; // private final static Long PERIOD = 300L; // // @PostConstruct // public void init() { // super.init(INITIALDELAY, PERIOD); // } // // @Override // public void reloadFromDb(ConcurrentMap<String, RcEmailAccountInfo> cached) { // Result<List<RcEmailAccountInfo>> result = emailAccountInfoService.list(); // if (result.isStatus()) { // for (RcEmailAccountInfo bean : result.getResultData()) { // cached.putIfAbsent(String.valueOf(bean.getId()), bean); // } // } // } // // } // Path: src/test/java/com/roncoo/adminlte/test/EamilAccountInfoTest/CacheTest.java import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.roncoo.adminlte.bean.entity.RcEmailAccountInfo; import com.roncoo.adminlte.cache.EmailAccountInfoCache; /* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.test.EamilAccountInfoTest; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext-core.xml") public class CacheTest { @Autowired private EmailAccountInfoCache emailAcountInfoCache; @Test public void testCache(){ System.out.println(emailAcountInfoCache); emailAcountInfoCache.init();
List<RcEmailAccountInfo> result = emailAcountInfoCache.getList();
roncoo/roncoo-adminlte-springmvc
src/main/java/com/roncoo/adminlte/controller/admin/IndexController.java
// Path: src/main/java/com/roncoo/adminlte/util/base/BaseController.java // public class BaseController { // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // // public static final String TEXT_UTF8 = "text/html;charset=UTF-8"; // public static final String JSON_UTF8 = "application/json;charset=UTF-8"; // public static final String XML_UTF8 = "application/xml;charset=UTF-8"; // // public static final String LIST = "list"; // public static final String VIEW = "view"; // public static final String ADD = "add"; // public static final String SAVE = "save"; // public static final String EDIT = "edit"; // public static final String UPDATE = "update"; // public static final String DELETE = "delete"; // public static final String PAGE = "page"; // // public static String redirect(String format, Object... arguments) { // return new StringBuffer("redirect:").append(MessageFormat.format(format, arguments)).toString(); // } // // public static void main(String[] args) { // System.out.println(redirect("/admin/emailAccountInfo/list")); // } // // }
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.roncoo.adminlte.util.base.BaseController;
/* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.controller.admin; /** * 登录功能 * * @author wujing */ @Controller @RequestMapping(value = "/admin")
// Path: src/main/java/com/roncoo/adminlte/util/base/BaseController.java // public class BaseController { // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // // public static final String TEXT_UTF8 = "text/html;charset=UTF-8"; // public static final String JSON_UTF8 = "application/json;charset=UTF-8"; // public static final String XML_UTF8 = "application/xml;charset=UTF-8"; // // public static final String LIST = "list"; // public static final String VIEW = "view"; // public static final String ADD = "add"; // public static final String SAVE = "save"; // public static final String EDIT = "edit"; // public static final String UPDATE = "update"; // public static final String DELETE = "delete"; // public static final String PAGE = "page"; // // public static String redirect(String format, Object... arguments) { // return new StringBuffer("redirect:").append(MessageFormat.format(format, arguments)).toString(); // } // // public static void main(String[] args) { // System.out.println(redirect("/admin/emailAccountInfo/list")); // } // // } // Path: src/main/java/com/roncoo/adminlte/controller/admin/IndexController.java import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.roncoo.adminlte.util.base.BaseController; /* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.controller.admin; /** * 登录功能 * * @author wujing */ @Controller @RequestMapping(value = "/admin")
public class IndexController extends BaseController {
roncoo/roncoo-adminlte-springmvc
src/test/java/com/roncoo/adminlte/test/dataDictionary/DataDictionaryTest.java
// Path: src/main/java/com/roncoo/adminlte/bean/entity/RcEmailInfo.java // public class RcEmailInfo implements Serializable { // private Long id; // // private String statusId; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date createTime; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date updateTime; // // private String toUser; // // private String fromUser; // // private String title; // // private String subject; // // private String content; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getStatusId() { // return statusId; // } // // public void setStatusId(String statusId) { // this.statusId = statusId == null ? null : statusId.trim(); // } // // 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 String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser == null ? null : toUser.trim(); // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser == null ? null : fromUser.trim(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title == null ? null : title.trim(); // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject == null ? null : subject.trim(); // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content == null ? null : content.trim(); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(getClass().getSimpleName()); // sb.append(" ["); // sb.append("Hash = ").append(hashCode()); // sb.append(", id=").append(id); // sb.append(", statusId=").append(statusId); // sb.append(", createTime=").append(createTime); // sb.append(", updateTime=").append(updateTime); // sb.append(", toUser=").append(toUser); // sb.append(", fromUser=").append(fromUser); // sb.append(", title=").append(title); // sb.append(", subject=").append(subject); // sb.append(", content=").append(content); // sb.append(", serialVersionUID=").append(serialVersionUID); // sb.append("]"); // return sb.toString(); // } // } // // Path: src/main/java/com/roncoo/adminlte/service/impl/dao/EmailInfoDao.java // public interface EmailInfoDao { // // /** // * // * 添加记录 // * // * @param rcEmailInfo // * @return int // */ // int insert(RcEmailInfo rcEmailInfo); // // /** // * 分页查询 // * // * @param pageCurrent // * @param pageSize // * @return // */ // Page<RcEmailInfo> listForPage(int pageCurrent, int pageSize,String premise,String datePremise); // // /** // * 根据id删除 // * // * @param id // */ // int deleteById(Long id); // // /** // * 根据id查询 // * // * @param id // */ // RcEmailInfo selectById(Long id); // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.roncoo.adminlte.bean.entity.RcEmailInfo; import com.roncoo.adminlte.service.impl.dao.EmailInfoDao;
package com.roncoo.adminlte.test.dataDictionary; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext-core.xml") public class DataDictionaryTest { @Autowired
// Path: src/main/java/com/roncoo/adminlte/bean/entity/RcEmailInfo.java // public class RcEmailInfo implements Serializable { // private Long id; // // private String statusId; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date createTime; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date updateTime; // // private String toUser; // // private String fromUser; // // private String title; // // private String subject; // // private String content; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getStatusId() { // return statusId; // } // // public void setStatusId(String statusId) { // this.statusId = statusId == null ? null : statusId.trim(); // } // // 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 String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser == null ? null : toUser.trim(); // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser == null ? null : fromUser.trim(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title == null ? null : title.trim(); // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject == null ? null : subject.trim(); // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content == null ? null : content.trim(); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(getClass().getSimpleName()); // sb.append(" ["); // sb.append("Hash = ").append(hashCode()); // sb.append(", id=").append(id); // sb.append(", statusId=").append(statusId); // sb.append(", createTime=").append(createTime); // sb.append(", updateTime=").append(updateTime); // sb.append(", toUser=").append(toUser); // sb.append(", fromUser=").append(fromUser); // sb.append(", title=").append(title); // sb.append(", subject=").append(subject); // sb.append(", content=").append(content); // sb.append(", serialVersionUID=").append(serialVersionUID); // sb.append("]"); // return sb.toString(); // } // } // // Path: src/main/java/com/roncoo/adminlte/service/impl/dao/EmailInfoDao.java // public interface EmailInfoDao { // // /** // * // * 添加记录 // * // * @param rcEmailInfo // * @return int // */ // int insert(RcEmailInfo rcEmailInfo); // // /** // * 分页查询 // * // * @param pageCurrent // * @param pageSize // * @return // */ // Page<RcEmailInfo> listForPage(int pageCurrent, int pageSize,String premise,String datePremise); // // /** // * 根据id删除 // * // * @param id // */ // int deleteById(Long id); // // /** // * 根据id查询 // * // * @param id // */ // RcEmailInfo selectById(Long id); // } // Path: src/test/java/com/roncoo/adminlte/test/dataDictionary/DataDictionaryTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.roncoo.adminlte.bean.entity.RcEmailInfo; import com.roncoo.adminlte.service.impl.dao.EmailInfoDao; package com.roncoo.adminlte.test.dataDictionary; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext-core.xml") public class DataDictionaryTest { @Autowired
private EmailInfoDao dao;
roncoo/roncoo-adminlte-springmvc
src/test/java/com/roncoo/adminlte/test/dataDictionary/DataDictionaryTest.java
// Path: src/main/java/com/roncoo/adminlte/bean/entity/RcEmailInfo.java // public class RcEmailInfo implements Serializable { // private Long id; // // private String statusId; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date createTime; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date updateTime; // // private String toUser; // // private String fromUser; // // private String title; // // private String subject; // // private String content; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getStatusId() { // return statusId; // } // // public void setStatusId(String statusId) { // this.statusId = statusId == null ? null : statusId.trim(); // } // // 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 String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser == null ? null : toUser.trim(); // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser == null ? null : fromUser.trim(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title == null ? null : title.trim(); // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject == null ? null : subject.trim(); // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content == null ? null : content.trim(); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(getClass().getSimpleName()); // sb.append(" ["); // sb.append("Hash = ").append(hashCode()); // sb.append(", id=").append(id); // sb.append(", statusId=").append(statusId); // sb.append(", createTime=").append(createTime); // sb.append(", updateTime=").append(updateTime); // sb.append(", toUser=").append(toUser); // sb.append(", fromUser=").append(fromUser); // sb.append(", title=").append(title); // sb.append(", subject=").append(subject); // sb.append(", content=").append(content); // sb.append(", serialVersionUID=").append(serialVersionUID); // sb.append("]"); // return sb.toString(); // } // } // // Path: src/main/java/com/roncoo/adminlte/service/impl/dao/EmailInfoDao.java // public interface EmailInfoDao { // // /** // * // * 添加记录 // * // * @param rcEmailInfo // * @return int // */ // int insert(RcEmailInfo rcEmailInfo); // // /** // * 分页查询 // * // * @param pageCurrent // * @param pageSize // * @return // */ // Page<RcEmailInfo> listForPage(int pageCurrent, int pageSize,String premise,String datePremise); // // /** // * 根据id删除 // * // * @param id // */ // int deleteById(Long id); // // /** // * 根据id查询 // * // * @param id // */ // RcEmailInfo selectById(Long id); // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.roncoo.adminlte.bean.entity.RcEmailInfo; import com.roncoo.adminlte.service.impl.dao.EmailInfoDao;
package com.roncoo.adminlte.test.dataDictionary; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext-core.xml") public class DataDictionaryTest { @Autowired private EmailInfoDao dao; @Test public void test() {
// Path: src/main/java/com/roncoo/adminlte/bean/entity/RcEmailInfo.java // public class RcEmailInfo implements Serializable { // private Long id; // // private String statusId; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date createTime; // // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // private Date updateTime; // // private String toUser; // // private String fromUser; // // private String title; // // private String subject; // // private String content; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getStatusId() { // return statusId; // } // // public void setStatusId(String statusId) { // this.statusId = statusId == null ? null : statusId.trim(); // } // // 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 String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser == null ? null : toUser.trim(); // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser == null ? null : fromUser.trim(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title == null ? null : title.trim(); // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject == null ? null : subject.trim(); // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content == null ? null : content.trim(); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(getClass().getSimpleName()); // sb.append(" ["); // sb.append("Hash = ").append(hashCode()); // sb.append(", id=").append(id); // sb.append(", statusId=").append(statusId); // sb.append(", createTime=").append(createTime); // sb.append(", updateTime=").append(updateTime); // sb.append(", toUser=").append(toUser); // sb.append(", fromUser=").append(fromUser); // sb.append(", title=").append(title); // sb.append(", subject=").append(subject); // sb.append(", content=").append(content); // sb.append(", serialVersionUID=").append(serialVersionUID); // sb.append("]"); // return sb.toString(); // } // } // // Path: src/main/java/com/roncoo/adminlte/service/impl/dao/EmailInfoDao.java // public interface EmailInfoDao { // // /** // * // * 添加记录 // * // * @param rcEmailInfo // * @return int // */ // int insert(RcEmailInfo rcEmailInfo); // // /** // * 分页查询 // * // * @param pageCurrent // * @param pageSize // * @return // */ // Page<RcEmailInfo> listForPage(int pageCurrent, int pageSize,String premise,String datePremise); // // /** // * 根据id删除 // * // * @param id // */ // int deleteById(Long id); // // /** // * 根据id查询 // * // * @param id // */ // RcEmailInfo selectById(Long id); // } // Path: src/test/java/com/roncoo/adminlte/test/dataDictionary/DataDictionaryTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.roncoo.adminlte.bean.entity.RcEmailInfo; import com.roncoo.adminlte.service.impl.dao.EmailInfoDao; package com.roncoo.adminlte.test.dataDictionary; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext-core.xml") public class DataDictionaryTest { @Autowired private EmailInfoDao dao; @Test public void test() {
RcEmailInfo info = new RcEmailInfo();
roncoo/roncoo-adminlte-springmvc
src/main/java/com/roncoo/adminlte/util/interceptor/SessionInterceptor.java
// Path: src/main/java/com/roncoo/adminlte/util/ConfUtil.java // public class ConfUtil { // // private ConfUtil() { // } // // /** // * 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例) // */ // private static Properties properties = new Properties(); // // // 通过类装载器装载进来 // static { // try { // // 从类路径下读取属性文件 // properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf.properties")); // } catch (IOException e) { // e.printStackTrace(); // } // } // // /** // * 根据key读取value // * // * @param keyName // * key // * @return // */ // public static String getProperty(String keyName) { // return getProperty(keyName, ""); // } // // /** // * 根据key读取value,key为空,返回默认值 // * // * @param keyName // * key // * @param defaultValue // * 默认值 // * @return // */ // public static String getProperty(String keyName, String defaultValue) { // return properties.getProperty(keyName, defaultValue); // } // } // // Path: src/main/java/com/roncoo/adminlte/util/Constants.java // public final class Constants { // // private Constants() { // } // // /** // * 常量 // * // * @author wujing // */ // public interface Token { // public final static String RONCOO = "roncoo"; // } // // /** // * 状态类型 // * // * @author wujing // */ // public interface Status { // public final static String ZERO = "0"; // public final static String ONE = "1"; // public final static String TWO = "2"; // public final static String THREE = "3"; // } // // /** // * 数字类型 // * // * @author wujing // * @version 1.0 // */ // public interface Num { // public final static int ZERO = 0; // public final static int ONE = 1; // public final static int FIVE = 5; // public final static int TEN = 10; // } // // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.roncoo.adminlte.util.ConfUtil; import com.roncoo.adminlte.util.Constants;
/* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.util.interceptor; /** * Session拦截器 * * @author wujing */ public class SessionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); if (session == null) {
// Path: src/main/java/com/roncoo/adminlte/util/ConfUtil.java // public class ConfUtil { // // private ConfUtil() { // } // // /** // * 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例) // */ // private static Properties properties = new Properties(); // // // 通过类装载器装载进来 // static { // try { // // 从类路径下读取属性文件 // properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf.properties")); // } catch (IOException e) { // e.printStackTrace(); // } // } // // /** // * 根据key读取value // * // * @param keyName // * key // * @return // */ // public static String getProperty(String keyName) { // return getProperty(keyName, ""); // } // // /** // * 根据key读取value,key为空,返回默认值 // * // * @param keyName // * key // * @param defaultValue // * 默认值 // * @return // */ // public static String getProperty(String keyName, String defaultValue) { // return properties.getProperty(keyName, defaultValue); // } // } // // Path: src/main/java/com/roncoo/adminlte/util/Constants.java // public final class Constants { // // private Constants() { // } // // /** // * 常量 // * // * @author wujing // */ // public interface Token { // public final static String RONCOO = "roncoo"; // } // // /** // * 状态类型 // * // * @author wujing // */ // public interface Status { // public final static String ZERO = "0"; // public final static String ONE = "1"; // public final static String TWO = "2"; // public final static String THREE = "3"; // } // // /** // * 数字类型 // * // * @author wujing // * @version 1.0 // */ // public interface Num { // public final static int ZERO = 0; // public final static int ONE = 1; // public final static int FIVE = 5; // public final static int TEN = 10; // } // // } // Path: src/main/java/com/roncoo/adminlte/util/interceptor/SessionInterceptor.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.roncoo.adminlte.util.ConfUtil; import com.roncoo.adminlte.util.Constants; /* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.util.interceptor; /** * Session拦截器 * * @author wujing */ public class SessionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); if (session == null) {
response.sendRedirect(ConfUtil.getProperty("redirectUrl"));
roncoo/roncoo-adminlte-springmvc
src/main/java/com/roncoo/adminlte/util/interceptor/SessionInterceptor.java
// Path: src/main/java/com/roncoo/adminlte/util/ConfUtil.java // public class ConfUtil { // // private ConfUtil() { // } // // /** // * 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例) // */ // private static Properties properties = new Properties(); // // // 通过类装载器装载进来 // static { // try { // // 从类路径下读取属性文件 // properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf.properties")); // } catch (IOException e) { // e.printStackTrace(); // } // } // // /** // * 根据key读取value // * // * @param keyName // * key // * @return // */ // public static String getProperty(String keyName) { // return getProperty(keyName, ""); // } // // /** // * 根据key读取value,key为空,返回默认值 // * // * @param keyName // * key // * @param defaultValue // * 默认值 // * @return // */ // public static String getProperty(String keyName, String defaultValue) { // return properties.getProperty(keyName, defaultValue); // } // } // // Path: src/main/java/com/roncoo/adminlte/util/Constants.java // public final class Constants { // // private Constants() { // } // // /** // * 常量 // * // * @author wujing // */ // public interface Token { // public final static String RONCOO = "roncoo"; // } // // /** // * 状态类型 // * // * @author wujing // */ // public interface Status { // public final static String ZERO = "0"; // public final static String ONE = "1"; // public final static String TWO = "2"; // public final static String THREE = "3"; // } // // /** // * 数字类型 // * // * @author wujing // * @version 1.0 // */ // public interface Num { // public final static int ZERO = 0; // public final static int ONE = 1; // public final static int FIVE = 5; // public final static int TEN = 10; // } // // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.roncoo.adminlte.util.ConfUtil; import com.roncoo.adminlte.util.Constants;
/* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.util.interceptor; /** * Session拦截器 * * @author wujing */ public class SessionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); if (session == null) { response.sendRedirect(ConfUtil.getProperty("redirectUrl")); return false; } else {
// Path: src/main/java/com/roncoo/adminlte/util/ConfUtil.java // public class ConfUtil { // // private ConfUtil() { // } // // /** // * 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例) // */ // private static Properties properties = new Properties(); // // // 通过类装载器装载进来 // static { // try { // // 从类路径下读取属性文件 // properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf.properties")); // } catch (IOException e) { // e.printStackTrace(); // } // } // // /** // * 根据key读取value // * // * @param keyName // * key // * @return // */ // public static String getProperty(String keyName) { // return getProperty(keyName, ""); // } // // /** // * 根据key读取value,key为空,返回默认值 // * // * @param keyName // * key // * @param defaultValue // * 默认值 // * @return // */ // public static String getProperty(String keyName, String defaultValue) { // return properties.getProperty(keyName, defaultValue); // } // } // // Path: src/main/java/com/roncoo/adminlte/util/Constants.java // public final class Constants { // // private Constants() { // } // // /** // * 常量 // * // * @author wujing // */ // public interface Token { // public final static String RONCOO = "roncoo"; // } // // /** // * 状态类型 // * // * @author wujing // */ // public interface Status { // public final static String ZERO = "0"; // public final static String ONE = "1"; // public final static String TWO = "2"; // public final static String THREE = "3"; // } // // /** // * 数字类型 // * // * @author wujing // * @version 1.0 // */ // public interface Num { // public final static int ZERO = 0; // public final static int ONE = 1; // public final static int FIVE = 5; // public final static int TEN = 10; // } // // } // Path: src/main/java/com/roncoo/adminlte/util/interceptor/SessionInterceptor.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.roncoo.adminlte.util.ConfUtil; import com.roncoo.adminlte.util.Constants; /* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.util.interceptor; /** * Session拦截器 * * @author wujing */ public class SessionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); if (session == null) { response.sendRedirect(ConfUtil.getProperty("redirectUrl")); return false; } else {
Object obj = session.getAttribute(Constants.Token.RONCOO);
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldBuildTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-build-test * */ public class MavenITHelloWorldBuildTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-build-test" );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldBuildTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-build-test * */ public class MavenITHelloWorldBuildTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-build-test" );
final File targetDir = calculateAndDeleteOutputDirectory( testDir, "target" );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldBuildTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-build-test * */ public class MavenITHelloWorldBuildTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-build-test" ); final File targetDir = calculateAndDeleteOutputDirectory( testDir, "target" ); final File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); final File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldBuildTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-build-test * */ public class MavenITHelloWorldBuildTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-build-test" ); final File targetDir = calculateAndDeleteOutputDirectory( testDir, "target" ); final File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); final File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
addPropertiesToVerifier( verifier );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldBuildTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-build-test * */ public class MavenITHelloWorldBuildTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-build-test" ); final File targetDir = calculateAndDeleteOutputDirectory( testDir, "target" ); final File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); final File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "compile" ); verifier.verifyErrorFreeLog();
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldBuildTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-build-test * */ public class MavenITHelloWorldBuildTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-build-test" ); final File targetDir = calculateAndDeleteOutputDirectory( testDir, "target" ); final File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); final File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "compile" ); verifier.verifyErrorFreeLog();
assertDirectoryContents( releaseDir, 4, Arrays.asList(
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldBuildTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
"/hello-world-build-test/hello-world" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, PROJECT_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog(); // We don't check all the files, just the most important ones // Different versions/installs of Visual Studio generate different file sets anyway! assertDirectoryContents( releaseDir, -1, Arrays.asList( new String[]{"hello-world.exe", "hello-world.obj", "hello-world.pdb"} ) ); assertDirectoryContents( debugDir, -1, Arrays.asList( new String[]{"hello-world.exe", "hello-world.obj", "hello-world.ilk", "hello-world.pdb"} ) ); File artifactsDir = new File( verifier.getArtifactMetadataPath( GROUPID, PROJECT_ARTIFACTID, VERSION ) ).getParentFile(); assertDirectoryContents( artifactsDir, 5, Arrays.asList( new String[]{ PROJECT_ARTIFACTID + "-" + VERSION + ".pom", PROJECT_ARTIFACTID + "-" + VERSION + ".exe", PROJECT_ARTIFACTID + "-" + VERSION + "-Win32-Debug.exe"} ) ); verifier.resetStreams(); verifier.executeGoal( "clean" ); verifier.verifyErrorFreeLog();
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldBuildTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; "/hello-world-build-test/hello-world" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, PROJECT_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog(); // We don't check all the files, just the most important ones // Different versions/installs of Visual Studio generate different file sets anyway! assertDirectoryContents( releaseDir, -1, Arrays.asList( new String[]{"hello-world.exe", "hello-world.obj", "hello-world.pdb"} ) ); assertDirectoryContents( debugDir, -1, Arrays.asList( new String[]{"hello-world.exe", "hello-world.obj", "hello-world.ilk", "hello-world.pdb"} ) ); File artifactsDir = new File( verifier.getArtifactMetadataPath( GROUPID, PROJECT_ARTIFACTID, VERSION ) ).getParentFile(); assertDirectoryContents( artifactsDir, 5, Arrays.asList( new String[]{ PROJECT_ARTIFACTID + "-" + VERSION + ".pom", PROJECT_ARTIFACTID + "-" + VERSION + ".exe", PROJECT_ARTIFACTID + "-" + VERSION + "-Win32-Debug.exe"} ) ); verifier.resetStreams(); verifier.executeGoal( "clean" ); verifier.verifyErrorFreeLog();
checkProjectBuildOutputIsCleaned( "hello-world", releaseDir );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITMultiPlatformTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITMultiPlatformTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/multi-platform-test" );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITMultiPlatformTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITMultiPlatformTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/multi-platform-test" );
File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITMultiPlatformTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITMultiPlatformTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/multi-platform-test" ); File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File win32DebugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); File x64ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "x64\\Release" ); File x64DebugDir = calculateAndDeleteOutputDirectory( testDir, "x64\\Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITMultiPlatformTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITMultiPlatformTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/multi-platform-test" ); File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File win32DebugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); File x64ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "x64\\Release" ); File x64DebugDir = calculateAndDeleteOutputDirectory( testDir, "x64\\Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
addPropertiesToVerifier( verifier );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITMultiPlatformTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITMultiPlatformTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/multi-platform-test" ); File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File win32DebugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); File x64ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "x64\\Release" ); File x64DebugDir = calculateAndDeleteOutputDirectory( testDir, "x64\\Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog();
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITMultiPlatformTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITMultiPlatformTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/multi-platform-test" ); File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File win32DebugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); File x64ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "x64\\Release" ); File x64DebugDir = calculateAndDeleteOutputDirectory( testDir, "x64\\Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog();
assertDirectoryContents( win32ReleaseDir, 4, Arrays.asList(
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITOutputDirectoryTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITOutputDirectoryTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/output-directory-test" );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITOutputDirectoryTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITOutputDirectoryTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/output-directory-test" );
File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Release" );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITOutputDirectoryTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITOutputDirectoryTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/output-directory-test" ); File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Release" ); File win32DebugDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITOutputDirectoryTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITOutputDirectoryTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/output-directory-test" ); File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Release" ); File win32DebugDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
addPropertiesToVerifier( verifier );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITOutputDirectoryTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITOutputDirectoryTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/output-directory-test" ); File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Release" ); File win32DebugDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog();
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITOutputDirectoryTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the multi-platform-test * */ public class MavenITOutputDirectoryTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/output-directory-test" ); File win32ReleaseDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Release" ); File win32DebugDir = calculateAndDeleteOutputDirectory( testDir, "Runtime\\Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog();
assertDirectoryContents( win32ReleaseDir, 5, Arrays.asList( new String[]
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldLibTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-lib-test * */ public class MavenITHelloWorldLibTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-lib-test" );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldLibTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-lib-test * */ public class MavenITHelloWorldLibTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-lib-test" );
File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldLibTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-lib-test * */ public class MavenITHelloWorldLibTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-lib-test" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldLibTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-lib-test * */ public class MavenITHelloWorldLibTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-lib-test" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
addPropertiesToVerifier( verifier );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldLibTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-lib-test * */ public class MavenITHelloWorldLibTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-lib-test" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog();
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldLibTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-lib-test * */ public class MavenITHelloWorldLibTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-lib-test" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog();
assertDirectoryContents( releaseDir, 1, Arrays.asList(
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldLibTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, PROJECT_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog(); // We don't check all the files, just the most important ones // Different versions/installs of Visual Studio generate different file sets anyway! assertDirectoryContents( releaseDir, -1, Arrays.asList( new String[]{"hello-world.obj", "hello-world-lib.lib"} ) ); assertDirectoryContents( debugDir, -1, Arrays.asList( new String[]{"hello-world.obj", "hello-world-lib.lib"} ) ); File artifactsDir = new File( verifier.getArtifactMetadataPath( GROUPID, PROJECT_ARTIFACTID, VERSION ) ).getParentFile(); assertDirectoryContents( artifactsDir, 5, Arrays.asList( new String[]{ PROJECT_ARTIFACTID + "-" + VERSION + ".pom", PROJECT_ARTIFACTID + "-" + VERSION + ".lib", PROJECT_ARTIFACTID + "-" + VERSION + "-Win32-Debug.lib"} ) ); verifier.resetStreams(); verifier.executeGoal( "clean" ); verifier.verifyErrorFreeLog();
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldLibTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, PROJECT_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog(); // We don't check all the files, just the most important ones // Different versions/installs of Visual Studio generate different file sets anyway! assertDirectoryContents( releaseDir, -1, Arrays.asList( new String[]{"hello-world.obj", "hello-world-lib.lib"} ) ); assertDirectoryContents( debugDir, -1, Arrays.asList( new String[]{"hello-world.obj", "hello-world-lib.lib"} ) ); File artifactsDir = new File( verifier.getArtifactMetadataPath( GROUPID, PROJECT_ARTIFACTID, VERSION ) ).getParentFile(); assertDirectoryContents( artifactsDir, 5, Arrays.asList( new String[]{ PROJECT_ARTIFACTID + "-" + VERSION + ".pom", PROJECT_ARTIFACTID + "-" + VERSION + ".lib", PROJECT_ARTIFACTID + "-" + VERSION + "-Win32-Debug.lib"} ) ); verifier.resetStreams(); verifier.executeGoal( "clean" ); verifier.verifyErrorFreeLog();
checkProjectBuildOutputIsCleaned( "hello-world-lib", releaseDir );
andi12/msbuild-maven-plugin
msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/MojoHelper.java
// Path: msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/configuration/BuildPlatform.java // public class BuildPlatform // { // /** // * String constant for platform name 'Win32' // */ // private static final String PLATFORM_WIN32 = "Win32"; // /** // * Constant for the default platform name. // */ // public static final String DEFAULT_PLATFORM = PLATFORM_WIN32; // // /** // * Construct a default BuildPlatform. // */ // public BuildPlatform() // { // name = DEFAULT_PLATFORM; // configurations = new ArrayList<BuildConfiguration>( Arrays.asList( RELEASE_CONFIGURATION ) ); // } // // /** // * Construct a BuildPlatform with the specified name. // * @param name the platform name // */ // public BuildPlatform( String name ) // { // this.name = name; // configurations = new ArrayList<BuildConfiguration>( Arrays.asList( RELEASE_CONFIGURATION ) ); // } // // @Override // public String toString() // { // return name; // } // // @Override // public int hashCode() // { // return name.hashCode(); // } // // @Override // public boolean equals( Object o ) // { // if ( name != null && name.equals( ( ( BuildPlatform ) o ).name ) ) // { // return true; // } // return false; // } // // /** // * Get the name of this platform // * @return the platform name // */ // public String getName() // { // return name; // } // // /** // * Get the list of BuildConfiguration's for this platform // * @return the build configurations // */ // public List<BuildConfiguration> getConfigurations() // { // if ( configurations.isEmpty() ) // { // configurations.add( new BuildConfiguration() ); // } // return configurations; // } // // /** // * Test if this platform is named 'Win32' // * @return true if this platform Win32 // */ // public boolean isWin32() // { // return PLATFORM_WIN32.equals( name ); // } // // /** // * Check the configurations and mark one as primary. // * @throws MojoExecutionException if duplicate configuration names are found // */ // public void identifyPrimaryConfiguration() throws MojoExecutionException // { // Set<String> configurationNames = new HashSet<String>(); // for ( BuildConfiguration configuration : configurations ) // { // if ( configurationNames.contains( configuration.getName() ) ) // { // throw new MojoExecutionException( "Duplicate configuration '" + configuration.getName() // + "' for '" + getName() + "', configuration names must be unique" ); // } // configurationNames.add( configuration.getName() ); // configuration.setPrimary( false ); // } // if ( configurations.contains( RELEASE_CONFIGURATION ) ) // { // configurations.get( configurations.indexOf( RELEASE_CONFIGURATION ) ).setPrimary( true ); // } // else if ( configurations.contains( DEBUG_CONFIGURATION ) ) // { // configurations.get( configurations.indexOf( DEBUG_CONFIGURATION ) ).setPrimary( true ); // } // else // { // configurations.get( 0 ).setPrimary( true ); // } // } // // private static final BuildConfiguration RELEASE_CONFIGURATION = new BuildConfiguration( "Release" ); // private static final BuildConfiguration DEBUG_CONFIGURATION = new BuildConfiguration( "Debug" ); // // @Parameter // private String name; // // @Parameter // private List<BuildConfiguration> configurations; // }
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import uk.org.raje.maven.plugin.msbuild.configuration.BuildPlatform;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild; /** * Collection of utilities used by Mojo's in the msbuild-maven-plugin. */ public class MojoHelper { // no instances private MojoHelper() { } /** * Validates the path to a command-line tool. * @param toolPath the configured tool path from the POM * @param toolName the name of the tool, used for logging messages * @param logger a Log to write messages to * @throws FileNotFoundException if the tool cannot be found */ public static void validateToolPath( File toolPath, String toolName, Log logger ) throws FileNotFoundException { logger.debug( "Validating path for " + toolName ); if ( toolPath == null ) { logger.error( "Missing " + toolName + " path" ); throw new FileNotFoundException(); } if ( !toolPath.exists() || !toolPath.isFile() ) { logger.error( "Could not find " + toolName + " at " + toolPath ); throw new FileNotFoundException( toolPath.getAbsolutePath() ); } logger.debug( "Found " + toolName + " at " + toolPath ); } /** * Check that we have a valid set of platforms. * If no platforms are configured we create 1 default platform. * @param platforms the list of BuildPlatform's to validate * @return the passed in list or a new list with a default platform added * @throws MojoExecutionException if the configuration is invalid. */
// Path: msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/configuration/BuildPlatform.java // public class BuildPlatform // { // /** // * String constant for platform name 'Win32' // */ // private static final String PLATFORM_WIN32 = "Win32"; // /** // * Constant for the default platform name. // */ // public static final String DEFAULT_PLATFORM = PLATFORM_WIN32; // // /** // * Construct a default BuildPlatform. // */ // public BuildPlatform() // { // name = DEFAULT_PLATFORM; // configurations = new ArrayList<BuildConfiguration>( Arrays.asList( RELEASE_CONFIGURATION ) ); // } // // /** // * Construct a BuildPlatform with the specified name. // * @param name the platform name // */ // public BuildPlatform( String name ) // { // this.name = name; // configurations = new ArrayList<BuildConfiguration>( Arrays.asList( RELEASE_CONFIGURATION ) ); // } // // @Override // public String toString() // { // return name; // } // // @Override // public int hashCode() // { // return name.hashCode(); // } // // @Override // public boolean equals( Object o ) // { // if ( name != null && name.equals( ( ( BuildPlatform ) o ).name ) ) // { // return true; // } // return false; // } // // /** // * Get the name of this platform // * @return the platform name // */ // public String getName() // { // return name; // } // // /** // * Get the list of BuildConfiguration's for this platform // * @return the build configurations // */ // public List<BuildConfiguration> getConfigurations() // { // if ( configurations.isEmpty() ) // { // configurations.add( new BuildConfiguration() ); // } // return configurations; // } // // /** // * Test if this platform is named 'Win32' // * @return true if this platform Win32 // */ // public boolean isWin32() // { // return PLATFORM_WIN32.equals( name ); // } // // /** // * Check the configurations and mark one as primary. // * @throws MojoExecutionException if duplicate configuration names are found // */ // public void identifyPrimaryConfiguration() throws MojoExecutionException // { // Set<String> configurationNames = new HashSet<String>(); // for ( BuildConfiguration configuration : configurations ) // { // if ( configurationNames.contains( configuration.getName() ) ) // { // throw new MojoExecutionException( "Duplicate configuration '" + configuration.getName() // + "' for '" + getName() + "', configuration names must be unique" ); // } // configurationNames.add( configuration.getName() ); // configuration.setPrimary( false ); // } // if ( configurations.contains( RELEASE_CONFIGURATION ) ) // { // configurations.get( configurations.indexOf( RELEASE_CONFIGURATION ) ).setPrimary( true ); // } // else if ( configurations.contains( DEBUG_CONFIGURATION ) ) // { // configurations.get( configurations.indexOf( DEBUG_CONFIGURATION ) ).setPrimary( true ); // } // else // { // configurations.get( 0 ).setPrimary( true ); // } // } // // private static final BuildConfiguration RELEASE_CONFIGURATION = new BuildConfiguration( "Release" ); // private static final BuildConfiguration DEBUG_CONFIGURATION = new BuildConfiguration( "Debug" ); // // @Parameter // private String name; // // @Parameter // private List<BuildConfiguration> configurations; // } // Path: msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/MojoHelper.java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import uk.org.raje.maven.plugin.msbuild.configuration.BuildPlatform; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild; /** * Collection of utilities used by Mojo's in the msbuild-maven-plugin. */ public class MojoHelper { // no instances private MojoHelper() { } /** * Validates the path to a command-line tool. * @param toolPath the configured tool path from the POM * @param toolName the name of the tool, used for logging messages * @param logger a Log to write messages to * @throws FileNotFoundException if the tool cannot be found */ public static void validateToolPath( File toolPath, String toolName, Log logger ) throws FileNotFoundException { logger.debug( "Validating path for " + toolName ); if ( toolPath == null ) { logger.error( "Missing " + toolName + " path" ); throw new FileNotFoundException(); } if ( !toolPath.exists() || !toolPath.isFile() ) { logger.error( "Could not find " + toolName + " at " + toolPath ); throw new FileNotFoundException( toolPath.getAbsolutePath() ); } logger.debug( "Found " + toolName + " at " + toolPath ); } /** * Check that we have a valid set of platforms. * If no platforms are configured we create 1 default platform. * @param platforms the list of BuildPlatform's to validate * @return the passed in list or a new list with a default platform added * @throws MojoExecutionException if the configuration is invalid. */
public static List<BuildPlatform> validatePlatforms( List<BuildPlatform> platforms ) throws MojoExecutionException
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldDllTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-dll-test * */ public class MavenITHelloWorldDllTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-dll-test" );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldDllTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-dll-test * */ public class MavenITHelloWorldDllTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-dll-test" );
File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldDllTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-dll-test * */ public class MavenITHelloWorldDllTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-dll-test" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldDllTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-dll-test * */ public class MavenITHelloWorldDllTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-dll-test" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
addPropertiesToVerifier( verifier );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldDllTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-dll-test * */ public class MavenITHelloWorldDllTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-dll-test" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog();
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldDllTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Integration test that runs the hello-world-dll-test * */ public class MavenITHelloWorldDllTest { @Test public void testSolutionBuild() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/hello-world-dll-test" ); File releaseDir = calculateAndDeleteOutputDirectory( testDir, "Release" ); File debugDir = calculateAndDeleteOutputDirectory( testDir, "Debug" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, SOLUTION_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog();
assertDirectoryContents( releaseDir, 4, Arrays.asList(
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldDllTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned;
Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, PROJECT_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog(); // We don't check all the files, just the most important ones // Different versions/installs of Visual Studio generate different file sets anyway! assertDirectoryContents( releaseDir, -1, Arrays.asList( new String[]{"hello-world-dll.dll", "hello-world-dll.obj", "stdafx.obj", "dllmain.obj", "hello-world-dll.pch", "hello-world-dll.pdb"} ) ); assertDirectoryContents( debugDir, -1, Arrays.asList( new String[]{"hello-world-dll.dll", "hello-world-dll.obj", "stdafx.obj", "dllmain.obj", "hello-world-dll.ilk", "hello-world-dll.pch", "hello-world-dll.pdb"} ) ); File artifactsDir = new File( verifier.getArtifactMetadataPath( GROUPID, PROJECT_ARTIFACTID, VERSION ) ).getParentFile(); assertDirectoryContents( artifactsDir, 5, Arrays.asList( new String[]{ PROJECT_ARTIFACTID + "-" + VERSION + ".pom", PROJECT_ARTIFACTID + "-" + VERSION + ".dll", PROJECT_ARTIFACTID + "-" + VERSION + "-Win32-Debug.dll"} ) ); verifier.resetStreams(); verifier.executeGoal( "clean" ); verifier.verifyErrorFreeLog();
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void assertDirectoryContents( File directory, int expectedCount, List<String> expectedFiles ) // { // assertTrue ( "Expected output directory missing: " + directory.getAbsolutePath(), directory.exists() ); // List<String> dirContents = Arrays.asList( directory.list() ); // if ( expectedCount != -1 ) // { // assertEquals( expectedCount, dirContents.size() ); // } // for ( String fileName: expectedFiles ) // { // assertTrue( "Expected file missing: " + fileName, dirContents.contains( fileName ) ); // } // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static File calculateAndDeleteOutputDirectory( File parent, String name ) throws IOException // { // File result = new File( parent, name ); // if ( result.exists() ) // { // for ( File content : result.listFiles() ) // { // // NOTE: No attempt to recurse, shouldn't ever be needed! // if ( !content.delete() ) // { // throw new IOException( "Failed to delete " + content.getAbsolutePath() ); // } // } // if ( !result.delete() ) // { // throw new IOException( "Failed to delete " + result.getAbsolutePath() ); // } // } // // return result; // } // // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void checkProjectBuildOutputIsCleaned( String projectName, File outputDir ) // { // if ( outputDir.exists() ) // if the directory doesn't exist we're clean // { // // What is left depends on exact tool version so we aren't too strict // List<String> dirContents = Arrays.asList( outputDir.list( new FilenameFilter() { // @Override // public boolean accept( File path, String name ) // { // return path.isFile(); // } // } ) ); // if ( dirContents.size() != 0 ) // if the directory contains something it should just be the log file // { // assertEquals( 1, dirContents.size() ); // assertTrue( "Unexpect files left after clean", // dirContents.contains( projectName + ".Build.CppClean.log" ) // VS 2010 // || dirContents.contains( projectName + ".log" ) // VS 2015 // ); // } // } // // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITHelloWorldDllTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Arrays; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.assertDirectoryContents; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.calculateAndDeleteOutputDirectory; import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.checkProjectBuildOutputIsCleaned; Verifier verifier = new Verifier( testDir.getAbsolutePath() ); addPropertiesToVerifier( verifier ); // Delete any existing artifact from the local repository verifier.deleteArtifacts( GROUPID, PROJECT_ARTIFACTID, VERSION ); verifier.executeGoal( "install" ); verifier.verifyErrorFreeLog(); // We don't check all the files, just the most important ones // Different versions/installs of Visual Studio generate different file sets anyway! assertDirectoryContents( releaseDir, -1, Arrays.asList( new String[]{"hello-world-dll.dll", "hello-world-dll.obj", "stdafx.obj", "dllmain.obj", "hello-world-dll.pch", "hello-world-dll.pdb"} ) ); assertDirectoryContents( debugDir, -1, Arrays.asList( new String[]{"hello-world-dll.dll", "hello-world-dll.obj", "stdafx.obj", "dllmain.obj", "hello-world-dll.ilk", "hello-world-dll.pch", "hello-world-dll.pdb"} ) ); File artifactsDir = new File( verifier.getArtifactMetadataPath( GROUPID, PROJECT_ARTIFACTID, VERSION ) ).getParentFile(); assertDirectoryContents( artifactsDir, 5, Arrays.asList( new String[]{ PROJECT_ARTIFACTID + "-" + VERSION + ".pom", PROJECT_ARTIFACTID + "-" + VERSION + ".dll", PROJECT_ARTIFACTID + "-" + VERSION + "-Win32-Debug.dll"} ) ); verifier.resetStreams(); verifier.executeGoal( "clean" ); verifier.verifyErrorFreeLog();
checkProjectBuildOutputIsCleaned( "hello-world-dll", releaseDir );
andi12/msbuild-maven-plugin
msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITSonarConfigurationTest.java
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // }
import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import java.io.File; import junitx.framework.FileAssert; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test;
/* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Test Sonar configuration generation. */ public class MavenITSonarConfigurationTest { /** * Test simple configuration with no CppCheck or CxxTest * @throws Exception if there is a problem setting up and running Maven */ @Test public void simpleConfig() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/sonar-config-test" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
// Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MSBuildMojoITHelper.java // static void addPropertiesToVerifier( Verifier verifier ) throws IOException // { // Properties props = new Properties(); // props.load( MSBuildMojoITHelper.class.getResourceAsStream( VERIFIER_PROPERTIES_FILE ) ); // Properties systemProps = verifier.getSystemProperties(); // systemProps.putAll( props ); // verifier.setSystemProperties( systemProps ); // } // Path: msbuild-maven-plugin-it/src/test/java/uk/org/raje/maven/plugin/msbuild/it/MavenITSonarConfigurationTest.java import static uk.org.raje.maven.plugin.msbuild.it.MSBuildMojoITHelper.addPropertiesToVerifier; import java.io.File; import junitx.framework.FileAssert; import org.apache.maven.it.Verifier; import org.apache.maven.it.util.ResourceExtractor; import org.junit.Test; /* * Copyright 2013 Andrew Everitt, Andrew Heckford, Daniele Masato * * 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 uk.org.raje.maven.plugin.msbuild.it; /** * Test Sonar configuration generation. */ public class MavenITSonarConfigurationTest { /** * Test simple configuration with no CppCheck or CxxTest * @throws Exception if there is a problem setting up and running Maven */ @Test public void simpleConfig() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/sonar-config-test" ); Verifier verifier = new Verifier( testDir.getAbsolutePath() );
addPropertiesToVerifier( verifier );
jaredrummler/TrueTypeParser
lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/io/ClosedInputStream.java
// Path: lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/io/IOUtils.java // public static final int EOF = -1;
import java.io.InputStream; import static com.jaredrummler.fontreader.io.IOUtils.EOF;
/* * Copyright (C) 2016 Jared Rummler <jared.rummler@gmail.com> * * 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.jaredrummler.fontreader.io; /** * Closed input stream. This stream returns EOF to all attempts to read * something from the stream. * <p> * Typically uses of this class include testing for corner cases in methods * that accept input streams and acting as a sentinel value instead of a * {@code null} input stream. */ public class ClosedInputStream extends InputStream { /** * A singleton. */ public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream(); /** * Returns -1 to indicate that the stream is closed. * * @return always -1 */ @Override public int read() {
// Path: lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/io/IOUtils.java // public static final int EOF = -1; // Path: lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/io/ClosedInputStream.java import java.io.InputStream; import static com.jaredrummler.fontreader.io.IOUtils.EOF; /* * Copyright (C) 2016 Jared Rummler <jared.rummler@gmail.com> * * 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.jaredrummler.fontreader.io; /** * Closed input stream. This stream returns EOF to all attempts to read * something from the stream. * <p> * Typically uses of this class include testing for corner cases in methods * that accept input streams and acting as a sentinel value instead of a * {@code null} input stream. */ public class ClosedInputStream extends InputStream { /** * A singleton. */ public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream(); /** * Returns -1 to indicate that the stream is closed. * * @return always -1 */ @Override public int read() {
return EOF;
jaredrummler/TrueTypeParser
lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/io/ByteArrayOutputStream.java
// Path: lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/io/IOUtils.java // public static final int EOF = -1;
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.SequenceInputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.jaredrummler.fontreader.io.IOUtils.EOF;
* the byte to write */ @Override public synchronized void write(final int b) { int inBufferPos = count - filledBufferSum; if (inBufferPos == currentBuffer.length) { needNewBuffer(count + 1); inBufferPos = 0; } currentBuffer[inBufferPos] = (byte) b; count++; } /** * Writes the entire contents of the specified input stream to this * byte stream. Bytes from the input stream are read directly into the * internal buffers of this streams. * * @param in * the input stream to read from * @return total number of bytes read from the input stream * (and written to this stream) * @throws IOException * if an I/O error occurs while reading the input stream * @since 1.4 */ public synchronized int write(final InputStream in) throws IOException { int readCount = 0; int inBufferPos = count - filledBufferSum; int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
// Path: lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/io/IOUtils.java // public static final int EOF = -1; // Path: lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/io/ByteArrayOutputStream.java import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.SequenceInputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.jaredrummler.fontreader.io.IOUtils.EOF; * the byte to write */ @Override public synchronized void write(final int b) { int inBufferPos = count - filledBufferSum; if (inBufferPos == currentBuffer.length) { needNewBuffer(count + 1); inBufferPos = 0; } currentBuffer[inBufferPos] = (byte) b; count++; } /** * Writes the entire contents of the specified input stream to this * byte stream. Bytes from the input stream are read directly into the * internal buffers of this streams. * * @param in * the input stream to read from * @return total number of bytes read from the input stream * (and written to this stream) * @throws IOException * if an I/O error occurs while reading the input stream * @since 1.4 */ public synchronized int write(final InputStream in) throws IOException { int readCount = 0; int inBufferPos = count - filledBufferSum; int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
while (n != EOF) {
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/ScanExceptionTest.java
// Path: src/main/java/org/usb4java/javax/ScanException.java // public final class ScanException extends RuntimeException // { // /** Serial version UID. */ // private static final long serialVersionUID = 1L; // // /** // * Constructor. // * // * @param message // * The error message. // * @param cause // * The root cause. // */ // ScanException(final String message, final Throwable cause) // { // super(message, cause); // } // }
import org.junit.Test; import org.usb4java.javax.ScanException; import static org.junit.Assert.assertEquals;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link ScanException} class. * * @author Klaus Reimer (k@ailis.de) */ public class ScanExceptionTest { /** * Tests the constructor. */ @Test public void testConstructor() { final Throwable cause = new RuntimeException(""); final String message = "Bang";
// Path: src/main/java/org/usb4java/javax/ScanException.java // public final class ScanException extends RuntimeException // { // /** Serial version UID. */ // private static final long serialVersionUID = 1L; // // /** // * Constructor. // * // * @param message // * The error message. // * @param cause // * The root cause. // */ // ScanException(final String message, final Throwable cause) // { // super(message, cause); // } // } // Path: src/test/java/org/usb4java/javax/ScanExceptionTest.java import org.junit.Test; import org.usb4java.javax.ScanException; import static org.junit.Assert.assertEquals; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link ScanException} class. * * @author Klaus Reimer (k@ailis.de) */ public class ScanExceptionTest { /** * Tests the constructor. */ @Test public void testConstructor() { final Throwable cause = new RuntimeException(""); final String message = "Bang";
final ScanException exception = new ScanException(message, cause);
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/DeviceListenerListTest.java
// Path: src/main/java/org/usb4java/javax/DeviceListenerList.java // final class DeviceListenerList extends // EventListenerList<UsbDeviceListener> implements UsbDeviceListener // { // /** // * Constructs a new USB device listener list. // */ // DeviceListenerList() // { // super(); // } // // @Override // public UsbDeviceListener[] toArray() // { // return getListeners().toArray( // new UsbDeviceListener[getListeners().size()]); // } // // @Override // public void usbDeviceDetached(final UsbDeviceEvent event) // { // for (final UsbDeviceListener listener: toArray()) // { // listener.usbDeviceDetached(event); // } // } // // @Override // public void errorEventOccurred(final UsbDeviceErrorEvent event) // { // for (final UsbDeviceListener listener: toArray()) // { // listener.errorEventOccurred(event); // } // } // // @Override // public void dataEventOccurred(final UsbDeviceDataEvent event) // { // for (final UsbDeviceListener listener: toArray()) // { // listener.dataEventOccurred(event); // } // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import javax.usb.UsbControlIrp; import javax.usb.UsbDevice; import javax.usb.event.UsbDeviceDataEvent; import javax.usb.event.UsbDeviceErrorEvent; import javax.usb.event.UsbDeviceListener; import org.junit.Before; import org.junit.Test; import org.usb4java.javax.DeviceListenerList;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link DeviceListenerList} class. * * @author Klaus Reimer (k@ailis.de) */ public class DeviceListenerListTest { /** The test subject. */
// Path: src/main/java/org/usb4java/javax/DeviceListenerList.java // final class DeviceListenerList extends // EventListenerList<UsbDeviceListener> implements UsbDeviceListener // { // /** // * Constructs a new USB device listener list. // */ // DeviceListenerList() // { // super(); // } // // @Override // public UsbDeviceListener[] toArray() // { // return getListeners().toArray( // new UsbDeviceListener[getListeners().size()]); // } // // @Override // public void usbDeviceDetached(final UsbDeviceEvent event) // { // for (final UsbDeviceListener listener: toArray()) // { // listener.usbDeviceDetached(event); // } // } // // @Override // public void errorEventOccurred(final UsbDeviceErrorEvent event) // { // for (final UsbDeviceListener listener: toArray()) // { // listener.errorEventOccurred(event); // } // } // // @Override // public void dataEventOccurred(final UsbDeviceDataEvent event) // { // for (final UsbDeviceListener listener: toArray()) // { // listener.dataEventOccurred(event); // } // } // } // Path: src/test/java/org/usb4java/javax/DeviceListenerListTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import javax.usb.UsbControlIrp; import javax.usb.UsbDevice; import javax.usb.event.UsbDeviceDataEvent; import javax.usb.event.UsbDeviceErrorEvent; import javax.usb.event.UsbDeviceListener; import org.junit.Before; import org.junit.Test; import org.usb4java.javax.DeviceListenerList; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link DeviceListenerList} class. * * @author Klaus Reimer (k@ailis.de) */ public class DeviceListenerListTest { /** The test subject. */
private DeviceListenerList list;
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/adapter/UsbDeviceAdapterTest.java
// Path: src/main/java/org/usb4java/javax/adapter/UsbDeviceAdapter.java // public abstract class UsbDeviceAdapter implements UsbDeviceListener // { // @Override // public void usbDeviceDetached(final UsbDeviceEvent event) // { // // Empty // } // // @Override // public void errorEventOccurred(final UsbDeviceErrorEvent event) // { // // Empty // } // // @Override // public void dataEventOccurred(final UsbDeviceDataEvent event) // { // // Empty // } // }
import javax.usb.event.UsbDeviceDataEvent; import javax.usb.event.UsbDeviceErrorEvent; import javax.usb.event.UsbDeviceEvent; import javax.usb.event.UsbDeviceListener; import org.junit.Test; import org.usb4java.javax.adapter.UsbDeviceAdapter;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax.adapter; /** * Test the {@link UsbDeviceAdapter} class. There is not really anything to * test there. This class just ensures that the class exists and provides * the needed methods. * * @author Klaus Reimer (k@ailis.de) */ public class UsbDeviceAdapterTest { /** * Ensure the existence of the needed methods. */ @Test public void testAbstractMethods() {
// Path: src/main/java/org/usb4java/javax/adapter/UsbDeviceAdapter.java // public abstract class UsbDeviceAdapter implements UsbDeviceListener // { // @Override // public void usbDeviceDetached(final UsbDeviceEvent event) // { // // Empty // } // // @Override // public void errorEventOccurred(final UsbDeviceErrorEvent event) // { // // Empty // } // // @Override // public void dataEventOccurred(final UsbDeviceDataEvent event) // { // // Empty // } // } // Path: src/test/java/org/usb4java/javax/adapter/UsbDeviceAdapterTest.java import javax.usb.event.UsbDeviceDataEvent; import javax.usb.event.UsbDeviceErrorEvent; import javax.usb.event.UsbDeviceEvent; import javax.usb.event.UsbDeviceListener; import org.junit.Test; import org.usb4java.javax.adapter.UsbDeviceAdapter; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax.adapter; /** * Test the {@link UsbDeviceAdapter} class. There is not really anything to * test there. This class just ensures that the class exists and provides * the needed methods. * * @author Klaus Reimer (k@ailis.de) */ public class UsbDeviceAdapterTest { /** * Ensure the existence of the needed methods. */ @Test public void testAbstractMethods() {
final UsbDeviceListener adapter = new UsbDeviceAdapter()
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/adapter/UsbPipeAdapterTest.java
// Path: src/main/java/org/usb4java/javax/adapter/UsbPipeAdapter.java // public abstract class UsbPipeAdapter implements UsbPipeListener // { // @Override // public void errorEventOccurred(final UsbPipeErrorEvent event) // { // // Empty // } // // @Override // public void dataEventOccurred(final UsbPipeDataEvent event) // { // // Empty // } // }
import javax.usb.event.UsbPipeDataEvent; import javax.usb.event.UsbPipeErrorEvent; import javax.usb.event.UsbPipeListener; import org.junit.Test; import org.usb4java.javax.adapter.UsbPipeAdapter;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax.adapter; /** * Test the {@link UsbPipeAdapter} class. There is not really anything to * test there. This class just ensures that the class exists and provides * the needed methods. * * @author Klaus Reimer (k@ailis.de) */ public class UsbPipeAdapterTest { /** * Ensure the existence of the needed methods. */ @Test public void testAbstractMethods() {
// Path: src/main/java/org/usb4java/javax/adapter/UsbPipeAdapter.java // public abstract class UsbPipeAdapter implements UsbPipeListener // { // @Override // public void errorEventOccurred(final UsbPipeErrorEvent event) // { // // Empty // } // // @Override // public void dataEventOccurred(final UsbPipeDataEvent event) // { // // Empty // } // } // Path: src/test/java/org/usb4java/javax/adapter/UsbPipeAdapterTest.java import javax.usb.event.UsbPipeDataEvent; import javax.usb.event.UsbPipeErrorEvent; import javax.usb.event.UsbPipeListener; import org.junit.Test; import org.usb4java.javax.adapter.UsbPipeAdapter; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax.adapter; /** * Test the {@link UsbPipeAdapter} class. There is not really anything to * test there. This class just ensures that the class exists and provides * the needed methods. * * @author Klaus Reimer (k@ailis.de) */ public class UsbPipeAdapterTest { /** * Ensure the existence of the needed methods. */ @Test public void testAbstractMethods() {
final UsbPipeListener adapter = new UsbPipeAdapter()
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/ConfigTest.java
// Path: src/main/java/org/usb4java/javax/Config.java // final class Config // { // /** Base key name for properties. */ // private static final String KEY_BASE = "org.usb4java.javax."; // // /** The default USB communication timeout in milliseconds. */ // private static final int DEFAULT_TIMEOUT = 5000; // // /** The default scan interval in milliseconds. */ // private static final int DEFAULT_SCAN_INTERVAL = 500; // // /** Key name for USB communication timeout. */ // private static final String TIMEOUT_KEY = KEY_BASE + "timeout"; // // /** Key name for USB communication timeout. */ // private static final String SCAN_INTERVAL_KEY = KEY_BASE + "scanInterval"; // // /** Key name for the USBDK usage flag. */ // private static final String USE_USBDK_KEY = KEY_BASE + "useUSBDK"; // // /** The timeout for USB communication in milliseconds. */ // private int timeout = DEFAULT_TIMEOUT; // // /** The scan interval in milliseconds. */ // private int scanInterval = DEFAULT_SCAN_INTERVAL; // // /** If USBDK is to be used on Windows. */ // private boolean useUSBDK = false; // // /** // * Constructs new configuration from the specified properties. // * // * @param properties // * The properties to read the configuration from. // */ // Config(final Properties properties) // { // // Read the USB communication timeout // if (properties.containsKey(TIMEOUT_KEY)) // { // this.timeout = Integer.valueOf(properties.getProperty(TIMEOUT_KEY)); // } // // // Read the USB device scan interval // if (properties.containsKey(SCAN_INTERVAL_KEY)) // { // this.scanInterval = Integer.valueOf(properties.getProperty( // SCAN_INTERVAL_KEY)); // } // // // Read the USBDK usage flag // if (properties.containsKey(USE_USBDK_KEY)) // { // this.useUSBDK = Boolean.valueOf(properties.getProperty(USE_USBDK_KEY)); // } // } // // /** // * Returns the USB communication timeout in milliseconds. // * // * @return The USB communication timeout in milliseconds. // */ // public int getTimeout() // { // return this.timeout; // } // // /** // * Returns the scan interval in milliseconds. // * // * @return The scan interval in milliseconds. // */ // public int getScanInterval() // { // return this.scanInterval; // } // // /** // * Check if USBDK is to be used on Windows. // * // * @return True if USBDK is to be used, false if not. // */ // public boolean isUseUSBDK() // { // return this.useUSBDK; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Properties; import org.junit.Test; import org.usb4java.javax.Config;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link Config} class. * * @author Klaus Reimer (k@ailis.de) */ public class ConfigTest { /** * Tests the default configuration */ @Test public void testDefaultConfiguration() { final Properties properties = new Properties();
// Path: src/main/java/org/usb4java/javax/Config.java // final class Config // { // /** Base key name for properties. */ // private static final String KEY_BASE = "org.usb4java.javax."; // // /** The default USB communication timeout in milliseconds. */ // private static final int DEFAULT_TIMEOUT = 5000; // // /** The default scan interval in milliseconds. */ // private static final int DEFAULT_SCAN_INTERVAL = 500; // // /** Key name for USB communication timeout. */ // private static final String TIMEOUT_KEY = KEY_BASE + "timeout"; // // /** Key name for USB communication timeout. */ // private static final String SCAN_INTERVAL_KEY = KEY_BASE + "scanInterval"; // // /** Key name for the USBDK usage flag. */ // private static final String USE_USBDK_KEY = KEY_BASE + "useUSBDK"; // // /** The timeout for USB communication in milliseconds. */ // private int timeout = DEFAULT_TIMEOUT; // // /** The scan interval in milliseconds. */ // private int scanInterval = DEFAULT_SCAN_INTERVAL; // // /** If USBDK is to be used on Windows. */ // private boolean useUSBDK = false; // // /** // * Constructs new configuration from the specified properties. // * // * @param properties // * The properties to read the configuration from. // */ // Config(final Properties properties) // { // // Read the USB communication timeout // if (properties.containsKey(TIMEOUT_KEY)) // { // this.timeout = Integer.valueOf(properties.getProperty(TIMEOUT_KEY)); // } // // // Read the USB device scan interval // if (properties.containsKey(SCAN_INTERVAL_KEY)) // { // this.scanInterval = Integer.valueOf(properties.getProperty( // SCAN_INTERVAL_KEY)); // } // // // Read the USBDK usage flag // if (properties.containsKey(USE_USBDK_KEY)) // { // this.useUSBDK = Boolean.valueOf(properties.getProperty(USE_USBDK_KEY)); // } // } // // /** // * Returns the USB communication timeout in milliseconds. // * // * @return The USB communication timeout in milliseconds. // */ // public int getTimeout() // { // return this.timeout; // } // // /** // * Returns the scan interval in milliseconds. // * // * @return The scan interval in milliseconds. // */ // public int getScanInterval() // { // return this.scanInterval; // } // // /** // * Check if USBDK is to be used on Windows. // * // * @return True if USBDK is to be used, false if not. // */ // public boolean isUseUSBDK() // { // return this.useUSBDK; // } // } // Path: src/test/java/org/usb4java/javax/ConfigTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Properties; import org.junit.Test; import org.usb4java.javax.Config; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link Config} class. * * @author Klaus Reimer (k@ailis.de) */ public class ConfigTest { /** * Tests the default configuration */ @Test public void testDefaultConfiguration() { final Properties properties = new Properties();
final Config config = new Config(properties);
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptorTest.java
// Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptor.java // public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor // implements UsbStringDescriptor // { // /** The serial version UID. */ // private static final long serialVersionUID = 1L; // // /** The string data in UTF-16LE encoding. */ // private final byte[] bString; // // /** // * Constructs a new string descriptor by reading the descriptor data // * from the specified byte buffer. // * // * @param data // * The descriptor data as a byte buffer. // */ // public SimpleUsbStringDescriptor(final ByteBuffer data) // { // super(data.get(0), data.get(1)); // // data.position(2); // this.bString = new byte[bLength() - 2]; // data.get(this.bString); // } // // /** // * Constructs a new string descriptor with the specified data. // * // * @param bLength // * The descriptor length. // * @param bDescriptorType // * The descriptor type. // * @param string // * The string. // * @throws UnsupportedEncodingException // * When system does not support UTF-16LE encoding. // */ // public SimpleUsbStringDescriptor(final byte bLength, // final byte bDescriptorType, final String string) // throws UnsupportedEncodingException // { // super(bLength, bDescriptorType); // this.bString = string.getBytes("UTF-16LE"); // } // // /** // * Copy constructor. // * // * @param descriptor // * The descriptor from which to copy the data. // */ // public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor) // { // super(descriptor.bLength(), descriptor.bDescriptorType()); // this.bString = descriptor.bString().clone(); // } // // @Override // public byte[] bString() // { // return this.bString.clone(); // } // // @Override // public String getString() throws UnsupportedEncodingException // { // return new String(this.bString, "UTF-16LE"); // } // // @Override // public boolean equals(final Object obj) // { // if (this == obj) return true; // if (obj == null || getClass() != obj.getClass()) return false; // final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj; // return new EqualsBuilder() // .append(bLength(), other.bLength()) // .append(bDescriptorType(), other.bDescriptorType()) // .append(this.bString, other.bString) // .isEquals(); // } // // @Override // public int hashCode() // { // return new HashCodeBuilder() // .append(bDescriptorType()) // .append(bLength()) // .append(this.bString) // .toHashCode(); // } // // @Override // public String toString() // { // return new String(this.bString, Charset.forName("UTF-16LE")); // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import org.junit.BeforeClass; import org.junit.Test; import org.usb4java.javax.descriptors.SimpleUsbStringDescriptor;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax.descriptors; /** * Tests the {@link SimpleUsbStringDescriptor}. * * @author Klaus Reimer (k@ailis.de) */ public class SimpleUsbStringDescriptorTest { /** The test subject. */
// Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptor.java // public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor // implements UsbStringDescriptor // { // /** The serial version UID. */ // private static final long serialVersionUID = 1L; // // /** The string data in UTF-16LE encoding. */ // private final byte[] bString; // // /** // * Constructs a new string descriptor by reading the descriptor data // * from the specified byte buffer. // * // * @param data // * The descriptor data as a byte buffer. // */ // public SimpleUsbStringDescriptor(final ByteBuffer data) // { // super(data.get(0), data.get(1)); // // data.position(2); // this.bString = new byte[bLength() - 2]; // data.get(this.bString); // } // // /** // * Constructs a new string descriptor with the specified data. // * // * @param bLength // * The descriptor length. // * @param bDescriptorType // * The descriptor type. // * @param string // * The string. // * @throws UnsupportedEncodingException // * When system does not support UTF-16LE encoding. // */ // public SimpleUsbStringDescriptor(final byte bLength, // final byte bDescriptorType, final String string) // throws UnsupportedEncodingException // { // super(bLength, bDescriptorType); // this.bString = string.getBytes("UTF-16LE"); // } // // /** // * Copy constructor. // * // * @param descriptor // * The descriptor from which to copy the data. // */ // public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor) // { // super(descriptor.bLength(), descriptor.bDescriptorType()); // this.bString = descriptor.bString().clone(); // } // // @Override // public byte[] bString() // { // return this.bString.clone(); // } // // @Override // public String getString() throws UnsupportedEncodingException // { // return new String(this.bString, "UTF-16LE"); // } // // @Override // public boolean equals(final Object obj) // { // if (this == obj) return true; // if (obj == null || getClass() != obj.getClass()) return false; // final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj; // return new EqualsBuilder() // .append(bLength(), other.bLength()) // .append(bDescriptorType(), other.bDescriptorType()) // .append(this.bString, other.bString) // .isEquals(); // } // // @Override // public int hashCode() // { // return new HashCodeBuilder() // .append(bDescriptorType()) // .append(bLength()) // .append(this.bString) // .toHashCode(); // } // // @Override // public String toString() // { // return new String(this.bString, Charset.forName("UTF-16LE")); // } // } // Path: src/test/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptorTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import org.junit.BeforeClass; import org.junit.Test; import org.usb4java.javax.descriptors.SimpleUsbStringDescriptor; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax.descriptors; /** * Tests the {@link SimpleUsbStringDescriptor}. * * @author Klaus Reimer (k@ailis.de) */ public class SimpleUsbStringDescriptorTest { /** The test subject. */
private static SimpleUsbStringDescriptor descriptor;
usb4java/usb4java-javax
src/main/java/org/usb4java/javax/AbstractDevice.java
// Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptor.java // public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor // implements UsbStringDescriptor // { // /** The serial version UID. */ // private static final long serialVersionUID = 1L; // // /** The string data in UTF-16LE encoding. */ // private final byte[] bString; // // /** // * Constructs a new string descriptor by reading the descriptor data // * from the specified byte buffer. // * // * @param data // * The descriptor data as a byte buffer. // */ // public SimpleUsbStringDescriptor(final ByteBuffer data) // { // super(data.get(0), data.get(1)); // // data.position(2); // this.bString = new byte[bLength() - 2]; // data.get(this.bString); // } // // /** // * Constructs a new string descriptor with the specified data. // * // * @param bLength // * The descriptor length. // * @param bDescriptorType // * The descriptor type. // * @param string // * The string. // * @throws UnsupportedEncodingException // * When system does not support UTF-16LE encoding. // */ // public SimpleUsbStringDescriptor(final byte bLength, // final byte bDescriptorType, final String string) // throws UnsupportedEncodingException // { // super(bLength, bDescriptorType); // this.bString = string.getBytes("UTF-16LE"); // } // // /** // * Copy constructor. // * // * @param descriptor // * The descriptor from which to copy the data. // */ // public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor) // { // super(descriptor.bLength(), descriptor.bDescriptorType()); // this.bString = descriptor.bString().clone(); // } // // @Override // public byte[] bString() // { // return this.bString.clone(); // } // // @Override // public String getString() throws UnsupportedEncodingException // { // return new String(this.bString, "UTF-16LE"); // } // // @Override // public boolean equals(final Object obj) // { // if (this == obj) return true; // if (obj == null || getClass() != obj.getClass()) return false; // final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj; // return new EqualsBuilder() // .append(bLength(), other.bLength()) // .append(bDescriptorType(), other.bDescriptorType()) // .append(this.bString, other.bString) // .isEquals(); // } // // @Override // public int hashCode() // { // return new HashCodeBuilder() // .append(bDescriptorType()) // .append(bLength()) // .append(this.bString) // .toHashCode(); // } // // @Override // public String toString() // { // return new String(this.bString, Charset.forName("UTF-16LE")); // } // }
import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.usb.UsbClaimException; import javax.usb.UsbConst; import javax.usb.UsbControlIrp; import javax.usb.UsbDevice; import javax.usb.UsbDeviceDescriptor; import javax.usb.UsbDisconnectedException; import javax.usb.UsbException; import javax.usb.UsbPlatformException; import javax.usb.UsbPort; import javax.usb.UsbStringDescriptor; import javax.usb.event.UsbDeviceEvent; import javax.usb.event.UsbDeviceListener; import javax.usb.util.DefaultUsbControlIrp; import org.usb4java.ConfigDescriptor; import org.usb4java.Device; import org.usb4java.DeviceHandle; import org.usb4java.LibUsb; import org.usb4java.javax.descriptors.SimpleUsbStringDescriptor;
@Override public final boolean isConfigured() { return getActiveUsbConfigurationNumber() != 0; } @Override public final UsbDeviceDescriptor getUsbDeviceDescriptor() { return this.id.getDeviceDescriptor(); } @Override public final UsbStringDescriptor getUsbStringDescriptor(final byte index) throws UsbException { checkConnected(); final short[] languages = getLanguages(); final DeviceHandle handle = open(); final short langId = languages.length == 0 ? 0 : languages[0]; final ByteBuffer data = ByteBuffer.allocateDirect(256); final int result = LibUsb.getStringDescriptor(handle, index, langId, data); if (result < 0) { throw ExceptionUtils.createPlatformException( "Unable to get string descriptor " + index + " from device " + this, result); }
// Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptor.java // public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor // implements UsbStringDescriptor // { // /** The serial version UID. */ // private static final long serialVersionUID = 1L; // // /** The string data in UTF-16LE encoding. */ // private final byte[] bString; // // /** // * Constructs a new string descriptor by reading the descriptor data // * from the specified byte buffer. // * // * @param data // * The descriptor data as a byte buffer. // */ // public SimpleUsbStringDescriptor(final ByteBuffer data) // { // super(data.get(0), data.get(1)); // // data.position(2); // this.bString = new byte[bLength() - 2]; // data.get(this.bString); // } // // /** // * Constructs a new string descriptor with the specified data. // * // * @param bLength // * The descriptor length. // * @param bDescriptorType // * The descriptor type. // * @param string // * The string. // * @throws UnsupportedEncodingException // * When system does not support UTF-16LE encoding. // */ // public SimpleUsbStringDescriptor(final byte bLength, // final byte bDescriptorType, final String string) // throws UnsupportedEncodingException // { // super(bLength, bDescriptorType); // this.bString = string.getBytes("UTF-16LE"); // } // // /** // * Copy constructor. // * // * @param descriptor // * The descriptor from which to copy the data. // */ // public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor) // { // super(descriptor.bLength(), descriptor.bDescriptorType()); // this.bString = descriptor.bString().clone(); // } // // @Override // public byte[] bString() // { // return this.bString.clone(); // } // // @Override // public String getString() throws UnsupportedEncodingException // { // return new String(this.bString, "UTF-16LE"); // } // // @Override // public boolean equals(final Object obj) // { // if (this == obj) return true; // if (obj == null || getClass() != obj.getClass()) return false; // final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj; // return new EqualsBuilder() // .append(bLength(), other.bLength()) // .append(bDescriptorType(), other.bDescriptorType()) // .append(this.bString, other.bString) // .isEquals(); // } // // @Override // public int hashCode() // { // return new HashCodeBuilder() // .append(bDescriptorType()) // .append(bLength()) // .append(this.bString) // .toHashCode(); // } // // @Override // public String toString() // { // return new String(this.bString, Charset.forName("UTF-16LE")); // } // } // Path: src/main/java/org/usb4java/javax/AbstractDevice.java import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.usb.UsbClaimException; import javax.usb.UsbConst; import javax.usb.UsbControlIrp; import javax.usb.UsbDevice; import javax.usb.UsbDeviceDescriptor; import javax.usb.UsbDisconnectedException; import javax.usb.UsbException; import javax.usb.UsbPlatformException; import javax.usb.UsbPort; import javax.usb.UsbStringDescriptor; import javax.usb.event.UsbDeviceEvent; import javax.usb.event.UsbDeviceListener; import javax.usb.util.DefaultUsbControlIrp; import org.usb4java.ConfigDescriptor; import org.usb4java.Device; import org.usb4java.DeviceHandle; import org.usb4java.LibUsb; import org.usb4java.javax.descriptors.SimpleUsbStringDescriptor; @Override public final boolean isConfigured() { return getActiveUsbConfigurationNumber() != 0; } @Override public final UsbDeviceDescriptor getUsbDeviceDescriptor() { return this.id.getDeviceDescriptor(); } @Override public final UsbStringDescriptor getUsbStringDescriptor(final byte index) throws UsbException { checkConnected(); final short[] languages = getLanguages(); final DeviceHandle handle = open(); final short langId = languages.length == 0 ? 0 : languages[0]; final ByteBuffer data = ByteBuffer.allocateDirect(256); final int result = LibUsb.getStringDescriptor(handle, index, langId, data); if (result < 0) { throw ExceptionUtils.createPlatformException( "Unable to get string descriptor " + index + " from device " + this, result); }
return new SimpleUsbStringDescriptor(data);
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/adapter/UsbServicesAdapterTest.java
// Path: src/main/java/org/usb4java/javax/adapter/UsbServicesAdapter.java // public abstract class UsbServicesAdapter implements UsbServicesListener // { // @Override // public void usbDeviceAttached(final UsbServicesEvent event) // { // // Empty // } // // @Override // public void usbDeviceDetached(final UsbServicesEvent event) // { // // Empty // } // }
import org.junit.Test; import org.usb4java.javax.adapter.UsbServicesAdapter; import javax.usb.event.UsbServicesEvent; import javax.usb.event.UsbServicesListener;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax.adapter; /** * Test the {@link UsbServicesAdapter} class. There is not really anything to * test there. This class just ensures that the class exists and provides * the needed methods. * * @author Klaus Reimer (k@ailis.de) */ public class UsbServicesAdapterTest { /** * Ensure the existence of the needed methods. */ @Test public void testAbstractMethods() {
// Path: src/main/java/org/usb4java/javax/adapter/UsbServicesAdapter.java // public abstract class UsbServicesAdapter implements UsbServicesListener // { // @Override // public void usbDeviceAttached(final UsbServicesEvent event) // { // // Empty // } // // @Override // public void usbDeviceDetached(final UsbServicesEvent event) // { // // Empty // } // } // Path: src/test/java/org/usb4java/javax/adapter/UsbServicesAdapterTest.java import org.junit.Test; import org.usb4java.javax.adapter.UsbServicesAdapter; import javax.usb.event.UsbServicesEvent; import javax.usb.event.UsbServicesListener; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax.adapter; /** * Test the {@link UsbServicesAdapter} class. There is not really anything to * test there. This class just ensures that the class exists and provides * the needed methods. * * @author Klaus Reimer (k@ailis.de) */ public class UsbServicesAdapterTest { /** * Ensure the existence of the needed methods. */ @Test public void testAbstractMethods() {
final UsbServicesListener adapter = new UsbServicesAdapter()
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/RootHubConfigurationTest.java
// Path: src/main/java/org/usb4java/javax/RootHubConfiguration.java // final class RootHubConfiguration implements UsbConfiguration // { // /** The virtual interfaces. */ // private final List<UsbInterface> interfaces = // new ArrayList<UsbInterface>(); // // /** The device this configuration belongs to. */ // private final UsbDevice device; // // /** The USB configuration descriptor. */ // private final UsbConfigurationDescriptor descriptor = // new SimpleUsbConfigurationDescriptor( // UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION, // UsbConst.DESCRIPTOR_TYPE_CONFIGURATION, // (byte) (UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION // + UsbConst.DESCRIPTOR_MIN_LENGTH_INTERFACE), // (byte) 1, // (byte) 1, // (byte) 0, // (byte) 0x80, // (byte) 0); // // /** // * Constructor. // * // * @param device // * The device this configuration belongs to. // */ // RootHubConfiguration(final UsbDevice device) // { // this.device = device; // this.interfaces.add(new RootHubInterface(this)); // } // // @Override // public boolean isActive() // { // return true; // } // // @Override // public List<UsbInterface> getUsbInterfaces() // { // return this.interfaces; // } // // @Override // public UsbInterface getUsbInterface(final byte number) // { // if (number != 0) return null; // return this.interfaces.get(0); // } // // @Override // public boolean containsUsbInterface(final byte number) // { // return number == 0; // } // // @Override // public UsbDevice getUsbDevice() // { // return this.device; // } // // @Override // public UsbConfigurationDescriptor getUsbConfigurationDescriptor() // { // return this.descriptor; // } // // @Override // public String getConfigurationString() // { // return null; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.List; import javax.usb.UsbDevice; import javax.usb.UsbInterface; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.usb4java.javax.RootHubConfiguration;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link RootHubConfiguration} class. * * @author Klaus Reimer (k@ailis.de) */ public class RootHubConfigurationTest { /** The test subject. */
// Path: src/main/java/org/usb4java/javax/RootHubConfiguration.java // final class RootHubConfiguration implements UsbConfiguration // { // /** The virtual interfaces. */ // private final List<UsbInterface> interfaces = // new ArrayList<UsbInterface>(); // // /** The device this configuration belongs to. */ // private final UsbDevice device; // // /** The USB configuration descriptor. */ // private final UsbConfigurationDescriptor descriptor = // new SimpleUsbConfigurationDescriptor( // UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION, // UsbConst.DESCRIPTOR_TYPE_CONFIGURATION, // (byte) (UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION // + UsbConst.DESCRIPTOR_MIN_LENGTH_INTERFACE), // (byte) 1, // (byte) 1, // (byte) 0, // (byte) 0x80, // (byte) 0); // // /** // * Constructor. // * // * @param device // * The device this configuration belongs to. // */ // RootHubConfiguration(final UsbDevice device) // { // this.device = device; // this.interfaces.add(new RootHubInterface(this)); // } // // @Override // public boolean isActive() // { // return true; // } // // @Override // public List<UsbInterface> getUsbInterfaces() // { // return this.interfaces; // } // // @Override // public UsbInterface getUsbInterface(final byte number) // { // if (number != 0) return null; // return this.interfaces.get(0); // } // // @Override // public boolean containsUsbInterface(final byte number) // { // return number == 0; // } // // @Override // public UsbDevice getUsbDevice() // { // return this.device; // } // // @Override // public UsbConfigurationDescriptor getUsbConfigurationDescriptor() // { // return this.descriptor; // } // // @Override // public String getConfigurationString() // { // return null; // } // } // Path: src/test/java/org/usb4java/javax/RootHubConfigurationTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.List; import javax.usb.UsbDevice; import javax.usb.UsbInterface; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.usb4java.javax.RootHubConfiguration; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link RootHubConfiguration} class. * * @author Klaus Reimer (k@ailis.de) */ public class RootHubConfigurationTest { /** The test subject. */
private RootHubConfiguration config;
usb4java/usb4java-javax
src/main/java/org/usb4java/javax/Endpoint.java
// Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbEndpointDescriptor.java // public final class SimpleUsbEndpointDescriptor extends SimpleUsbDescriptor // implements UsbEndpointDescriptor // { // /** Serial version UID. */ // private static final long serialVersionUID = 1L; // // /** The poll interval. */ // private final byte bInterval; // // /** The maximum packet size. */ // private final short wMaxPacketSize; // // /** The endpoint attributes. */ // private final byte bmAttributes; // // /** The endpoint address. */ // private final byte bEndpointAddress; // // /** // * Constructor. // * // * @param bLength // * The descriptor length. // * @param bDescriptorType // * The descriptor type. // * @param bEndpointAddress // * The address of the endpoint. // * @param bmAttributes // * The endpoint attributes. // * @param wMaxPacketSize // * The maximum packet size. // * @param bInterval // * The poll interval. // */ // public SimpleUsbEndpointDescriptor(final byte bLength, // final byte bDescriptorType, final byte bEndpointAddress, // final byte bmAttributes, final short wMaxPacketSize, // final byte bInterval) // { // super(bLength, bDescriptorType); // this.bEndpointAddress = bEndpointAddress; // this.wMaxPacketSize = wMaxPacketSize; // this.bmAttributes = bmAttributes; // this.bInterval = bInterval; // } // // /** // * Construct from a libusb4java endpoint descriptor. // * // * @param descriptor // * The descriptor from which to copy the data. // */ // public SimpleUsbEndpointDescriptor(final EndpointDescriptor descriptor) // { // this(descriptor.bLength(), // descriptor.bDescriptorType(), // descriptor.bEndpointAddress(), // descriptor.bmAttributes(), // descriptor.wMaxPacketSize(), // descriptor.bInterval()); // } // // @Override // public byte bEndpointAddress() // { // return this.bEndpointAddress; // } // // @Override // public byte bmAttributes() // { // return this.bmAttributes; // } // // @Override // public short wMaxPacketSize() // { // return this.wMaxPacketSize; // } // // @Override // public byte bInterval() // { // return this.bInterval; // } // // @Override // public int hashCode() // { // return new HashCodeBuilder() // .append(bDescriptorType()) // .append(bLength()) // .append(this.bEndpointAddress) // .append(this.bInterval) // .append(this.bmAttributes) // .append(this.wMaxPacketSize) // .toHashCode(); // } // // @Override // public boolean equals(final Object obj) // { // if (this == obj) return true; // if (obj == null || getClass() != obj.getClass()) return false; // final SimpleUsbEndpointDescriptor other = // (SimpleUsbEndpointDescriptor) obj; // return new EqualsBuilder() // .append(bLength(), other.bLength()) // .append(bDescriptorType(), other.bDescriptorType()) // .append(this.bEndpointAddress, other.bEndpointAddress) // .append(this.bInterval, other.bInterval) // .append(this.bmAttributes, other.bmAttributes) // .append(this.wMaxPacketSize, other.wMaxPacketSize) // .isEquals(); // } // // @Override // public String toString() // { // return String.format( // "Endpoint Descriptor:%n" + // " bLength %18d%n" + // " bDescriptorType %10d%n" + // " bEndpointAddress %9s EP %d %s%n" + // " bmAttributes %13d%n" + // " Transfer Type %s%n" + // " Synch Type %s%n" + // " Usage Type %s%n" + // " wMaxPacketSize %11d%n" + // " bInterval %16d%n", // bLength() & 0xff, // bDescriptorType() & 0xff, // String.format("0x%02x", bEndpointAddress() & 0xff), // bEndpointAddress() & 0x0f, // DescriptorUtils.getDirectionName(bEndpointAddress()), // bmAttributes() & 0xff, // DescriptorUtils.getTransferTypeName(bmAttributes()), // DescriptorUtils.getSynchTypeName(bmAttributes()), // DescriptorUtils.getUsageTypeName(bmAttributes()), // wMaxPacketSize() & 0xffff, // bInterval() & 0xff); // } // }
import javax.usb.UsbConst; import javax.usb.UsbEndpoint; import javax.usb.UsbEndpointDescriptor; import javax.usb.UsbPipe; import org.usb4java.EndpointDescriptor; import org.usb4java.javax.descriptors.SimpleUsbEndpointDescriptor;
/* * Copyright (C) 2011 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * usb4java implementation of UsbEndpoint. * * @author Klaus Reimer (k@ailis.de) */ final class Endpoint implements UsbEndpoint { /** The interface this endpoint belongs to. */ private final Interface iface; /** The endpoint descriptor. */ private final UsbEndpointDescriptor descriptor; /** The USB pipe for this endpoint. */ private final Pipe pipe; /** * Constructor. * * @param iface * The interface this endpoint belongs to. * @param descriptor * The libusb endpoint descriptor. */ Endpoint(final Interface iface, final EndpointDescriptor descriptor) { this.iface = iface;
// Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbEndpointDescriptor.java // public final class SimpleUsbEndpointDescriptor extends SimpleUsbDescriptor // implements UsbEndpointDescriptor // { // /** Serial version UID. */ // private static final long serialVersionUID = 1L; // // /** The poll interval. */ // private final byte bInterval; // // /** The maximum packet size. */ // private final short wMaxPacketSize; // // /** The endpoint attributes. */ // private final byte bmAttributes; // // /** The endpoint address. */ // private final byte bEndpointAddress; // // /** // * Constructor. // * // * @param bLength // * The descriptor length. // * @param bDescriptorType // * The descriptor type. // * @param bEndpointAddress // * The address of the endpoint. // * @param bmAttributes // * The endpoint attributes. // * @param wMaxPacketSize // * The maximum packet size. // * @param bInterval // * The poll interval. // */ // public SimpleUsbEndpointDescriptor(final byte bLength, // final byte bDescriptorType, final byte bEndpointAddress, // final byte bmAttributes, final short wMaxPacketSize, // final byte bInterval) // { // super(bLength, bDescriptorType); // this.bEndpointAddress = bEndpointAddress; // this.wMaxPacketSize = wMaxPacketSize; // this.bmAttributes = bmAttributes; // this.bInterval = bInterval; // } // // /** // * Construct from a libusb4java endpoint descriptor. // * // * @param descriptor // * The descriptor from which to copy the data. // */ // public SimpleUsbEndpointDescriptor(final EndpointDescriptor descriptor) // { // this(descriptor.bLength(), // descriptor.bDescriptorType(), // descriptor.bEndpointAddress(), // descriptor.bmAttributes(), // descriptor.wMaxPacketSize(), // descriptor.bInterval()); // } // // @Override // public byte bEndpointAddress() // { // return this.bEndpointAddress; // } // // @Override // public byte bmAttributes() // { // return this.bmAttributes; // } // // @Override // public short wMaxPacketSize() // { // return this.wMaxPacketSize; // } // // @Override // public byte bInterval() // { // return this.bInterval; // } // // @Override // public int hashCode() // { // return new HashCodeBuilder() // .append(bDescriptorType()) // .append(bLength()) // .append(this.bEndpointAddress) // .append(this.bInterval) // .append(this.bmAttributes) // .append(this.wMaxPacketSize) // .toHashCode(); // } // // @Override // public boolean equals(final Object obj) // { // if (this == obj) return true; // if (obj == null || getClass() != obj.getClass()) return false; // final SimpleUsbEndpointDescriptor other = // (SimpleUsbEndpointDescriptor) obj; // return new EqualsBuilder() // .append(bLength(), other.bLength()) // .append(bDescriptorType(), other.bDescriptorType()) // .append(this.bEndpointAddress, other.bEndpointAddress) // .append(this.bInterval, other.bInterval) // .append(this.bmAttributes, other.bmAttributes) // .append(this.wMaxPacketSize, other.wMaxPacketSize) // .isEquals(); // } // // @Override // public String toString() // { // return String.format( // "Endpoint Descriptor:%n" + // " bLength %18d%n" + // " bDescriptorType %10d%n" + // " bEndpointAddress %9s EP %d %s%n" + // " bmAttributes %13d%n" + // " Transfer Type %s%n" + // " Synch Type %s%n" + // " Usage Type %s%n" + // " wMaxPacketSize %11d%n" + // " bInterval %16d%n", // bLength() & 0xff, // bDescriptorType() & 0xff, // String.format("0x%02x", bEndpointAddress() & 0xff), // bEndpointAddress() & 0x0f, // DescriptorUtils.getDirectionName(bEndpointAddress()), // bmAttributes() & 0xff, // DescriptorUtils.getTransferTypeName(bmAttributes()), // DescriptorUtils.getSynchTypeName(bmAttributes()), // DescriptorUtils.getUsageTypeName(bmAttributes()), // wMaxPacketSize() & 0xffff, // bInterval() & 0xff); // } // } // Path: src/main/java/org/usb4java/javax/Endpoint.java import javax.usb.UsbConst; import javax.usb.UsbEndpoint; import javax.usb.UsbEndpointDescriptor; import javax.usb.UsbPipe; import org.usb4java.EndpointDescriptor; import org.usb4java.javax.descriptors.SimpleUsbEndpointDescriptor; /* * Copyright (C) 2011 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * usb4java implementation of UsbEndpoint. * * @author Klaus Reimer (k@ailis.de) */ final class Endpoint implements UsbEndpoint { /** The interface this endpoint belongs to. */ private final Interface iface; /** The endpoint descriptor. */ private final UsbEndpointDescriptor descriptor; /** The USB pipe for this endpoint. */ private final Pipe pipe; /** * Constructor. * * @param iface * The interface this endpoint belongs to. * @param descriptor * The libusb endpoint descriptor. */ Endpoint(final Interface iface, final EndpointDescriptor descriptor) { this.iface = iface;
this.descriptor = new SimpleUsbEndpointDescriptor(descriptor);
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/PipeListenerListTest.java
// Path: src/main/java/org/usb4java/javax/PipeListenerList.java // final class PipeListenerList extends // EventListenerList<UsbPipeListener> implements UsbPipeListener // { // /** // * Constructs a new USB pipe listener list. // */ // PipeListenerList() // { // super(); // } // // @Override // public UsbPipeListener[] toArray() // { // return getListeners().toArray( // new UsbPipeListener[getListeners().size()]); // } // // @Override // public void errorEventOccurred(final UsbPipeErrorEvent event) // { // for (final UsbPipeListener listener: toArray()) // { // listener.errorEventOccurred(event); // } // } // // @Override // public void dataEventOccurred(final UsbPipeDataEvent event) // { // for (final UsbPipeListener listener: toArray()) // { // listener.dataEventOccurred(event); // } // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import javax.usb.UsbException; import javax.usb.UsbPipe; import javax.usb.event.UsbPipeDataEvent; import javax.usb.event.UsbPipeErrorEvent; import javax.usb.event.UsbPipeListener; import org.junit.Before; import org.junit.Test; import org.usb4java.javax.PipeListenerList;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link PipeListenerList} class. * * @author Klaus Reimer (k@ailis.de) */ public class PipeListenerListTest { /** The test subject. */
// Path: src/main/java/org/usb4java/javax/PipeListenerList.java // final class PipeListenerList extends // EventListenerList<UsbPipeListener> implements UsbPipeListener // { // /** // * Constructs a new USB pipe listener list. // */ // PipeListenerList() // { // super(); // } // // @Override // public UsbPipeListener[] toArray() // { // return getListeners().toArray( // new UsbPipeListener[getListeners().size()]); // } // // @Override // public void errorEventOccurred(final UsbPipeErrorEvent event) // { // for (final UsbPipeListener listener: toArray()) // { // listener.errorEventOccurred(event); // } // } // // @Override // public void dataEventOccurred(final UsbPipeDataEvent event) // { // for (final UsbPipeListener listener: toArray()) // { // listener.dataEventOccurred(event); // } // } // } // Path: src/test/java/org/usb4java/javax/PipeListenerListTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import javax.usb.UsbException; import javax.usb.UsbPipe; import javax.usb.event.UsbPipeDataEvent; import javax.usb.event.UsbPipeErrorEvent; import javax.usb.event.UsbPipeListener; import org.junit.Before; import org.junit.Test; import org.usb4java.javax.PipeListenerList; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link PipeListenerList} class. * * @author Klaus Reimer (k@ailis.de) */ public class PipeListenerListTest { /** The test subject. */
private PipeListenerList list;
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/ServicesExceptionTest.java
// Path: src/main/java/org/usb4java/javax/ServicesException.java // public final class ServicesException extends RuntimeException // { // /** Serial version UID. */ // private static final long serialVersionUID = 1L; // // /** // * Constructor. // * // * @param message // * The error message. // * @param cause // * The root cause. // */ // ServicesException(final String message, final Throwable cause) // { // super(message, cause); // } // }
import org.junit.Test; import org.usb4java.javax.ServicesException; import static org.junit.Assert.assertEquals;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link ServicesException} class. * * @author Klaus Reimer (k@ailis.de) */ public class ServicesExceptionTest { /** * Tests the constructor. */ @Test public void testConstructor() { final Throwable cause = new RuntimeException(""); final String message = "Bang";
// Path: src/main/java/org/usb4java/javax/ServicesException.java // public final class ServicesException extends RuntimeException // { // /** Serial version UID. */ // private static final long serialVersionUID = 1L; // // /** // * Constructor. // * // * @param message // * The error message. // * @param cause // * The root cause. // */ // ServicesException(final String message, final Throwable cause) // { // super(message, cause); // } // } // Path: src/test/java/org/usb4java/javax/ServicesExceptionTest.java import org.junit.Test; import org.usb4java.javax.ServicesException; import static org.junit.Assert.assertEquals; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link ServicesException} class. * * @author Klaus Reimer (k@ailis.de) */ public class ServicesExceptionTest { /** * Tests the constructor. */ @Test public void testConstructor() { final Throwable cause = new RuntimeException(""); final String message = "Bang";
final ServicesException exception =
usb4java/usb4java-javax
src/test/java/org/usb4java/javax/ServicesListenerListTest.java
// Path: src/main/java/org/usb4java/javax/ServicesListenerList.java // final class ServicesListenerList extends // EventListenerList<UsbServicesListener> implements UsbServicesListener // { // /** // * Constructs a new USB services listener list. // */ // ServicesListenerList() // { // super(); // } // // @Override // public UsbServicesListener[] toArray() // { // return getListeners().toArray( // new UsbServicesListener[getListeners().size()]); // } // // @Override // public void usbDeviceAttached(final UsbServicesEvent event) // { // for (final UsbServicesListener listener: toArray()) // { // listener.usbDeviceAttached(event); // } // } // // @Override // public void usbDeviceDetached(final UsbServicesEvent event) // { // for (final UsbServicesListener listener: toArray()) // { // listener.usbDeviceDetached(event); // } // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import javax.usb.UsbDevice; import javax.usb.UsbServices; import javax.usb.event.UsbServicesEvent; import javax.usb.event.UsbServicesListener; import org.junit.Before; import org.junit.Test; import org.usb4java.javax.ServicesListenerList;
/* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link ServicesListenerList} class. * * @author Klaus Reimer (k@ailis.de) */ public class ServicesListenerListTest { /** The test subject. */
// Path: src/main/java/org/usb4java/javax/ServicesListenerList.java // final class ServicesListenerList extends // EventListenerList<UsbServicesListener> implements UsbServicesListener // { // /** // * Constructs a new USB services listener list. // */ // ServicesListenerList() // { // super(); // } // // @Override // public UsbServicesListener[] toArray() // { // return getListeners().toArray( // new UsbServicesListener[getListeners().size()]); // } // // @Override // public void usbDeviceAttached(final UsbServicesEvent event) // { // for (final UsbServicesListener listener: toArray()) // { // listener.usbDeviceAttached(event); // } // } // // @Override // public void usbDeviceDetached(final UsbServicesEvent event) // { // for (final UsbServicesListener listener: toArray()) // { // listener.usbDeviceDetached(event); // } // } // } // Path: src/test/java/org/usb4java/javax/ServicesListenerListTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import javax.usb.UsbDevice; import javax.usb.UsbServices; import javax.usb.event.UsbServicesEvent; import javax.usb.event.UsbServicesListener; import org.junit.Before; import org.junit.Test; import org.usb4java.javax.ServicesListenerList; /* * Copyright (C) 2013 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package org.usb4java.javax; /** * Tests the {@link ServicesListenerList} class. * * @author Klaus Reimer (k@ailis.de) */ public class ServicesListenerListTest { /** The test subject. */
private ServicesListenerList list;
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/service/verifier/GoogleSafeBrowsingUrlVerifier.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleCondition.java // public class GoogleCondition implements Condition { // @Override // public boolean matches( // final ConditionContext context, // final AnnotatedTypeMetadata annotatedTypeMetadata) { // final String apiKey = context.getEnvironment().getProperty("provider.google.key"); // // return !StringUtils.isEmpty(apiKey); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleSafeBrowsingConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); // private static final String PARAMETER_API_KEY = "apiKey"; // private static final String PARAMETER_API_VERSION = "apiVersion"; // private static final String PARAMETER_APP_VERSION = "appVersion"; // private static final String PARAMETER_APP_NAME = "client"; // private final Map<String, String> parameters; // private final String apiUrl; // // @Autowired // public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) { // this.parameters = populateParameterMap(server, app); // this.apiUrl = server.getEndpoint(); // // if (!StringUtils.isEmpty(parameters.get(PARAMETER_API_KEY)) && // !StringUtils.isEmpty(parameters.get(PARAMETER_API_VERSION))) { // LOGGER.info("Google Safe Browsing API is configured with an API key"); // } // } // // private HashMap<String, String> populateParameterMap( // GoogleApiSettings server, // ApplicationSettings app) { // final HashMap<String, String> map = new HashMap<>(); // map.put(PARAMETER_API_KEY, server.getCredential()); // map.put(PARAMETER_API_VERSION, server.getVersion()); // map.put(PARAMETER_APP_VERSION, app.getVersion()); // map.put(PARAMETER_APP_NAME, app.getName()); // return map; // } // // public final String getApiUrl() { // return apiUrl; // } // // public final Map<String, String> getParameters() { // return new HashMap<>(parameters); // } // }
import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Map; import be.drissamri.config.safebrowsing.google.GoogleCondition; import be.drissamri.config.safebrowsing.google.GoogleSafeBrowsingConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Conditional; import org.springframework.http.HttpStatus;
/** * The MIT License (MIT) * * Copyright (c) 2015 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; /** * Validate URL with the Google Safe Browsing API. * @author Driss Amri (drissamri@gmail.com) * @version $Id$ */ @Component @Conditional(GoogleCondition.class) public class GoogleSafeBrowsingUrlVerifier implements UrlVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingUrlVerifier.class); private static final String PARAMETER_URL = "url";
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleCondition.java // public class GoogleCondition implements Condition { // @Override // public boolean matches( // final ConditionContext context, // final AnnotatedTypeMetadata annotatedTypeMetadata) { // final String apiKey = context.getEnvironment().getProperty("provider.google.key"); // // return !StringUtils.isEmpty(apiKey); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleSafeBrowsingConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); // private static final String PARAMETER_API_KEY = "apiKey"; // private static final String PARAMETER_API_VERSION = "apiVersion"; // private static final String PARAMETER_APP_VERSION = "appVersion"; // private static final String PARAMETER_APP_NAME = "client"; // private final Map<String, String> parameters; // private final String apiUrl; // // @Autowired // public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) { // this.parameters = populateParameterMap(server, app); // this.apiUrl = server.getEndpoint(); // // if (!StringUtils.isEmpty(parameters.get(PARAMETER_API_KEY)) && // !StringUtils.isEmpty(parameters.get(PARAMETER_API_VERSION))) { // LOGGER.info("Google Safe Browsing API is configured with an API key"); // } // } // // private HashMap<String, String> populateParameterMap( // GoogleApiSettings server, // ApplicationSettings app) { // final HashMap<String, String> map = new HashMap<>(); // map.put(PARAMETER_API_KEY, server.getCredential()); // map.put(PARAMETER_API_VERSION, server.getVersion()); // map.put(PARAMETER_APP_VERSION, app.getVersion()); // map.put(PARAMETER_APP_NAME, app.getName()); // return map; // } // // public final String getApiUrl() { // return apiUrl; // } // // public final Map<String, String> getParameters() { // return new HashMap<>(parameters); // } // } // Path: linkshortener-api/src/main/java/be/drissamri/service/verifier/GoogleSafeBrowsingUrlVerifier.java import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Map; import be.drissamri.config.safebrowsing.google.GoogleCondition; import be.drissamri.config.safebrowsing.google.GoogleSafeBrowsingConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Conditional; import org.springframework.http.HttpStatus; /** * The MIT License (MIT) * * Copyright (c) 2015 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; /** * Validate URL with the Google Safe Browsing API. * @author Driss Amri (drissamri@gmail.com) * @version $Id$ */ @Component @Conditional(GoogleCondition.class) public class GoogleSafeBrowsingUrlVerifier implements UrlVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingUrlVerifier.class); private static final String PARAMETER_URL = "url";
private final GoogleSafeBrowsingConfig config;
drissamri/linkshortener
linkshortener-api/src/test/java/be/drissamri/service/verifier/PhishTankUrlVerifierTest.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankConfig.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(PhishTankConfig.class); // private static final String PARAMETER_API_KEY = "app_key"; // private static final String PARAMETER_FORMAT = "format"; // private static final String RESPONSE_FORMAT = "json"; // private final String apiUrl; // private final MultiValueMap<String, String> parameters; // // @Autowired // public PhishTankConfig(PhishTankSettings settings) { // this.apiUrl = settings.getEndpoint(); // this.parameters = new LinkedMultiValueMap<>(); // parameters.add(PARAMETER_API_KEY, settings.getCredential()); // parameters.add(PARAMETER_FORMAT, RESPONSE_FORMAT); // // if (!StringUtils.isEmpty(parameters.getFirst(PARAMETER_API_KEY)) // && !StringUtils.isEmpty(parameters.get(PARAMETER_FORMAT))) { // LOGGER.info("PhishTank API is configured with an API key"); // } // } // // public final String getApiUrl() { // return apiUrl; // } // // public final MultiValueMap<String, String> getParameters() { // return new LinkedMultiValueMap<>(parameters); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankSettings.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankSettings implements ApiSettings { // private final String endpoint; // private final String credential; // // @Autowired // public PhishTankSettings( // @Value("${provider.phishtank.url}") final String endpoint, // @Value("${provider.phishtank.key}") final String credential) { // this.endpoint = endpoint; // this.credential = credential; // } // // @Override // public final String getEndpoint() { // return this.endpoint; // } // // @Override // public final String getCredential() { // return this.credential; // } // // @Override // public final String getVersion() { // return "v1"; // } // }
import be.drissamri.config.safebrowsing.phishtank.PhishTankConfig; import be.drissamri.config.safebrowsing.phishtank.PhishTankSettings; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.*;
package be.drissamri.service.verifier; public class PhishTankUrlVerifierTest { private PhishTankUrlVerifier phishTankUrlVerifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; private static final String JSON_PHISH_RESULT = "{ 'results': { 'in_database': true } }"; private static final String JSON_SAFE_RESULT = "{ 'results': { 'in_database': false } }"; private static final String JSON_UNKOWN_RESULT = "{ }"; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); phishTankUrlVerifier = new PhishTankUrlVerifier( restTemplate,
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankConfig.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(PhishTankConfig.class); // private static final String PARAMETER_API_KEY = "app_key"; // private static final String PARAMETER_FORMAT = "format"; // private static final String RESPONSE_FORMAT = "json"; // private final String apiUrl; // private final MultiValueMap<String, String> parameters; // // @Autowired // public PhishTankConfig(PhishTankSettings settings) { // this.apiUrl = settings.getEndpoint(); // this.parameters = new LinkedMultiValueMap<>(); // parameters.add(PARAMETER_API_KEY, settings.getCredential()); // parameters.add(PARAMETER_FORMAT, RESPONSE_FORMAT); // // if (!StringUtils.isEmpty(parameters.getFirst(PARAMETER_API_KEY)) // && !StringUtils.isEmpty(parameters.get(PARAMETER_FORMAT))) { // LOGGER.info("PhishTank API is configured with an API key"); // } // } // // public final String getApiUrl() { // return apiUrl; // } // // public final MultiValueMap<String, String> getParameters() { // return new LinkedMultiValueMap<>(parameters); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankSettings.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankSettings implements ApiSettings { // private final String endpoint; // private final String credential; // // @Autowired // public PhishTankSettings( // @Value("${provider.phishtank.url}") final String endpoint, // @Value("${provider.phishtank.key}") final String credential) { // this.endpoint = endpoint; // this.credential = credential; // } // // @Override // public final String getEndpoint() { // return this.endpoint; // } // // @Override // public final String getCredential() { // return this.credential; // } // // @Override // public final String getVersion() { // return "v1"; // } // } // Path: linkshortener-api/src/test/java/be/drissamri/service/verifier/PhishTankUrlVerifierTest.java import be.drissamri.config.safebrowsing.phishtank.PhishTankConfig; import be.drissamri.config.safebrowsing.phishtank.PhishTankSettings; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.*; package be.drissamri.service.verifier; public class PhishTankUrlVerifierTest { private PhishTankUrlVerifier phishTankUrlVerifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; private static final String JSON_PHISH_RESULT = "{ 'results': { 'in_database': true } }"; private static final String JSON_SAFE_RESULT = "{ 'results': { 'in_database': false } }"; private static final String JSON_UNKOWN_RESULT = "{ }"; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); phishTankUrlVerifier = new PhishTankUrlVerifier( restTemplate,
new PhishTankConfig(
drissamri/linkshortener
linkshortener-api/src/test/java/be/drissamri/service/verifier/PhishTankUrlVerifierTest.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankConfig.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(PhishTankConfig.class); // private static final String PARAMETER_API_KEY = "app_key"; // private static final String PARAMETER_FORMAT = "format"; // private static final String RESPONSE_FORMAT = "json"; // private final String apiUrl; // private final MultiValueMap<String, String> parameters; // // @Autowired // public PhishTankConfig(PhishTankSettings settings) { // this.apiUrl = settings.getEndpoint(); // this.parameters = new LinkedMultiValueMap<>(); // parameters.add(PARAMETER_API_KEY, settings.getCredential()); // parameters.add(PARAMETER_FORMAT, RESPONSE_FORMAT); // // if (!StringUtils.isEmpty(parameters.getFirst(PARAMETER_API_KEY)) // && !StringUtils.isEmpty(parameters.get(PARAMETER_FORMAT))) { // LOGGER.info("PhishTank API is configured with an API key"); // } // } // // public final String getApiUrl() { // return apiUrl; // } // // public final MultiValueMap<String, String> getParameters() { // return new LinkedMultiValueMap<>(parameters); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankSettings.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankSettings implements ApiSettings { // private final String endpoint; // private final String credential; // // @Autowired // public PhishTankSettings( // @Value("${provider.phishtank.url}") final String endpoint, // @Value("${provider.phishtank.key}") final String credential) { // this.endpoint = endpoint; // this.credential = credential; // } // // @Override // public final String getEndpoint() { // return this.endpoint; // } // // @Override // public final String getCredential() { // return this.credential; // } // // @Override // public final String getVersion() { // return "v1"; // } // }
import be.drissamri.config.safebrowsing.phishtank.PhishTankConfig; import be.drissamri.config.safebrowsing.phishtank.PhishTankSettings; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.*;
package be.drissamri.service.verifier; public class PhishTankUrlVerifierTest { private PhishTankUrlVerifier phishTankUrlVerifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; private static final String JSON_PHISH_RESULT = "{ 'results': { 'in_database': true } }"; private static final String JSON_SAFE_RESULT = "{ 'results': { 'in_database': false } }"; private static final String JSON_UNKOWN_RESULT = "{ }"; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); phishTankUrlVerifier = new PhishTankUrlVerifier( restTemplate, new PhishTankConfig(
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankConfig.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(PhishTankConfig.class); // private static final String PARAMETER_API_KEY = "app_key"; // private static final String PARAMETER_FORMAT = "format"; // private static final String RESPONSE_FORMAT = "json"; // private final String apiUrl; // private final MultiValueMap<String, String> parameters; // // @Autowired // public PhishTankConfig(PhishTankSettings settings) { // this.apiUrl = settings.getEndpoint(); // this.parameters = new LinkedMultiValueMap<>(); // parameters.add(PARAMETER_API_KEY, settings.getCredential()); // parameters.add(PARAMETER_FORMAT, RESPONSE_FORMAT); // // if (!StringUtils.isEmpty(parameters.getFirst(PARAMETER_API_KEY)) // && !StringUtils.isEmpty(parameters.get(PARAMETER_FORMAT))) { // LOGGER.info("PhishTank API is configured with an API key"); // } // } // // public final String getApiUrl() { // return apiUrl; // } // // public final MultiValueMap<String, String> getParameters() { // return new LinkedMultiValueMap<>(parameters); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankSettings.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankSettings implements ApiSettings { // private final String endpoint; // private final String credential; // // @Autowired // public PhishTankSettings( // @Value("${provider.phishtank.url}") final String endpoint, // @Value("${provider.phishtank.key}") final String credential) { // this.endpoint = endpoint; // this.credential = credential; // } // // @Override // public final String getEndpoint() { // return this.endpoint; // } // // @Override // public final String getCredential() { // return this.credential; // } // // @Override // public final String getVersion() { // return "v1"; // } // } // Path: linkshortener-api/src/test/java/be/drissamri/service/verifier/PhishTankUrlVerifierTest.java import be.drissamri.config.safebrowsing.phishtank.PhishTankConfig; import be.drissamri.config.safebrowsing.phishtank.PhishTankSettings; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.*; package be.drissamri.service.verifier; public class PhishTankUrlVerifierTest { private PhishTankUrlVerifier phishTankUrlVerifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; private static final String JSON_PHISH_RESULT = "{ 'results': { 'in_database': true } }"; private static final String JSON_SAFE_RESULT = "{ 'results': { 'in_database': false } }"; private static final String JSON_UNKOWN_RESULT = "{ }"; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); phishTankUrlVerifier = new PhishTankUrlVerifier( restTemplate, new PhishTankConfig(
new PhishTankSettings("", "")
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/service/verifier/UrlVerifiers.java
// Path: linkshortener-api/src/main/java/be/drissamri/service/exception/LinkshortenerException.java // public class LinkshortenerException extends RuntimeException { // // public LinkshortenerException(String message) { // super(message); // } // // public LinkshortenerException(String message, Throwable cause) { // super(message, cause); // } // // }
import be.drissamri.service.exception.LinkshortenerException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
package be.drissamri.service.verifier; @Component public class UrlVerifiers { private static final Logger LOGGER = LoggerFactory.getLogger(UrlVerifier.class); private static final String ENCODING_UTF8 = "UTF-8"; private final List<UrlVerifier> verifiers; @Autowired public UrlVerifiers(List<UrlVerifier> vrfrs) { this.verifiers = vrfrs; } public boolean isSafe(String url) { boolean safe = true; final String encodedUrl; try { encodedUrl = URLEncoder.encode(url, ENCODING_UTF8); } catch (UnsupportedEncodingException e) { LOGGER.warn("Unable to encode url: {}", url);
// Path: linkshortener-api/src/main/java/be/drissamri/service/exception/LinkshortenerException.java // public class LinkshortenerException extends RuntimeException { // // public LinkshortenerException(String message) { // super(message); // } // // public LinkshortenerException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: linkshortener-api/src/main/java/be/drissamri/service/verifier/UrlVerifiers.java import be.drissamri.service.exception.LinkshortenerException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; package be.drissamri.service.verifier; @Component public class UrlVerifiers { private static final Logger LOGGER = LoggerFactory.getLogger(UrlVerifier.class); private static final String ENCODING_UTF8 = "UTF-8"; private final List<UrlVerifier> verifiers; @Autowired public UrlVerifiers(List<UrlVerifier> vrfrs) { this.verifiers = vrfrs; } public boolean isSafe(String url) { boolean safe = true; final String encodedUrl; try { encodedUrl = URLEncoder.encode(url, ENCODING_UTF8); } catch (UnsupportedEncodingException e) { LOGGER.warn("Unable to encode url: {}", url);
throw new LinkshortenerException("Unable to encode to UTF-8", e);
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/service/impl/Base36HashService.java
// Path: linkshortener-api/src/main/java/be/drissamri/service/HashService.java // public interface HashService { // String shorten(String url); // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/SupportedProtocol.java // public enum SupportedProtocol { // HTTP("http"), // HTTPS("https"); // // private String protocol; // // SupportedProtocol(String protocol) { // this.protocol = protocol; // } // // public String getProtocol() { // return protocol; // } // // public static boolean contains(String prtcl) { // boolean supported = false; // for (SupportedProtocol validProtocol : SupportedProtocol.values()) { // if (StringUtils.startsWithIgnoreCase(prtcl, validProtocol.getProtocol())) { // supported = true; // break; // } // } // // return supported; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/exception/InvalidURLException.java // public class InvalidURLException extends LinkshortenerException { // // public InvalidURLException(String message) { // super(message); // } // // public InvalidURLException(String message, Throwable cause) { // super(message, cause); // } // }
import be.drissamri.service.HashService; import be.drissamri.service.SupportedProtocol; import be.drissamri.service.exception.InvalidURLException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.impl; @Service public class Base36HashService implements HashService { private static final int RADIX = 36; private static final String PIPE = "-"; @Override public String shorten(String url) { return encode(url); } private String encode(String url) { if (StringUtils.isEmpty(url)) {
// Path: linkshortener-api/src/main/java/be/drissamri/service/HashService.java // public interface HashService { // String shorten(String url); // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/SupportedProtocol.java // public enum SupportedProtocol { // HTTP("http"), // HTTPS("https"); // // private String protocol; // // SupportedProtocol(String protocol) { // this.protocol = protocol; // } // // public String getProtocol() { // return protocol; // } // // public static boolean contains(String prtcl) { // boolean supported = false; // for (SupportedProtocol validProtocol : SupportedProtocol.values()) { // if (StringUtils.startsWithIgnoreCase(prtcl, validProtocol.getProtocol())) { // supported = true; // break; // } // } // // return supported; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/exception/InvalidURLException.java // public class InvalidURLException extends LinkshortenerException { // // public InvalidURLException(String message) { // super(message); // } // // public InvalidURLException(String message, Throwable cause) { // super(message, cause); // } // } // Path: linkshortener-api/src/main/java/be/drissamri/service/impl/Base36HashService.java import be.drissamri.service.HashService; import be.drissamri.service.SupportedProtocol; import be.drissamri.service.exception.InvalidURLException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.impl; @Service public class Base36HashService implements HashService { private static final int RADIX = 36; private static final String PIPE = "-"; @Override public String shorten(String url) { return encode(url); } private String encode(String url) { if (StringUtils.isEmpty(url)) {
throw new InvalidURLException("Supplied invalid url: empty");
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/service/impl/Base36HashService.java
// Path: linkshortener-api/src/main/java/be/drissamri/service/HashService.java // public interface HashService { // String shorten(String url); // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/SupportedProtocol.java // public enum SupportedProtocol { // HTTP("http"), // HTTPS("https"); // // private String protocol; // // SupportedProtocol(String protocol) { // this.protocol = protocol; // } // // public String getProtocol() { // return protocol; // } // // public static boolean contains(String prtcl) { // boolean supported = false; // for (SupportedProtocol validProtocol : SupportedProtocol.values()) { // if (StringUtils.startsWithIgnoreCase(prtcl, validProtocol.getProtocol())) { // supported = true; // break; // } // } // // return supported; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/exception/InvalidURLException.java // public class InvalidURLException extends LinkshortenerException { // // public InvalidURLException(String message) { // super(message); // } // // public InvalidURLException(String message, Throwable cause) { // super(message, cause); // } // }
import be.drissamri.service.HashService; import be.drissamri.service.SupportedProtocol; import be.drissamri.service.exception.InvalidURLException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.impl; @Service public class Base36HashService implements HashService { private static final int RADIX = 36; private static final String PIPE = "-"; @Override public String shorten(String url) { return encode(url); } private String encode(String url) { if (StringUtils.isEmpty(url)) { throw new InvalidURLException("Supplied invalid url: empty"); }
// Path: linkshortener-api/src/main/java/be/drissamri/service/HashService.java // public interface HashService { // String shorten(String url); // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/SupportedProtocol.java // public enum SupportedProtocol { // HTTP("http"), // HTTPS("https"); // // private String protocol; // // SupportedProtocol(String protocol) { // this.protocol = protocol; // } // // public String getProtocol() { // return protocol; // } // // public static boolean contains(String prtcl) { // boolean supported = false; // for (SupportedProtocol validProtocol : SupportedProtocol.values()) { // if (StringUtils.startsWithIgnoreCase(prtcl, validProtocol.getProtocol())) { // supported = true; // break; // } // } // // return supported; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/exception/InvalidURLException.java // public class InvalidURLException extends LinkshortenerException { // // public InvalidURLException(String message) { // super(message); // } // // public InvalidURLException(String message, Throwable cause) { // super(message, cause); // } // } // Path: linkshortener-api/src/main/java/be/drissamri/service/impl/Base36HashService.java import be.drissamri.service.HashService; import be.drissamri.service.SupportedProtocol; import be.drissamri.service.exception.InvalidURLException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.impl; @Service public class Base36HashService implements HashService { private static final int RADIX = 36; private static final String PIPE = "-"; @Override public String shorten(String url) { return encode(url); } private String encode(String url) { if (StringUtils.isEmpty(url)) { throw new InvalidURLException("Supplied invalid url: empty"); }
boolean isSupportedProtocol = SupportedProtocol.contains(url);
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankSettings.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApiSettings.java // public interface ApiSettings { // String getEndpoint(); // String getCredential(); // String getVersion(); // }
import be.drissamri.config.safebrowsing.ApiSettings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config.safebrowsing.phishtank; @Component @Conditional(PhishTankCondition.class)
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApiSettings.java // public interface ApiSettings { // String getEndpoint(); // String getCredential(); // String getVersion(); // } // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankSettings.java import be.drissamri.config.safebrowsing.ApiSettings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config.safebrowsing.phishtank; @Component @Conditional(PhishTankCondition.class)
public class PhishTankSettings implements ApiSettings {
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/rest/RedirectController.java
// Path: linkshortener-api/src/main/java/be/drissamri/service/LinkService.java // public interface LinkService { // List<LinkEntity> find(int offset, int limit); // // LinkEntity create(String url); // // String findUrlByHash(String hash); // // void deleteByHash(String hash); // }
import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import java.net.URI; import be.drissamri.service.LinkService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.ws.rs.GET; import javax.ws.rs.Path;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.rest; @Component @Path("/") public class RedirectController {
// Path: linkshortener-api/src/main/java/be/drissamri/service/LinkService.java // public interface LinkService { // List<LinkEntity> find(int offset, int limit); // // LinkEntity create(String url); // // String findUrlByHash(String hash); // // void deleteByHash(String hash); // } // Path: linkshortener-api/src/main/java/be/drissamri/rest/RedirectController.java import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import java.net.URI; import be.drissamri.service.LinkService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.ws.rs.GET; import javax.ws.rs.Path; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.rest; @Component @Path("/") public class RedirectController {
private LinkService service;
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/service/verifier/PhishTankUrlVerifier.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankCondition.java // public class PhishTankCondition implements Condition { // @Override // public boolean matches( // final ConditionContext context, // final AnnotatedTypeMetadata annotatedTypeMetadata) { // final String apiKey = context.getEnvironment().getProperty("provider.phishtank.key"); // // return !StringUtils.isEmpty(apiKey); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankConfig.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(PhishTankConfig.class); // private static final String PARAMETER_API_KEY = "app_key"; // private static final String PARAMETER_FORMAT = "format"; // private static final String RESPONSE_FORMAT = "json"; // private final String apiUrl; // private final MultiValueMap<String, String> parameters; // // @Autowired // public PhishTankConfig(PhishTankSettings settings) { // this.apiUrl = settings.getEndpoint(); // this.parameters = new LinkedMultiValueMap<>(); // parameters.add(PARAMETER_API_KEY, settings.getCredential()); // parameters.add(PARAMETER_FORMAT, RESPONSE_FORMAT); // // if (!StringUtils.isEmpty(parameters.getFirst(PARAMETER_API_KEY)) // && !StringUtils.isEmpty(parameters.get(PARAMETER_FORMAT))) { // LOGGER.info("PhishTank API is configured with an API key"); // } // } // // public final String getApiUrl() { // return apiUrl; // } // // public final MultiValueMap<String, String> getParameters() { // return new LinkedMultiValueMap<>(parameters); // } // }
import org.springframework.context.annotation.Conditional; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import be.drissamri.config.safebrowsing.phishtank.PhishTankCondition; import be.drissamri.config.safebrowsing.phishtank.PhishTankConfig; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired;
/** * The MIT License (MIT) * * Copyright (c) 2015 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; /** * Validate URL with the PhishTank API. * @author Driss Amri (drissamri@gmail.com) * @version $Id$ */ @Component @Conditional(PhishTankCondition.class) public class PhishTankUrlVerifier implements UrlVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingUrlVerifier.class); private static final String PARAMETER_URL = "url"; private static final String IN_DATABASE_PARSE_EXPRESSION = "results.in_database"; private final RestTemplate client;
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankCondition.java // public class PhishTankCondition implements Condition { // @Override // public boolean matches( // final ConditionContext context, // final AnnotatedTypeMetadata annotatedTypeMetadata) { // final String apiKey = context.getEnvironment().getProperty("provider.phishtank.key"); // // return !StringUtils.isEmpty(apiKey); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/phishtank/PhishTankConfig.java // @Component // @Conditional(PhishTankCondition.class) // public class PhishTankConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(PhishTankConfig.class); // private static final String PARAMETER_API_KEY = "app_key"; // private static final String PARAMETER_FORMAT = "format"; // private static final String RESPONSE_FORMAT = "json"; // private final String apiUrl; // private final MultiValueMap<String, String> parameters; // // @Autowired // public PhishTankConfig(PhishTankSettings settings) { // this.apiUrl = settings.getEndpoint(); // this.parameters = new LinkedMultiValueMap<>(); // parameters.add(PARAMETER_API_KEY, settings.getCredential()); // parameters.add(PARAMETER_FORMAT, RESPONSE_FORMAT); // // if (!StringUtils.isEmpty(parameters.getFirst(PARAMETER_API_KEY)) // && !StringUtils.isEmpty(parameters.get(PARAMETER_FORMAT))) { // LOGGER.info("PhishTank API is configured with an API key"); // } // } // // public final String getApiUrl() { // return apiUrl; // } // // public final MultiValueMap<String, String> getParameters() { // return new LinkedMultiValueMap<>(parameters); // } // } // Path: linkshortener-api/src/main/java/be/drissamri/service/verifier/PhishTankUrlVerifier.java import org.springframework.context.annotation.Conditional; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import be.drissamri.config.safebrowsing.phishtank.PhishTankCondition; import be.drissamri.config.safebrowsing.phishtank.PhishTankConfig; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * The MIT License (MIT) * * Copyright (c) 2015 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; /** * Validate URL with the PhishTank API. * @author Driss Amri (drissamri@gmail.com) * @version $Id$ */ @Component @Conditional(PhishTankCondition.class) public class PhishTankUrlVerifier implements UrlVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingUrlVerifier.class); private static final String PARAMETER_URL = "url"; private static final String IN_DATABASE_PARSE_EXPRESSION = "results.in_database"; private final RestTemplate client;
private final PhishTankConfig config;
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleApiSettings.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApiSettings.java // public interface ApiSettings { // String getEndpoint(); // String getCredential(); // String getVersion(); // }
import be.drissamri.config.safebrowsing.ApiSettings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config.safebrowsing.google; @Component @Conditional(GoogleCondition.class)
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApiSettings.java // public interface ApiSettings { // String getEndpoint(); // String getCredential(); // String getVersion(); // } // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleApiSettings.java import be.drissamri.config.safebrowsing.ApiSettings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config.safebrowsing.google; @Component @Conditional(GoogleCondition.class)
public class GoogleApiSettings implements ApiSettings {
drissamri/linkshortener
linkshortener-api/src/test/java/be/drissamri/service/Base36HashServiceTest.java
// Path: linkshortener-api/src/main/java/be/drissamri/service/exception/InvalidURLException.java // public class InvalidURLException extends LinkshortenerException { // // public InvalidURLException(String message) { // super(message); // } // // public InvalidURLException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/impl/Base36HashService.java // @Service // public class Base36HashService implements HashService { // private static final int RADIX = 36; // private static final String PIPE = "-"; // // @Override // public String shorten(String url) { // return encode(url); // } // // private String encode(String url) { // if (StringUtils.isEmpty(url)) { // throw new InvalidURLException("Supplied invalid url: empty"); // } // // boolean isSupportedProtocol = SupportedProtocol.contains(url); // if (!isSupportedProtocol) { // throw new InvalidURLException("URL protocol not supported"); // } // // String hexValue = Integer.toString(url.hashCode(), RADIX); // if (hexValue.startsWith(PIPE)) { // hexValue = hexValue.substring(1); // } // // // TODO: Implement database check to prevent collisions // return hexValue; // } // // }
import be.drissamri.service.exception.InvalidURLException; import be.drissamri.service.impl.Base36HashService; import org.junit.Ignore; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
package be.drissamri.service; @Ignore public class Base36HashServiceTest {
// Path: linkshortener-api/src/main/java/be/drissamri/service/exception/InvalidURLException.java // public class InvalidURLException extends LinkshortenerException { // // public InvalidURLException(String message) { // super(message); // } // // public InvalidURLException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/impl/Base36HashService.java // @Service // public class Base36HashService implements HashService { // private static final int RADIX = 36; // private static final String PIPE = "-"; // // @Override // public String shorten(String url) { // return encode(url); // } // // private String encode(String url) { // if (StringUtils.isEmpty(url)) { // throw new InvalidURLException("Supplied invalid url: empty"); // } // // boolean isSupportedProtocol = SupportedProtocol.contains(url); // if (!isSupportedProtocol) { // throw new InvalidURLException("URL protocol not supported"); // } // // String hexValue = Integer.toString(url.hashCode(), RADIX); // if (hexValue.startsWith(PIPE)) { // hexValue = hexValue.substring(1); // } // // // TODO: Implement database check to prevent collisions // return hexValue; // } // // } // Path: linkshortener-api/src/test/java/be/drissamri/service/Base36HashServiceTest.java import be.drissamri.service.exception.InvalidURLException; import be.drissamri.service.impl.Base36HashService; import org.junit.Ignore; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; package be.drissamri.service; @Ignore public class Base36HashServiceTest {
private Base36HashService base36ShortenService = new Base36HashService();
drissamri/linkshortener
linkshortener-api/src/test/java/be/drissamri/service/Base36HashServiceTest.java
// Path: linkshortener-api/src/main/java/be/drissamri/service/exception/InvalidURLException.java // public class InvalidURLException extends LinkshortenerException { // // public InvalidURLException(String message) { // super(message); // } // // public InvalidURLException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/impl/Base36HashService.java // @Service // public class Base36HashService implements HashService { // private static final int RADIX = 36; // private static final String PIPE = "-"; // // @Override // public String shorten(String url) { // return encode(url); // } // // private String encode(String url) { // if (StringUtils.isEmpty(url)) { // throw new InvalidURLException("Supplied invalid url: empty"); // } // // boolean isSupportedProtocol = SupportedProtocol.contains(url); // if (!isSupportedProtocol) { // throw new InvalidURLException("URL protocol not supported"); // } // // String hexValue = Integer.toString(url.hashCode(), RADIX); // if (hexValue.startsWith(PIPE)) { // hexValue = hexValue.substring(1); // } // // // TODO: Implement database check to prevent collisions // return hexValue; // } // // }
import be.drissamri.service.exception.InvalidURLException; import be.drissamri.service.impl.Base36HashService; import org.junit.Ignore; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
package be.drissamri.service; @Ignore public class Base36HashServiceTest { private Base36HashService base36ShortenService = new Base36HashService(); @Test public void validHttpUrlShouldReturnAHash() { String result = base36ShortenService.shorten("http://www.drissamri.be"); assertThat(result).isEqualTo("miufvo"); } @Test public void validHttpsUrlShouldReturnAHash() { String result = base36ShortenService.shorten("https://www.drissamri.be"); assertThat(result).isEqualTo("3yq02h"); }
// Path: linkshortener-api/src/main/java/be/drissamri/service/exception/InvalidURLException.java // public class InvalidURLException extends LinkshortenerException { // // public InvalidURLException(String message) { // super(message); // } // // public InvalidURLException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/impl/Base36HashService.java // @Service // public class Base36HashService implements HashService { // private static final int RADIX = 36; // private static final String PIPE = "-"; // // @Override // public String shorten(String url) { // return encode(url); // } // // private String encode(String url) { // if (StringUtils.isEmpty(url)) { // throw new InvalidURLException("Supplied invalid url: empty"); // } // // boolean isSupportedProtocol = SupportedProtocol.contains(url); // if (!isSupportedProtocol) { // throw new InvalidURLException("URL protocol not supported"); // } // // String hexValue = Integer.toString(url.hashCode(), RADIX); // if (hexValue.startsWith(PIPE)) { // hexValue = hexValue.substring(1); // } // // // TODO: Implement database check to prevent collisions // return hexValue; // } // // } // Path: linkshortener-api/src/test/java/be/drissamri/service/Base36HashServiceTest.java import be.drissamri.service.exception.InvalidURLException; import be.drissamri.service.impl.Base36HashService; import org.junit.Ignore; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; package be.drissamri.service; @Ignore public class Base36HashServiceTest { private Base36HashService base36ShortenService = new Base36HashService(); @Test public void validHttpUrlShouldReturnAHash() { String result = base36ShortenService.shorten("http://www.drissamri.be"); assertThat(result).isEqualTo("miufvo"); } @Test public void validHttpsUrlShouldReturnAHash() { String result = base36ShortenService.shorten("https://www.drissamri.be"); assertThat(result).isEqualTo("3yq02h"); }
@Test(expected = InvalidURLException.class)
drissamri/linkshortener
linkshortener-api/src/test/java/be/drissamri/service/verifier/GoogleSafeBrowsingUrlVerifierTest.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApplicationSettings.java // @Component // public class ApplicationSettings { // private final String name; // private final String version; // // @Autowired // public ApplicationSettings( // @Value("${info.build.name}") String name, // @Value("${info.build.version}") String vrsn) { // this.name = name; // this.version = vrsn; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleApiSettings.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleApiSettings implements ApiSettings { // private String endpoint; // private String version; // private String credential; // // @Autowired // public GoogleApiSettings( // @Value("${provider.google.url:}") String url, // @Value("${provider.google.version:}") String version, // @Value("${provider.google.key:}") String key) { // this.endpoint = url; // this.version = version; // this.credential = key; // } // // @Override // public String getCredential() { // return credential; // } // // @Override // public String getEndpoint() { // return endpoint; // } // // @Override // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleSafeBrowsingConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); // private static final String PARAMETER_API_KEY = "apiKey"; // private static final String PARAMETER_API_VERSION = "apiVersion"; // private static final String PARAMETER_APP_VERSION = "appVersion"; // private static final String PARAMETER_APP_NAME = "client"; // private final Map<String, String> parameters; // private final String apiUrl; // // @Autowired // public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) { // this.parameters = populateParameterMap(server, app); // this.apiUrl = server.getEndpoint(); // // if (!StringUtils.isEmpty(parameters.get(PARAMETER_API_KEY)) && // !StringUtils.isEmpty(parameters.get(PARAMETER_API_VERSION))) { // LOGGER.info("Google Safe Browsing API is configured with an API key"); // } // } // // private HashMap<String, String> populateParameterMap( // GoogleApiSettings server, // ApplicationSettings app) { // final HashMap<String, String> map = new HashMap<>(); // map.put(PARAMETER_API_KEY, server.getCredential()); // map.put(PARAMETER_API_VERSION, server.getVersion()); // map.put(PARAMETER_APP_VERSION, app.getVersion()); // map.put(PARAMETER_APP_NAME, app.getName()); // return map; // } // // public final String getApiUrl() { // return apiUrl; // } // // public final Map<String, String> getParameters() { // return new HashMap<>(parameters); // } // }
import org.junit.Test; import static org.mockito.BDDMockito.given; import org.mockito.Matchers; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import be.drissamri.config.safebrowsing.ApplicationSettings; import be.drissamri.config.safebrowsing.google.GoogleApiSettings; import be.drissamri.config.safebrowsing.google.GoogleSafeBrowsingConfig; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; public class GoogleSafeBrowsingUrlVerifierTest { private GoogleSafeBrowsingUrlVerifier verifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; @Before public void setUp() { MockitoAnnotations.initMocks(this);
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApplicationSettings.java // @Component // public class ApplicationSettings { // private final String name; // private final String version; // // @Autowired // public ApplicationSettings( // @Value("${info.build.name}") String name, // @Value("${info.build.version}") String vrsn) { // this.name = name; // this.version = vrsn; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleApiSettings.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleApiSettings implements ApiSettings { // private String endpoint; // private String version; // private String credential; // // @Autowired // public GoogleApiSettings( // @Value("${provider.google.url:}") String url, // @Value("${provider.google.version:}") String version, // @Value("${provider.google.key:}") String key) { // this.endpoint = url; // this.version = version; // this.credential = key; // } // // @Override // public String getCredential() { // return credential; // } // // @Override // public String getEndpoint() { // return endpoint; // } // // @Override // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleSafeBrowsingConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); // private static final String PARAMETER_API_KEY = "apiKey"; // private static final String PARAMETER_API_VERSION = "apiVersion"; // private static final String PARAMETER_APP_VERSION = "appVersion"; // private static final String PARAMETER_APP_NAME = "client"; // private final Map<String, String> parameters; // private final String apiUrl; // // @Autowired // public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) { // this.parameters = populateParameterMap(server, app); // this.apiUrl = server.getEndpoint(); // // if (!StringUtils.isEmpty(parameters.get(PARAMETER_API_KEY)) && // !StringUtils.isEmpty(parameters.get(PARAMETER_API_VERSION))) { // LOGGER.info("Google Safe Browsing API is configured with an API key"); // } // } // // private HashMap<String, String> populateParameterMap( // GoogleApiSettings server, // ApplicationSettings app) { // final HashMap<String, String> map = new HashMap<>(); // map.put(PARAMETER_API_KEY, server.getCredential()); // map.put(PARAMETER_API_VERSION, server.getVersion()); // map.put(PARAMETER_APP_VERSION, app.getVersion()); // map.put(PARAMETER_APP_NAME, app.getName()); // return map; // } // // public final String getApiUrl() { // return apiUrl; // } // // public final Map<String, String> getParameters() { // return new HashMap<>(parameters); // } // } // Path: linkshortener-api/src/test/java/be/drissamri/service/verifier/GoogleSafeBrowsingUrlVerifierTest.java import org.junit.Test; import static org.mockito.BDDMockito.given; import org.mockito.Matchers; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import be.drissamri.config.safebrowsing.ApplicationSettings; import be.drissamri.config.safebrowsing.google.GoogleApiSettings; import be.drissamri.config.safebrowsing.google.GoogleSafeBrowsingConfig; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; public class GoogleSafeBrowsingUrlVerifierTest { private GoogleSafeBrowsingUrlVerifier verifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; @Before public void setUp() { MockitoAnnotations.initMocks(this);
GoogleApiSettings google = new GoogleApiSettings("apiUrl", "apiVersion", "apiKey");
drissamri/linkshortener
linkshortener-api/src/test/java/be/drissamri/service/verifier/GoogleSafeBrowsingUrlVerifierTest.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApplicationSettings.java // @Component // public class ApplicationSettings { // private final String name; // private final String version; // // @Autowired // public ApplicationSettings( // @Value("${info.build.name}") String name, // @Value("${info.build.version}") String vrsn) { // this.name = name; // this.version = vrsn; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleApiSettings.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleApiSettings implements ApiSettings { // private String endpoint; // private String version; // private String credential; // // @Autowired // public GoogleApiSettings( // @Value("${provider.google.url:}") String url, // @Value("${provider.google.version:}") String version, // @Value("${provider.google.key:}") String key) { // this.endpoint = url; // this.version = version; // this.credential = key; // } // // @Override // public String getCredential() { // return credential; // } // // @Override // public String getEndpoint() { // return endpoint; // } // // @Override // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleSafeBrowsingConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); // private static final String PARAMETER_API_KEY = "apiKey"; // private static final String PARAMETER_API_VERSION = "apiVersion"; // private static final String PARAMETER_APP_VERSION = "appVersion"; // private static final String PARAMETER_APP_NAME = "client"; // private final Map<String, String> parameters; // private final String apiUrl; // // @Autowired // public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) { // this.parameters = populateParameterMap(server, app); // this.apiUrl = server.getEndpoint(); // // if (!StringUtils.isEmpty(parameters.get(PARAMETER_API_KEY)) && // !StringUtils.isEmpty(parameters.get(PARAMETER_API_VERSION))) { // LOGGER.info("Google Safe Browsing API is configured with an API key"); // } // } // // private HashMap<String, String> populateParameterMap( // GoogleApiSettings server, // ApplicationSettings app) { // final HashMap<String, String> map = new HashMap<>(); // map.put(PARAMETER_API_KEY, server.getCredential()); // map.put(PARAMETER_API_VERSION, server.getVersion()); // map.put(PARAMETER_APP_VERSION, app.getVersion()); // map.put(PARAMETER_APP_NAME, app.getName()); // return map; // } // // public final String getApiUrl() { // return apiUrl; // } // // public final Map<String, String> getParameters() { // return new HashMap<>(parameters); // } // }
import org.junit.Test; import static org.mockito.BDDMockito.given; import org.mockito.Matchers; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import be.drissamri.config.safebrowsing.ApplicationSettings; import be.drissamri.config.safebrowsing.google.GoogleApiSettings; import be.drissamri.config.safebrowsing.google.GoogleSafeBrowsingConfig; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; public class GoogleSafeBrowsingUrlVerifierTest { private GoogleSafeBrowsingUrlVerifier verifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; @Before public void setUp() { MockitoAnnotations.initMocks(this); GoogleApiSettings google = new GoogleApiSettings("apiUrl", "apiVersion", "apiKey");
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApplicationSettings.java // @Component // public class ApplicationSettings { // private final String name; // private final String version; // // @Autowired // public ApplicationSettings( // @Value("${info.build.name}") String name, // @Value("${info.build.version}") String vrsn) { // this.name = name; // this.version = vrsn; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleApiSettings.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleApiSettings implements ApiSettings { // private String endpoint; // private String version; // private String credential; // // @Autowired // public GoogleApiSettings( // @Value("${provider.google.url:}") String url, // @Value("${provider.google.version:}") String version, // @Value("${provider.google.key:}") String key) { // this.endpoint = url; // this.version = version; // this.credential = key; // } // // @Override // public String getCredential() { // return credential; // } // // @Override // public String getEndpoint() { // return endpoint; // } // // @Override // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleSafeBrowsingConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); // private static final String PARAMETER_API_KEY = "apiKey"; // private static final String PARAMETER_API_VERSION = "apiVersion"; // private static final String PARAMETER_APP_VERSION = "appVersion"; // private static final String PARAMETER_APP_NAME = "client"; // private final Map<String, String> parameters; // private final String apiUrl; // // @Autowired // public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) { // this.parameters = populateParameterMap(server, app); // this.apiUrl = server.getEndpoint(); // // if (!StringUtils.isEmpty(parameters.get(PARAMETER_API_KEY)) && // !StringUtils.isEmpty(parameters.get(PARAMETER_API_VERSION))) { // LOGGER.info("Google Safe Browsing API is configured with an API key"); // } // } // // private HashMap<String, String> populateParameterMap( // GoogleApiSettings server, // ApplicationSettings app) { // final HashMap<String, String> map = new HashMap<>(); // map.put(PARAMETER_API_KEY, server.getCredential()); // map.put(PARAMETER_API_VERSION, server.getVersion()); // map.put(PARAMETER_APP_VERSION, app.getVersion()); // map.put(PARAMETER_APP_NAME, app.getName()); // return map; // } // // public final String getApiUrl() { // return apiUrl; // } // // public final Map<String, String> getParameters() { // return new HashMap<>(parameters); // } // } // Path: linkshortener-api/src/test/java/be/drissamri/service/verifier/GoogleSafeBrowsingUrlVerifierTest.java import org.junit.Test; import static org.mockito.BDDMockito.given; import org.mockito.Matchers; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import be.drissamri.config.safebrowsing.ApplicationSettings; import be.drissamri.config.safebrowsing.google.GoogleApiSettings; import be.drissamri.config.safebrowsing.google.GoogleSafeBrowsingConfig; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; public class GoogleSafeBrowsingUrlVerifierTest { private GoogleSafeBrowsingUrlVerifier verifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; @Before public void setUp() { MockitoAnnotations.initMocks(this); GoogleApiSettings google = new GoogleApiSettings("apiUrl", "apiVersion", "apiKey");
ApplicationSettings app = new ApplicationSettings("appName", "appVersion");
drissamri/linkshortener
linkshortener-api/src/test/java/be/drissamri/service/verifier/GoogleSafeBrowsingUrlVerifierTest.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApplicationSettings.java // @Component // public class ApplicationSettings { // private final String name; // private final String version; // // @Autowired // public ApplicationSettings( // @Value("${info.build.name}") String name, // @Value("${info.build.version}") String vrsn) { // this.name = name; // this.version = vrsn; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleApiSettings.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleApiSettings implements ApiSettings { // private String endpoint; // private String version; // private String credential; // // @Autowired // public GoogleApiSettings( // @Value("${provider.google.url:}") String url, // @Value("${provider.google.version:}") String version, // @Value("${provider.google.key:}") String key) { // this.endpoint = url; // this.version = version; // this.credential = key; // } // // @Override // public String getCredential() { // return credential; // } // // @Override // public String getEndpoint() { // return endpoint; // } // // @Override // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleSafeBrowsingConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); // private static final String PARAMETER_API_KEY = "apiKey"; // private static final String PARAMETER_API_VERSION = "apiVersion"; // private static final String PARAMETER_APP_VERSION = "appVersion"; // private static final String PARAMETER_APP_NAME = "client"; // private final Map<String, String> parameters; // private final String apiUrl; // // @Autowired // public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) { // this.parameters = populateParameterMap(server, app); // this.apiUrl = server.getEndpoint(); // // if (!StringUtils.isEmpty(parameters.get(PARAMETER_API_KEY)) && // !StringUtils.isEmpty(parameters.get(PARAMETER_API_VERSION))) { // LOGGER.info("Google Safe Browsing API is configured with an API key"); // } // } // // private HashMap<String, String> populateParameterMap( // GoogleApiSettings server, // ApplicationSettings app) { // final HashMap<String, String> map = new HashMap<>(); // map.put(PARAMETER_API_KEY, server.getCredential()); // map.put(PARAMETER_API_VERSION, server.getVersion()); // map.put(PARAMETER_APP_VERSION, app.getVersion()); // map.put(PARAMETER_APP_NAME, app.getName()); // return map; // } // // public final String getApiUrl() { // return apiUrl; // } // // public final Map<String, String> getParameters() { // return new HashMap<>(parameters); // } // }
import org.junit.Test; import static org.mockito.BDDMockito.given; import org.mockito.Matchers; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import be.drissamri.config.safebrowsing.ApplicationSettings; import be.drissamri.config.safebrowsing.google.GoogleApiSettings; import be.drissamri.config.safebrowsing.google.GoogleSafeBrowsingConfig; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; public class GoogleSafeBrowsingUrlVerifierTest { private GoogleSafeBrowsingUrlVerifier verifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; @Before public void setUp() { MockitoAnnotations.initMocks(this); GoogleApiSettings google = new GoogleApiSettings("apiUrl", "apiVersion", "apiKey"); ApplicationSettings app = new ApplicationSettings("appName", "appVersion"); verifier = new GoogleSafeBrowsingUrlVerifier(restTemplate,
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApplicationSettings.java // @Component // public class ApplicationSettings { // private final String name; // private final String version; // // @Autowired // public ApplicationSettings( // @Value("${info.build.name}") String name, // @Value("${info.build.version}") String vrsn) { // this.name = name; // this.version = vrsn; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleApiSettings.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleApiSettings implements ApiSettings { // private String endpoint; // private String version; // private String credential; // // @Autowired // public GoogleApiSettings( // @Value("${provider.google.url:}") String url, // @Value("${provider.google.version:}") String version, // @Value("${provider.google.key:}") String key) { // this.endpoint = url; // this.version = version; // this.credential = key; // } // // @Override // public String getCredential() { // return credential; // } // // @Override // public String getEndpoint() { // return endpoint; // } // // @Override // public String getVersion() { // return version; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java // @Component // @Conditional(GoogleCondition.class) // public class GoogleSafeBrowsingConfig { // private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); // private static final String PARAMETER_API_KEY = "apiKey"; // private static final String PARAMETER_API_VERSION = "apiVersion"; // private static final String PARAMETER_APP_VERSION = "appVersion"; // private static final String PARAMETER_APP_NAME = "client"; // private final Map<String, String> parameters; // private final String apiUrl; // // @Autowired // public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) { // this.parameters = populateParameterMap(server, app); // this.apiUrl = server.getEndpoint(); // // if (!StringUtils.isEmpty(parameters.get(PARAMETER_API_KEY)) && // !StringUtils.isEmpty(parameters.get(PARAMETER_API_VERSION))) { // LOGGER.info("Google Safe Browsing API is configured with an API key"); // } // } // // private HashMap<String, String> populateParameterMap( // GoogleApiSettings server, // ApplicationSettings app) { // final HashMap<String, String> map = new HashMap<>(); // map.put(PARAMETER_API_KEY, server.getCredential()); // map.put(PARAMETER_API_VERSION, server.getVersion()); // map.put(PARAMETER_APP_VERSION, app.getVersion()); // map.put(PARAMETER_APP_NAME, app.getName()); // return map; // } // // public final String getApiUrl() { // return apiUrl; // } // // public final Map<String, String> getParameters() { // return new HashMap<>(parameters); // } // } // Path: linkshortener-api/src/test/java/be/drissamri/service/verifier/GoogleSafeBrowsingUrlVerifierTest.java import org.junit.Test; import static org.mockito.BDDMockito.given; import org.mockito.Matchers; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import be.drissamri.config.safebrowsing.ApplicationSettings; import be.drissamri.config.safebrowsing.google.GoogleApiSettings; import be.drissamri.config.safebrowsing.google.GoogleSafeBrowsingConfig; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.service.verifier; public class GoogleSafeBrowsingUrlVerifierTest { private GoogleSafeBrowsingUrlVerifier verifier; @Mock private RestTemplate restTemplate; private static final String LONG_URL = "http://www.drissamri.be"; @Before public void setUp() { MockitoAnnotations.initMocks(this); GoogleApiSettings google = new GoogleApiSettings("apiUrl", "apiVersion", "apiKey"); ApplicationSettings app = new ApplicationSettings("appName", "appVersion"); verifier = new GoogleSafeBrowsingUrlVerifier(restTemplate,
new GoogleSafeBrowsingConfig(google, app));
drissamri/linkshortener
linkshortener-web/src/main/java/be/drissamri/controller/LinkController.java
// Path: linkshortener-web/src/main/java/be/drissamri/model/Link.java // public class Link { // private String url; // private String hash; // private String shortUrl; // // public Link(String shortUrl, String url, String hash) { // this.shortUrl = shortUrl; // this.url = url; // this.hash = hash; // } // // public Link() { // // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getShortUrl() { // return shortUrl; // } // // public void setShortUrl(String shortUrl) { // this.shortUrl = shortUrl; // } // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // @Override // public int hashCode() { // return Objects.hashCode(url); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final Link other = (Link) obj; // return Objects.equals(this.url, other.url) && Objects.equals(this.shortUrl, other.shortUrl); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/LinkService.java // public interface LinkService { // List<LinkEntity> find(int offset, int limit); // // LinkEntity create(String url); // // String findUrlByHash(String hash); // // void deleteByHash(String hash); // }
import be.drissamri.model.Link; import be.drissamri.service.LinkService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.controller; @RestController public class LinkController {
// Path: linkshortener-web/src/main/java/be/drissamri/model/Link.java // public class Link { // private String url; // private String hash; // private String shortUrl; // // public Link(String shortUrl, String url, String hash) { // this.shortUrl = shortUrl; // this.url = url; // this.hash = hash; // } // // public Link() { // // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getShortUrl() { // return shortUrl; // } // // public void setShortUrl(String shortUrl) { // this.shortUrl = shortUrl; // } // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // @Override // public int hashCode() { // return Objects.hashCode(url); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final Link other = (Link) obj; // return Objects.equals(this.url, other.url) && Objects.equals(this.shortUrl, other.shortUrl); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/LinkService.java // public interface LinkService { // List<LinkEntity> find(int offset, int limit); // // LinkEntity create(String url); // // String findUrlByHash(String hash); // // void deleteByHash(String hash); // } // Path: linkshortener-web/src/main/java/be/drissamri/controller/LinkController.java import be.drissamri.model.Link; import be.drissamri.service.LinkService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.controller; @RestController public class LinkController {
private final LinkService service;
drissamri/linkshortener
linkshortener-web/src/main/java/be/drissamri/controller/LinkController.java
// Path: linkshortener-web/src/main/java/be/drissamri/model/Link.java // public class Link { // private String url; // private String hash; // private String shortUrl; // // public Link(String shortUrl, String url, String hash) { // this.shortUrl = shortUrl; // this.url = url; // this.hash = hash; // } // // public Link() { // // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getShortUrl() { // return shortUrl; // } // // public void setShortUrl(String shortUrl) { // this.shortUrl = shortUrl; // } // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // @Override // public int hashCode() { // return Objects.hashCode(url); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final Link other = (Link) obj; // return Objects.equals(this.url, other.url) && Objects.equals(this.shortUrl, other.shortUrl); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/LinkService.java // public interface LinkService { // List<LinkEntity> find(int offset, int limit); // // LinkEntity create(String url); // // String findUrlByHash(String hash); // // void deleteByHash(String hash); // }
import be.drissamri.model.Link; import be.drissamri.service.LinkService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.controller; @RestController public class LinkController { private final LinkService service; @Autowired public LinkController(LinkService srvc) { this.service = srvc; } @RequestMapping("/links")
// Path: linkshortener-web/src/main/java/be/drissamri/model/Link.java // public class Link { // private String url; // private String hash; // private String shortUrl; // // public Link(String shortUrl, String url, String hash) { // this.shortUrl = shortUrl; // this.url = url; // this.hash = hash; // } // // public Link() { // // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getShortUrl() { // return shortUrl; // } // // public void setShortUrl(String shortUrl) { // this.shortUrl = shortUrl; // } // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // @Override // public int hashCode() { // return Objects.hashCode(url); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final Link other = (Link) obj; // return Objects.equals(this.url, other.url) && Objects.equals(this.shortUrl, other.shortUrl); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/service/LinkService.java // public interface LinkService { // List<LinkEntity> find(int offset, int limit); // // LinkEntity create(String url); // // String findUrlByHash(String hash); // // void deleteByHash(String hash); // } // Path: linkshortener-web/src/main/java/be/drissamri/controller/LinkController.java import be.drissamri.model.Link; import be.drissamri.service.LinkService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.controller; @RestController public class LinkController { private final LinkService service; @Autowired public LinkController(LinkService srvc) { this.service = srvc; } @RequestMapping("/links")
public Link createLink(@RequestParam(value = "longUrl") String longUrl) {
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/config/JerseyConfig.java
// Path: linkshortener-api/src/main/java/be/drissamri/rest/LinkController.java // @Component // @Path(LinkController.LINKS) // public class LinkController { // private static final Logger LOGGER = LoggerFactory.getLogger(LinkController.class); // public static final String LINKS = "/links"; // private final LinkService service; // // @Autowired // public LinkController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Produces(MediaType.APPLICATION_JSON) // public final Response find( // @Context UriInfo context, // @QueryParam("expand") @DefaultValue("false") final boolean expand, // @QueryParam("offset") @DefaultValue("1") final int offset, // @QueryParam("limit") @DefaultValue("10") final int limit) throws Exception { // LOGGER.debug("Find links request. expand: {} - offset: {}, limit: {}", expand, offset, limit); // // final List<LinkEntity> foundLinks = service.find(offset, limit); // // final List<Resource> resources = foundLinks // .stream() // .map(link -> expand ? new LinkResource(context, link) : new Resource(context, link.getHash())) // .collect(Collectors.toList()); // // final CollectionResource collection = new CollectionResource(context, resources, offset, limit); // LOGGER.debug("Returning collection of {} links", collection.get("size")); // return Response.ok().entity(collection).build(); // } // // @POST // @Consumes(MediaType.APPLICATION_FORM_URLENCODED) // @Produces(MediaType.APPLICATION_JSON) // public final Response createShortLink(@Context UriInfo context, @FormParam("url") String url) { // LOGGER.debug("Shorten request for: {}", url); // final LinkResource link = new LinkResource(context, this.service.create(url)); // LOGGER.debug("Returning link: {}", link); // return created(link); // } // // @DELETE // @Path("/{hash}") // @Produces(MediaType.APPLICATION_JSON) // public final Response deleteLinkByHash(@PathParam(value = "hash") String hash) { // LOGGER.info("Request link delete for hash: {}", hash); // this.service.deleteByHash(hash); // return Response.noContent().build(); // } // // private Response created(Resource createdResource) { // final String href = (String) createdResource.get("href"); // return Response // .created(URI.create(href)) // .entity(createdResource) // .build(); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/rest/RedirectController.java // @Component // @Path("/") // public class RedirectController { // private LinkService service; // // @Autowired // public RedirectController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Path("/{hash}") // public Response redirect(@PathParam("hash") String hash) { // Response response; // // final String url = service.findUrlByHash(hash); // if (!StringUtils.isEmpty(url)) { // URI uri = URI.create(url); // response = Response // .status(Response.Status.MOVED_PERMANENTLY) // .location(uri) // .build(); // } else { // response = Response // .status(Response.Status.BAD_REQUEST) // .build(); // } // // return response; // } // }
import be.drissamri.rest.LinkController; import be.drissamri.rest.RedirectController; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config; @Component @ApplicationPath("/api/v1") public class JerseyConfig extends ResourceConfig { public JerseyConfig() { packages("be.drissamri.rest");
// Path: linkshortener-api/src/main/java/be/drissamri/rest/LinkController.java // @Component // @Path(LinkController.LINKS) // public class LinkController { // private static final Logger LOGGER = LoggerFactory.getLogger(LinkController.class); // public static final String LINKS = "/links"; // private final LinkService service; // // @Autowired // public LinkController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Produces(MediaType.APPLICATION_JSON) // public final Response find( // @Context UriInfo context, // @QueryParam("expand") @DefaultValue("false") final boolean expand, // @QueryParam("offset") @DefaultValue("1") final int offset, // @QueryParam("limit") @DefaultValue("10") final int limit) throws Exception { // LOGGER.debug("Find links request. expand: {} - offset: {}, limit: {}", expand, offset, limit); // // final List<LinkEntity> foundLinks = service.find(offset, limit); // // final List<Resource> resources = foundLinks // .stream() // .map(link -> expand ? new LinkResource(context, link) : new Resource(context, link.getHash())) // .collect(Collectors.toList()); // // final CollectionResource collection = new CollectionResource(context, resources, offset, limit); // LOGGER.debug("Returning collection of {} links", collection.get("size")); // return Response.ok().entity(collection).build(); // } // // @POST // @Consumes(MediaType.APPLICATION_FORM_URLENCODED) // @Produces(MediaType.APPLICATION_JSON) // public final Response createShortLink(@Context UriInfo context, @FormParam("url") String url) { // LOGGER.debug("Shorten request for: {}", url); // final LinkResource link = new LinkResource(context, this.service.create(url)); // LOGGER.debug("Returning link: {}", link); // return created(link); // } // // @DELETE // @Path("/{hash}") // @Produces(MediaType.APPLICATION_JSON) // public final Response deleteLinkByHash(@PathParam(value = "hash") String hash) { // LOGGER.info("Request link delete for hash: {}", hash); // this.service.deleteByHash(hash); // return Response.noContent().build(); // } // // private Response created(Resource createdResource) { // final String href = (String) createdResource.get("href"); // return Response // .created(URI.create(href)) // .entity(createdResource) // .build(); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/rest/RedirectController.java // @Component // @Path("/") // public class RedirectController { // private LinkService service; // // @Autowired // public RedirectController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Path("/{hash}") // public Response redirect(@PathParam("hash") String hash) { // Response response; // // final String url = service.findUrlByHash(hash); // if (!StringUtils.isEmpty(url)) { // URI uri = URI.create(url); // response = Response // .status(Response.Status.MOVED_PERMANENTLY) // .location(uri) // .build(); // } else { // response = Response // .status(Response.Status.BAD_REQUEST) // .build(); // } // // return response; // } // } // Path: linkshortener-api/src/main/java/be/drissamri/config/JerseyConfig.java import be.drissamri.rest.LinkController; import be.drissamri.rest.RedirectController; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config; @Component @ApplicationPath("/api/v1") public class JerseyConfig extends ResourceConfig { public JerseyConfig() { packages("be.drissamri.rest");
register(LinkController.class);
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/config/JerseyConfig.java
// Path: linkshortener-api/src/main/java/be/drissamri/rest/LinkController.java // @Component // @Path(LinkController.LINKS) // public class LinkController { // private static final Logger LOGGER = LoggerFactory.getLogger(LinkController.class); // public static final String LINKS = "/links"; // private final LinkService service; // // @Autowired // public LinkController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Produces(MediaType.APPLICATION_JSON) // public final Response find( // @Context UriInfo context, // @QueryParam("expand") @DefaultValue("false") final boolean expand, // @QueryParam("offset") @DefaultValue("1") final int offset, // @QueryParam("limit") @DefaultValue("10") final int limit) throws Exception { // LOGGER.debug("Find links request. expand: {} - offset: {}, limit: {}", expand, offset, limit); // // final List<LinkEntity> foundLinks = service.find(offset, limit); // // final List<Resource> resources = foundLinks // .stream() // .map(link -> expand ? new LinkResource(context, link) : new Resource(context, link.getHash())) // .collect(Collectors.toList()); // // final CollectionResource collection = new CollectionResource(context, resources, offset, limit); // LOGGER.debug("Returning collection of {} links", collection.get("size")); // return Response.ok().entity(collection).build(); // } // // @POST // @Consumes(MediaType.APPLICATION_FORM_URLENCODED) // @Produces(MediaType.APPLICATION_JSON) // public final Response createShortLink(@Context UriInfo context, @FormParam("url") String url) { // LOGGER.debug("Shorten request for: {}", url); // final LinkResource link = new LinkResource(context, this.service.create(url)); // LOGGER.debug("Returning link: {}", link); // return created(link); // } // // @DELETE // @Path("/{hash}") // @Produces(MediaType.APPLICATION_JSON) // public final Response deleteLinkByHash(@PathParam(value = "hash") String hash) { // LOGGER.info("Request link delete for hash: {}", hash); // this.service.deleteByHash(hash); // return Response.noContent().build(); // } // // private Response created(Resource createdResource) { // final String href = (String) createdResource.get("href"); // return Response // .created(URI.create(href)) // .entity(createdResource) // .build(); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/rest/RedirectController.java // @Component // @Path("/") // public class RedirectController { // private LinkService service; // // @Autowired // public RedirectController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Path("/{hash}") // public Response redirect(@PathParam("hash") String hash) { // Response response; // // final String url = service.findUrlByHash(hash); // if (!StringUtils.isEmpty(url)) { // URI uri = URI.create(url); // response = Response // .status(Response.Status.MOVED_PERMANENTLY) // .location(uri) // .build(); // } else { // response = Response // .status(Response.Status.BAD_REQUEST) // .build(); // } // // return response; // } // }
import be.drissamri.rest.LinkController; import be.drissamri.rest.RedirectController; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component;
/* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config; @Component @ApplicationPath("/api/v1") public class JerseyConfig extends ResourceConfig { public JerseyConfig() { packages("be.drissamri.rest"); register(LinkController.class);
// Path: linkshortener-api/src/main/java/be/drissamri/rest/LinkController.java // @Component // @Path(LinkController.LINKS) // public class LinkController { // private static final Logger LOGGER = LoggerFactory.getLogger(LinkController.class); // public static final String LINKS = "/links"; // private final LinkService service; // // @Autowired // public LinkController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Produces(MediaType.APPLICATION_JSON) // public final Response find( // @Context UriInfo context, // @QueryParam("expand") @DefaultValue("false") final boolean expand, // @QueryParam("offset") @DefaultValue("1") final int offset, // @QueryParam("limit") @DefaultValue("10") final int limit) throws Exception { // LOGGER.debug("Find links request. expand: {} - offset: {}, limit: {}", expand, offset, limit); // // final List<LinkEntity> foundLinks = service.find(offset, limit); // // final List<Resource> resources = foundLinks // .stream() // .map(link -> expand ? new LinkResource(context, link) : new Resource(context, link.getHash())) // .collect(Collectors.toList()); // // final CollectionResource collection = new CollectionResource(context, resources, offset, limit); // LOGGER.debug("Returning collection of {} links", collection.get("size")); // return Response.ok().entity(collection).build(); // } // // @POST // @Consumes(MediaType.APPLICATION_FORM_URLENCODED) // @Produces(MediaType.APPLICATION_JSON) // public final Response createShortLink(@Context UriInfo context, @FormParam("url") String url) { // LOGGER.debug("Shorten request for: {}", url); // final LinkResource link = new LinkResource(context, this.service.create(url)); // LOGGER.debug("Returning link: {}", link); // return created(link); // } // // @DELETE // @Path("/{hash}") // @Produces(MediaType.APPLICATION_JSON) // public final Response deleteLinkByHash(@PathParam(value = "hash") String hash) { // LOGGER.info("Request link delete for hash: {}", hash); // this.service.deleteByHash(hash); // return Response.noContent().build(); // } // // private Response created(Resource createdResource) { // final String href = (String) createdResource.get("href"); // return Response // .created(URI.create(href)) // .entity(createdResource) // .build(); // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/rest/RedirectController.java // @Component // @Path("/") // public class RedirectController { // private LinkService service; // // @Autowired // public RedirectController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Path("/{hash}") // public Response redirect(@PathParam("hash") String hash) { // Response response; // // final String url = service.findUrlByHash(hash); // if (!StringUtils.isEmpty(url)) { // URI uri = URI.create(url); // response = Response // .status(Response.Status.MOVED_PERMANENTLY) // .location(uri) // .build(); // } else { // response = Response // .status(Response.Status.BAD_REQUEST) // .build(); // } // // return response; // } // } // Path: linkshortener-api/src/main/java/be/drissamri/config/JerseyConfig.java import be.drissamri.rest.LinkController; import be.drissamri.rest.RedirectController; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; /* * The MIT License (MIT) * * Copyright (c) 2014 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config; @Component @ApplicationPath("/api/v1") public class JerseyConfig extends ResourceConfig { public JerseyConfig() { packages("be.drissamri.rest"); register(LinkController.class);
register(RedirectController.class);
drissamri/linkshortener
linkshortener-api/src/test/java/be/drissamri/it/LinkControllerIT.java
// Path: linkshortener-web/src/main/java/be/drissamri/Application.java // @SpringBootApplication // public class Application { // private static final int TWO_SECONDS = 2000; // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // // @Bean // public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) { // return new RestTemplate(requestFactory); // } // // @Bean // public ClientHttpRequestFactory clientHttpRequestFactory() { // final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); // factory.setReadTimeout(TWO_SECONDS); // factory.setConnectTimeout(TWO_SECONDS); // return factory; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/rest/LinkController.java // @Component // @Path(LinkController.LINKS) // public class LinkController { // private static final Logger LOGGER = LoggerFactory.getLogger(LinkController.class); // public static final String LINKS = "/links"; // private final LinkService service; // // @Autowired // public LinkController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Produces(MediaType.APPLICATION_JSON) // public final Response find( // @Context UriInfo context, // @QueryParam("expand") @DefaultValue("false") final boolean expand, // @QueryParam("offset") @DefaultValue("1") final int offset, // @QueryParam("limit") @DefaultValue("10") final int limit) throws Exception { // LOGGER.debug("Find links request. expand: {} - offset: {}, limit: {}", expand, offset, limit); // // final List<LinkEntity> foundLinks = service.find(offset, limit); // // final List<Resource> resources = foundLinks // .stream() // .map(link -> expand ? new LinkResource(context, link) : new Resource(context, link.getHash())) // .collect(Collectors.toList()); // // final CollectionResource collection = new CollectionResource(context, resources, offset, limit); // LOGGER.debug("Returning collection of {} links", collection.get("size")); // return Response.ok().entity(collection).build(); // } // // @POST // @Consumes(MediaType.APPLICATION_FORM_URLENCODED) // @Produces(MediaType.APPLICATION_JSON) // public final Response createShortLink(@Context UriInfo context, @FormParam("url") String url) { // LOGGER.debug("Shorten request for: {}", url); // final LinkResource link = new LinkResource(context, this.service.create(url)); // LOGGER.debug("Returning link: {}", link); // return created(link); // } // // @DELETE // @Path("/{hash}") // @Produces(MediaType.APPLICATION_JSON) // public final Response deleteLinkByHash(@PathParam(value = "hash") String hash) { // LOGGER.info("Request link delete for hash: {}", hash); // this.service.deleteByHash(hash); // return Response.noContent().build(); // } // // private Response created(Resource createdResource) { // final String href = (String) createdResource.get("href"); // return Response // .created(URI.create(href)) // .entity(createdResource) // .build(); // } // }
import be.drissamri.Application; import be.drissamri.rest.LinkController; import com.jayway.restassured.RestAssured; import com.jayway.restassured.path.json.JsonPath; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static com.jayway.restassured.RestAssured.basic; import static com.jayway.restassured.RestAssured.given; import static javax.ws.rs.core.Response.Status.*; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.empty;
package be.drissamri.it; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest("server.port:0") public class LinkControllerIT { private static final String LONG_URL = "http://www.drissamri.be"; private static final String PARAMETER_HASH = "hash"; private static final String PARAMETER_URL = "url"; public static final String API_V1 = "/api/v1"; @Value("${local.server.port}") private int port; @Before public void setUp() { RestAssured.authentication = basic("admin", "secret"); RestAssured.port = port; } @Test public void shouldReturnOKWhenRetrievingAllLinks() { // @formatter:off createLink(LONG_URL); given() .contentType(MediaType.APPLICATION_JSON_VALUE)
// Path: linkshortener-web/src/main/java/be/drissamri/Application.java // @SpringBootApplication // public class Application { // private static final int TWO_SECONDS = 2000; // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // // @Bean // public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) { // return new RestTemplate(requestFactory); // } // // @Bean // public ClientHttpRequestFactory clientHttpRequestFactory() { // final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); // factory.setReadTimeout(TWO_SECONDS); // factory.setConnectTimeout(TWO_SECONDS); // return factory; // } // } // // Path: linkshortener-api/src/main/java/be/drissamri/rest/LinkController.java // @Component // @Path(LinkController.LINKS) // public class LinkController { // private static final Logger LOGGER = LoggerFactory.getLogger(LinkController.class); // public static final String LINKS = "/links"; // private final LinkService service; // // @Autowired // public LinkController(LinkService srvc) { // this.service = srvc; // } // // @GET // @Produces(MediaType.APPLICATION_JSON) // public final Response find( // @Context UriInfo context, // @QueryParam("expand") @DefaultValue("false") final boolean expand, // @QueryParam("offset") @DefaultValue("1") final int offset, // @QueryParam("limit") @DefaultValue("10") final int limit) throws Exception { // LOGGER.debug("Find links request. expand: {} - offset: {}, limit: {}", expand, offset, limit); // // final List<LinkEntity> foundLinks = service.find(offset, limit); // // final List<Resource> resources = foundLinks // .stream() // .map(link -> expand ? new LinkResource(context, link) : new Resource(context, link.getHash())) // .collect(Collectors.toList()); // // final CollectionResource collection = new CollectionResource(context, resources, offset, limit); // LOGGER.debug("Returning collection of {} links", collection.get("size")); // return Response.ok().entity(collection).build(); // } // // @POST // @Consumes(MediaType.APPLICATION_FORM_URLENCODED) // @Produces(MediaType.APPLICATION_JSON) // public final Response createShortLink(@Context UriInfo context, @FormParam("url") String url) { // LOGGER.debug("Shorten request for: {}", url); // final LinkResource link = new LinkResource(context, this.service.create(url)); // LOGGER.debug("Returning link: {}", link); // return created(link); // } // // @DELETE // @Path("/{hash}") // @Produces(MediaType.APPLICATION_JSON) // public final Response deleteLinkByHash(@PathParam(value = "hash") String hash) { // LOGGER.info("Request link delete for hash: {}", hash); // this.service.deleteByHash(hash); // return Response.noContent().build(); // } // // private Response created(Resource createdResource) { // final String href = (String) createdResource.get("href"); // return Response // .created(URI.create(href)) // .entity(createdResource) // .build(); // } // } // Path: linkshortener-api/src/test/java/be/drissamri/it/LinkControllerIT.java import be.drissamri.Application; import be.drissamri.rest.LinkController; import com.jayway.restassured.RestAssured; import com.jayway.restassured.path.json.JsonPath; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static com.jayway.restassured.RestAssured.basic; import static com.jayway.restassured.RestAssured.given; import static javax.ws.rs.core.Response.Status.*; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.empty; package be.drissamri.it; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest("server.port:0") public class LinkControllerIT { private static final String LONG_URL = "http://www.drissamri.be"; private static final String PARAMETER_HASH = "hash"; private static final String PARAMETER_URL = "url"; public static final String API_V1 = "/api/v1"; @Value("${local.server.port}") private int port; @Before public void setUp() { RestAssured.authentication = basic("admin", "secret"); RestAssured.port = port; } @Test public void shouldReturnOKWhenRetrievingAllLinks() { // @formatter:off createLink(LONG_URL); given() .contentType(MediaType.APPLICATION_JSON_VALUE)
.get(API_V1 + LinkController.LINKS)
drissamri/linkshortener
linkshortener-web/src/main/java/be/drissamri/service/LinkServiceImpl.java
// Path: linkshortener-web/src/main/java/be/drissamri/model/Link.java // public class Link { // private String url; // private String hash; // private String shortUrl; // // public Link(String shortUrl, String url, String hash) { // this.shortUrl = shortUrl; // this.url = url; // this.hash = hash; // } // // public Link() { // // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getShortUrl() { // return shortUrl; // } // // public void setShortUrl(String shortUrl) { // this.shortUrl = shortUrl; // } // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // @Override // public int hashCode() { // return Objects.hashCode(url); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final Link other = (Link) obj; // return Objects.equals(this.url, other.url) && Objects.equals(this.shortUrl, other.shortUrl); // } // }
import be.drissamri.model.Link; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate;
package be.drissamri.service; @Service public class LinkServiceImpl implements LinkService { private static final Logger LOGGER = LoggerFactory.getLogger(LinkServiceImpl.class); private static final String URL_PARAMETER = "url"; private String endpoint; private RestTemplate client; @Autowired public LinkServiceImpl(RestTemplate clnt, @Value("${linkshortener.api.base.url}") String apiUrl) { this.client = clnt; this.endpoint = apiUrl; LOGGER.debug("Linkshortener API URL: {}", apiUrl); } @Override
// Path: linkshortener-web/src/main/java/be/drissamri/model/Link.java // public class Link { // private String url; // private String hash; // private String shortUrl; // // public Link(String shortUrl, String url, String hash) { // this.shortUrl = shortUrl; // this.url = url; // this.hash = hash; // } // // public Link() { // // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getShortUrl() { // return shortUrl; // } // // public void setShortUrl(String shortUrl) { // this.shortUrl = shortUrl; // } // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // @Override // public int hashCode() { // return Objects.hashCode(url); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final Link other = (Link) obj; // return Objects.equals(this.url, other.url) && Objects.equals(this.shortUrl, other.shortUrl); // } // } // Path: linkshortener-web/src/main/java/be/drissamri/service/LinkServiceImpl.java import be.drissamri.model.Link; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; package be.drissamri.service; @Service public class LinkServiceImpl implements LinkService { private static final Logger LOGGER = LoggerFactory.getLogger(LinkServiceImpl.class); private static final String URL_PARAMETER = "url"; private String endpoint; private RestTemplate client; @Autowired public LinkServiceImpl(RestTemplate clnt, @Value("${linkshortener.api.base.url}") String apiUrl) { this.client = clnt; this.endpoint = apiUrl; LOGGER.debug("Linkshortener API URL: {}", apiUrl); } @Override
public Link createLink(String url) {
drissamri/linkshortener
linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApplicationSettings.java // @Component // public class ApplicationSettings { // private final String name; // private final String version; // // @Autowired // public ApplicationSettings( // @Value("${info.build.name}") String name, // @Value("${info.build.version}") String vrsn) { // this.name = name; // this.version = vrsn; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // }
import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import be.drissamri.config.safebrowsing.ApplicationSettings; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Conditional;
/** * The MIT License (MIT) * * Copyright (c) 2015 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so,| subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config.safebrowsing.google; /** * Validate URL with the PhishTank API. * @author Driss Amri (drissamri@gmail.com) * @version $Id$ */ @Component @Conditional(GoogleCondition.class) public class GoogleSafeBrowsingConfig { private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); private static final String PARAMETER_API_KEY = "apiKey"; private static final String PARAMETER_API_VERSION = "apiVersion"; private static final String PARAMETER_APP_VERSION = "appVersion"; private static final String PARAMETER_APP_NAME = "client"; private final Map<String, String> parameters; private final String apiUrl; @Autowired
// Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/ApplicationSettings.java // @Component // public class ApplicationSettings { // private final String name; // private final String version; // // @Autowired // public ApplicationSettings( // @Value("${info.build.name}") String name, // @Value("${info.build.version}") String vrsn) { // this.name = name; // this.version = vrsn; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // } // Path: linkshortener-api/src/main/java/be/drissamri/config/safebrowsing/google/GoogleSafeBrowsingConfig.java import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import be.drissamri.config.safebrowsing.ApplicationSettings; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Conditional; /** * The MIT License (MIT) * * Copyright (c) 2015 Driss Amri * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so,| subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package be.drissamri.config.safebrowsing.google; /** * Validate URL with the PhishTank API. * @author Driss Amri (drissamri@gmail.com) * @version $Id$ */ @Component @Conditional(GoogleCondition.class) public class GoogleSafeBrowsingConfig { private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSafeBrowsingConfig.class); private static final String PARAMETER_API_KEY = "apiKey"; private static final String PARAMETER_API_VERSION = "apiVersion"; private static final String PARAMETER_APP_VERSION = "appVersion"; private static final String PARAMETER_APP_NAME = "client"; private final Map<String, String> parameters; private final String apiUrl; @Autowired
public GoogleSafeBrowsingConfig(GoogleApiSettings server, ApplicationSettings app) {
Yarikx/reductor
example/src/main/java/com/yheriatovych/reductor/example/reductor/filter/FilterActions.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: example/src/main/java/com/yheriatovych/reductor/example/model/NotesFilter.java // public enum NotesFilter { // ALL, // CHECKED, // UNCHECKED // }
import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.example.model.NotesFilter;
package com.yheriatovych.reductor.example.reductor.filter; @ActionCreator public interface FilterActions { String SET_FILTER = "SET_FILTER";
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: example/src/main/java/com/yheriatovych/reductor/example/model/NotesFilter.java // public enum NotesFilter { // ALL, // CHECKED, // UNCHECKED // } // Path: example/src/main/java/com/yheriatovych/reductor/example/reductor/filter/FilterActions.java import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.example.model.NotesFilter; package com.yheriatovych.reductor.example.reductor.filter; @ActionCreator public interface FilterActions { String SET_FILTER = "SET_FILTER";
@ActionCreator.Action(SET_FILTER)
Yarikx/reductor
example/src/main/java/com/yheriatovych/reductor/example/reductor/filter/FilterActions.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: example/src/main/java/com/yheriatovych/reductor/example/model/NotesFilter.java // public enum NotesFilter { // ALL, // CHECKED, // UNCHECKED // }
import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.example.model.NotesFilter;
package com.yheriatovych.reductor.example.reductor.filter; @ActionCreator public interface FilterActions { String SET_FILTER = "SET_FILTER"; @ActionCreator.Action(SET_FILTER)
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: example/src/main/java/com/yheriatovych/reductor/example/model/NotesFilter.java // public enum NotesFilter { // ALL, // CHECKED, // UNCHECKED // } // Path: example/src/main/java/com/yheriatovych/reductor/example/reductor/filter/FilterActions.java import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.example.model.NotesFilter; package com.yheriatovych.reductor.example.reductor.filter; @ActionCreator public interface FilterActions { String SET_FILTER = "SET_FILTER"; @ActionCreator.Action(SET_FILTER)
Action setFilter(NotesFilter filter);
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorProcessingStep.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Utils.java // public static String createGeneratedFileComment() { // return String.format("Generated by %s (https://github.com/Yarikx/reductor)", ReductorAnnotationProcessor.class.getCanonicalName()); // }
import com.google.auto.common.BasicAnnotationProcessor; import com.google.common.collect.SetMultimap; import com.squareup.javapoet.*; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.*; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.Map; import java.util.Set; import static com.yheriatovych.reductor.processor.Utils.createGeneratedFileComment;
package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorProcessingStep implements BasicAnnotationProcessor.ProcessingStep { private final Env env; private final Map<String, ActionCreatorElement> knownActionCreators; public ActionCreatorProcessingStep(Env env, Map<String, ActionCreatorElement> knownActionCreators) { this.env = env; this.knownActionCreators = knownActionCreators; } @Override public Set<Element> process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { for (Element element : elementsByAnnotation.values()) { try { ActionCreatorElement creatorElement = ActionCreatorElement.parse(element, env); knownActionCreators.put(env.getElements().getBinaryName((TypeElement) element).toString(), creatorElement); emitActionCreator(creatorElement, env);
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Utils.java // public static String createGeneratedFileComment() { // return String.format("Generated by %s (https://github.com/Yarikx/reductor)", ReductorAnnotationProcessor.class.getCanonicalName()); // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorProcessingStep.java import com.google.auto.common.BasicAnnotationProcessor; import com.google.common.collect.SetMultimap; import com.squareup.javapoet.*; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.*; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.Map; import java.util.Set; import static com.yheriatovych.reductor.processor.Utils.createGeneratedFileComment; package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorProcessingStep implements BasicAnnotationProcessor.ProcessingStep { private final Env env; private final Map<String, ActionCreatorElement> knownActionCreators; public ActionCreatorProcessingStep(Env env, Map<String, ActionCreatorElement> knownActionCreators) { this.env = env; this.knownActionCreators = knownActionCreators; } @Override public Set<Element> process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { for (Element element : elementsByAnnotation.values()) { try { ActionCreatorElement creatorElement = ActionCreatorElement.parse(element, env); knownActionCreators.put(env.getElements().getBinaryName((TypeElement) element).toString(), creatorElement); emitActionCreator(creatorElement, env);
} catch (ValidationException ve) {
Yarikx/reductor
compiller/src/test/java/com/yheriatovych/reductor/processor/AutoReducerGeneratorTest.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // }
import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
"import com.yheriatovych.reductor.Reducer;\n" + "import com.yheriatovych.reductor.annotations.AutoReducer;\n" + "\n" + "@AutoReducer\n" + "public abstract class FoobarReducer implements Reducer<String>{\n" + " @AutoReducer.Action(\"ACTION_1\")\n" + " String uppercase(String state) {\n" + " return state.toUpperCase();\n" + " }\n" + "}"); JavaFileObject generatedPojo = JavaFileObjects.forSourceString("test.FoobarReducerImpl", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Action;\n" + "\n" + "class FoobarReducerImpl extends FoobarReducer {\n" + " @Override\n" + " public String reduce(String state, Action action) {\n" + " switch (action.type) {\n" + " case \"ACTION_1\":\n" + " return uppercase(state);\n" + " default:\n" + " return state;\n" + " }\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // } // Path: compiller/src/test/java/com/yheriatovych/reductor/processor/AutoReducerGeneratorTest.java import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; "import com.yheriatovych.reductor.Reducer;\n" + "import com.yheriatovych.reductor.annotations.AutoReducer;\n" + "\n" + "@AutoReducer\n" + "public abstract class FoobarReducer implements Reducer<String>{\n" + " @AutoReducer.Action(\"ACTION_1\")\n" + " String uppercase(String state) {\n" + " return state.toUpperCase();\n" + " }\n" + "}"); JavaFileObject generatedPojo = JavaFileObjects.forSourceString("test.FoobarReducerImpl", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Action;\n" + "\n" + "class FoobarReducerImpl extends FoobarReducer {\n" + " @Override\n" + " public String reduce(String state, Action action) {\n" + " switch (action.type) {\n" + " case \"ACTION_1\":\n" + " return uppercase(state);\n" + " default:\n" + " return state;\n" + " }\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
.processedWith(new ReductorAnnotationProcessor())
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateElement.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import java.util.ArrayList; import java.util.List; import java.util.Map;
package com.yheriatovych.reductor.processor.combinedstate; public class CombinedStateElement { public final TypeElement stateTypeElement; public final List<StateProperty> properties; public CombinedStateElement(TypeElement stateTypeElement, List<StateProperty> getters) { this.stateTypeElement = stateTypeElement; properties = getters; }
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateElement.java import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import java.util.ArrayList; import java.util.List; import java.util.Map; package com.yheriatovych.reductor.processor.combinedstate; public class CombinedStateElement { public final TypeElement stateTypeElement; public final List<StateProperty> properties; public CombinedStateElement(TypeElement stateTypeElement, List<StateProperty> getters) { this.stateTypeElement = stateTypeElement; properties = getters; }
public static CombinedStateElement parseCombinedElement(TypeElement typeElement, Env env) throws ValidationException {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateElement.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import java.util.ArrayList; import java.util.List; import java.util.Map;
package com.yheriatovych.reductor.processor.combinedstate; public class CombinedStateElement { public final TypeElement stateTypeElement; public final List<StateProperty> properties; public CombinedStateElement(TypeElement stateTypeElement, List<StateProperty> getters) { this.stateTypeElement = stateTypeElement; properties = getters; }
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateElement.java import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import java.util.ArrayList; import java.util.List; import java.util.Map; package com.yheriatovych.reductor.processor.combinedstate; public class CombinedStateElement { public final TypeElement stateTypeElement; public final List<StateProperty> properties; public CombinedStateElement(TypeElement stateTypeElement, List<StateProperty> getters) { this.stateTypeElement = stateTypeElement; properties = getters; }
public static CombinedStateElement parseCombinedElement(TypeElement typeElement, Env env) throws ValidationException {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateElement.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import java.util.ArrayList; import java.util.List; import java.util.Map;
return null; } else { throw new ValidationException(typeElement, "Only interfaces and @AutoValue classes are supported as @%s", CombinedState.class.getSimpleName()); } } List<StateProperty> properties = new ArrayList<>(); for (Element element : typeElement.getEnclosedElements()) { StateProperty stateProperty = StateProperty.parseStateProperty(element); if (stateProperty != null) { properties.add(stateProperty); } } return new CombinedStateElement(typeElement, properties); } private static boolean hasAutoValueAnnotation(TypeElement typeElement, Env env) { Name autoValueName = env.getElements().getName("com.google.auto.value.AutoValue"); for (AnnotationMirror annotationMirror : typeElement.getAnnotationMirrors()) { DeclaredType annotationType = annotationMirror.getAnnotationType(); Name qualifiedName = MoreElements.asType(annotationType.asElement()).getQualifiedName(); if (qualifiedName.equals(autoValueName)) { return true; } } return false; } public TypeName getCombinedReducerActionType() {
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateElement.java import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import java.util.ArrayList; import java.util.List; import java.util.Map; return null; } else { throw new ValidationException(typeElement, "Only interfaces and @AutoValue classes are supported as @%s", CombinedState.class.getSimpleName()); } } List<StateProperty> properties = new ArrayList<>(); for (Element element : typeElement.getEnclosedElements()) { StateProperty stateProperty = StateProperty.parseStateProperty(element); if (stateProperty != null) { properties.add(stateProperty); } } return new CombinedStateElement(typeElement, properties); } private static boolean hasAutoValueAnnotation(TypeElement typeElement, Env env) { Name autoValueName = env.getElements().getName("com.google.auto.value.AutoValue"); for (AnnotationMirror annotationMirror : typeElement.getAnnotationMirrors()) { DeclaredType annotationType = annotationMirror.getAnnotationType(); Name qualifiedName = MoreElements.asType(annotationType.asElement()).getQualifiedName(); if (qualifiedName.equals(autoValueName)) { return true; } } return false; } public TypeName getCombinedReducerActionType() {
return TypeName.get(Action.class);
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorElement.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorElement { public final List<ActionCreatorAction> actions; private final TypeElement typeElement; private Map<String, ActionCreatorAction> actionMap; private ActionCreatorElement(List<ActionCreatorAction> actions, TypeElement typeElement) { this.actions = actions; this.typeElement = typeElement; actionMap = new HashMap<>(); for (ActionCreatorAction action : actions) { actionMap.put(action.actionType, action); } } public boolean hasAction(String actionType, List<? extends VariableElement> reducerArgs) { ActionCreatorAction actionCreator = actionMap.get(actionType); if (actionCreator == null || reducerArgs.size() != actionCreator.arguments.size()) return false; List<? extends VariableElement> arguments = actionCreator.arguments; for (int i = 0; i < arguments.size(); i++) { //we are doing black magic with checking if TypeName are equals //instead of checking if two TypeMirrors are equals because TypeMirrors can be different for the same type //happens when code is processed with several number of processing steps TypeName creatorArgType = actionCreator.argumentTypes.get(i); TypeName reducerArgType = TypeName.get(reducerArgs.get(i).asType()); if (!creatorArgType.equals(reducerArgType)) { return false; } } return true; }
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorElement.java import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorElement { public final List<ActionCreatorAction> actions; private final TypeElement typeElement; private Map<String, ActionCreatorAction> actionMap; private ActionCreatorElement(List<ActionCreatorAction> actions, TypeElement typeElement) { this.actions = actions; this.typeElement = typeElement; actionMap = new HashMap<>(); for (ActionCreatorAction action : actions) { actionMap.put(action.actionType, action); } } public boolean hasAction(String actionType, List<? extends VariableElement> reducerArgs) { ActionCreatorAction actionCreator = actionMap.get(actionType); if (actionCreator == null || reducerArgs.size() != actionCreator.arguments.size()) return false; List<? extends VariableElement> arguments = actionCreator.arguments; for (int i = 0; i < arguments.size(); i++) { //we are doing black magic with checking if TypeName are equals //instead of checking if two TypeMirrors are equals because TypeMirrors can be different for the same type //happens when code is processed with several number of processing steps TypeName creatorArgType = actionCreator.argumentTypes.get(i); TypeName reducerArgType = TypeName.get(reducerArgs.get(i).asType()); if (!creatorArgType.equals(reducerArgType)) { return false; } } return true; }
public String getPackageName(Env env) {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorElement.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
public boolean hasAction(String actionType, List<? extends VariableElement> reducerArgs) { ActionCreatorAction actionCreator = actionMap.get(actionType); if (actionCreator == null || reducerArgs.size() != actionCreator.arguments.size()) return false; List<? extends VariableElement> arguments = actionCreator.arguments; for (int i = 0; i < arguments.size(); i++) { //we are doing black magic with checking if TypeName are equals //instead of checking if two TypeMirrors are equals because TypeMirrors can be different for the same type //happens when code is processed with several number of processing steps TypeName creatorArgType = actionCreator.argumentTypes.get(i); TypeName reducerArgType = TypeName.get(reducerArgs.get(i).asType()); if (!creatorArgType.equals(reducerArgType)) { return false; } } return true; } public String getPackageName(Env env) { return env.getPackageName(typeElement); } public String getName(Env env) { return env.getElements().getBinaryName(typeElement).toString(); } public TypeMirror getType() { return typeElement.asType(); }
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorElement.java import com.google.auto.common.MoreElements; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public boolean hasAction(String actionType, List<? extends VariableElement> reducerArgs) { ActionCreatorAction actionCreator = actionMap.get(actionType); if (actionCreator == null || reducerArgs.size() != actionCreator.arguments.size()) return false; List<? extends VariableElement> arguments = actionCreator.arguments; for (int i = 0; i < arguments.size(); i++) { //we are doing black magic with checking if TypeName are equals //instead of checking if two TypeMirrors are equals because TypeMirrors can be different for the same type //happens when code is processed with several number of processing steps TypeName creatorArgType = actionCreator.argumentTypes.get(i); TypeName reducerArgType = TypeName.get(reducerArgs.get(i).asType()); if (!creatorArgType.equals(reducerArgType)) { return false; } } return true; } public String getPackageName(Env env) { return env.getPackageName(typeElement); } public String getName(Env env) { return env.getElements().getBinaryName(typeElement).toString(); } public TypeMirror getType() { return typeElement.asType(); }
public static ActionCreatorElement parse(Element element, Env env) throws ValidationException {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/StateProperty.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Reducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror;
package com.yheriatovych.reductor.processor.combinedstate; public class StateProperty { public final String name; public final TypeMirror stateType; public final ExecutableElement executableElement; private StateProperty(String name, TypeMirror stateType, ExecutableElement executableElement) { this.name = name; this.stateType = stateType; this.executableElement = executableElement; }
// Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/StateProperty.java import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Reducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; package com.yheriatovych.reductor.processor.combinedstate; public class StateProperty { public final String name; public final TypeMirror stateType; public final ExecutableElement executableElement; private StateProperty(String name, TypeMirror stateType, ExecutableElement executableElement) { this.name = name; this.stateType = stateType; this.executableElement = executableElement; }
public TypeMirror boxedStateType(Env env) {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/StateProperty.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Reducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror;
package com.yheriatovych.reductor.processor.combinedstate; public class StateProperty { public final String name; public final TypeMirror stateType; public final ExecutableElement executableElement; private StateProperty(String name, TypeMirror stateType, ExecutableElement executableElement) { this.name = name; this.stateType = stateType; this.executableElement = executableElement; } public TypeMirror boxedStateType(Env env) { if(stateType.getKind().isPrimitive()) { return env.getTypes().boxedClass(MoreTypes.asPrimitiveType(stateType)).asType(); } return stateType; }
// Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/StateProperty.java import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Reducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; package com.yheriatovych.reductor.processor.combinedstate; public class StateProperty { public final String name; public final TypeMirror stateType; public final ExecutableElement executableElement; private StateProperty(String name, TypeMirror stateType, ExecutableElement executableElement) { this.name = name; this.stateType = stateType; this.executableElement = executableElement; } public TypeMirror boxedStateType(Env env) { if(stateType.getKind().isPrimitive()) { return env.getTypes().boxedClass(MoreTypes.asPrimitiveType(stateType)).asType(); } return stateType; }
static StateProperty parseStateProperty(Element element) throws ValidationException {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/StateProperty.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Reducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror;
StateProperty stateProperty; if (element.getKind() != ElementKind.METHOD) return null; //We don't care about static methods, just ignore if (element.getModifiers().contains(Modifier.STATIC)) return null; //We also don't care about default methods. //If default method is there, it probably not meant to be override if (element.getModifiers().contains(Modifier.DEFAULT)) return null; ExecutableElement executableElement = (ExecutableElement) element; String propertyName = executableElement.getSimpleName().toString(); TypeMirror stateType = executableElement.getReturnType(); if (!executableElement.getParameters().isEmpty()) throw new ValidationException(executableElement, "state property accessor %s should not have any parameters", executableElement); if (stateType.getKind() == TypeKind.VOID) { throw new ValidationException(executableElement, "void is not allowed as return type for property method %s", executableElement); } stateProperty = new StateProperty(propertyName, stateType, executableElement); return stateProperty; } public TypeName getReducerInterfaceTypeName() { TypeName stateType = TypeName.get(this.stateType); if (stateType.isPrimitive()) { stateType = stateType.box(); }
// Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/StateProperty.java import com.google.auto.common.MoreTypes; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Reducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; StateProperty stateProperty; if (element.getKind() != ElementKind.METHOD) return null; //We don't care about static methods, just ignore if (element.getModifiers().contains(Modifier.STATIC)) return null; //We also don't care about default methods. //If default method is there, it probably not meant to be override if (element.getModifiers().contains(Modifier.DEFAULT)) return null; ExecutableElement executableElement = (ExecutableElement) element; String propertyName = executableElement.getSimpleName().toString(); TypeMirror stateType = executableElement.getReturnType(); if (!executableElement.getParameters().isEmpty()) throw new ValidationException(executableElement, "state property accessor %s should not have any parameters", executableElement); if (stateType.getKind() == TypeKind.VOID) { throw new ValidationException(executableElement, "void is not allowed as return type for property method %s", executableElement); } stateProperty = new StateProperty(propertyName, stateType, executableElement); return stateProperty; } public TypeName getReducerInterfaceTypeName() { TypeName stateType = TypeName.get(this.stateType); if (stateType.isPrimitive()) { stateType = stateType.box(); }
return ParameterizedTypeName.get(ClassName.get(Reducer.class), stateType);
Yarikx/reductor
example/src/main/java/com/yheriatovych/reductor/example/reductor/notelist/NotesActions.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // }
import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator;
package com.yheriatovych.reductor.example.reductor.notelist; @ActionCreator public interface NotesActions { String ADD_ACTION = "ADD_ITEM"; String TOGGLE = "TOGGLE"; String REMOVE_ITEM = "REMOVE_ITEM";
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // Path: example/src/main/java/com/yheriatovych/reductor/example/reductor/notelist/NotesActions.java import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; package com.yheriatovych.reductor.example.reductor.notelist; @ActionCreator public interface NotesActions { String ADD_ACTION = "ADD_ITEM"; String TOGGLE = "TOGGLE"; String REMOVE_ITEM = "REMOVE_ITEM";
@ActionCreator.Action(NotesActions.ADD_ACTION)
Yarikx/reductor
compiller/src/test/java/com/yheriatovych/reductor/processor/CombinedStateImplTest.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // }
import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
" String bar();\n" + "}"); JavaFileObject generatedPojo = JavaFileObjects.forSourceString("test.FoobarImpl", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "\n" + "public final class FoobarImpl implements Foobar {\n" + " private final int foo;\n" + "\n" + " private final String bar;\n" + "\n" + " public FoobarImpl(int foo, String bar) {\n" + " this.foo = foo;\n" + " this.bar = bar;\n" + " }\n" + "\n" + " @Override\n" + " public int foo() {\n" + " return foo;\n" + " }\n" + "\n" + " @Override\n" + " public String bar() {\n" + " return bar;\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // } // Path: compiller/src/test/java/com/yheriatovych/reductor/processor/CombinedStateImplTest.java import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; " String bar();\n" + "}"); JavaFileObject generatedPojo = JavaFileObjects.forSourceString("test.FoobarImpl", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "\n" + "public final class FoobarImpl implements Foobar {\n" + " private final int foo;\n" + "\n" + " private final String bar;\n" + "\n" + " public FoobarImpl(int foo, String bar) {\n" + " this.foo = foo;\n" + " this.bar = bar;\n" + " }\n" + "\n" + " @Override\n" + " public int foo() {\n" + " return foo;\n" + " }\n" + "\n" + " @Override\n" + " public String bar() {\n" + " return bar;\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
.processedWith(new ReductorAnnotationProcessor())
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateAutoValueExtension.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.service.AutoService; import com.google.auto.value.extension.AutoValueExtension; import com.squareup.javapoet.ClassName; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement;
package com.yheriatovych.reductor.processor.combinedstate; @AutoService(AutoValueExtension.class) public class CombinedStateAutoValueExtension extends AutoValueExtension { @Override public String generateClass(Context context, String className, String classToExtend, boolean isFinal) { //So yeah, we are generating code in `applicable` method, not here //The reason for it: If we declare that some class is applicable for this extension, we need to contribute to //value class hierarchy. But we don't need it actually. //The only thing we need to do is to generate another class (Reducer) return null; } @Override public boolean applicable(Context context) { TypeElement typeElement = context.autoValueClass(); boolean isApplicable = typeElement.getAnnotation(CombinedState.class) != null; if (isApplicable) { ProcessingEnvironment processingEnvironment = context.processingEnvironment();
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateAutoValueExtension.java import com.google.auto.service.AutoService; import com.google.auto.value.extension.AutoValueExtension; import com.squareup.javapoet.ClassName; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; package com.yheriatovych.reductor.processor.combinedstate; @AutoService(AutoValueExtension.class) public class CombinedStateAutoValueExtension extends AutoValueExtension { @Override public String generateClass(Context context, String className, String classToExtend, boolean isFinal) { //So yeah, we are generating code in `applicable` method, not here //The reason for it: If we declare that some class is applicable for this extension, we need to contribute to //value class hierarchy. But we don't need it actually. //The only thing we need to do is to generate another class (Reducer) return null; } @Override public boolean applicable(Context context) { TypeElement typeElement = context.autoValueClass(); boolean isApplicable = typeElement.getAnnotation(CombinedState.class) != null; if (isApplicable) { ProcessingEnvironment processingEnvironment = context.processingEnvironment();
Env env = new Env(processingEnvironment.getTypeUtils(), processingEnvironment.getElementUtils(), processingEnvironment.getMessager(), processingEnvironment.getFiler());
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateAutoValueExtension.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.google.auto.service.AutoService; import com.google.auto.value.extension.AutoValueExtension; import com.squareup.javapoet.ClassName; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement;
package com.yheriatovych.reductor.processor.combinedstate; @AutoService(AutoValueExtension.class) public class CombinedStateAutoValueExtension extends AutoValueExtension { @Override public String generateClass(Context context, String className, String classToExtend, boolean isFinal) { //So yeah, we are generating code in `applicable` method, not here //The reason for it: If we declare that some class is applicable for this extension, we need to contribute to //value class hierarchy. But we don't need it actually. //The only thing we need to do is to generate another class (Reducer) return null; } @Override public boolean applicable(Context context) { TypeElement typeElement = context.autoValueClass(); boolean isApplicable = typeElement.getAnnotation(CombinedState.class) != null; if (isApplicable) { ProcessingEnvironment processingEnvironment = context.processingEnvironment(); Env env = new Env(processingEnvironment.getTypeUtils(), processingEnvironment.getElementUtils(), processingEnvironment.getMessager(), processingEnvironment.getFiler()); try { CombinedStateElement combinedStateElement = CombinedStateElement.parseAutoValueCombinedElement(typeElement, context.properties()); CombinedStateProcessingStep.emmitCombinedReducer(env, combinedStateElement, ClassName.get(context.packageName(), "AutoValue_" + context.autoValueClass().getSimpleName()));
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/combinedstate/CombinedStateAutoValueExtension.java import com.google.auto.service.AutoService; import com.google.auto.value.extension.AutoValueExtension; import com.squareup.javapoet.ClassName; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; package com.yheriatovych.reductor.processor.combinedstate; @AutoService(AutoValueExtension.class) public class CombinedStateAutoValueExtension extends AutoValueExtension { @Override public String generateClass(Context context, String className, String classToExtend, boolean isFinal) { //So yeah, we are generating code in `applicable` method, not here //The reason for it: If we declare that some class is applicable for this extension, we need to contribute to //value class hierarchy. But we don't need it actually. //The only thing we need to do is to generate another class (Reducer) return null; } @Override public boolean applicable(Context context) { TypeElement typeElement = context.autoValueClass(); boolean isApplicable = typeElement.getAnnotation(CombinedState.class) != null; if (isApplicable) { ProcessingEnvironment processingEnvironment = context.processingEnvironment(); Env env = new Env(processingEnvironment.getTypeUtils(), processingEnvironment.getElementUtils(), processingEnvironment.getMessager(), processingEnvironment.getFiler()); try { CombinedStateElement combinedStateElement = CombinedStateElement.parseAutoValueCombinedElement(typeElement, context.properties()); CombinedStateProcessingStep.emmitCombinedReducer(env, combinedStateElement, ClassName.get(context.packageName(), "AutoValue_" + context.autoValueClass().getSimpleName()));
} catch (ValidationException ve) {
Yarikx/reductor
compiller/src/test/java/com/yheriatovych/reductor/processor/ActionCreatorValidateReducerTest.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // }
import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
package com.yheriatovych.reductor.processor; public class ActionCreatorValidateReducerTest { @Test public void testSimpleReducerValidation() { JavaFileObject source = JavaFileObjects.forSourceString("test.Foobar", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Action;\n" + "import com.yheriatovych.reductor.Reducer;\n" + "import com.yheriatovych.reductor.annotations.ActionCreator;\n" + "import com.yheriatovych.reductor.annotations.AutoReducer;\n" + "\n" + "public class Foobar {\n" + " @ActionCreator\n" + " public interface TestCreator {\n" + " @ActionCreator.Action(\"TEST\")\n" + " Action testAction(int foo, String bar, Object baz);\n" + " }\n" + " \n" + " @AutoReducer\n" + " public static abstract class TestReducer implements Reducer<String> {\n" + " @AutoReducer.Action(value = \"TEST\", from = TestCreator.class)\n" + " String handleTest(String state, int foo, String bar, Object baz) {\n" + " return state;\n" + " }\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // } // Path: compiller/src/test/java/com/yheriatovych/reductor/processor/ActionCreatorValidateReducerTest.java import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; package com.yheriatovych.reductor.processor; public class ActionCreatorValidateReducerTest { @Test public void testSimpleReducerValidation() { JavaFileObject source = JavaFileObjects.forSourceString("test.Foobar", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Action;\n" + "import com.yheriatovych.reductor.Reducer;\n" + "import com.yheriatovych.reductor.annotations.ActionCreator;\n" + "import com.yheriatovych.reductor.annotations.AutoReducer;\n" + "\n" + "public class Foobar {\n" + " @ActionCreator\n" + " public interface TestCreator {\n" + " @ActionCreator.Action(\"TEST\")\n" + " Action testAction(int foo, String bar, Object baz);\n" + " }\n" + " \n" + " @AutoReducer\n" + " public static abstract class TestReducer implements Reducer<String> {\n" + " @AutoReducer.Action(value = \"TEST\", from = TestCreator.class)\n" + " String handleTest(String state, int foo, String bar, Object baz) {\n" + " return state;\n" + " }\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
.processedWith(new ReductorAnnotationProcessor())
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/autoreducer/ReduceAction.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorElement.java // public class ActionCreatorElement { // public final List<ActionCreatorAction> actions; // private final TypeElement typeElement; // private Map<String, ActionCreatorAction> actionMap; // // private ActionCreatorElement(List<ActionCreatorAction> actions, TypeElement typeElement) { // this.actions = actions; // this.typeElement = typeElement; // actionMap = new HashMap<>(); // for (ActionCreatorAction action : actions) { // actionMap.put(action.actionType, action); // } // } // // public boolean hasAction(String actionType, List<? extends VariableElement> reducerArgs) { // ActionCreatorAction actionCreator = actionMap.get(actionType); // if (actionCreator == null || reducerArgs.size() != actionCreator.arguments.size()) return false; // List<? extends VariableElement> arguments = actionCreator.arguments; // for (int i = 0; i < arguments.size(); i++) { // //we are doing black magic with checking if TypeName are equals // //instead of checking if two TypeMirrors are equals because TypeMirrors can be different for the same type // //happens when code is processed with several number of processing steps // TypeName creatorArgType = actionCreator.argumentTypes.get(i); // TypeName reducerArgType = TypeName.get(reducerArgs.get(i).asType()); // if (!creatorArgType.equals(reducerArgType)) { // return false; // } // } // return true; // } // // public String getPackageName(Env env) { // return env.getPackageName(typeElement); // } // // public String getName(Env env) { // return env.getElements().getBinaryName(typeElement).toString(); // } // // public TypeMirror getType() { // return typeElement.asType(); // } // // public static ActionCreatorElement parse(Element element, Env env) throws ValidationException { // if (element.getKind() != ElementKind.INTERFACE) { // throw new ValidationException(element, "%s annotated with @%s should be interface", element, ActionCreator.class.getSimpleName()); // } // TypeElement typeElement = MoreElements.asType(element); // // List<ActionCreatorAction> actions = new ArrayList<>(); // for (Element methodElement : typeElement.getEnclosedElements()) { // if (methodElement.getKind() != ElementKind.METHOD) continue; // actions.add(ActionCreatorAction.parse(MoreElements.asExecutable(methodElement), env)); // } // // return new ActionCreatorElement(actions, typeElement); // } // }
import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.annotations.AutoReducer; import com.yheriatovych.reductor.processor.*; import com.yheriatovych.reductor.processor.actioncreator.ActionCreatorElement; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import java.util.ArrayList; import java.util.List; import java.util.Map;
package com.yheriatovych.reductor.processor.autoreducer; public class ReduceAction { public final String action; public final List<VariableElement> args; public final ExecutableElement executableElement; public final boolean generateActionCreator; private ReduceAction(String action, List<VariableElement> args, ExecutableElement executableElement, boolean generateActionCreator) { this.executableElement = executableElement; this.args = args; this.action = action; this.generateActionCreator = generateActionCreator; }
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorElement.java // public class ActionCreatorElement { // public final List<ActionCreatorAction> actions; // private final TypeElement typeElement; // private Map<String, ActionCreatorAction> actionMap; // // private ActionCreatorElement(List<ActionCreatorAction> actions, TypeElement typeElement) { // this.actions = actions; // this.typeElement = typeElement; // actionMap = new HashMap<>(); // for (ActionCreatorAction action : actions) { // actionMap.put(action.actionType, action); // } // } // // public boolean hasAction(String actionType, List<? extends VariableElement> reducerArgs) { // ActionCreatorAction actionCreator = actionMap.get(actionType); // if (actionCreator == null || reducerArgs.size() != actionCreator.arguments.size()) return false; // List<? extends VariableElement> arguments = actionCreator.arguments; // for (int i = 0; i < arguments.size(); i++) { // //we are doing black magic with checking if TypeName are equals // //instead of checking if two TypeMirrors are equals because TypeMirrors can be different for the same type // //happens when code is processed with several number of processing steps // TypeName creatorArgType = actionCreator.argumentTypes.get(i); // TypeName reducerArgType = TypeName.get(reducerArgs.get(i).asType()); // if (!creatorArgType.equals(reducerArgType)) { // return false; // } // } // return true; // } // // public String getPackageName(Env env) { // return env.getPackageName(typeElement); // } // // public String getName(Env env) { // return env.getElements().getBinaryName(typeElement).toString(); // } // // public TypeMirror getType() { // return typeElement.asType(); // } // // public static ActionCreatorElement parse(Element element, Env env) throws ValidationException { // if (element.getKind() != ElementKind.INTERFACE) { // throw new ValidationException(element, "%s annotated with @%s should be interface", element, ActionCreator.class.getSimpleName()); // } // TypeElement typeElement = MoreElements.asType(element); // // List<ActionCreatorAction> actions = new ArrayList<>(); // for (Element methodElement : typeElement.getEnclosedElements()) { // if (methodElement.getKind() != ElementKind.METHOD) continue; // actions.add(ActionCreatorAction.parse(MoreElements.asExecutable(methodElement), env)); // } // // return new ActionCreatorElement(actions, typeElement); // } // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/autoreducer/ReduceAction.java import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.annotations.AutoReducer; import com.yheriatovych.reductor.processor.*; import com.yheriatovych.reductor.processor.actioncreator.ActionCreatorElement; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import java.util.ArrayList; import java.util.List; import java.util.Map; package com.yheriatovych.reductor.processor.autoreducer; public class ReduceAction { public final String action; public final List<VariableElement> args; public final ExecutableElement executableElement; public final boolean generateActionCreator; private ReduceAction(String action, List<VariableElement> args, ExecutableElement executableElement, boolean generateActionCreator) { this.executableElement = executableElement; this.args = args; this.action = action; this.generateActionCreator = generateActionCreator; }
public static ReduceAction parseReduceAction(Env env, TypeMirror stateType, ExecutableElement element, Map<String, ActionCreatorElement> knownActionCreators) throws ValidationException {
Yarikx/reductor
compiller/src/test/java/com/yheriatovych/reductor/processor/AutoReducerValidationTest.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // }
import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
package com.yheriatovych.reductor.processor; public class AutoReducerValidationTest { @Test public void testFailIfReducerIsInterace() { JavaFileObject source = JavaFileObjects.forSourceString("test.FoobarReducer", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Reducer;\n" + "import com.yheriatovych.reductor.annotations.AutoReducer;\n" + "\n" + "@AutoReducer\n" + "public interface FoobarReducer extends Reducer<String> {\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // } // Path: compiller/src/test/java/com/yheriatovych/reductor/processor/AutoReducerValidationTest.java import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; package com.yheriatovych.reductor.processor; public class AutoReducerValidationTest { @Test public void testFailIfReducerIsInterace() { JavaFileObject source = JavaFileObjects.forSourceString("test.FoobarReducer", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Reducer;\n" + "import com.yheriatovych.reductor.annotations.AutoReducer;\n" + "\n" + "@AutoReducer\n" + "public interface FoobarReducer extends Reducer<String> {\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
.processedWith(new ReductorAnnotationProcessor())
Yarikx/reductor
compiller/src/test/java/com/yheriatovych/reductor/processor/CombinedStateReducerTest.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // }
import com.google.auto.value.processor.AutoValueProcessor; import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
" public Foobar reduce(Foobar state, Action action) {\n" + "\n" + " if (state != null) {\n" + " }\n" + "\n" + "\n" + " //If all values are the same there is no need to create an object\n" + " if (state != null) {\n" + " return state;\n" + " } else {\n" + " return new FoobarImpl();\n" + " }\n" + " }\n" + "\n" + " public static Builder builder() {\n" + " return new Builder();\n" + " }\n" + "\n" + " public static class Builder {\n" + " private Builder() {\n" + " }\n" + "\n" + " public FoobarReducer build() {\n" + " return new FoobarReducer();\n" + " }\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // } // Path: compiller/src/test/java/com/yheriatovych/reductor/processor/CombinedStateReducerTest.java import com.google.auto.value.processor.AutoValueProcessor; import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; " public Foobar reduce(Foobar state, Action action) {\n" + "\n" + " if (state != null) {\n" + " }\n" + "\n" + "\n" + " //If all values are the same there is no need to create an object\n" + " if (state != null) {\n" + " return state;\n" + " } else {\n" + " return new FoobarImpl();\n" + " }\n" + " }\n" + "\n" + " public static Builder builder() {\n" + " return new Builder();\n" + " }\n" + "\n" + " public static class Builder {\n" + " private Builder() {\n" + " }\n" + "\n" + " public FoobarReducer build() {\n" + " return new FoobarReducer();\n" + " }\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
.processedWith(new ReductorAnnotationProcessor())
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/autoreducer/AutoReducerInit.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationUtils.java // public class ValidationUtils { // public static void validateReturnsState(Env env, TypeMirror stateType, ExecutableElement element) throws ValidationException { // if (!env.getTypes().isAssignable(element.getReturnType(), stateType)) { // throw new ValidationException(element, "Method %s should return type assignable to state type %s", element, stateType); // } // } // // public static void validateIsNotPrivate(ExecutableElement element) throws ValidationException { // if (element.getModifiers().contains(Modifier.PRIVATE)) { // throw new ValidationException(element, "%s has 'private' modifier and is not accessible from child classes", element); // } // } // }
import com.yheriatovych.reductor.annotations.AutoReducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import com.yheriatovych.reductor.processor.ValidationUtils; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeMirror;
package com.yheriatovych.reductor.processor.autoreducer; public class AutoReducerInit { public final ExecutableElement executableElement; private AutoReducerInit(ExecutableElement executableElement) { this.executableElement = executableElement; } public String getName() { return executableElement.getSimpleName().toString(); }
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationUtils.java // public class ValidationUtils { // public static void validateReturnsState(Env env, TypeMirror stateType, ExecutableElement element) throws ValidationException { // if (!env.getTypes().isAssignable(element.getReturnType(), stateType)) { // throw new ValidationException(element, "Method %s should return type assignable to state type %s", element, stateType); // } // } // // public static void validateIsNotPrivate(ExecutableElement element) throws ValidationException { // if (element.getModifiers().contains(Modifier.PRIVATE)) { // throw new ValidationException(element, "%s has 'private' modifier and is not accessible from child classes", element); // } // } // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/autoreducer/AutoReducerInit.java import com.yheriatovych.reductor.annotations.AutoReducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import com.yheriatovych.reductor.processor.ValidationUtils; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeMirror; package com.yheriatovych.reductor.processor.autoreducer; public class AutoReducerInit { public final ExecutableElement executableElement; private AutoReducerInit(ExecutableElement executableElement) { this.executableElement = executableElement; } public String getName() { return executableElement.getSimpleName().toString(); }
public static AutoReducerInit parse(Env env, ExecutableElement executableElement, TypeMirror stateType) throws ValidationException {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/autoreducer/AutoReducerInit.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationUtils.java // public class ValidationUtils { // public static void validateReturnsState(Env env, TypeMirror stateType, ExecutableElement element) throws ValidationException { // if (!env.getTypes().isAssignable(element.getReturnType(), stateType)) { // throw new ValidationException(element, "Method %s should return type assignable to state type %s", element, stateType); // } // } // // public static void validateIsNotPrivate(ExecutableElement element) throws ValidationException { // if (element.getModifiers().contains(Modifier.PRIVATE)) { // throw new ValidationException(element, "%s has 'private' modifier and is not accessible from child classes", element); // } // } // }
import com.yheriatovych.reductor.annotations.AutoReducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import com.yheriatovych.reductor.processor.ValidationUtils; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeMirror;
package com.yheriatovych.reductor.processor.autoreducer; public class AutoReducerInit { public final ExecutableElement executableElement; private AutoReducerInit(ExecutableElement executableElement) { this.executableElement = executableElement; } public String getName() { return executableElement.getSimpleName().toString(); }
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationUtils.java // public class ValidationUtils { // public static void validateReturnsState(Env env, TypeMirror stateType, ExecutableElement element) throws ValidationException { // if (!env.getTypes().isAssignable(element.getReturnType(), stateType)) { // throw new ValidationException(element, "Method %s should return type assignable to state type %s", element, stateType); // } // } // // public static void validateIsNotPrivate(ExecutableElement element) throws ValidationException { // if (element.getModifiers().contains(Modifier.PRIVATE)) { // throw new ValidationException(element, "%s has 'private' modifier and is not accessible from child classes", element); // } // } // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/autoreducer/AutoReducerInit.java import com.yheriatovych.reductor.annotations.AutoReducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import com.yheriatovych.reductor.processor.ValidationUtils; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeMirror; package com.yheriatovych.reductor.processor.autoreducer; public class AutoReducerInit { public final ExecutableElement executableElement; private AutoReducerInit(ExecutableElement executableElement) { this.executableElement = executableElement; } public String getName() { return executableElement.getSimpleName().toString(); }
public static AutoReducerInit parse(Env env, ExecutableElement executableElement, TypeMirror stateType) throws ValidationException {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/autoreducer/AutoReducerInit.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationUtils.java // public class ValidationUtils { // public static void validateReturnsState(Env env, TypeMirror stateType, ExecutableElement element) throws ValidationException { // if (!env.getTypes().isAssignable(element.getReturnType(), stateType)) { // throw new ValidationException(element, "Method %s should return type assignable to state type %s", element, stateType); // } // } // // public static void validateIsNotPrivate(ExecutableElement element) throws ValidationException { // if (element.getModifiers().contains(Modifier.PRIVATE)) { // throw new ValidationException(element, "%s has 'private' modifier and is not accessible from child classes", element); // } // } // }
import com.yheriatovych.reductor.annotations.AutoReducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import com.yheriatovych.reductor.processor.ValidationUtils; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeMirror;
package com.yheriatovych.reductor.processor.autoreducer; public class AutoReducerInit { public final ExecutableElement executableElement; private AutoReducerInit(ExecutableElement executableElement) { this.executableElement = executableElement; } public String getName() { return executableElement.getSimpleName().toString(); } public static AutoReducerInit parse(Env env, ExecutableElement executableElement, TypeMirror stateType) throws ValidationException { if (executableElement.getAnnotation(AutoReducer.Action.class) != null) { throw new ValidationException(executableElement, "Method %s should be may be annotated" + " with either @AutoReducer.InitialState or @AutoReducer.Action but not both", executableElement); }
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationUtils.java // public class ValidationUtils { // public static void validateReturnsState(Env env, TypeMirror stateType, ExecutableElement element) throws ValidationException { // if (!env.getTypes().isAssignable(element.getReturnType(), stateType)) { // throw new ValidationException(element, "Method %s should return type assignable to state type %s", element, stateType); // } // } // // public static void validateIsNotPrivate(ExecutableElement element) throws ValidationException { // if (element.getModifiers().contains(Modifier.PRIVATE)) { // throw new ValidationException(element, "%s has 'private' modifier and is not accessible from child classes", element); // } // } // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/autoreducer/AutoReducerInit.java import com.yheriatovych.reductor.annotations.AutoReducer; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import com.yheriatovych.reductor.processor.ValidationUtils; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeMirror; package com.yheriatovych.reductor.processor.autoreducer; public class AutoReducerInit { public final ExecutableElement executableElement; private AutoReducerInit(ExecutableElement executableElement) { this.executableElement = executableElement; } public String getName() { return executableElement.getSimpleName().toString(); } public static AutoReducerInit parse(Env env, ExecutableElement executableElement, TypeMirror stateType) throws ValidationException { if (executableElement.getAnnotation(AutoReducer.Action.class) != null) { throw new ValidationException(executableElement, "Method %s should be may be annotated" + " with either @AutoReducer.InitialState or @AutoReducer.Action but not both", executableElement); }
ValidationUtils.validateReturnsState(env, stateType, executableElement);
Yarikx/reductor
reductor-rxjava/src/main/java/com/yheriatovych/reductor/rx/RxStore.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Cancelable.java // public interface Cancelable { // void cancel(); // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Cursor.java // public interface Cursor<State> { // /** // * @return return current state // */ // State getState(); // // /** // * Subscribe for state changes // * <p> // * Note: current state will not be dispatched immediately after subscribe // * // * @param listener callback which will be notified each time state changes // * @return instance of {@link Cancelable} to be used to cancel subscription (remove listener) // */ // Cancelable subscribe(StateChangeListener<State> listener); // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Cursors.java // public class Cursors { // private Cursors(){} // // /** // * Creates a Cursor by applying a specified function to state. // * // * @param cursor source Cursor to be mapped // * @param mapper the function that will be applied to a state. Must be free of side effects. // * @param <State> source state type // * @param <R> the output state type // * @return Cursor that holds state of type T produced by mapper function // */ // public static <State, R> Cursor<R> map(Cursor<State> cursor, Function<State, R> mapper) { // return new MappedCursor<>(cursor, mapper); // } // // /** // * Notify listener for every state in Store. // * <p> // * Note: equivalent to {@link Cursor#subscribe(StateChangeListener)} but current state will be propagated too // * // * @param cursor source Cursor // * @param listener callback which will be notified // * @param <State> source state type // * @return instance of {@link Cancelable} to be used to cancel subscription (remove listener) // */ // public static <State> Cancelable forEach(Cursor<State> cursor, StateChangeListener<State> listener) { // Cancelable cancelable = cursor.subscribe(listener); // listener.onStateChanged(cursor.getState()); // return cancelable; // } // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Store.java // public class Store<State> implements Dispatcher, Cursor<State> { // public static final String INIT_ACTION = "@@reductor/INIT"; // // private final Reducer<State> reducer; // private Dispatcher dispatcher; // private final List<StateChangeListener<State>> listeners = new CopyOnWriteArrayList<>(); // private volatile State state; // // private Store(Reducer<State> reducer, State initialState, Middleware<State>[] middlewares) { // this.reducer = reducer; // this.state = initialState; // // dispatcher = this::dispatchAction; // dispatchAction(Action.create(INIT_ACTION)); // // for (int i = middlewares.length - 1; i >= 0; i--) { // Middleware<State> middleware = middlewares[i]; // dispatcher = middleware.create(Store.this, dispatcher); // } // } // // private void dispatchAction(final Object actionObject) { // if (actionObject instanceof Action) { // final Action action = (Action) actionObject; // synchronized (this) { // state = reducer.reduce(state, action); // } // for (StateChangeListener<State> listener : listeners) { // listener.onStateChanged(state); // } // } else { // throw new IllegalArgumentException(String.format("action %s of %s is not instance of %s, use custom Middleware to dispatch another types of actions", actionObject, actionObject.getClass(), Action.class)); // } // } // // /** // * Create store with given {@link Reducer} and optional array of {@link Middleware} // * // * @param reducer Reducer of type S which will be used to dispatch actions // * @param middlewares array of middlewares to be used to dispatch actions in the same order as provided // * look {@link Middleware} for more information // * @param <S> type of state to hold and maintain // * @return Store initialised with initialState // */ // @SafeVarargs // public static <S> Store<S> create(Reducer<S> reducer, Middleware<S>... middlewares) { // return create(reducer, null, middlewares); // } // // /** // * Create store with given {@link Reducer}, initalState and optional array of {@link Middleware} // * // * @param reducer Reducer of type S which will be used to dispatch actions // * @param initialState state to be initial state of create store // * @param middlewares array of middlewares to be used to dispatch actions in the same order as provided // * look {@link Middleware} for more information // * @param <S> type of state to hold and maintain // * @return Store initialised with initialState // */ // @SafeVarargs // public static <S> Store<S> create(Reducer<S> reducer, S initialState, Middleware<S>... middlewares) { // return new Store<>(reducer, initialState, middlewares); // } // // /** // * Dispatch action through {@link Reducer} and store the next state // * // * @param action action to be dispatched, usually instance of {@link Action} // * but custom {@link Middleware} can be used to support other types of actions // */ // public void dispatch(final Object action) { // dispatcher.dispatch(action); // } // // /** // * {@inheritDoc} // */ // public State getState() { // return state; // } // // /** // * {@inheritDoc} // */ // public Cancelable subscribe(final StateChangeListener<State> listener) { // listeners.add(listener); // return () -> listeners.remove(listener); // } // }
import com.yheriatovych.reductor.Cancelable; import com.yheriatovych.reductor.Cursor; import com.yheriatovych.reductor.Cursors; import com.yheriatovych.reductor.Store; import rx.Emitter; import rx.Observable;
package com.yheriatovych.reductor.rx; public final class RxStore { /** * Create observable of state changes from specified {@link Cursor} * <p> * Note: This method will emit current sate immediately after subscribe */ public static <State> Observable<State> asObservable(final Cursor<State> cursor) { return Observable.fromEmitter(emitter -> {
// Path: lib/src/main/java/com/yheriatovych/reductor/Cancelable.java // public interface Cancelable { // void cancel(); // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Cursor.java // public interface Cursor<State> { // /** // * @return return current state // */ // State getState(); // // /** // * Subscribe for state changes // * <p> // * Note: current state will not be dispatched immediately after subscribe // * // * @param listener callback which will be notified each time state changes // * @return instance of {@link Cancelable} to be used to cancel subscription (remove listener) // */ // Cancelable subscribe(StateChangeListener<State> listener); // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Cursors.java // public class Cursors { // private Cursors(){} // // /** // * Creates a Cursor by applying a specified function to state. // * // * @param cursor source Cursor to be mapped // * @param mapper the function that will be applied to a state. Must be free of side effects. // * @param <State> source state type // * @param <R> the output state type // * @return Cursor that holds state of type T produced by mapper function // */ // public static <State, R> Cursor<R> map(Cursor<State> cursor, Function<State, R> mapper) { // return new MappedCursor<>(cursor, mapper); // } // // /** // * Notify listener for every state in Store. // * <p> // * Note: equivalent to {@link Cursor#subscribe(StateChangeListener)} but current state will be propagated too // * // * @param cursor source Cursor // * @param listener callback which will be notified // * @param <State> source state type // * @return instance of {@link Cancelable} to be used to cancel subscription (remove listener) // */ // public static <State> Cancelable forEach(Cursor<State> cursor, StateChangeListener<State> listener) { // Cancelable cancelable = cursor.subscribe(listener); // listener.onStateChanged(cursor.getState()); // return cancelable; // } // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Store.java // public class Store<State> implements Dispatcher, Cursor<State> { // public static final String INIT_ACTION = "@@reductor/INIT"; // // private final Reducer<State> reducer; // private Dispatcher dispatcher; // private final List<StateChangeListener<State>> listeners = new CopyOnWriteArrayList<>(); // private volatile State state; // // private Store(Reducer<State> reducer, State initialState, Middleware<State>[] middlewares) { // this.reducer = reducer; // this.state = initialState; // // dispatcher = this::dispatchAction; // dispatchAction(Action.create(INIT_ACTION)); // // for (int i = middlewares.length - 1; i >= 0; i--) { // Middleware<State> middleware = middlewares[i]; // dispatcher = middleware.create(Store.this, dispatcher); // } // } // // private void dispatchAction(final Object actionObject) { // if (actionObject instanceof Action) { // final Action action = (Action) actionObject; // synchronized (this) { // state = reducer.reduce(state, action); // } // for (StateChangeListener<State> listener : listeners) { // listener.onStateChanged(state); // } // } else { // throw new IllegalArgumentException(String.format("action %s of %s is not instance of %s, use custom Middleware to dispatch another types of actions", actionObject, actionObject.getClass(), Action.class)); // } // } // // /** // * Create store with given {@link Reducer} and optional array of {@link Middleware} // * // * @param reducer Reducer of type S which will be used to dispatch actions // * @param middlewares array of middlewares to be used to dispatch actions in the same order as provided // * look {@link Middleware} for more information // * @param <S> type of state to hold and maintain // * @return Store initialised with initialState // */ // @SafeVarargs // public static <S> Store<S> create(Reducer<S> reducer, Middleware<S>... middlewares) { // return create(reducer, null, middlewares); // } // // /** // * Create store with given {@link Reducer}, initalState and optional array of {@link Middleware} // * // * @param reducer Reducer of type S which will be used to dispatch actions // * @param initialState state to be initial state of create store // * @param middlewares array of middlewares to be used to dispatch actions in the same order as provided // * look {@link Middleware} for more information // * @param <S> type of state to hold and maintain // * @return Store initialised with initialState // */ // @SafeVarargs // public static <S> Store<S> create(Reducer<S> reducer, S initialState, Middleware<S>... middlewares) { // return new Store<>(reducer, initialState, middlewares); // } // // /** // * Dispatch action through {@link Reducer} and store the next state // * // * @param action action to be dispatched, usually instance of {@link Action} // * but custom {@link Middleware} can be used to support other types of actions // */ // public void dispatch(final Object action) { // dispatcher.dispatch(action); // } // // /** // * {@inheritDoc} // */ // public State getState() { // return state; // } // // /** // * {@inheritDoc} // */ // public Cancelable subscribe(final StateChangeListener<State> listener) { // listeners.add(listener); // return () -> listeners.remove(listener); // } // } // Path: reductor-rxjava/src/main/java/com/yheriatovych/reductor/rx/RxStore.java import com.yheriatovych.reductor.Cancelable; import com.yheriatovych.reductor.Cursor; import com.yheriatovych.reductor.Cursors; import com.yheriatovych.reductor.Store; import rx.Emitter; import rx.Observable; package com.yheriatovych.reductor.rx; public final class RxStore { /** * Create observable of state changes from specified {@link Cursor} * <p> * Note: This method will emit current sate immediately after subscribe */ public static <State> Observable<State> asObservable(final Cursor<State> cursor) { return Observable.fromEmitter(emitter -> {
final Cancelable cancelable = Cursors.forEach(cursor, emitter::onNext);
Yarikx/reductor
reductor-rxjava/src/main/java/com/yheriatovych/reductor/rx/RxStore.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Cancelable.java // public interface Cancelable { // void cancel(); // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Cursor.java // public interface Cursor<State> { // /** // * @return return current state // */ // State getState(); // // /** // * Subscribe for state changes // * <p> // * Note: current state will not be dispatched immediately after subscribe // * // * @param listener callback which will be notified each time state changes // * @return instance of {@link Cancelable} to be used to cancel subscription (remove listener) // */ // Cancelable subscribe(StateChangeListener<State> listener); // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Cursors.java // public class Cursors { // private Cursors(){} // // /** // * Creates a Cursor by applying a specified function to state. // * // * @param cursor source Cursor to be mapped // * @param mapper the function that will be applied to a state. Must be free of side effects. // * @param <State> source state type // * @param <R> the output state type // * @return Cursor that holds state of type T produced by mapper function // */ // public static <State, R> Cursor<R> map(Cursor<State> cursor, Function<State, R> mapper) { // return new MappedCursor<>(cursor, mapper); // } // // /** // * Notify listener for every state in Store. // * <p> // * Note: equivalent to {@link Cursor#subscribe(StateChangeListener)} but current state will be propagated too // * // * @param cursor source Cursor // * @param listener callback which will be notified // * @param <State> source state type // * @return instance of {@link Cancelable} to be used to cancel subscription (remove listener) // */ // public static <State> Cancelable forEach(Cursor<State> cursor, StateChangeListener<State> listener) { // Cancelable cancelable = cursor.subscribe(listener); // listener.onStateChanged(cursor.getState()); // return cancelable; // } // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Store.java // public class Store<State> implements Dispatcher, Cursor<State> { // public static final String INIT_ACTION = "@@reductor/INIT"; // // private final Reducer<State> reducer; // private Dispatcher dispatcher; // private final List<StateChangeListener<State>> listeners = new CopyOnWriteArrayList<>(); // private volatile State state; // // private Store(Reducer<State> reducer, State initialState, Middleware<State>[] middlewares) { // this.reducer = reducer; // this.state = initialState; // // dispatcher = this::dispatchAction; // dispatchAction(Action.create(INIT_ACTION)); // // for (int i = middlewares.length - 1; i >= 0; i--) { // Middleware<State> middleware = middlewares[i]; // dispatcher = middleware.create(Store.this, dispatcher); // } // } // // private void dispatchAction(final Object actionObject) { // if (actionObject instanceof Action) { // final Action action = (Action) actionObject; // synchronized (this) { // state = reducer.reduce(state, action); // } // for (StateChangeListener<State> listener : listeners) { // listener.onStateChanged(state); // } // } else { // throw new IllegalArgumentException(String.format("action %s of %s is not instance of %s, use custom Middleware to dispatch another types of actions", actionObject, actionObject.getClass(), Action.class)); // } // } // // /** // * Create store with given {@link Reducer} and optional array of {@link Middleware} // * // * @param reducer Reducer of type S which will be used to dispatch actions // * @param middlewares array of middlewares to be used to dispatch actions in the same order as provided // * look {@link Middleware} for more information // * @param <S> type of state to hold and maintain // * @return Store initialised with initialState // */ // @SafeVarargs // public static <S> Store<S> create(Reducer<S> reducer, Middleware<S>... middlewares) { // return create(reducer, null, middlewares); // } // // /** // * Create store with given {@link Reducer}, initalState and optional array of {@link Middleware} // * // * @param reducer Reducer of type S which will be used to dispatch actions // * @param initialState state to be initial state of create store // * @param middlewares array of middlewares to be used to dispatch actions in the same order as provided // * look {@link Middleware} for more information // * @param <S> type of state to hold and maintain // * @return Store initialised with initialState // */ // @SafeVarargs // public static <S> Store<S> create(Reducer<S> reducer, S initialState, Middleware<S>... middlewares) { // return new Store<>(reducer, initialState, middlewares); // } // // /** // * Dispatch action through {@link Reducer} and store the next state // * // * @param action action to be dispatched, usually instance of {@link Action} // * but custom {@link Middleware} can be used to support other types of actions // */ // public void dispatch(final Object action) { // dispatcher.dispatch(action); // } // // /** // * {@inheritDoc} // */ // public State getState() { // return state; // } // // /** // * {@inheritDoc} // */ // public Cancelable subscribe(final StateChangeListener<State> listener) { // listeners.add(listener); // return () -> listeners.remove(listener); // } // }
import com.yheriatovych.reductor.Cancelable; import com.yheriatovych.reductor.Cursor; import com.yheriatovych.reductor.Cursors; import com.yheriatovych.reductor.Store; import rx.Emitter; import rx.Observable;
package com.yheriatovych.reductor.rx; public final class RxStore { /** * Create observable of state changes from specified {@link Cursor} * <p> * Note: This method will emit current sate immediately after subscribe */ public static <State> Observable<State> asObservable(final Cursor<State> cursor) { return Observable.fromEmitter(emitter -> {
// Path: lib/src/main/java/com/yheriatovych/reductor/Cancelable.java // public interface Cancelable { // void cancel(); // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Cursor.java // public interface Cursor<State> { // /** // * @return return current state // */ // State getState(); // // /** // * Subscribe for state changes // * <p> // * Note: current state will not be dispatched immediately after subscribe // * // * @param listener callback which will be notified each time state changes // * @return instance of {@link Cancelable} to be used to cancel subscription (remove listener) // */ // Cancelable subscribe(StateChangeListener<State> listener); // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Cursors.java // public class Cursors { // private Cursors(){} // // /** // * Creates a Cursor by applying a specified function to state. // * // * @param cursor source Cursor to be mapped // * @param mapper the function that will be applied to a state. Must be free of side effects. // * @param <State> source state type // * @param <R> the output state type // * @return Cursor that holds state of type T produced by mapper function // */ // public static <State, R> Cursor<R> map(Cursor<State> cursor, Function<State, R> mapper) { // return new MappedCursor<>(cursor, mapper); // } // // /** // * Notify listener for every state in Store. // * <p> // * Note: equivalent to {@link Cursor#subscribe(StateChangeListener)} but current state will be propagated too // * // * @param cursor source Cursor // * @param listener callback which will be notified // * @param <State> source state type // * @return instance of {@link Cancelable} to be used to cancel subscription (remove listener) // */ // public static <State> Cancelable forEach(Cursor<State> cursor, StateChangeListener<State> listener) { // Cancelable cancelable = cursor.subscribe(listener); // listener.onStateChanged(cursor.getState()); // return cancelable; // } // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Store.java // public class Store<State> implements Dispatcher, Cursor<State> { // public static final String INIT_ACTION = "@@reductor/INIT"; // // private final Reducer<State> reducer; // private Dispatcher dispatcher; // private final List<StateChangeListener<State>> listeners = new CopyOnWriteArrayList<>(); // private volatile State state; // // private Store(Reducer<State> reducer, State initialState, Middleware<State>[] middlewares) { // this.reducer = reducer; // this.state = initialState; // // dispatcher = this::dispatchAction; // dispatchAction(Action.create(INIT_ACTION)); // // for (int i = middlewares.length - 1; i >= 0; i--) { // Middleware<State> middleware = middlewares[i]; // dispatcher = middleware.create(Store.this, dispatcher); // } // } // // private void dispatchAction(final Object actionObject) { // if (actionObject instanceof Action) { // final Action action = (Action) actionObject; // synchronized (this) { // state = reducer.reduce(state, action); // } // for (StateChangeListener<State> listener : listeners) { // listener.onStateChanged(state); // } // } else { // throw new IllegalArgumentException(String.format("action %s of %s is not instance of %s, use custom Middleware to dispatch another types of actions", actionObject, actionObject.getClass(), Action.class)); // } // } // // /** // * Create store with given {@link Reducer} and optional array of {@link Middleware} // * // * @param reducer Reducer of type S which will be used to dispatch actions // * @param middlewares array of middlewares to be used to dispatch actions in the same order as provided // * look {@link Middleware} for more information // * @param <S> type of state to hold and maintain // * @return Store initialised with initialState // */ // @SafeVarargs // public static <S> Store<S> create(Reducer<S> reducer, Middleware<S>... middlewares) { // return create(reducer, null, middlewares); // } // // /** // * Create store with given {@link Reducer}, initalState and optional array of {@link Middleware} // * // * @param reducer Reducer of type S which will be used to dispatch actions // * @param initialState state to be initial state of create store // * @param middlewares array of middlewares to be used to dispatch actions in the same order as provided // * look {@link Middleware} for more information // * @param <S> type of state to hold and maintain // * @return Store initialised with initialState // */ // @SafeVarargs // public static <S> Store<S> create(Reducer<S> reducer, S initialState, Middleware<S>... middlewares) { // return new Store<>(reducer, initialState, middlewares); // } // // /** // * Dispatch action through {@link Reducer} and store the next state // * // * @param action action to be dispatched, usually instance of {@link Action} // * but custom {@link Middleware} can be used to support other types of actions // */ // public void dispatch(final Object action) { // dispatcher.dispatch(action); // } // // /** // * {@inheritDoc} // */ // public State getState() { // return state; // } // // /** // * {@inheritDoc} // */ // public Cancelable subscribe(final StateChangeListener<State> listener) { // listeners.add(listener); // return () -> listeners.remove(listener); // } // } // Path: reductor-rxjava/src/main/java/com/yheriatovych/reductor/rx/RxStore.java import com.yheriatovych.reductor.Cancelable; import com.yheriatovych.reductor.Cursor; import com.yheriatovych.reductor.Cursors; import com.yheriatovych.reductor.Store; import rx.Emitter; import rx.Observable; package com.yheriatovych.reductor.rx; public final class RxStore { /** * Create observable of state changes from specified {@link Cursor} * <p> * Note: This method will emit current sate immediately after subscribe */ public static <State> Observable<State> asObservable(final Cursor<State> cursor) { return Observable.fromEmitter(emitter -> {
final Cancelable cancelable = Cursors.forEach(cursor, emitter::onNext);
Yarikx/reductor
example/src/main/java/com/yheriatovych/reductor/example/reductor/utils/SetStateReducer.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // }
import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.Reducer;
package com.yheriatovych.reductor.example.reductor.utils; /** * Reducer which wrap other {@link com.yheriatovych.reductor.Reducer} and add one action: * "SET_GLOBAL_STATE" to be able to replace state with provided value */ public class SetStateReducer<T> implements Reducer<T> { public static final String SET_GLOBAL_STATE = "SET_GLOBAL_STATE"; private final Reducer<T> source; public SetStateReducer(Reducer<T> source) { this.source = source; }
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // } // Path: example/src/main/java/com/yheriatovych/reductor/example/reductor/utils/SetStateReducer.java import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.Reducer; package com.yheriatovych.reductor.example.reductor.utils; /** * Reducer which wrap other {@link com.yheriatovych.reductor.Reducer} and add one action: * "SET_GLOBAL_STATE" to be able to replace state with provided value */ public class SetStateReducer<T> implements Reducer<T> { public static final String SET_GLOBAL_STATE = "SET_GLOBAL_STATE"; private final Reducer<T> source; public SetStateReducer(Reducer<T> source) { this.source = source; }
public static <T> Action setStateAction(T value) {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/Utils.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // }
import com.google.auto.common.MoreTypes; import com.squareup.javapoet.AnnotationSpec; import com.yheriatovych.reductor.Reducer; import javax.annotation.Generated; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.List;
package com.yheriatovych.reductor.processor; public class Utils { public interface Func1<T, R> { R call(T value); } public interface Func2<T1, T2, R> { R call(T1 value1, T2 value2); } public static DeclaredType getReducerSuperInterface(DeclaredType reducerType) { List<? extends TypeMirror> supertypes = MoreTypes.asTypeElement(reducerType).getInterfaces(); for (TypeMirror supertype : supertypes) {
// Path: lib/src/main/java/com/yheriatovych/reductor/Reducer.java // public interface Reducer<State> { // /** // * Produce new state based on current state and action to dispatch. // * <p> // * Reducer is responsible to populate initial state if null is passed as 'state' argument // * <p> // * Note: // * This function should be pure. No side effects, no API calls! // * // * @param state state to be reduced // * @param action minimum representation of change to be performed on state // * @return a new state // */ // State reduce(State state, Action action); // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Utils.java import com.google.auto.common.MoreTypes; import com.squareup.javapoet.AnnotationSpec; import com.yheriatovych.reductor.Reducer; import javax.annotation.Generated; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.List; package com.yheriatovych.reductor.processor; public class Utils { public interface Func1<T, R> { R call(T value); } public interface Func2<T1, T2, R> { R call(T1 value1, T2 value2); } public static DeclaredType getReducerSuperInterface(DeclaredType reducerType) { List<? extends TypeMirror> supertypes = MoreTypes.asTypeElement(reducerType).getInterfaces(); for (TypeMirror supertype : supertypes) {
boolean isReducer = MoreTypes.isTypeOf(Reducer.class, supertype);
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorAction.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.List;
package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorAction { public final String actionType; public final String methodName; public final List<? extends VariableElement> arguments; public final List<TypeName> argumentTypes; private ActionCreatorAction(String actionType, String methodName, List<? extends VariableElement> arguments) { this.actionType = actionType; this.methodName = methodName; this.arguments = arguments; this.argumentTypes = new ArrayList<>(arguments.size()); for (VariableElement argument : arguments) { argumentTypes.add(TypeName.get(argument.asType())); } }
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorAction.java import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.List; package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorAction { public final String actionType; public final String methodName; public final List<? extends VariableElement> arguments; public final List<TypeName> argumentTypes; private ActionCreatorAction(String actionType, String methodName, List<? extends VariableElement> arguments) { this.actionType = actionType; this.methodName = methodName; this.arguments = arguments; this.argumentTypes = new ArrayList<>(arguments.size()); for (VariableElement argument : arguments) { argumentTypes.add(TypeName.get(argument.asType())); } }
public static ActionCreatorAction parse(ExecutableElement element, Env env) throws ValidationException {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorAction.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.List;
package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorAction { public final String actionType; public final String methodName; public final List<? extends VariableElement> arguments; public final List<TypeName> argumentTypes; private ActionCreatorAction(String actionType, String methodName, List<? extends VariableElement> arguments) { this.actionType = actionType; this.methodName = methodName; this.arguments = arguments; this.argumentTypes = new ArrayList<>(arguments.size()); for (VariableElement argument : arguments) { argumentTypes.add(TypeName.get(argument.asType())); } }
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorAction.java import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.List; package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorAction { public final String actionType; public final String methodName; public final List<? extends VariableElement> arguments; public final List<TypeName> argumentTypes; private ActionCreatorAction(String actionType, String methodName, List<? extends VariableElement> arguments) { this.actionType = actionType; this.methodName = methodName; this.arguments = arguments; this.argumentTypes = new ArrayList<>(arguments.size()); for (VariableElement argument : arguments) { argumentTypes.add(TypeName.get(argument.asType())); } }
public static ActionCreatorAction parse(ExecutableElement element, Env env) throws ValidationException {
Yarikx/reductor
compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorAction.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // }
import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.List;
package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorAction { public final String actionType; public final String methodName; public final List<? extends VariableElement> arguments; public final List<TypeName> argumentTypes; private ActionCreatorAction(String actionType, String methodName, List<? extends VariableElement> arguments) { this.actionType = actionType; this.methodName = methodName; this.arguments = arguments; this.argumentTypes = new ArrayList<>(arguments.size()); for (VariableElement argument : arguments) { argumentTypes.add(TypeName.get(argument.asType())); } } public static ActionCreatorAction parse(ExecutableElement element, Env env) throws ValidationException {
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/Env.java // public class Env { // private final Types types; // private final Elements elements; // private final Messager messager; // private final Filer filer; // // public Env(Types types, Elements elements, Messager messager, Filer filer) { // this.types = types; // this.elements = elements; // this.messager = messager; // this.filer = filer; // } // // public void printError(Element element, String message, Object... args) { // printMessage(Diagnostic.Kind.ERROR, element, message, args); // } // // private void printMessage(Diagnostic.Kind level, Element element, String message, Object... args) { // messager.printMessage(level, String.format(message, args), element); // } // // public Types getTypes() { // return types; // } // // public Filer getFiler() { // return filer; // } // // public String getPackageName(Element element) { // return elements.getPackageOf(element).getQualifiedName().toString(); // } // // public TypeMirror asType(Class<?> clazz) { // return elements.getTypeElement(clazz.getCanonicalName()) // .asType(); // } // // public Elements getElements() { // return elements; // } // } // // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ValidationException.java // public class ValidationException extends Exception { // private final Element element; // private final String message; // // public ValidationException(Element element, String message, Object... args) { // this.element = element; // this.message = String.format(message, args); // } // // public Element getElement() { // return element; // } // // @Override // public String getMessage() { // return message; // } // // } // Path: compiller/src/main/java/com/yheriatovych/reductor/processor/actioncreator/ActionCreatorAction.java import com.squareup.javapoet.TypeName; import com.yheriatovych.reductor.Action; import com.yheriatovych.reductor.annotations.ActionCreator; import com.yheriatovych.reductor.processor.Env; import com.yheriatovych.reductor.processor.ValidationException; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.List; package com.yheriatovych.reductor.processor.actioncreator; public class ActionCreatorAction { public final String actionType; public final String methodName; public final List<? extends VariableElement> arguments; public final List<TypeName> argumentTypes; private ActionCreatorAction(String actionType, String methodName, List<? extends VariableElement> arguments) { this.actionType = actionType; this.methodName = methodName; this.arguments = arguments; this.argumentTypes = new ArrayList<>(arguments.size()); for (VariableElement argument : arguments) { argumentTypes.add(TypeName.get(argument.asType())); } } public static ActionCreatorAction parse(ExecutableElement element, Env env) throws ValidationException {
ActionCreator.Action annotation = element.getAnnotation(ActionCreator.Action.class);
Yarikx/reductor
example/src/main/java/com/yheriatovych/reductor/example/model/AppState.java
// Path: example/src/main/java/com/yheriatovych/reductor/example/Utils.java // public interface Utils { // interface Predicate<T> { // boolean call(T value); // } // // static <T> PStack<T> filter(PStack<T> xs, Predicate<T> predicate) { // if (xs.isEmpty()) return xs; // else { // T head = xs.get(0); // PStack<T> tail = xs.subList(1); // if (predicate.call(head)) { // return filter(tail, predicate).plus(head); // } else { // return filter(tail, predicate); // } // } // } // // }
import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.example.Utils; import org.pcollections.ConsPStack; import java.util.List;
package com.yheriatovych.reductor.example.model; @CombinedState @AutoValue public abstract class AppState { public abstract List<Note> notes(); public abstract NotesFilter filter(); public static TypeAdapter<AppState> typeAdapter(Gson gson) { return new AutoValue_AppState.GsonTypeAdapter(gson); } public List<Note> getFilteredNotes() { List<Note> notes = this.notes(); NotesFilter filter = this.filter();
// Path: example/src/main/java/com/yheriatovych/reductor/example/Utils.java // public interface Utils { // interface Predicate<T> { // boolean call(T value); // } // // static <T> PStack<T> filter(PStack<T> xs, Predicate<T> predicate) { // if (xs.isEmpty()) return xs; // else { // T head = xs.get(0); // PStack<T> tail = xs.subList(1); // if (predicate.call(head)) { // return filter(tail, predicate).plus(head); // } else { // return filter(tail, predicate); // } // } // } // // } // Path: example/src/main/java/com/yheriatovych/reductor/example/model/AppState.java import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.yheriatovych.reductor.annotations.CombinedState; import com.yheriatovych.reductor.example.Utils; import org.pcollections.ConsPStack; import java.util.List; package com.yheriatovych.reductor.example.model; @CombinedState @AutoValue public abstract class AppState { public abstract List<Note> notes(); public abstract NotesFilter filter(); public static TypeAdapter<AppState> typeAdapter(Gson gson) { return new AutoValue_AppState.GsonTypeAdapter(gson); } public List<Note> getFilteredNotes() { List<Note> notes = this.notes(); NotesFilter filter = this.filter();
return Utils.filter(ConsPStack.from(notes), note ->
Yarikx/reductor
reductor-observable/src/main/java/com/yheriatovych/reductor/observable/Epics.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // }
import com.yheriatovych.reductor.Action; import rx.Observable; import rx.functions.Func1;
package com.yheriatovych.reductor.observable; public class Epics { private Epics() { } /** * Combine several Epics into one. * <p> * Returned streams will be merged with {@link Observable#merge(Iterable)} * * @param epics Epics to combine * @param <T> state type * @return Epic that will combine all provided epics behaviour */ public static <T> Epic<T> combineEpics(Iterable<Epic<T>> epics) { return (actions, store) -> Observable.from(epics) .flatMap(epic -> epic.run(actions, store)); } /** * Useful predicate to be used with {@link Observable#filter(Func1)} in Epic implementation * to filter only actions with specific {@link Action#type} * * @param type Action type filtered * @return Predicate that will check if {@link Action#type} equals to specified type */
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // Path: reductor-observable/src/main/java/com/yheriatovych/reductor/observable/Epics.java import com.yheriatovych.reductor.Action; import rx.Observable; import rx.functions.Func1; package com.yheriatovych.reductor.observable; public class Epics { private Epics() { } /** * Combine several Epics into one. * <p> * Returned streams will be merged with {@link Observable#merge(Iterable)} * * @param epics Epics to combine * @param <T> state type * @return Epic that will combine all provided epics behaviour */ public static <T> Epic<T> combineEpics(Iterable<Epic<T>> epics) { return (actions, store) -> Observable.from(epics) .flatMap(epic -> epic.run(actions, store)); } /** * Useful predicate to be used with {@link Observable#filter(Func1)} in Epic implementation * to filter only actions with specific {@link Action#type} * * @param type Action type filtered * @return Predicate that will check if {@link Action#type} equals to specified type */
public static Func1<Action, Boolean> ofType(String type) {
Yarikx/reductor
reductor-observable-rxjava2/src/main/java/com/yheriatovych/reductor/observable/rxjava2/Epics.java
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // }
import com.yheriatovych.reductor.Action; import io.reactivex.Observable; import io.reactivex.functions.Predicate;
package com.yheriatovych.reductor.observable.rxjava2; public class Epics { private Epics() { } /** * Combine several Epics into one. * <p> * Returned streams will be merged with {@link Observable#merge(Iterable)} * * @param epics Epics to combine * @param <T> state type * @return Epic that will combine all provided epics behaviour */ public static <T> Epic<T> combineEpics(Iterable<Epic<T>> epics) { return (actions, store) -> Observable.fromIterable(epics) .flatMap(epic -> epic.run(actions, store)); } /** * Useful predicate to be used with {@link Observable#filter(Predicate)} in Epic implementation * to filter only actions with specific {@link Action#type} * * @param type Action type filtered * @return Predicate that will check if {@link Action#type} equals to specified type */
// Path: lib/src/main/java/com/yheriatovych/reductor/Action.java // public class Action { // public final String type; // public final Object[] values; // // /** // * Create Action object with specified type and values // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // */ // public Action(String type, Object[] values) { // this.type = type; // this.values = values; // } // // /** // * Create Action with defined type without any attached payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // */ // public Action(String type) { // this(type, new Object[0]); // } // // /** // * Factory method to create action with defined type and any number of attached values as payload // * // * @param type String type of action, will be used by {@link Reducer} for dispatch // * @param values any number of arbitrary objects that can be attached as payload to this action // * @return created Action // */ // public static Action create(String type, Object... values) { // return new Action(type, values); // } // // /** // * Returns action value at given position // * @param index value position // * @return value at position // */ // @SuppressWarnings("unchecked") // public <T> T getValue(int index) { // return (T) values[index]; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Action action = (Action) o; // // if (type != null ? !type.equals(action.type) : action.type != null) return false; // // Probably incorrect - comparing Object[] arrays with Arrays.equals // return Arrays.equals(values, action.values); // // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + Arrays.hashCode(values); // return result; // } // // @Override // public String toString() { // return "Action{" + // "type='" + type + '\'' + // ", values=" + Arrays.toString(values) + // '}'; // } // } // Path: reductor-observable-rxjava2/src/main/java/com/yheriatovych/reductor/observable/rxjava2/Epics.java import com.yheriatovych.reductor.Action; import io.reactivex.Observable; import io.reactivex.functions.Predicate; package com.yheriatovych.reductor.observable.rxjava2; public class Epics { private Epics() { } /** * Combine several Epics into one. * <p> * Returned streams will be merged with {@link Observable#merge(Iterable)} * * @param epics Epics to combine * @param <T> state type * @return Epic that will combine all provided epics behaviour */ public static <T> Epic<T> combineEpics(Iterable<Epic<T>> epics) { return (actions, store) -> Observable.fromIterable(epics) .flatMap(epic -> epic.run(actions, store)); } /** * Useful predicate to be used with {@link Observable#filter(Predicate)} in Epic implementation * to filter only actions with specific {@link Action#type} * * @param type Action type filtered * @return Predicate that will check if {@link Action#type} equals to specified type */
public static Predicate<Action> ofType(String type) {
Yarikx/reductor
compiller/src/test/java/com/yheriatovych/reductor/processor/ActionCreatorProcessingStepTest.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // }
import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
package com.yheriatovych.reductor.processor; public class ActionCreatorProcessingStepTest { @Test public void testGeneratedReducerForNoPayloadActionHandler() { JavaFileObject source = JavaFileObjects.forSourceString("test.Foobar", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Action;\n" + "import com.yheriatovych.reductor.annotations.ActionCreator;\n" + "\n" + "@ActionCreator\n" + "public interface Foobar {\n" + " @ActionCreator.Action(\"foobar\")\n" + " Action foobar();\n" + "}"); JavaFileObject generatedPojo = JavaFileObjects.forSourceString("test.Foobar_AutoImpl", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Action;\n" + "\n" + "public final class Foobar_AutoImpl implements Foobar {\n" + " @Override\n" + " public Action foobar() {\n" + " return Action.create(\"foobar\");\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // } // Path: compiller/src/test/java/com/yheriatovych/reductor/processor/ActionCreatorProcessingStepTest.java import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; package com.yheriatovych.reductor.processor; public class ActionCreatorProcessingStepTest { @Test public void testGeneratedReducerForNoPayloadActionHandler() { JavaFileObject source = JavaFileObjects.forSourceString("test.Foobar", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Action;\n" + "import com.yheriatovych.reductor.annotations.ActionCreator;\n" + "\n" + "@ActionCreator\n" + "public interface Foobar {\n" + " @ActionCreator.Action(\"foobar\")\n" + " Action foobar();\n" + "}"); JavaFileObject generatedPojo = JavaFileObjects.forSourceString("test.Foobar_AutoImpl", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "import com.yheriatovych.reductor.Action;\n" + "\n" + "public final class Foobar_AutoImpl implements Foobar {\n" + " @Override\n" + " public Action foobar() {\n" + " return Action.create(\"foobar\");\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
.processedWith(new ReductorAnnotationProcessor())
Yarikx/reductor
compiller/src/test/java/com/yheriatovych/reductor/processor/CombinedStateValidationTest.java
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // }
import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
" String bar();\n" + "}"); JavaFileObject generatedPojo = JavaFileObjects.forSourceString("test.Foobar", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "\n" + "public final class FoobarImpl implements Foobar {\n" + " private final int foo;\n" + "\n" + " private final String bar;\n" + "\n" + " public FoobarImpl(int foo, String bar) {\n" + " this.foo = foo;\n" + " this.bar = bar;\n" + " }\n" + "\n" + " @Override\n" + " public int foo() {\n" + " return foo;\n" + " }\n" + "\n" + " @Override\n" + " public String bar() {\n" + " return bar;\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
// Path: compiller/src/main/java/com/yheriatovych/reductor/processor/ReductorAnnotationProcessor.java // @AutoService(Processor.class) // public class ReductorAnnotationProcessor extends BasicAnnotationProcessor { // @Override // protected Iterable<? extends ProcessingStep> initSteps() { // Env env = new Env(processingEnv.getTypeUtils(), // processingEnv.getElementUtils(), // processingEnv.getMessager(), // processingEnv.getFiler()); // // Map<String, ActionCreatorElement> knownActionCreators = new HashMap<>(); // // return Arrays.asList( // new CombinedStateProcessingStep(env), // new ActionCreatorProcessingStep(env, knownActionCreators), // new AutoReducerProcessingStep(env, knownActionCreators) // ); // } // // @Override // public SourceVersion getSupportedSourceVersion() { // return SourceVersion.latestSupported(); // } // } // Path: compiller/src/test/java/com/yheriatovych/reductor/processor/CombinedStateValidationTest.java import com.google.testing.compile.JavaFileObjects; import com.yheriatovych.reductor.processor.ReductorAnnotationProcessor; import org.junit.Test; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; " String bar();\n" + "}"); JavaFileObject generatedPojo = JavaFileObjects.forSourceString("test.Foobar", "// Generated by com.yheriatovych.reductor.processor.ReductorAnnotationProcessor (https://github.com/Yarikx/reductor)\n" + "package test;" + "\n" + "\n" + "public final class FoobarImpl implements Foobar {\n" + " private final int foo;\n" + "\n" + " private final String bar;\n" + "\n" + " public FoobarImpl(int foo, String bar) {\n" + " this.foo = foo;\n" + " this.bar = bar;\n" + " }\n" + "\n" + " @Override\n" + " public int foo() {\n" + " return foo;\n" + " }\n" + "\n" + " @Override\n" + " public String bar() {\n" + " return bar;\n" + " }\n" + "}"); assertAbout(javaSource()).that(source) .withCompilerOptions("-Xlint:-processing")
.processedWith(new ReductorAnnotationProcessor())
AnujaK/restfiddle
src/main/java/com/restfiddle/controller/rest/ProjectController.java
// Path: src/main/java/com/restfiddle/dao/NodeRepository.java // public interface NodeRepository extends RfRepository<BaseNode, String> { // // @Query("{ 'parentId' : ?0 }") // public List<BaseNode> getChildren(String nodeId); // // @Query("{ 'projectId' : ?0 }") // public List<BaseNode> findNodesFromAProject(String projectId); // // @Query("{ 'projectId' : ?0 ,$or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public List<BaseNode> searchNodesFromAProject(String projectId, String search); // // @Query("{ 'projectId' : ?0 , nodeType : {$exists:false}, name : { $regex : ?1, $options: 'i' }} }") // public List<BaseNode> findRequestsFromAProject(String projectId, String search); // // @Query("{'workspaceId' : ?0, 'starred' : true , name : { $regex : ?1, $options: 'i'}}") // public Page<BaseNode> findStarredNodes(String workspaceId, String search, Pageable pageable); // // @Query("{ 'tags' : ?0 }") // public Page<BaseNode> findTaggedNodes(String tagId, Pageable pageable); // // @Query("{ 'tags' : ?0 , $or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public Page<BaseNode> searchTaggedNodes(String tagId, String search, Pageable pageable); // // @Query("{ 'workspaceId' : ?0, 'nodeType' : 'PROJECT', name : { $regex : ?1, $options: 'i'}}") // public List<BaseNode> findProjectsfromAWorkspace(String workspaceId, String search); // } // // Path: src/main/java/com/restfiddle/dao/ProjectRepository.java // public interface ProjectRepository extends RfRepository<Project, String> { // // // TODO : Implement me! // @Query("{ 'workspaceId' : '' }") // public List<Project> findProjectsFromAWorkspace(@Param("workspaceId") String workspaceId); // }
import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.restfiddle.constant.NodeType; import com.restfiddle.dao.NodeRepository; import com.restfiddle.dao.ProjectRepository; import com.restfiddle.dao.WorkspaceRepository; import com.restfiddle.dto.NodeDTO; import com.restfiddle.dto.ProjectDTO; import com.restfiddle.entity.BaseNode; import com.restfiddle.entity.Project; import com.restfiddle.entity.Workspace;
/* * Copyright 2014 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @EnableAutoConfiguration @ComponentScan @Transactional public class ProjectController { Logger logger = LoggerFactory.getLogger(ProjectController.class); @Resource private WorkspaceRepository workspaceRepository; @Resource
// Path: src/main/java/com/restfiddle/dao/NodeRepository.java // public interface NodeRepository extends RfRepository<BaseNode, String> { // // @Query("{ 'parentId' : ?0 }") // public List<BaseNode> getChildren(String nodeId); // // @Query("{ 'projectId' : ?0 }") // public List<BaseNode> findNodesFromAProject(String projectId); // // @Query("{ 'projectId' : ?0 ,$or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public List<BaseNode> searchNodesFromAProject(String projectId, String search); // // @Query("{ 'projectId' : ?0 , nodeType : {$exists:false}, name : { $regex : ?1, $options: 'i' }} }") // public List<BaseNode> findRequestsFromAProject(String projectId, String search); // // @Query("{'workspaceId' : ?0, 'starred' : true , name : { $regex : ?1, $options: 'i'}}") // public Page<BaseNode> findStarredNodes(String workspaceId, String search, Pageable pageable); // // @Query("{ 'tags' : ?0 }") // public Page<BaseNode> findTaggedNodes(String tagId, Pageable pageable); // // @Query("{ 'tags' : ?0 , $or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public Page<BaseNode> searchTaggedNodes(String tagId, String search, Pageable pageable); // // @Query("{ 'workspaceId' : ?0, 'nodeType' : 'PROJECT', name : { $regex : ?1, $options: 'i'}}") // public List<BaseNode> findProjectsfromAWorkspace(String workspaceId, String search); // } // // Path: src/main/java/com/restfiddle/dao/ProjectRepository.java // public interface ProjectRepository extends RfRepository<Project, String> { // // // TODO : Implement me! // @Query("{ 'workspaceId' : '' }") // public List<Project> findProjectsFromAWorkspace(@Param("workspaceId") String workspaceId); // } // Path: src/main/java/com/restfiddle/controller/rest/ProjectController.java import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.restfiddle.constant.NodeType; import com.restfiddle.dao.NodeRepository; import com.restfiddle.dao.ProjectRepository; import com.restfiddle.dao.WorkspaceRepository; import com.restfiddle.dto.NodeDTO; import com.restfiddle.dto.ProjectDTO; import com.restfiddle.entity.BaseNode; import com.restfiddle.entity.Project; import com.restfiddle.entity.Workspace; /* * Copyright 2014 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @EnableAutoConfiguration @ComponentScan @Transactional public class ProjectController { Logger logger = LoggerFactory.getLogger(ProjectController.class); @Resource private WorkspaceRepository workspaceRepository; @Resource
private ProjectRepository projectRepository;
AnujaK/restfiddle
src/main/java/com/restfiddle/controller/rest/ProjectController.java
// Path: src/main/java/com/restfiddle/dao/NodeRepository.java // public interface NodeRepository extends RfRepository<BaseNode, String> { // // @Query("{ 'parentId' : ?0 }") // public List<BaseNode> getChildren(String nodeId); // // @Query("{ 'projectId' : ?0 }") // public List<BaseNode> findNodesFromAProject(String projectId); // // @Query("{ 'projectId' : ?0 ,$or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public List<BaseNode> searchNodesFromAProject(String projectId, String search); // // @Query("{ 'projectId' : ?0 , nodeType : {$exists:false}, name : { $regex : ?1, $options: 'i' }} }") // public List<BaseNode> findRequestsFromAProject(String projectId, String search); // // @Query("{'workspaceId' : ?0, 'starred' : true , name : { $regex : ?1, $options: 'i'}}") // public Page<BaseNode> findStarredNodes(String workspaceId, String search, Pageable pageable); // // @Query("{ 'tags' : ?0 }") // public Page<BaseNode> findTaggedNodes(String tagId, Pageable pageable); // // @Query("{ 'tags' : ?0 , $or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public Page<BaseNode> searchTaggedNodes(String tagId, String search, Pageable pageable); // // @Query("{ 'workspaceId' : ?0, 'nodeType' : 'PROJECT', name : { $regex : ?1, $options: 'i'}}") // public List<BaseNode> findProjectsfromAWorkspace(String workspaceId, String search); // } // // Path: src/main/java/com/restfiddle/dao/ProjectRepository.java // public interface ProjectRepository extends RfRepository<Project, String> { // // // TODO : Implement me! // @Query("{ 'workspaceId' : '' }") // public List<Project> findProjectsFromAWorkspace(@Param("workspaceId") String workspaceId); // }
import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.restfiddle.constant.NodeType; import com.restfiddle.dao.NodeRepository; import com.restfiddle.dao.ProjectRepository; import com.restfiddle.dao.WorkspaceRepository; import com.restfiddle.dto.NodeDTO; import com.restfiddle.dto.ProjectDTO; import com.restfiddle.entity.BaseNode; import com.restfiddle.entity.Project; import com.restfiddle.entity.Workspace;
/* * Copyright 2014 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @EnableAutoConfiguration @ComponentScan @Transactional public class ProjectController { Logger logger = LoggerFactory.getLogger(ProjectController.class); @Resource private WorkspaceRepository workspaceRepository; @Resource private ProjectRepository projectRepository; @Resource
// Path: src/main/java/com/restfiddle/dao/NodeRepository.java // public interface NodeRepository extends RfRepository<BaseNode, String> { // // @Query("{ 'parentId' : ?0 }") // public List<BaseNode> getChildren(String nodeId); // // @Query("{ 'projectId' : ?0 }") // public List<BaseNode> findNodesFromAProject(String projectId); // // @Query("{ 'projectId' : ?0 ,$or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public List<BaseNode> searchNodesFromAProject(String projectId, String search); // // @Query("{ 'projectId' : ?0 , nodeType : {$exists:false}, name : { $regex : ?1, $options: 'i' }} }") // public List<BaseNode> findRequestsFromAProject(String projectId, String search); // // @Query("{'workspaceId' : ?0, 'starred' : true , name : { $regex : ?1, $options: 'i'}}") // public Page<BaseNode> findStarredNodes(String workspaceId, String search, Pageable pageable); // // @Query("{ 'tags' : ?0 }") // public Page<BaseNode> findTaggedNodes(String tagId, Pageable pageable); // // @Query("{ 'tags' : ?0 , $or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public Page<BaseNode> searchTaggedNodes(String tagId, String search, Pageable pageable); // // @Query("{ 'workspaceId' : ?0, 'nodeType' : 'PROJECT', name : { $regex : ?1, $options: 'i'}}") // public List<BaseNode> findProjectsfromAWorkspace(String workspaceId, String search); // } // // Path: src/main/java/com/restfiddle/dao/ProjectRepository.java // public interface ProjectRepository extends RfRepository<Project, String> { // // // TODO : Implement me! // @Query("{ 'workspaceId' : '' }") // public List<Project> findProjectsFromAWorkspace(@Param("workspaceId") String workspaceId); // } // Path: src/main/java/com/restfiddle/controller/rest/ProjectController.java import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.restfiddle.constant.NodeType; import com.restfiddle.dao.NodeRepository; import com.restfiddle.dao.ProjectRepository; import com.restfiddle.dao.WorkspaceRepository; import com.restfiddle.dto.NodeDTO; import com.restfiddle.dto.ProjectDTO; import com.restfiddle.entity.BaseNode; import com.restfiddle.entity.Project; import com.restfiddle.entity.Workspace; /* * Copyright 2014 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @EnableAutoConfiguration @ComponentScan @Transactional public class ProjectController { Logger logger = LoggerFactory.getLogger(ProjectController.class); @Resource private WorkspaceRepository workspaceRepository; @Resource private ProjectRepository projectRepository; @Resource
private NodeRepository nodeRepository;