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
|
---|---|---|---|---|---|---|
KoperGroup/koper | koper-demo/src/main/java/koper/demo/message/service/impl/MemberServiceImpl.java | // Path: koper-demo/src/main/java/koper/demo/message/entity/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phoneNo;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNo() {
// return phoneNo;
// }
//
// public void setPhoneNo(String phoneNo) {
// this.phoneNo = phoneNo;
// }
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/mapper/MemberMapper.java
// public interface MemberMapper {
//
// Integer createMember(Member member);
//
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/service/MemberService.java
// public interface MemberService {
//
// void signup(Member member);
//
// }
//
// Path: koper-core/src/main/java/koper/sender/MessageSender.java
// public interface MessageSender {
//
// void send(String topic, String msg);
//
// void send(String topic, String key, String msg);
//
// void send(String topic, Object msg);
//
// void send(String topic, String key, Object msg);
// }
| import koper.demo.message.entity.Member;
import koper.demo.message.mapper.MemberMapper;
import koper.demo.message.service.MemberService;
import koper.sender.MessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package koper.demo.message.service.impl;
/**
* @author caie
*/
@Service
public class MemberServiceImpl implements MemberService {
@Autowired | // Path: koper-demo/src/main/java/koper/demo/message/entity/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phoneNo;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNo() {
// return phoneNo;
// }
//
// public void setPhoneNo(String phoneNo) {
// this.phoneNo = phoneNo;
// }
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/mapper/MemberMapper.java
// public interface MemberMapper {
//
// Integer createMember(Member member);
//
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/service/MemberService.java
// public interface MemberService {
//
// void signup(Member member);
//
// }
//
// Path: koper-core/src/main/java/koper/sender/MessageSender.java
// public interface MessageSender {
//
// void send(String topic, String msg);
//
// void send(String topic, String key, String msg);
//
// void send(String topic, Object msg);
//
// void send(String topic, String key, Object msg);
// }
// Path: koper-demo/src/main/java/koper/demo/message/service/impl/MemberServiceImpl.java
import koper.demo.message.entity.Member;
import koper.demo.message.mapper.MemberMapper;
import koper.demo.message.service.MemberService;
import koper.sender.MessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package koper.demo.message.service.impl;
/**
* @author caie
*/
@Service
public class MemberServiceImpl implements MemberService {
@Autowired | private MemberMapper memberMapper; |
KoperGroup/koper | koper-demo/src/main/java/koper/demo/message/service/impl/MemberServiceImpl.java | // Path: koper-demo/src/main/java/koper/demo/message/entity/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phoneNo;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNo() {
// return phoneNo;
// }
//
// public void setPhoneNo(String phoneNo) {
// this.phoneNo = phoneNo;
// }
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/mapper/MemberMapper.java
// public interface MemberMapper {
//
// Integer createMember(Member member);
//
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/service/MemberService.java
// public interface MemberService {
//
// void signup(Member member);
//
// }
//
// Path: koper-core/src/main/java/koper/sender/MessageSender.java
// public interface MessageSender {
//
// void send(String topic, String msg);
//
// void send(String topic, String key, String msg);
//
// void send(String topic, Object msg);
//
// void send(String topic, String key, Object msg);
// }
| import koper.demo.message.entity.Member;
import koper.demo.message.mapper.MemberMapper;
import koper.demo.message.service.MemberService;
import koper.sender.MessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package koper.demo.message.service.impl;
/**
* @author caie
*/
@Service
public class MemberServiceImpl implements MemberService {
@Autowired
private MemberMapper memberMapper;
private static final String MEMBER_SIGNUP_TOPIC = "koper.demo.message.notifyMemberAfterSignup";
@Autowired | // Path: koper-demo/src/main/java/koper/demo/message/entity/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phoneNo;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNo() {
// return phoneNo;
// }
//
// public void setPhoneNo(String phoneNo) {
// this.phoneNo = phoneNo;
// }
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/mapper/MemberMapper.java
// public interface MemberMapper {
//
// Integer createMember(Member member);
//
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/service/MemberService.java
// public interface MemberService {
//
// void signup(Member member);
//
// }
//
// Path: koper-core/src/main/java/koper/sender/MessageSender.java
// public interface MessageSender {
//
// void send(String topic, String msg);
//
// void send(String topic, String key, String msg);
//
// void send(String topic, Object msg);
//
// void send(String topic, String key, Object msg);
// }
// Path: koper-demo/src/main/java/koper/demo/message/service/impl/MemberServiceImpl.java
import koper.demo.message.entity.Member;
import koper.demo.message.mapper.MemberMapper;
import koper.demo.message.service.MemberService;
import koper.sender.MessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package koper.demo.message.service.impl;
/**
* @author caie
*/
@Service
public class MemberServiceImpl implements MemberService {
@Autowired
private MemberMapper memberMapper;
private static final String MEMBER_SIGNUP_TOPIC = "koper.demo.message.notifyMemberAfterSignup";
@Autowired | private MessageSender messageSender; |
KoperGroup/koper | koper-demo/src/main/java/koper/demo/message/service/impl/MemberServiceImpl.java | // Path: koper-demo/src/main/java/koper/demo/message/entity/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phoneNo;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNo() {
// return phoneNo;
// }
//
// public void setPhoneNo(String phoneNo) {
// this.phoneNo = phoneNo;
// }
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/mapper/MemberMapper.java
// public interface MemberMapper {
//
// Integer createMember(Member member);
//
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/service/MemberService.java
// public interface MemberService {
//
// void signup(Member member);
//
// }
//
// Path: koper-core/src/main/java/koper/sender/MessageSender.java
// public interface MessageSender {
//
// void send(String topic, String msg);
//
// void send(String topic, String key, String msg);
//
// void send(String topic, Object msg);
//
// void send(String topic, String key, Object msg);
// }
| import koper.demo.message.entity.Member;
import koper.demo.message.mapper.MemberMapper;
import koper.demo.message.service.MemberService;
import koper.sender.MessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package koper.demo.message.service.impl;
/**
* @author caie
*/
@Service
public class MemberServiceImpl implements MemberService {
@Autowired
private MemberMapper memberMapper;
private static final String MEMBER_SIGNUP_TOPIC = "koper.demo.message.notifyMemberAfterSignup";
@Autowired
private MessageSender messageSender;
| // Path: koper-demo/src/main/java/koper/demo/message/entity/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phoneNo;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNo() {
// return phoneNo;
// }
//
// public void setPhoneNo(String phoneNo) {
// this.phoneNo = phoneNo;
// }
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/mapper/MemberMapper.java
// public interface MemberMapper {
//
// Integer createMember(Member member);
//
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/service/MemberService.java
// public interface MemberService {
//
// void signup(Member member);
//
// }
//
// Path: koper-core/src/main/java/koper/sender/MessageSender.java
// public interface MessageSender {
//
// void send(String topic, String msg);
//
// void send(String topic, String key, String msg);
//
// void send(String topic, Object msg);
//
// void send(String topic, String key, Object msg);
// }
// Path: koper-demo/src/main/java/koper/demo/message/service/impl/MemberServiceImpl.java
import koper.demo.message.entity.Member;
import koper.demo.message.mapper.MemberMapper;
import koper.demo.message.service.MemberService;
import koper.sender.MessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package koper.demo.message.service.impl;
/**
* @author caie
*/
@Service
public class MemberServiceImpl implements MemberService {
@Autowired
private MemberMapper memberMapper;
private static final String MEMBER_SIGNUP_TOPIC = "koper.demo.message.notifyMemberAfterSignup";
@Autowired
private MessageSender messageSender;
| public void signup(Member member) { |
KoperGroup/koper | koper-demo/src/main/java/koper/demo/message/mapper/impl/MemberMapperImpl.java | // Path: koper-demo/src/main/java/koper/demo/message/entity/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phoneNo;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNo() {
// return phoneNo;
// }
//
// public void setPhoneNo(String phoneNo) {
// this.phoneNo = phoneNo;
// }
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/mapper/MemberMapper.java
// public interface MemberMapper {
//
// Integer createMember(Member member);
//
// }
| import koper.demo.message.entity.Member;
import koper.demo.message.mapper.MemberMapper;
import org.springframework.stereotype.Repository; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.demo.message.mapper.impl;
/**
* @author caie
* @since 1.2
*/
@Repository
public class MemberMapperImpl implements MemberMapper {
@Override | // Path: koper-demo/src/main/java/koper/demo/message/entity/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phoneNo;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNo() {
// return phoneNo;
// }
//
// public void setPhoneNo(String phoneNo) {
// this.phoneNo = phoneNo;
// }
// }
//
// Path: koper-demo/src/main/java/koper/demo/message/mapper/MemberMapper.java
// public interface MemberMapper {
//
// Integer createMember(Member member);
//
// }
// Path: koper-demo/src/main/java/koper/demo/message/mapper/impl/MemberMapperImpl.java
import koper.demo.message.entity.Member;
import koper.demo.message.mapper.MemberMapper;
import org.springframework.stereotype.Repository;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.demo.message.mapper.impl;
/**
* @author caie
* @since 1.2
*/
@Repository
public class MemberMapperImpl implements MemberMapper {
@Override | public Integer createMember(Member member) { |
KoperGroup/koper | koper-testcase/src/test/java/koper/kafka/KafkaSenderTest.java | // Path: koper-testcase/src/main/java/koper/demo/trading/mapper/Order.java
// public class Order {
//
// public String orderId;
// public String orderName;
// public Date createDate;
// public String memberId;
// public BigDecimal totalPrice;
//
// public String getOrderId() {
// return orderId;
// }
// public void setOrderId(String orderId) {
// this.orderId = orderId;
// }
// public String getOrderName() {
// return orderName;
// }
// public void setOrderName(String orderName) {
// this.orderName = orderName;
// }
// public Date getCreateDate() {
// return createDate;
// }
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
// public String getMemberId() {
// return memberId;
// }
// public void setMemberId(String memberId) {
// this.memberId = memberId;
// }
// public BigDecimal getTotalPrice() {
// return totalPrice;
// }
// public void setTotalPrice(BigDecimal totalPrice) {
// this.totalPrice = totalPrice;
// }
//
// @Override
// public String toString() {
// return "Order{" +
// "orderId='" + orderId + '\'' +
// ", orderName='" + orderName + '\'' +
// ", createDate=" + createDate +
// ", memberId='" + memberId + '\'' +
// ", totalPrice=" + totalPrice +
// '}';
// }
// }
//
// Path: koper-core/src/main/java/koper/sender/MessageSender.java
// public interface MessageSender {
//
// void send(String topic, String msg);
//
// void send(String topic, String key, String msg);
//
// void send(String topic, Object msg);
//
// void send(String topic, String key, Object msg);
// }
| import junit.textui.TestRunner;
import koper.demo.trading.mapper.Order;
import koper.sender.MessageSender;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import java.math.BigDecimal;
import java.util.Date; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.kafka;
/**
* @author kk
* @since 1.0
*/
public class KafkaSenderTest extends AbstractDependencyInjectionSpringContextTests {
private MessageSender messageSender;
public void setMessageSender(MessageSender messageSender) {
this.messageSender = messageSender;
}
@Override
protected String[] getConfigLocations() {
return new String[]{"classpath:kafka/context-data-producer.xml"};
}
/**
* 测试,发10条消息。
* 调用 messageSender.send(topic2, msg) 发送消息
*/
public void test() throws Exception {
String topic2 = "XXXXX";
String msgBase2 = "orderId_";
for (int i = 0; i < 100; i++) {
String key = msgBase2 + i + "_" + System.currentTimeMillis();
String msg = key;
messageSender.send(topic2, msg);
}
// async 模式,需要等待消息发送完毕
//Thread.sleep(10 * 1000);
}
public static void main(String[] args) {
TestRunner.run(KafkaSenderTest.class);
}
public void testSendOrderMsg() {
String orderTopic = "zhaimi.orderListener";
String demoTopic = "XXXXX";
String msg = "123";
messageSender.send(demoTopic, msg);
// messageSender.send(orderTopic, msg);
| // Path: koper-testcase/src/main/java/koper/demo/trading/mapper/Order.java
// public class Order {
//
// public String orderId;
// public String orderName;
// public Date createDate;
// public String memberId;
// public BigDecimal totalPrice;
//
// public String getOrderId() {
// return orderId;
// }
// public void setOrderId(String orderId) {
// this.orderId = orderId;
// }
// public String getOrderName() {
// return orderName;
// }
// public void setOrderName(String orderName) {
// this.orderName = orderName;
// }
// public Date getCreateDate() {
// return createDate;
// }
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
// public String getMemberId() {
// return memberId;
// }
// public void setMemberId(String memberId) {
// this.memberId = memberId;
// }
// public BigDecimal getTotalPrice() {
// return totalPrice;
// }
// public void setTotalPrice(BigDecimal totalPrice) {
// this.totalPrice = totalPrice;
// }
//
// @Override
// public String toString() {
// return "Order{" +
// "orderId='" + orderId + '\'' +
// ", orderName='" + orderName + '\'' +
// ", createDate=" + createDate +
// ", memberId='" + memberId + '\'' +
// ", totalPrice=" + totalPrice +
// '}';
// }
// }
//
// Path: koper-core/src/main/java/koper/sender/MessageSender.java
// public interface MessageSender {
//
// void send(String topic, String msg);
//
// void send(String topic, String key, String msg);
//
// void send(String topic, Object msg);
//
// void send(String topic, String key, Object msg);
// }
// Path: koper-testcase/src/test/java/koper/kafka/KafkaSenderTest.java
import junit.textui.TestRunner;
import koper.demo.trading.mapper.Order;
import koper.sender.MessageSender;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import java.math.BigDecimal;
import java.util.Date;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.kafka;
/**
* @author kk
* @since 1.0
*/
public class KafkaSenderTest extends AbstractDependencyInjectionSpringContextTests {
private MessageSender messageSender;
public void setMessageSender(MessageSender messageSender) {
this.messageSender = messageSender;
}
@Override
protected String[] getConfigLocations() {
return new String[]{"classpath:kafka/context-data-producer.xml"};
}
/**
* 测试,发10条消息。
* 调用 messageSender.send(topic2, msg) 发送消息
*/
public void test() throws Exception {
String topic2 = "XXXXX";
String msgBase2 = "orderId_";
for (int i = 0; i < 100; i++) {
String key = msgBase2 + i + "_" + System.currentTimeMillis();
String msg = key;
messageSender.send(topic2, msg);
}
// async 模式,需要等待消息发送完毕
//Thread.sleep(10 * 1000);
}
public static void main(String[] args) {
TestRunner.run(KafkaSenderTest.class);
}
public void testSendOrderMsg() {
String orderTopic = "zhaimi.orderListener";
String demoTopic = "XXXXX";
String msg = "123";
messageSender.send(demoTopic, msg);
// messageSender.send(orderTopic, msg);
| Order order = new Order(); |
KoperGroup/koper | koper-testcase/src/test/java/koper/kafka/KafkaBatchSenderTest.java | // Path: koper-testcase/src/main/java/koper/demo/trading/mapper/Order.java
// public class Order {
//
// public String orderId;
// public String orderName;
// public Date createDate;
// public String memberId;
// public BigDecimal totalPrice;
//
// public String getOrderId() {
// return orderId;
// }
// public void setOrderId(String orderId) {
// this.orderId = orderId;
// }
// public String getOrderName() {
// return orderName;
// }
// public void setOrderName(String orderName) {
// this.orderName = orderName;
// }
// public Date getCreateDate() {
// return createDate;
// }
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
// public String getMemberId() {
// return memberId;
// }
// public void setMemberId(String memberId) {
// this.memberId = memberId;
// }
// public BigDecimal getTotalPrice() {
// return totalPrice;
// }
// public void setTotalPrice(BigDecimal totalPrice) {
// this.totalPrice = totalPrice;
// }
//
// @Override
// public String toString() {
// return "Order{" +
// "orderId='" + orderId + '\'' +
// ", orderName='" + orderName + '\'' +
// ", createDate=" + createDate +
// ", memberId='" + memberId + '\'' +
// ", totalPrice=" + totalPrice +
// '}';
// }
// }
//
// Path: koper-testcase/src/main/java/koper/demo/trading/mapper/OrderMapper.java
// public interface OrderMapper {
//
// String getOrder(String orderId, Order order);
//
// String cancelOrder(Order order);
//
// String createOrder(String memberId, Order order);
//
// String updateOrder(Order order);
//
// String insertOrder(Order order);
//
// /**
// * @param orderId
// * @param order
// * @return
// */
// String deleteOrder(String orderId, Order order);
//
// String deleteOldOrder(int orderId, boolean reserve);
//
// String cancelOldOrder(Order order);
// }
| import koper.demo.trading.mapper.Order;
import koper.demo.trading.mapper.OrderMapper;
import junit.textui.TestRunner;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.kafka;
/**
* KafkaBatchSenderTest
*
* @author kk [email protected]
* @since 1.0
* 2016年3月25日
*/
public class KafkaBatchSenderTest extends AbstractDependencyInjectionSpringContextTests {
private OrderMapper orderMapper;
/**
* @param orderMapper the orderMapper to set
*/
public void setOrderMapper(OrderMapper orderMapper) {
this.orderMapper = orderMapper;
}
@Override
protected String[] getConfigLocations() {
return new String[]{
"classpath:kafka/context-data-message.xml",
"classpath:kafka/context-data-producer.xml"
};
}
| // Path: koper-testcase/src/main/java/koper/demo/trading/mapper/Order.java
// public class Order {
//
// public String orderId;
// public String orderName;
// public Date createDate;
// public String memberId;
// public BigDecimal totalPrice;
//
// public String getOrderId() {
// return orderId;
// }
// public void setOrderId(String orderId) {
// this.orderId = orderId;
// }
// public String getOrderName() {
// return orderName;
// }
// public void setOrderName(String orderName) {
// this.orderName = orderName;
// }
// public Date getCreateDate() {
// return createDate;
// }
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
// public String getMemberId() {
// return memberId;
// }
// public void setMemberId(String memberId) {
// this.memberId = memberId;
// }
// public BigDecimal getTotalPrice() {
// return totalPrice;
// }
// public void setTotalPrice(BigDecimal totalPrice) {
// this.totalPrice = totalPrice;
// }
//
// @Override
// public String toString() {
// return "Order{" +
// "orderId='" + orderId + '\'' +
// ", orderName='" + orderName + '\'' +
// ", createDate=" + createDate +
// ", memberId='" + memberId + '\'' +
// ", totalPrice=" + totalPrice +
// '}';
// }
// }
//
// Path: koper-testcase/src/main/java/koper/demo/trading/mapper/OrderMapper.java
// public interface OrderMapper {
//
// String getOrder(String orderId, Order order);
//
// String cancelOrder(Order order);
//
// String createOrder(String memberId, Order order);
//
// String updateOrder(Order order);
//
// String insertOrder(Order order);
//
// /**
// * @param orderId
// * @param order
// * @return
// */
// String deleteOrder(String orderId, Order order);
//
// String deleteOldOrder(int orderId, boolean reserve);
//
// String cancelOldOrder(Order order);
// }
// Path: koper-testcase/src/test/java/koper/kafka/KafkaBatchSenderTest.java
import koper.demo.trading.mapper.Order;
import koper.demo.trading.mapper.OrderMapper;
import junit.textui.TestRunner;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.kafka;
/**
* KafkaBatchSenderTest
*
* @author kk [email protected]
* @since 1.0
* 2016年3月25日
*/
public class KafkaBatchSenderTest extends AbstractDependencyInjectionSpringContextTests {
private OrderMapper orderMapper;
/**
* @param orderMapper the orderMapper to set
*/
public void setOrderMapper(OrderMapper orderMapper) {
this.orderMapper = orderMapper;
}
@Override
protected String[] getConfigLocations() {
return new String[]{
"classpath:kafka/context-data-message.xml",
"classpath:kafka/context-data-producer.xml"
};
}
| private Order newOrder(int i) { |
KoperGroup/koper | koper-dataevent/src/main/java/koper/event/DataEvent.java | // Path: koper-core/src/main/java/koper/MsgBean.java
// public class MsgBean<K, V> implements Serializable {
//
// private static final long serialVersionUID = -4387811273059946901L;
//
// private String topic;
// private K key;
// private V value;
// private String valueType;
//
// private Date produceTime;
// private String produceIP;
// private long producePid;
// private long produceTid;
//
// private Date receiveTime;
// private Date consumeTime;
// private String cosumerIP;
// private long consumerPid;
// private long cosumerTid;
//
// public String getTopic() {
// return topic;
// }
//
// public void setTopic(String topic) {
// this.topic = topic;
// }
//
// public K getKey() {
// return key;
// }
//
// public void setKey(K key) {
// this.key = key;
// }
//
// public V getValue() {
// return value;
// }
//
// public void setValue(V value) {
// this.value = value;
// }
//
// public String getValueType() {
// return valueType;
// }
//
// public void setValueType(String valueType) {
// this.valueType = valueType;
// }
//
// public Date getProduceTime() {
// return produceTime;
// }
//
// public void setProduceTime(Date produceTime) {
// this.produceTime = produceTime;
// }
//
// /**
// * @param receiveTime the receiveTime to set
// */
// public void setReceiveTime(Date receiveTime) {
// this.receiveTime = receiveTime;
// }
//
// /**
// * @return the receiveTime
// */
// public Date getReceiveTime() {
// return receiveTime;
// }
//
// public Date getConsumeTime() {
// return consumeTime;
// }
//
// public void setConsumeTime(Date consumeTime) {
// this.consumeTime = consumeTime;
// }
//
//
// public String getProduceIP() {
// return produceIP;
// }
//
// public void setProduceIP(String produceIP) {
// this.produceIP = produceIP;
// }
//
// public long getProducePid() {
// return producePid;
// }
//
// public void setProducePid(long producePid) {
// this.producePid = producePid;
// }
//
// public long getProduceTid() {
// return produceTid;
// }
//
// public void setProduceTid(long produceTid) {
// this.produceTid = produceTid;
// }
//
// public String getConsumerIP() {
// return cosumerIP;
// }
//
// public void setConsumerIP(String cosumerIP) {
// this.cosumerIP = cosumerIP;
// }
//
// public long getConsumerPid() {
// return consumerPid;
// }
//
// public void setConsumerPid(long ccosumerPid) {
// this.consumerPid = ccosumerPid;
// }
//
// public long getConsumerTid() {
// return cosumerTid;
// }
//
// public void setConsumerTid(long cosumerTid) {
// this.cosumerTid = cosumerTid;
// }
//
// public long getReceiveUseTime() {
// return consumeTime == null || produceTime == null ? -1 : receiveTime.getTime() - produceTime.getTime();
// }
//
// public long getConsumeUseTime() {
// return consumeTime == null || produceTime == null ? -1 : consumeTime.getTime() - produceTime.getTime();
// }
//
// @Override
// public boolean equals(Object obj) {
// //TODO:待实现
// return super.equals(obj);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
//
// }
| import koper.MsgBean;
import java.util.List; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.event;
/**
* DataEvent.
* 数据事件。封装Event和数据消息内容。
*
* @author kk [email protected]
* @since 1.0
* 2016年2月19日
*/
public interface DataEvent {
void setException(String exception);
String getException();
void setResult(Object result);
Object getResult();
void setArgs(List<?> args);
List<?> getArgs();
| // Path: koper-core/src/main/java/koper/MsgBean.java
// public class MsgBean<K, V> implements Serializable {
//
// private static final long serialVersionUID = -4387811273059946901L;
//
// private String topic;
// private K key;
// private V value;
// private String valueType;
//
// private Date produceTime;
// private String produceIP;
// private long producePid;
// private long produceTid;
//
// private Date receiveTime;
// private Date consumeTime;
// private String cosumerIP;
// private long consumerPid;
// private long cosumerTid;
//
// public String getTopic() {
// return topic;
// }
//
// public void setTopic(String topic) {
// this.topic = topic;
// }
//
// public K getKey() {
// return key;
// }
//
// public void setKey(K key) {
// this.key = key;
// }
//
// public V getValue() {
// return value;
// }
//
// public void setValue(V value) {
// this.value = value;
// }
//
// public String getValueType() {
// return valueType;
// }
//
// public void setValueType(String valueType) {
// this.valueType = valueType;
// }
//
// public Date getProduceTime() {
// return produceTime;
// }
//
// public void setProduceTime(Date produceTime) {
// this.produceTime = produceTime;
// }
//
// /**
// * @param receiveTime the receiveTime to set
// */
// public void setReceiveTime(Date receiveTime) {
// this.receiveTime = receiveTime;
// }
//
// /**
// * @return the receiveTime
// */
// public Date getReceiveTime() {
// return receiveTime;
// }
//
// public Date getConsumeTime() {
// return consumeTime;
// }
//
// public void setConsumeTime(Date consumeTime) {
// this.consumeTime = consumeTime;
// }
//
//
// public String getProduceIP() {
// return produceIP;
// }
//
// public void setProduceIP(String produceIP) {
// this.produceIP = produceIP;
// }
//
// public long getProducePid() {
// return producePid;
// }
//
// public void setProducePid(long producePid) {
// this.producePid = producePid;
// }
//
// public long getProduceTid() {
// return produceTid;
// }
//
// public void setProduceTid(long produceTid) {
// this.produceTid = produceTid;
// }
//
// public String getConsumerIP() {
// return cosumerIP;
// }
//
// public void setConsumerIP(String cosumerIP) {
// this.cosumerIP = cosumerIP;
// }
//
// public long getConsumerPid() {
// return consumerPid;
// }
//
// public void setConsumerPid(long ccosumerPid) {
// this.consumerPid = ccosumerPid;
// }
//
// public long getConsumerTid() {
// return cosumerTid;
// }
//
// public void setConsumerTid(long cosumerTid) {
// this.cosumerTid = cosumerTid;
// }
//
// public long getReceiveUseTime() {
// return consumeTime == null || produceTime == null ? -1 : receiveTime.getTime() - produceTime.getTime();
// }
//
// public long getConsumeUseTime() {
// return consumeTime == null || produceTime == null ? -1 : consumeTime.getTime() - produceTime.getTime();
// }
//
// @Override
// public boolean equals(Object obj) {
// //TODO:待实现
// return super.equals(obj);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
//
// }
// Path: koper-dataevent/src/main/java/koper/event/DataEvent.java
import koper.MsgBean;
import java.util.List;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.event;
/**
* DataEvent.
* 数据事件。封装Event和数据消息内容。
*
* @author kk [email protected]
* @since 1.0
* 2016年2月19日
*/
public interface DataEvent {
void setException(String exception);
String getException();
void setResult(Object result);
Object getResult();
void setArgs(List<?> args);
List<?> getArgs();
| void setMsgBean(MsgBean<String, String> msgBean); |
KoperGroup/koper | koper-testcase/src/test/java/koper/kafka/databind/DataEventDataBindTestCase.java | // Path: koper-testcase/src/main/java/koper/demo/member/mapper/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phone;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// @Override
// public String toString() {
// return "Member{" +
// "id=" + id +
// ", name='" + name + '\'' +
// ", phone='" + phone + '\'' +
// '}';
// }
// }
//
// Path: koper-testcase/src/main/java/koper/demo/member/mapper/MemberMapper.java
// public interface MemberMapper {
//
// String insertMember(Integer id, String name, String phone);
//
// String cancelMember(Integer id, Member member);
//
// String deleteMember(Integer id, String name);
//
// String updateMember(Double id, Long name, BigDecimal account);
//
// String insertWithFloatAndShortAndByteAndChar(Float fl, Short s, Byte b, Character c);
//
// String deleteWithIntegerAndStringAndDataEvent(Integer id, String name);
//
//
// }
| import koper.demo.member.mapper.Member;
import koper.demo.member.mapper.MemberMapper;
import org.junit.Test;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import java.math.BigDecimal; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.kafka.databind;
/**
* 对应的 Listener 为 MemberListener
*
* @author caie
* @since 1.2
* 2016年8月5日
*/
public class DataEventDataBindTestCase extends AbstractDependencyInjectionSpringContextTests {
private MemberMapper memberMapper;
public void setOrderMapper(MemberMapper memberMapper) {
this.memberMapper = memberMapper;
}
@Override
protected String[] getConfigLocations() {
return new String[]{"kafka/context-data-message.xml",
"kafka/context-data-producer.xml"
};
}
@Test
public void testInsertMember() {
final Integer id = 1;
final String name = "test_name";
final String phone = "15397300000";
memberMapper.insertMember(id, name, phone);
}
@Test
public void testCancelMember() {
final Integer id = 1; | // Path: koper-testcase/src/main/java/koper/demo/member/mapper/Member.java
// public class Member {
//
// private Integer id;
//
// private String name;
//
// private String phone;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// @Override
// public String toString() {
// return "Member{" +
// "id=" + id +
// ", name='" + name + '\'' +
// ", phone='" + phone + '\'' +
// '}';
// }
// }
//
// Path: koper-testcase/src/main/java/koper/demo/member/mapper/MemberMapper.java
// public interface MemberMapper {
//
// String insertMember(Integer id, String name, String phone);
//
// String cancelMember(Integer id, Member member);
//
// String deleteMember(Integer id, String name);
//
// String updateMember(Double id, Long name, BigDecimal account);
//
// String insertWithFloatAndShortAndByteAndChar(Float fl, Short s, Byte b, Character c);
//
// String deleteWithIntegerAndStringAndDataEvent(Integer id, String name);
//
//
// }
// Path: koper-testcase/src/test/java/koper/kafka/databind/DataEventDataBindTestCase.java
import koper.demo.member.mapper.Member;
import koper.demo.member.mapper.MemberMapper;
import org.junit.Test;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import java.math.BigDecimal;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.kafka.databind;
/**
* 对应的 Listener 为 MemberListener
*
* @author caie
* @since 1.2
* 2016年8月5日
*/
public class DataEventDataBindTestCase extends AbstractDependencyInjectionSpringContextTests {
private MemberMapper memberMapper;
public void setOrderMapper(MemberMapper memberMapper) {
this.memberMapper = memberMapper;
}
@Override
protected String[] getConfigLocations() {
return new String[]{"kafka/context-data-message.xml",
"kafka/context-data-producer.xml"
};
}
@Test
public void testInsertMember() {
final Integer id = 1;
final String name = "test_name";
final String phone = "15397300000";
memberMapper.insertMember(id, name, phone);
}
@Test
public void testCancelMember() {
final Integer id = 1; | Member member = new Member(); |
KoperGroup/koper | koper-testcase/src/main/java/koper/event/InsertOrderListener.java | // Path: koper-testcase/src/main/java/koper/demo/trading/mapper/Order.java
// public class Order {
//
// public String orderId;
// public String orderName;
// public Date createDate;
// public String memberId;
// public BigDecimal totalPrice;
//
// public String getOrderId() {
// return orderId;
// }
// public void setOrderId(String orderId) {
// this.orderId = orderId;
// }
// public String getOrderName() {
// return orderName;
// }
// public void setOrderName(String orderName) {
// this.orderName = orderName;
// }
// public Date getCreateDate() {
// return createDate;
// }
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
// public String getMemberId() {
// return memberId;
// }
// public void setMemberId(String memberId) {
// this.memberId = memberId;
// }
// public BigDecimal getTotalPrice() {
// return totalPrice;
// }
// public void setTotalPrice(BigDecimal totalPrice) {
// this.totalPrice = totalPrice;
// }
//
// @Override
// public String toString() {
// return "Order{" +
// "orderId='" + orderId + '\'' +
// ", orderName='" + orderName + '\'' +
// ", createDate=" + createDate +
// ", memberId='" + memberId + '\'' +
// ", totalPrice=" + totalPrice +
// '}';
// }
// }
| import com.alibaba.fastjson.JSON;
import koper.demo.trading.mapper.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.event;
/**
* InsertOrderListener. 订单日志监听器
*
* @author kk [email protected]
* @since 1.0
* 2016年3月21日
*/
@Component
@DataListener(dataObject = "com.zhaimi.koper.demo.trading.mapper.impl.OrderMapperImpl")
public class InsertOrderListener {
private static Logger log = LoggerFactory.getLogger(InsertOrderListener.class);
public static AtomicInteger counter = new AtomicInteger();
public static long start;
public static long end;
public ReentrantLock lock = new ReentrantLock();
public Condition condition = lock.newCondition();
/**
* onInsertOrder事件响应处理方法
* 从event中获取数据:输入参数args,返回值 result。
* 数据格式为JSON。使用 fastjson工具类 进行解析
*
* @param event
*/
public void onInsertOrder(DataEvent event) {
if (start == 0)
start = new Date().getTime();
List<?> args = event.getArgs();
//数据解析:需要根据生产接口定义的参数个数,数据类型进行解析
//根据定义,第一个参数类型为 Order 类型 | // Path: koper-testcase/src/main/java/koper/demo/trading/mapper/Order.java
// public class Order {
//
// public String orderId;
// public String orderName;
// public Date createDate;
// public String memberId;
// public BigDecimal totalPrice;
//
// public String getOrderId() {
// return orderId;
// }
// public void setOrderId(String orderId) {
// this.orderId = orderId;
// }
// public String getOrderName() {
// return orderName;
// }
// public void setOrderName(String orderName) {
// this.orderName = orderName;
// }
// public Date getCreateDate() {
// return createDate;
// }
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
// public String getMemberId() {
// return memberId;
// }
// public void setMemberId(String memberId) {
// this.memberId = memberId;
// }
// public BigDecimal getTotalPrice() {
// return totalPrice;
// }
// public void setTotalPrice(BigDecimal totalPrice) {
// this.totalPrice = totalPrice;
// }
//
// @Override
// public String toString() {
// return "Order{" +
// "orderId='" + orderId + '\'' +
// ", orderName='" + orderName + '\'' +
// ", createDate=" + createDate +
// ", memberId='" + memberId + '\'' +
// ", totalPrice=" + totalPrice +
// '}';
// }
// }
// Path: koper-testcase/src/main/java/koper/event/InsertOrderListener.java
import com.alibaba.fastjson.JSON;
import koper.demo.trading.mapper.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.event;
/**
* InsertOrderListener. 订单日志监听器
*
* @author kk [email protected]
* @since 1.0
* 2016年3月21日
*/
@Component
@DataListener(dataObject = "com.zhaimi.koper.demo.trading.mapper.impl.OrderMapperImpl")
public class InsertOrderListener {
private static Logger log = LoggerFactory.getLogger(InsertOrderListener.class);
public static AtomicInteger counter = new AtomicInteger();
public static long start;
public static long end;
public ReentrantLock lock = new ReentrantLock();
public Condition condition = lock.newCondition();
/**
* onInsertOrder事件响应处理方法
* 从event中获取数据:输入参数args,返回值 result。
* 数据格式为JSON。使用 fastjson工具类 进行解析
*
* @param event
*/
public void onInsertOrder(DataEvent event) {
if (start == 0)
start = new Date().getTime();
List<?> args = event.getArgs();
//数据解析:需要根据生产接口定义的参数个数,数据类型进行解析
//根据定义,第一个参数类型为 Order 类型 | Order order = JSON.parseObject(args.get(0).toString(), Order.class); |
KoperGroup/koper | koper-dataevent/src/main/java/koper/event/DataEventListenerPostProcessor.java | // Path: koper-core/src/main/java/koper/MessageListenerBeanPostProcessor.java
// public class MessageListenerBeanPostProcessor implements BeanPostProcessor {
//
// private static final Logger log = LoggerFactory.getLogger(MessageListenerBeanPostProcessor.class);
//
// @Autowired
// private ConsumerLauncher consumerLauncher;
//
//
// @Override
// public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// return bean;
// }
//
// /**
// * Find and register message listeners.
// */
// @Override
// public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//
// if (bean instanceof MsgBeanListener) {
// log.info("*** MsgBeanListener found:" + bean);
// registerMsgBeanListener((MsgBeanListener) bean);
// } else if (bean.getClass().getAnnotation(Listen.class) != null) {
// // pojo listener
// final Listen listenAnnotation = bean.getClass().getAnnotation(Listen.class);
// final String topic = listenAnnotation.topic();
// if (StringUtils.isBlank(topic)) {
// throw new RuntimeException(
// String.format("class %s, @Listen annotation topic not specified, please check", bean)
// );
// } else {
// registerListener(bean, topic);
// }
// }
// return bean;
// }
//
// /**
// * 注册消息监听器
// *
// * @param listener
// */
// protected void registerMsgBeanListener(MsgBeanListener listener) {
//
// Class<?> clazz = listener.getClass();
// Method method;
// String topic = null;
// Listen listen;
// method = getMethod(clazz, "onMsgBean");
// listen = method == null ? null : method.getAnnotation(Listen.class);
//
// if (listen == null) {
// // 先拿类上的 Listen 注解, 没有再拿方法上的Listen
// final Listen clazzAnnotation = ReflectUtil.getListenAnnotation(clazz);
// if (clazzAnnotation == null) {
// method = getMethod(clazz, "onMessage");
// listen = method == null ? null : method.getAnnotation(Listen.class);
// } else {
// listen = clazzAnnotation;
// }
// }
//
// if (listen == null) {
// log.info("Tip>>> Topic not specified! @Listen annotation not declared on event method 'onMessage or onMsgBean' of bean " + listener);
// } else {
// topic = listen.topic();
// }
//
// registerListener(listener, topic);
// }
//
// /**
// * registerListener to registry.
// *
// * @param listener
// * @param topic
// */
// protected void registerListener(Object listener, String topic) {
// if (StringUtils.isNotBlank(topic)) {
// consumerLauncher.getListenerRegistry().register(topic, listener);
// log.info("注册监听器 Register listener '{}' on topic '{}'", listener, topic);
// }
// }
//
// /**
// * 获取第一个方法
// *
// * @param clazz
// * @param methodName
// * @return
// */
// protected Method getMethod(Class<?> clazz, String methodName) {
//
// Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz); //clazz.getDeclaredMethods();
// Method findMethod = null;
// for (Method method : methods) {
// if (method.getName().equals(methodName)
// && method.getAnnotations().length != 0) {
// findMethod = method;
// }
// }
// return findMethod;
// }
// }
//
// Path: koper-core/src/main/java/koper/MsgBeanListener.java
// public interface MsgBeanListener {
// /**
// * @see MessageListener#onMessage(java.lang.String)
// */
// public void onMsgBean(MsgBean<String, String> msgBean);
//
// }
| import koper.Listen;
import koper.MessageListenerBeanPostProcessor;
import koper.MsgBeanListener;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.event;
/**
* DataEventListenerPostProcessor
*
* @author kk [email protected]
* @since 1.0
* 2016年2月19日
*/
public class DataEventListenerPostProcessor extends MessageListenerBeanPostProcessor {
/**
* bean初始化后注册DataEvent数据时间监听器
*
* @see MessageListenerBeanPostProcessor#postProcessAfterInitialization(Object, String)
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Object bean0 = bean;
final Listen listenAnnotation = bean.getClass().getAnnotation(Listen.class); | // Path: koper-core/src/main/java/koper/MessageListenerBeanPostProcessor.java
// public class MessageListenerBeanPostProcessor implements BeanPostProcessor {
//
// private static final Logger log = LoggerFactory.getLogger(MessageListenerBeanPostProcessor.class);
//
// @Autowired
// private ConsumerLauncher consumerLauncher;
//
//
// @Override
// public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// return bean;
// }
//
// /**
// * Find and register message listeners.
// */
// @Override
// public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//
// if (bean instanceof MsgBeanListener) {
// log.info("*** MsgBeanListener found:" + bean);
// registerMsgBeanListener((MsgBeanListener) bean);
// } else if (bean.getClass().getAnnotation(Listen.class) != null) {
// // pojo listener
// final Listen listenAnnotation = bean.getClass().getAnnotation(Listen.class);
// final String topic = listenAnnotation.topic();
// if (StringUtils.isBlank(topic)) {
// throw new RuntimeException(
// String.format("class %s, @Listen annotation topic not specified, please check", bean)
// );
// } else {
// registerListener(bean, topic);
// }
// }
// return bean;
// }
//
// /**
// * 注册消息监听器
// *
// * @param listener
// */
// protected void registerMsgBeanListener(MsgBeanListener listener) {
//
// Class<?> clazz = listener.getClass();
// Method method;
// String topic = null;
// Listen listen;
// method = getMethod(clazz, "onMsgBean");
// listen = method == null ? null : method.getAnnotation(Listen.class);
//
// if (listen == null) {
// // 先拿类上的 Listen 注解, 没有再拿方法上的Listen
// final Listen clazzAnnotation = ReflectUtil.getListenAnnotation(clazz);
// if (clazzAnnotation == null) {
// method = getMethod(clazz, "onMessage");
// listen = method == null ? null : method.getAnnotation(Listen.class);
// } else {
// listen = clazzAnnotation;
// }
// }
//
// if (listen == null) {
// log.info("Tip>>> Topic not specified! @Listen annotation not declared on event method 'onMessage or onMsgBean' of bean " + listener);
// } else {
// topic = listen.topic();
// }
//
// registerListener(listener, topic);
// }
//
// /**
// * registerListener to registry.
// *
// * @param listener
// * @param topic
// */
// protected void registerListener(Object listener, String topic) {
// if (StringUtils.isNotBlank(topic)) {
// consumerLauncher.getListenerRegistry().register(topic, listener);
// log.info("注册监听器 Register listener '{}' on topic '{}'", listener, topic);
// }
// }
//
// /**
// * 获取第一个方法
// *
// * @param clazz
// * @param methodName
// * @return
// */
// protected Method getMethod(Class<?> clazz, String methodName) {
//
// Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz); //clazz.getDeclaredMethods();
// Method findMethod = null;
// for (Method method : methods) {
// if (method.getName().equals(methodName)
// && method.getAnnotations().length != 0) {
// findMethod = method;
// }
// }
// return findMethod;
// }
// }
//
// Path: koper-core/src/main/java/koper/MsgBeanListener.java
// public interface MsgBeanListener {
// /**
// * @see MessageListener#onMessage(java.lang.String)
// */
// public void onMsgBean(MsgBean<String, String> msgBean);
//
// }
// Path: koper-dataevent/src/main/java/koper/event/DataEventListenerPostProcessor.java
import koper.Listen;
import koper.MessageListenerBeanPostProcessor;
import koper.MsgBeanListener;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package koper.event;
/**
* DataEventListenerPostProcessor
*
* @author kk [email protected]
* @since 1.0
* 2016年2月19日
*/
public class DataEventListenerPostProcessor extends MessageListenerBeanPostProcessor {
/**
* bean初始化后注册DataEvent数据时间监听器
*
* @see MessageListenerBeanPostProcessor#postProcessAfterInitialization(Object, String)
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Object bean0 = bean;
final Listen listenAnnotation = bean.getClass().getAnnotation(Listen.class); | if (listenAnnotation != null || bean instanceof MsgBeanListener) { |
codeforboston/ungentry | data_processing/ungentry/src/testFoursquareCall.java | // Path: data_processing/ungentry/src/foursquare/Arguments.java
// public class Arguments {
//
// TreeSet<Pair<String,String>> _args;
//
// public Arguments(){
// _args = new TreeSet<Pair<String,String>>();
// }
//
// public void addArg(String iKey, String iValue){
// _args.add(new ImmutablePair<String,String>(iKey,iValue));
// }
//
// public void addLL(String iLong, String iLat){
// addArg("ll",iLong+","+iLat);
// }
//
// public void addIntent(String iValue){
// addArg("intent",iValue);
// }
//
// public void addSouthWest(String iLong, String iLat){
// addArg("sw",iLong+","+iLat);
// }
//
// public void addNorthEast(String iLong, String iLat){
// addArg("ne",iLong+","+iLat);
// }
//
// public void addPrice(String iValue){
// addArg("price",iValue);
// }
//
// public String toString(){
//
// StringBuffer aBuffer = new StringBuffer();
//
//
// for (Pair<String,String> aPair:_args) {
// aBuffer.append("&");
// aBuffer.append(aPair.getKey());
// aBuffer.append("=");
// aBuffer.append(aPair.getValue());
// }
//
// return aBuffer.toString();
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSReply.java
// public class FSReply {
//
// public FSMeta meta;
// public FSResponse response;
//
// public FSReply(){
//
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSResponse.java
// public class FSResponse {
//
// public FSVenue[] venues;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSVenue.java
// public class FSVenue {
//
// public String id;
// public String name;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/Foursquare.java
// public class Foursquare {
//
// public static String _base_url_search = "https://api.foursquare.com/v2/venues/search";
// public static String _base_url_explore = "https://api.foursquare.com/v2/venues/explore";
//
// public static String CLIENT_ID = "BV0L2QQ1LM3MSCHE202WKCOQGAXKZTEBQ2JT1NZIQXZDVLHW";
// public static String CLIENT_SECRET = "NZ1JVUJBTICYLYDYPDTEUEYDYUGVDZ3D2BY1CAWH3TD21EVK";
//
// public static FSReply getData(Arguments iArgs){
//
// FSReply aRes = null;
//
// // v is API version
// String args = "?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&v=20130815";
// //&ll=40.7,-74&price=1,2,3,4";
//
// args += iArgs.toString();
//
// URL aUrl;
// try {
// aUrl = new URL(_base_url_search+args);
//
// BufferedReader in = new BufferedReader(
// new InputStreamReader(aUrl.openStream()));
//
// String inputLine;
// StringBuffer iBuffer = new StringBuffer();
// while ((inputLine = in.readLine()) != null)
// iBuffer.append(inputLine);
// in.close();
//
// Gson aGson = new Gson();
// aRes = aGson.fromJson(iBuffer.toString(), FSReply.class);
//
// } catch (MalformedURLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return aRes;
//
//
// }
//
//
//
// }
| import foursquare.Arguments;
import foursquare.FSReply;
import foursquare.FSResponse;
import foursquare.FSVenue;
import foursquare.Foursquare; |
public class testFoursquareCall {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments aFArgs = new Arguments();
// aFArgs.addLL("40.7", "-74");
aFArgs.addPrice("1,2,3,4");
aFArgs.addIntent("browse");
aFArgs.addNorthEast("40.695","-74.005");
aFArgs.addSouthWest("40.705","-73.995");
| // Path: data_processing/ungentry/src/foursquare/Arguments.java
// public class Arguments {
//
// TreeSet<Pair<String,String>> _args;
//
// public Arguments(){
// _args = new TreeSet<Pair<String,String>>();
// }
//
// public void addArg(String iKey, String iValue){
// _args.add(new ImmutablePair<String,String>(iKey,iValue));
// }
//
// public void addLL(String iLong, String iLat){
// addArg("ll",iLong+","+iLat);
// }
//
// public void addIntent(String iValue){
// addArg("intent",iValue);
// }
//
// public void addSouthWest(String iLong, String iLat){
// addArg("sw",iLong+","+iLat);
// }
//
// public void addNorthEast(String iLong, String iLat){
// addArg("ne",iLong+","+iLat);
// }
//
// public void addPrice(String iValue){
// addArg("price",iValue);
// }
//
// public String toString(){
//
// StringBuffer aBuffer = new StringBuffer();
//
//
// for (Pair<String,String> aPair:_args) {
// aBuffer.append("&");
// aBuffer.append(aPair.getKey());
// aBuffer.append("=");
// aBuffer.append(aPair.getValue());
// }
//
// return aBuffer.toString();
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSReply.java
// public class FSReply {
//
// public FSMeta meta;
// public FSResponse response;
//
// public FSReply(){
//
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSResponse.java
// public class FSResponse {
//
// public FSVenue[] venues;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSVenue.java
// public class FSVenue {
//
// public String id;
// public String name;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/Foursquare.java
// public class Foursquare {
//
// public static String _base_url_search = "https://api.foursquare.com/v2/venues/search";
// public static String _base_url_explore = "https://api.foursquare.com/v2/venues/explore";
//
// public static String CLIENT_ID = "BV0L2QQ1LM3MSCHE202WKCOQGAXKZTEBQ2JT1NZIQXZDVLHW";
// public static String CLIENT_SECRET = "NZ1JVUJBTICYLYDYPDTEUEYDYUGVDZ3D2BY1CAWH3TD21EVK";
//
// public static FSReply getData(Arguments iArgs){
//
// FSReply aRes = null;
//
// // v is API version
// String args = "?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&v=20130815";
// //&ll=40.7,-74&price=1,2,3,4";
//
// args += iArgs.toString();
//
// URL aUrl;
// try {
// aUrl = new URL(_base_url_search+args);
//
// BufferedReader in = new BufferedReader(
// new InputStreamReader(aUrl.openStream()));
//
// String inputLine;
// StringBuffer iBuffer = new StringBuffer();
// while ((inputLine = in.readLine()) != null)
// iBuffer.append(inputLine);
// in.close();
//
// Gson aGson = new Gson();
// aRes = aGson.fromJson(iBuffer.toString(), FSReply.class);
//
// } catch (MalformedURLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return aRes;
//
//
// }
//
//
//
// }
// Path: data_processing/ungentry/src/testFoursquareCall.java
import foursquare.Arguments;
import foursquare.FSReply;
import foursquare.FSResponse;
import foursquare.FSVenue;
import foursquare.Foursquare;
public class testFoursquareCall {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments aFArgs = new Arguments();
// aFArgs.addLL("40.7", "-74");
aFArgs.addPrice("1,2,3,4");
aFArgs.addIntent("browse");
aFArgs.addNorthEast("40.695","-74.005");
aFArgs.addSouthWest("40.705","-73.995");
| FSReply aRes = Foursquare.getData(aFArgs); |
codeforboston/ungentry | data_processing/ungentry/src/testFoursquareCall.java | // Path: data_processing/ungentry/src/foursquare/Arguments.java
// public class Arguments {
//
// TreeSet<Pair<String,String>> _args;
//
// public Arguments(){
// _args = new TreeSet<Pair<String,String>>();
// }
//
// public void addArg(String iKey, String iValue){
// _args.add(new ImmutablePair<String,String>(iKey,iValue));
// }
//
// public void addLL(String iLong, String iLat){
// addArg("ll",iLong+","+iLat);
// }
//
// public void addIntent(String iValue){
// addArg("intent",iValue);
// }
//
// public void addSouthWest(String iLong, String iLat){
// addArg("sw",iLong+","+iLat);
// }
//
// public void addNorthEast(String iLong, String iLat){
// addArg("ne",iLong+","+iLat);
// }
//
// public void addPrice(String iValue){
// addArg("price",iValue);
// }
//
// public String toString(){
//
// StringBuffer aBuffer = new StringBuffer();
//
//
// for (Pair<String,String> aPair:_args) {
// aBuffer.append("&");
// aBuffer.append(aPair.getKey());
// aBuffer.append("=");
// aBuffer.append(aPair.getValue());
// }
//
// return aBuffer.toString();
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSReply.java
// public class FSReply {
//
// public FSMeta meta;
// public FSResponse response;
//
// public FSReply(){
//
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSResponse.java
// public class FSResponse {
//
// public FSVenue[] venues;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSVenue.java
// public class FSVenue {
//
// public String id;
// public String name;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/Foursquare.java
// public class Foursquare {
//
// public static String _base_url_search = "https://api.foursquare.com/v2/venues/search";
// public static String _base_url_explore = "https://api.foursquare.com/v2/venues/explore";
//
// public static String CLIENT_ID = "BV0L2QQ1LM3MSCHE202WKCOQGAXKZTEBQ2JT1NZIQXZDVLHW";
// public static String CLIENT_SECRET = "NZ1JVUJBTICYLYDYPDTEUEYDYUGVDZ3D2BY1CAWH3TD21EVK";
//
// public static FSReply getData(Arguments iArgs){
//
// FSReply aRes = null;
//
// // v is API version
// String args = "?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&v=20130815";
// //&ll=40.7,-74&price=1,2,3,4";
//
// args += iArgs.toString();
//
// URL aUrl;
// try {
// aUrl = new URL(_base_url_search+args);
//
// BufferedReader in = new BufferedReader(
// new InputStreamReader(aUrl.openStream()));
//
// String inputLine;
// StringBuffer iBuffer = new StringBuffer();
// while ((inputLine = in.readLine()) != null)
// iBuffer.append(inputLine);
// in.close();
//
// Gson aGson = new Gson();
// aRes = aGson.fromJson(iBuffer.toString(), FSReply.class);
//
// } catch (MalformedURLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return aRes;
//
//
// }
//
//
//
// }
| import foursquare.Arguments;
import foursquare.FSReply;
import foursquare.FSResponse;
import foursquare.FSVenue;
import foursquare.Foursquare; |
public class testFoursquareCall {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments aFArgs = new Arguments();
// aFArgs.addLL("40.7", "-74");
aFArgs.addPrice("1,2,3,4");
aFArgs.addIntent("browse");
aFArgs.addNorthEast("40.695","-74.005");
aFArgs.addSouthWest("40.705","-73.995");
| // Path: data_processing/ungentry/src/foursquare/Arguments.java
// public class Arguments {
//
// TreeSet<Pair<String,String>> _args;
//
// public Arguments(){
// _args = new TreeSet<Pair<String,String>>();
// }
//
// public void addArg(String iKey, String iValue){
// _args.add(new ImmutablePair<String,String>(iKey,iValue));
// }
//
// public void addLL(String iLong, String iLat){
// addArg("ll",iLong+","+iLat);
// }
//
// public void addIntent(String iValue){
// addArg("intent",iValue);
// }
//
// public void addSouthWest(String iLong, String iLat){
// addArg("sw",iLong+","+iLat);
// }
//
// public void addNorthEast(String iLong, String iLat){
// addArg("ne",iLong+","+iLat);
// }
//
// public void addPrice(String iValue){
// addArg("price",iValue);
// }
//
// public String toString(){
//
// StringBuffer aBuffer = new StringBuffer();
//
//
// for (Pair<String,String> aPair:_args) {
// aBuffer.append("&");
// aBuffer.append(aPair.getKey());
// aBuffer.append("=");
// aBuffer.append(aPair.getValue());
// }
//
// return aBuffer.toString();
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSReply.java
// public class FSReply {
//
// public FSMeta meta;
// public FSResponse response;
//
// public FSReply(){
//
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSResponse.java
// public class FSResponse {
//
// public FSVenue[] venues;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSVenue.java
// public class FSVenue {
//
// public String id;
// public String name;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/Foursquare.java
// public class Foursquare {
//
// public static String _base_url_search = "https://api.foursquare.com/v2/venues/search";
// public static String _base_url_explore = "https://api.foursquare.com/v2/venues/explore";
//
// public static String CLIENT_ID = "BV0L2QQ1LM3MSCHE202WKCOQGAXKZTEBQ2JT1NZIQXZDVLHW";
// public static String CLIENT_SECRET = "NZ1JVUJBTICYLYDYPDTEUEYDYUGVDZ3D2BY1CAWH3TD21EVK";
//
// public static FSReply getData(Arguments iArgs){
//
// FSReply aRes = null;
//
// // v is API version
// String args = "?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&v=20130815";
// //&ll=40.7,-74&price=1,2,3,4";
//
// args += iArgs.toString();
//
// URL aUrl;
// try {
// aUrl = new URL(_base_url_search+args);
//
// BufferedReader in = new BufferedReader(
// new InputStreamReader(aUrl.openStream()));
//
// String inputLine;
// StringBuffer iBuffer = new StringBuffer();
// while ((inputLine = in.readLine()) != null)
// iBuffer.append(inputLine);
// in.close();
//
// Gson aGson = new Gson();
// aRes = aGson.fromJson(iBuffer.toString(), FSReply.class);
//
// } catch (MalformedURLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return aRes;
//
//
// }
//
//
//
// }
// Path: data_processing/ungentry/src/testFoursquareCall.java
import foursquare.Arguments;
import foursquare.FSReply;
import foursquare.FSResponse;
import foursquare.FSVenue;
import foursquare.Foursquare;
public class testFoursquareCall {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments aFArgs = new Arguments();
// aFArgs.addLL("40.7", "-74");
aFArgs.addPrice("1,2,3,4");
aFArgs.addIntent("browse");
aFArgs.addNorthEast("40.695","-74.005");
aFArgs.addSouthWest("40.705","-73.995");
| FSReply aRes = Foursquare.getData(aFArgs); |
codeforboston/ungentry | data_processing/ungentry/src/testFoursquareCall.java | // Path: data_processing/ungentry/src/foursquare/Arguments.java
// public class Arguments {
//
// TreeSet<Pair<String,String>> _args;
//
// public Arguments(){
// _args = new TreeSet<Pair<String,String>>();
// }
//
// public void addArg(String iKey, String iValue){
// _args.add(new ImmutablePair<String,String>(iKey,iValue));
// }
//
// public void addLL(String iLong, String iLat){
// addArg("ll",iLong+","+iLat);
// }
//
// public void addIntent(String iValue){
// addArg("intent",iValue);
// }
//
// public void addSouthWest(String iLong, String iLat){
// addArg("sw",iLong+","+iLat);
// }
//
// public void addNorthEast(String iLong, String iLat){
// addArg("ne",iLong+","+iLat);
// }
//
// public void addPrice(String iValue){
// addArg("price",iValue);
// }
//
// public String toString(){
//
// StringBuffer aBuffer = new StringBuffer();
//
//
// for (Pair<String,String> aPair:_args) {
// aBuffer.append("&");
// aBuffer.append(aPair.getKey());
// aBuffer.append("=");
// aBuffer.append(aPair.getValue());
// }
//
// return aBuffer.toString();
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSReply.java
// public class FSReply {
//
// public FSMeta meta;
// public FSResponse response;
//
// public FSReply(){
//
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSResponse.java
// public class FSResponse {
//
// public FSVenue[] venues;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSVenue.java
// public class FSVenue {
//
// public String id;
// public String name;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/Foursquare.java
// public class Foursquare {
//
// public static String _base_url_search = "https://api.foursquare.com/v2/venues/search";
// public static String _base_url_explore = "https://api.foursquare.com/v2/venues/explore";
//
// public static String CLIENT_ID = "BV0L2QQ1LM3MSCHE202WKCOQGAXKZTEBQ2JT1NZIQXZDVLHW";
// public static String CLIENT_SECRET = "NZ1JVUJBTICYLYDYPDTEUEYDYUGVDZ3D2BY1CAWH3TD21EVK";
//
// public static FSReply getData(Arguments iArgs){
//
// FSReply aRes = null;
//
// // v is API version
// String args = "?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&v=20130815";
// //&ll=40.7,-74&price=1,2,3,4";
//
// args += iArgs.toString();
//
// URL aUrl;
// try {
// aUrl = new URL(_base_url_search+args);
//
// BufferedReader in = new BufferedReader(
// new InputStreamReader(aUrl.openStream()));
//
// String inputLine;
// StringBuffer iBuffer = new StringBuffer();
// while ((inputLine = in.readLine()) != null)
// iBuffer.append(inputLine);
// in.close();
//
// Gson aGson = new Gson();
// aRes = aGson.fromJson(iBuffer.toString(), FSReply.class);
//
// } catch (MalformedURLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return aRes;
//
//
// }
//
//
//
// }
| import foursquare.Arguments;
import foursquare.FSReply;
import foursquare.FSResponse;
import foursquare.FSVenue;
import foursquare.Foursquare; |
public class testFoursquareCall {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments aFArgs = new Arguments();
// aFArgs.addLL("40.7", "-74");
aFArgs.addPrice("1,2,3,4");
aFArgs.addIntent("browse");
aFArgs.addNorthEast("40.695","-74.005");
aFArgs.addSouthWest("40.705","-73.995");
FSReply aRes = Foursquare.getData(aFArgs);
if (aRes!=null) {
System.out.println("#venues:"+aRes.response.venues.length);
| // Path: data_processing/ungentry/src/foursquare/Arguments.java
// public class Arguments {
//
// TreeSet<Pair<String,String>> _args;
//
// public Arguments(){
// _args = new TreeSet<Pair<String,String>>();
// }
//
// public void addArg(String iKey, String iValue){
// _args.add(new ImmutablePair<String,String>(iKey,iValue));
// }
//
// public void addLL(String iLong, String iLat){
// addArg("ll",iLong+","+iLat);
// }
//
// public void addIntent(String iValue){
// addArg("intent",iValue);
// }
//
// public void addSouthWest(String iLong, String iLat){
// addArg("sw",iLong+","+iLat);
// }
//
// public void addNorthEast(String iLong, String iLat){
// addArg("ne",iLong+","+iLat);
// }
//
// public void addPrice(String iValue){
// addArg("price",iValue);
// }
//
// public String toString(){
//
// StringBuffer aBuffer = new StringBuffer();
//
//
// for (Pair<String,String> aPair:_args) {
// aBuffer.append("&");
// aBuffer.append(aPair.getKey());
// aBuffer.append("=");
// aBuffer.append(aPair.getValue());
// }
//
// return aBuffer.toString();
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSReply.java
// public class FSReply {
//
// public FSMeta meta;
// public FSResponse response;
//
// public FSReply(){
//
// }
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSResponse.java
// public class FSResponse {
//
// public FSVenue[] venues;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/FSVenue.java
// public class FSVenue {
//
// public String id;
// public String name;
//
// }
//
// Path: data_processing/ungentry/src/foursquare/Foursquare.java
// public class Foursquare {
//
// public static String _base_url_search = "https://api.foursquare.com/v2/venues/search";
// public static String _base_url_explore = "https://api.foursquare.com/v2/venues/explore";
//
// public static String CLIENT_ID = "BV0L2QQ1LM3MSCHE202WKCOQGAXKZTEBQ2JT1NZIQXZDVLHW";
// public static String CLIENT_SECRET = "NZ1JVUJBTICYLYDYPDTEUEYDYUGVDZ3D2BY1CAWH3TD21EVK";
//
// public static FSReply getData(Arguments iArgs){
//
// FSReply aRes = null;
//
// // v is API version
// String args = "?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&v=20130815";
// //&ll=40.7,-74&price=1,2,3,4";
//
// args += iArgs.toString();
//
// URL aUrl;
// try {
// aUrl = new URL(_base_url_search+args);
//
// BufferedReader in = new BufferedReader(
// new InputStreamReader(aUrl.openStream()));
//
// String inputLine;
// StringBuffer iBuffer = new StringBuffer();
// while ((inputLine = in.readLine()) != null)
// iBuffer.append(inputLine);
// in.close();
//
// Gson aGson = new Gson();
// aRes = aGson.fromJson(iBuffer.toString(), FSReply.class);
//
// } catch (MalformedURLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return aRes;
//
//
// }
//
//
//
// }
// Path: data_processing/ungentry/src/testFoursquareCall.java
import foursquare.Arguments;
import foursquare.FSReply;
import foursquare.FSResponse;
import foursquare.FSVenue;
import foursquare.Foursquare;
public class testFoursquareCall {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments aFArgs = new Arguments();
// aFArgs.addLL("40.7", "-74");
aFArgs.addPrice("1,2,3,4");
aFArgs.addIntent("browse");
aFArgs.addNorthEast("40.695","-74.005");
aFArgs.addSouthWest("40.705","-73.995");
FSReply aRes = Foursquare.getData(aFArgs);
if (aRes!=null) {
System.out.println("#venues:"+aRes.response.venues.length);
| for (FSVenue aVenue:aRes.response.venues){ |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/license/LicenseTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
| import android.content.Context;
import android.content.res.Resources;
import android.os.Parcel;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.bluelinelabs.logansquare.LoganSquare;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import static org.junit.Assert.assertEquals; | package com.ToxicBakery.app.screenshot_redaction.license;
@RunWith(AndroidJUnit4.class)
public class LicenseTest {
@Rule | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/license/LicenseTest.java
import android.content.Context;
import android.content.res.Resources;
import android.os.Parcel;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.bluelinelabs.logansquare.LoganSquare;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
package com.ToxicBakery.app.screenshot_redaction.license;
@RunWith(AndroidJUnit4.class)
public class LicenseTest {
@Rule | public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/widget/ResultRedaction.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ocr/engine/OcrWordResult.java
// public class OcrWordResult implements Parcelable {
//
// private static final String TAG = "OcrWordResult";
//
// public static final Creator<OcrWordResult> CREATOR = new Creator<OcrWordResult>() {
// @Override
// public OcrWordResult createFromParcel(Parcel in) {
// return new OcrWordResult(in);
// }
//
// @Override
// public OcrWordResult[] newArray(int size) {
// return new OcrWordResult[size];
// }
// };
//
// private final String word;
//
// @FloatRange(from = 0.0, to = 1.0)
// private final double confidence;
//
// private final Rect boundingBox;
//
// public OcrWordResult(@NonNull String word,
// @FloatRange(from = 0.0, to = 1.0) double confidence,
// @NonNull Rect boundingBox) {
//
// this.boundingBox = boundingBox;
// this.word = word;
// this.confidence = confidence;
// }
//
// protected OcrWordResult(Parcel in) {
// word = in.readString();
// confidence = in.readDouble();
// boundingBox = in.readParcelable(Rect.class.getClassLoader());
// }
//
// public Rect getBoundingBox() {
// return boundingBox;
// }
//
// public String getWord() {
// return word;
// }
//
// @FloatRange(from = 0.0, to = 1.0)
// public double getWordConfidence() {
// return confidence;
// }
//
// @Override
// public String toString() {
// try {
// return new JSONObject()
// .put("word", word)
// .put("boundingBox", boundingBox)
// .toString();
// } catch (JSONException e) {
// Log.e(TAG, "Failed to convert to JSON", e);
// return "";
// }
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(word);
// dest.writeDouble(confidence);
// dest.writeParcelable(boundingBox, flags);
// }
//
// }
| import android.os.Parcel;
import android.os.Parcelable;
import com.ToxicBakery.app.screenshot_redaction.ocr.engine.OcrWordResult; | package com.ToxicBakery.app.screenshot_redaction.widget;
public class ResultRedaction implements Parcelable {
public static final Creator<ResultRedaction> CREATOR = new Creator<ResultRedaction>() {
@Override
public ResultRedaction createFromParcel(Parcel in) {
return new ResultRedaction(in);
}
@Override
public ResultRedaction[] newArray(int size) {
return new ResultRedaction[size];
}
};
| // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ocr/engine/OcrWordResult.java
// public class OcrWordResult implements Parcelable {
//
// private static final String TAG = "OcrWordResult";
//
// public static final Creator<OcrWordResult> CREATOR = new Creator<OcrWordResult>() {
// @Override
// public OcrWordResult createFromParcel(Parcel in) {
// return new OcrWordResult(in);
// }
//
// @Override
// public OcrWordResult[] newArray(int size) {
// return new OcrWordResult[size];
// }
// };
//
// private final String word;
//
// @FloatRange(from = 0.0, to = 1.0)
// private final double confidence;
//
// private final Rect boundingBox;
//
// public OcrWordResult(@NonNull String word,
// @FloatRange(from = 0.0, to = 1.0) double confidence,
// @NonNull Rect boundingBox) {
//
// this.boundingBox = boundingBox;
// this.word = word;
// this.confidence = confidence;
// }
//
// protected OcrWordResult(Parcel in) {
// word = in.readString();
// confidence = in.readDouble();
// boundingBox = in.readParcelable(Rect.class.getClassLoader());
// }
//
// public Rect getBoundingBox() {
// return boundingBox;
// }
//
// public String getWord() {
// return word;
// }
//
// @FloatRange(from = 0.0, to = 1.0)
// public double getWordConfidence() {
// return confidence;
// }
//
// @Override
// public String toString() {
// try {
// return new JSONObject()
// .put("word", word)
// .put("boundingBox", boundingBox)
// .toString();
// } catch (JSONException e) {
// Log.e(TAG, "Failed to convert to JSON", e);
// return "";
// }
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(word);
// dest.writeDouble(confidence);
// dest.writeParcelable(boundingBox, flags);
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/widget/ResultRedaction.java
import android.os.Parcel;
import android.os.Parcelable;
import com.ToxicBakery.app.screenshot_redaction.ocr.engine.OcrWordResult;
package com.ToxicBakery.app.screenshot_redaction.widget;
public class ResultRedaction implements Parcelable {
public static final Creator<ResultRedaction> CREATOR = new Creator<ResultRedaction>() {
@Override
public ResultRedaction createFromParcel(Parcel in) {
return new ResultRedaction(in);
}
@Override
public ResultRedaction[] newArray(int size) {
return new ResultRedaction[size];
}
};
| private final OcrWordResult wordResult; |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/observer/ScreenshotObserver.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ScreenshotApplication.java
// public class ScreenshotApplication extends Application {
//
// private static final String[] PERMISSIONS = {
// Manifest.permission.READ_EXTERNAL_STORAGE
// };
//
// private static final String TAG = "ScreenshotApplication";
// private static final String REMOVE_OLD_DIR = "REMOVE_OLD_DIR";
//
// private ScreenShotNotifications screenShotNotifications;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// // Install Timber
// if (BuildConfig.DEBUG) {
// Timber.plant(new Timber.DebugTree());
// }
//
// Once.initialise(this);
// screenShotNotifications = new ScreenShotNotifications(this);
//
// Observable.just(true)
// .subscribeOn(AndroidSchedulers.mainThread())
// .subscribe(new Action1<Boolean>() {
// @Override
// public void call(Boolean aBoolean) {
// initializeResources();
// }
// });
// }
//
// /**
// * Gets the screenshot notification instance from the process application.
// *
// * @return screenshot notification instance
// */
// public ScreenShotNotifications getScreenShotNotifications() {
// return screenShotNotifications;
// }
//
// void initializeResources() {
// if (!Once.beenDone(REMOVE_OLD_DIR)) {
// Once.markDone(REMOVE_OLD_DIR);
//
// File externalFilesDir = getApplicationContext().getExternalFilesDir(null);
// if (externalFilesDir != null
// && externalFilesDir.exists()
// && !externalFilesDir.delete()) {
//
// Log.e(TAG, "Failed to delete external storage directory");
// }
// }
//
// if (Is.lessThan(MARSHMALLOW) || PermissionCheck.hasPermissions(getApplicationContext(), PERMISSIONS)) {
// new CopyToSdCard()
// .copy(new TessDataRawResourceCopyConfiguration(getApplicationContext(), R.raw.eng));
//
// DictionaryEnglish.getInstance(getApplicationContext());
// DictionaryEnglishNames.getInstance(getApplicationContext());
// ScreenshotService.startScreenshotService(getApplicationContext());
// }
// }
//
// }
| import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.ScreenshotApplication;
import java.io.File;
import java.util.Date;
import static android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI; | public ObserverImpl(@NonNull Context context,
@NonNull IOnScreenShotListener onScreenShotListener) {
super(null);
this.context = context;
this.onScreenShotListener = onScreenShotListener;
contentResolver = context.getContentResolver();
lastDate = System.currentTimeMillis();
}
@Override
public void onChange(boolean selfChange) {
Cursor cursor = contentResolver.query(EXTERNAL_CONTENT_URI, PROJECTION, SELECTION, null, SORT_ORDER);
try {
if (cursor != null) {
int idxData = cursor.getColumnIndex(Media.DATA);
int idxDate = cursor.getColumnIndex(Media.DATE_ADDED);
if (cursor.moveToFirst()) {
String path = cursor.getString(idxData);
File file = new File(path);
Uri uri = Uri.fromFile(file);
long date = cursor.getInt(idxDate) * 1000L;
if (date < lastDate) {
// Date is before the most recent
Log.i(TAG, "Screenshot date " + new Date(date) + " is before " + new Date(lastDate));
// Likely a deletion | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ScreenshotApplication.java
// public class ScreenshotApplication extends Application {
//
// private static final String[] PERMISSIONS = {
// Manifest.permission.READ_EXTERNAL_STORAGE
// };
//
// private static final String TAG = "ScreenshotApplication";
// private static final String REMOVE_OLD_DIR = "REMOVE_OLD_DIR";
//
// private ScreenShotNotifications screenShotNotifications;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// // Install Timber
// if (BuildConfig.DEBUG) {
// Timber.plant(new Timber.DebugTree());
// }
//
// Once.initialise(this);
// screenShotNotifications = new ScreenShotNotifications(this);
//
// Observable.just(true)
// .subscribeOn(AndroidSchedulers.mainThread())
// .subscribe(new Action1<Boolean>() {
// @Override
// public void call(Boolean aBoolean) {
// initializeResources();
// }
// });
// }
//
// /**
// * Gets the screenshot notification instance from the process application.
// *
// * @return screenshot notification instance
// */
// public ScreenShotNotifications getScreenShotNotifications() {
// return screenShotNotifications;
// }
//
// void initializeResources() {
// if (!Once.beenDone(REMOVE_OLD_DIR)) {
// Once.markDone(REMOVE_OLD_DIR);
//
// File externalFilesDir = getApplicationContext().getExternalFilesDir(null);
// if (externalFilesDir != null
// && externalFilesDir.exists()
// && !externalFilesDir.delete()) {
//
// Log.e(TAG, "Failed to delete external storage directory");
// }
// }
//
// if (Is.lessThan(MARSHMALLOW) || PermissionCheck.hasPermissions(getApplicationContext(), PERMISSIONS)) {
// new CopyToSdCard()
// .copy(new TessDataRawResourceCopyConfiguration(getApplicationContext(), R.raw.eng));
//
// DictionaryEnglish.getInstance(getApplicationContext());
// DictionaryEnglishNames.getInstance(getApplicationContext());
// ScreenshotService.startScreenshotService(getApplicationContext());
// }
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/observer/ScreenshotObserver.java
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.ScreenshotApplication;
import java.io.File;
import java.util.Date;
import static android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
public ObserverImpl(@NonNull Context context,
@NonNull IOnScreenShotListener onScreenShotListener) {
super(null);
this.context = context;
this.onScreenShotListener = onScreenShotListener;
contentResolver = context.getContentResolver();
lastDate = System.currentTimeMillis();
}
@Override
public void onChange(boolean selfChange) {
Cursor cursor = contentResolver.query(EXTERNAL_CONTENT_URI, PROJECTION, SELECTION, null, SORT_ORDER);
try {
if (cursor != null) {
int idxData = cursor.getColumnIndex(Media.DATA);
int idxDate = cursor.getColumnIndex(Media.DATE_ADDED);
if (cursor.moveToFirst()) {
String path = cursor.getString(idxData);
File file = new File(path);
Uri uri = Uri.fromFile(file);
long date = cursor.getInt(idxDate) * 1000L;
if (date < lastDate) {
// Date is before the most recent
Log.i(TAG, "Screenshot date " + new Date(date) + " is before " + new Date(lastDate));
// Likely a deletion | ((ScreenshotApplication) context.getApplicationContext()) |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivityLicenses.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentLicenseList.java
// public class FragmentLicenseList extends Fragment {
//
// public static final String TAG = "FragmentLicenseList";
//
// private static RxBus<License> licenseRxBus = new RxBus<>();
//
// private Adapter adapter;
// private Subscription subscribeLoadLicenses;
// private Subscription subscriptionRxBus;
//
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
// if (supportActionBar != null) {
// supportActionBar.setDisplayHomeAsUpEnabled(true);
// }
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// return inflater.inflate(R.layout.fragment_license_list, container, false);
// }
//
// @Override
// public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// adapter = new Adapter();
//
// RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
// recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST));
// recyclerView.setAdapter(adapter);
// }
//
// @Override
// public void onResume() {
// super.onResume();
//
// subscribeLoadLicenses = Licensing.getLicenses(getContext())
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Action1<License[]>() {
// @Override
// public void call(License[] licenses) {
// adapter.setLicenses(licenses);
// adapter.notifyDataSetChanged();
// }
// });
//
// subscriptionRxBus = licenseRxBus.toObserverable()
// .subscribe(new Action1<License>() {
// @Override
// public void call(License license) {
// getFragmentManager().beginTransaction()
// .replace(R.id.container, FragmentLicenseView.createInstance(license), FragmentLicenseView.TAG)
// .addToBackStack(null)
// .commit();
// }
// });
// }
//
// @Override
// public void onPause() {
// super.onPause();
//
// if (subscribeLoadLicenses != null && !subscribeLoadLicenses.isUnsubscribed()) {
// subscribeLoadLicenses.unsubscribe();
// }
//
// if (subscriptionRxBus != null && !subscriptionRxBus.isUnsubscribed()) {
// subscriptionRxBus.unsubscribe();
// }
// }
//
// /**
// * @param <T>
// * @see <a href="http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/">http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/</a>
// */
// static public class RxBus<T> {
//
// private final PublishSubject<T> publishSubject = PublishSubject.create();
// private final Subject<T, T> bus = new SerializedSubject<>(publishSubject);
//
// public void send(T o) {
// bus.onNext(o);
// }
//
// public Observable<T> toObserverable() {
// return bus;
// }
//
// }
//
// static class Adapter extends RecyclerView.Adapter<ViewHolder> {
//
// private final List<License> licenseList;
//
// public Adapter() {
// licenseList = new ArrayList<>();
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.selectable_simple_list_item, parent, false);
//
// return new ViewHolder(view);
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// License license = licenseList.get(position);
// holder.bind(license);
// }
//
// @Override
// public int getItemCount() {
// return licenseList.size();
// }
//
// void setLicenses(License[] licenses) {
// licenseList.clear();
// licenseList.addAll(Arrays.asList(licenses));
// Collections.sort(licenseList, new Comparator<License>() {
// @Override
// public int compare(License lhs, License rhs) {
// return lhs.getName()
// .compareToIgnoreCase(rhs.getName());
// }
// });
// }
//
// }
//
// static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//
// private final TextView textViewLicense;
//
// private License license;
//
// public ViewHolder(View itemView) {
// super(itemView);
//
// textViewLicense = (TextView) itemView.findViewById(android.R.id.text1);
//
// itemView.setOnClickListener(this);
// }
//
// @Override
// public void onClick(View v) {
// licenseRxBus.send(license);
// }
//
// void bind(License license) {
// textViewLicense.setText(license.getName());
// this.license = license;
// }
//
// }
//
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentLicenseList; | package com.ToxicBakery.app.screenshot_redaction;
public class ActivityLicenses extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_licenses);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction() | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentLicenseList.java
// public class FragmentLicenseList extends Fragment {
//
// public static final String TAG = "FragmentLicenseList";
//
// private static RxBus<License> licenseRxBus = new RxBus<>();
//
// private Adapter adapter;
// private Subscription subscribeLoadLicenses;
// private Subscription subscriptionRxBus;
//
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
// if (supportActionBar != null) {
// supportActionBar.setDisplayHomeAsUpEnabled(true);
// }
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// return inflater.inflate(R.layout.fragment_license_list, container, false);
// }
//
// @Override
// public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// adapter = new Adapter();
//
// RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
// recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST));
// recyclerView.setAdapter(adapter);
// }
//
// @Override
// public void onResume() {
// super.onResume();
//
// subscribeLoadLicenses = Licensing.getLicenses(getContext())
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Action1<License[]>() {
// @Override
// public void call(License[] licenses) {
// adapter.setLicenses(licenses);
// adapter.notifyDataSetChanged();
// }
// });
//
// subscriptionRxBus = licenseRxBus.toObserverable()
// .subscribe(new Action1<License>() {
// @Override
// public void call(License license) {
// getFragmentManager().beginTransaction()
// .replace(R.id.container, FragmentLicenseView.createInstance(license), FragmentLicenseView.TAG)
// .addToBackStack(null)
// .commit();
// }
// });
// }
//
// @Override
// public void onPause() {
// super.onPause();
//
// if (subscribeLoadLicenses != null && !subscribeLoadLicenses.isUnsubscribed()) {
// subscribeLoadLicenses.unsubscribe();
// }
//
// if (subscriptionRxBus != null && !subscriptionRxBus.isUnsubscribed()) {
// subscriptionRxBus.unsubscribe();
// }
// }
//
// /**
// * @param <T>
// * @see <a href="http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/">http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/</a>
// */
// static public class RxBus<T> {
//
// private final PublishSubject<T> publishSubject = PublishSubject.create();
// private final Subject<T, T> bus = new SerializedSubject<>(publishSubject);
//
// public void send(T o) {
// bus.onNext(o);
// }
//
// public Observable<T> toObserverable() {
// return bus;
// }
//
// }
//
// static class Adapter extends RecyclerView.Adapter<ViewHolder> {
//
// private final List<License> licenseList;
//
// public Adapter() {
// licenseList = new ArrayList<>();
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.selectable_simple_list_item, parent, false);
//
// return new ViewHolder(view);
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// License license = licenseList.get(position);
// holder.bind(license);
// }
//
// @Override
// public int getItemCount() {
// return licenseList.size();
// }
//
// void setLicenses(License[] licenses) {
// licenseList.clear();
// licenseList.addAll(Arrays.asList(licenses));
// Collections.sort(licenseList, new Comparator<License>() {
// @Override
// public int compare(License lhs, License rhs) {
// return lhs.getName()
// .compareToIgnoreCase(rhs.getName());
// }
// });
// }
//
// }
//
// static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//
// private final TextView textViewLicense;
//
// private License license;
//
// public ViewHolder(View itemView) {
// super(itemView);
//
// textViewLicense = (TextView) itemView.findViewById(android.R.id.text1);
//
// itemView.setOnClickListener(this);
// }
//
// @Override
// public void onClick(View v) {
// licenseRxBus.send(license);
// }
//
// void bind(License license) {
// textViewLicense.setText(license.getName());
// this.license = license;
// }
//
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivityLicenses.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentLicenseList;
package com.ToxicBakery.app.screenshot_redaction;
public class ActivityLicenses extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_licenses);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction() | .replace(R.id.container, new FragmentLicenseList(), FragmentLicenseList.TAG) |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/license/LicensingTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import org.junit.Rule;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; | package com.ToxicBakery.app.screenshot_redaction.license;
@RunWith(AndroidJUnit4.class)
public class LicensingTest {
@Rule | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/license/LicensingTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import org.junit.Rule;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
package com.ToxicBakery.app.screenshot_redaction.license;
@RunWith(AndroidJUnit4.class)
public class LicensingTest {
@Rule | public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class); |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ocr/engine/TessTwoOcrEngineTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
| import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.IntRange;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.ocr.engine;
@RunWith(AndroidJUnit4.class)
public class TessTwoOcrEngineTest {
@Rule | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ocr/engine/TessTwoOcrEngineTest.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.IntRange;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.ocr.engine;
@RunWith(AndroidJUnit4.class)
public class TessTwoOcrEngineTest {
@Rule | public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyAction.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
| import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import jonathanfinerty.once.Once;
import rx.functions.Action1;
import static jonathanfinerty.once.Once.THIS_APP_VERSION; | package com.ToxicBakery.app.screenshot_redaction.copy;
class CopyAction implements Action1<CopyToSdCard.ICopyConfiguration> {
private static final String TAG = "CopyAction";
| // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyAction.java
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import jonathanfinerty.once.Once;
import rx.functions.Action1;
import static jonathanfinerty.once.Once.THIS_APP_VERSION;
package com.ToxicBakery.app.screenshot_redaction.copy;
class CopyAction implements Action1<CopyToSdCard.ICopyConfiguration> {
private static final String TAG = "CopyAction";
| private final CopyBus copyBus; |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule | public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class); |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception { | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception { | subscription = CopyBus.getInstance() |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception {
subscription = CopyBus.getInstance()
.register()
.first()
.subscribeOn(Schedulers.io()) | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception {
subscription = CopyBus.getInstance()
.register()
.first()
.subscribeOn(Schedulers.io()) | .subscribe(new Action1<CopyToSdCard.ICopyConfiguration>() { |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception {
subscription = CopyBus.getInstance()
.register()
.first()
.subscribeOn(Schedulers.io())
.subscribe(new Action1<CopyToSdCard.ICopyConfiguration>() {
@Override
public void call(CopyToSdCard.ICopyConfiguration iCopyConfiguration) {
semaphore.release();
}
});
DictionaryEnglish.getInstance(getContext());
}
@After
public void tearDown() throws Exception {
subscription.unsubscribe();
}
@SuppressWarnings("unused") | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception {
subscription = CopyBus.getInstance()
.register()
.first()
.subscribeOn(Schedulers.io())
.subscribe(new Action1<CopyToSdCard.ICopyConfiguration>() {
@Override
public void call(CopyToSdCard.ICopyConfiguration iCopyConfiguration) {
semaphore.release();
}
});
DictionaryEnglish.getInstance(getContext());
}
@After
public void tearDown() throws Exception {
subscription.unsubscribe();
}
@SuppressWarnings("unused") | public void onEvent(WordListRawResourceCopyConfiguration copyConfiguration) { |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglish.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglish implements IDictionary {
private static final String TAG = "DictionaryEnglish";
private static DictionaryEnglish instance;
@VisibleForTesting | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglish.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglish implements IDictionary {
private static final String TAG = "DictionaryEnglish";
private static DictionaryEnglish instance;
@VisibleForTesting | final ICopyConfiguration copyConfiguration; |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglish.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglish implements IDictionary {
private static final String TAG = "DictionaryEnglish";
private static DictionaryEnglish instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
| // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglish.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglish implements IDictionary {
private static final String TAG = "DictionaryEnglish";
private static DictionaryEnglish instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
| private final CopyBus copyBus; |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglish.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglish implements IDictionary {
private static final String TAG = "DictionaryEnglish";
private static DictionaryEnglish instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
private final CopyBus copyBus;
private Set<String> words;
DictionaryEnglish(@NonNull Context context) { | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglish.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglish implements IDictionary {
private static final String TAG = "DictionaryEnglish";
private static DictionaryEnglish instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
private final CopyBus copyBus;
private Set<String> words;
DictionaryEnglish(@NonNull Context context) { | copyConfiguration = new WordListRawResourceCopyConfiguration(context, R.raw.wordlist_english); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglish.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglish implements IDictionary {
private static final String TAG = "DictionaryEnglish";
private static DictionaryEnglish instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
private final CopyBus copyBus;
private Set<String> words;
DictionaryEnglish(@NonNull Context context) {
copyConfiguration = new WordListRawResourceCopyConfiguration(context, R.raw.wordlist_english);
copyBus = CopyBus.getInstance();
listenCopy(); | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglish.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglish implements IDictionary {
private static final String TAG = "DictionaryEnglish";
private static DictionaryEnglish instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
private final CopyBus copyBus;
private Set<String> words;
DictionaryEnglish(@NonNull Context context) {
copyConfiguration = new WordListRawResourceCopyConfiguration(context, R.raw.wordlist_english);
copyBus = CopyBus.getInstance();
listenCopy(); | new CopyToSdCard().copy(copyConfiguration); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentLicenseView.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/license/License.java
// @SuppressWarnings("unused")
// @JsonObject
// public final class License implements Parcelable {
//
// public static final Creator<License> CREATOR = new Creator<License>() {
// @Override
// public License createFromParcel(Parcel in) {
// return new License(in);
// }
//
// @Override
// public License[] newArray(int size) {
// return new License[size];
// }
// };
//
// @JsonField
// String name;
//
// @JsonField
// String licenseIdentifier;
//
// /**
// * Package private constructor for Logan Square
// */
// License() {
// }
//
// protected License(Parcel in) {
// name = in.readString();
// licenseIdentifier = in.readString();
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(name);
// dest.writeString(licenseIdentifier);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// public String getLicenseIdentifier() {
// return licenseIdentifier;
// }
//
// public String getName() {
// return name;
// }
//
// @WorkerThread
// public String getLicenseText(@NonNull Context context) throws IOException {
// context = context.getApplicationContext();
// Resources resources = context.getResources();
//
// final int identifier = resources.getIdentifier(
// licenseIdentifier,
// "raw",
// context.getPackageName()
// );
//
// try (InputStream inputStream = resources.openRawResource(identifier)) {
// return IOUtils.toString(inputStream);
// }
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.license.License;
import java.io.IOException;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.fragment;
public class FragmentLicenseView extends Fragment {
public static final String TAG = "FragmentLicenseView";
private static final String EXTRA_LICENSE = "EXTRA_LICENSE";
| // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/license/License.java
// @SuppressWarnings("unused")
// @JsonObject
// public final class License implements Parcelable {
//
// public static final Creator<License> CREATOR = new Creator<License>() {
// @Override
// public License createFromParcel(Parcel in) {
// return new License(in);
// }
//
// @Override
// public License[] newArray(int size) {
// return new License[size];
// }
// };
//
// @JsonField
// String name;
//
// @JsonField
// String licenseIdentifier;
//
// /**
// * Package private constructor for Logan Square
// */
// License() {
// }
//
// protected License(Parcel in) {
// name = in.readString();
// licenseIdentifier = in.readString();
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(name);
// dest.writeString(licenseIdentifier);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// public String getLicenseIdentifier() {
// return licenseIdentifier;
// }
//
// public String getName() {
// return name;
// }
//
// @WorkerThread
// public String getLicenseText(@NonNull Context context) throws IOException {
// context = context.getApplicationContext();
// Resources resources = context.getResources();
//
// final int identifier = resources.getIdentifier(
// licenseIdentifier,
// "raw",
// context.getPackageName()
// );
//
// try (InputStream inputStream = resources.openRawResource(identifier)) {
// return IOUtils.toString(inputStream);
// }
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentLicenseView.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.license.License;
import java.io.IOException;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.fragment;
public class FragmentLicenseView extends Fragment {
public static final String TAG = "FragmentLicenseView";
private static final String EXTRA_LICENSE = "EXTRA_LICENSE";
| private License license; |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/receiver/BootReceiver.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/service/ScreenshotService.java
// public class ScreenshotService extends Service {
//
// private static final String TAG = "ScreenshotService";
//
// private static final String[] REQUIRED_PERMISSIONS = {
// Manifest.permission.READ_EXTERNAL_STORAGE
// };
//
// private ScreenshotObserver screenshotObserver;
// private boolean isObserving;
//
// public static void startScreenshotService(@NonNull Context context) {
// if (PermissionCheck.hasPermissions(context, REQUIRED_PERMISSIONS)) {
// Intent intent = new Intent(context, ScreenshotService.class);
// context.startService(intent);
// }
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// if (!isObserving) {
// Log.d(TAG, "Starting observer.");
// try {
// ScreenshotContentObserver screenshotContentObserver = new ScreenshotContentObserver(getApplicationContext());
// screenshotObserver = new ScreenshotObserver(this, screenshotContentObserver);
// isObserving = true;
// } catch (UriObserver.ObserverException e) {
// Log.e(TAG, "Failed to start observer.", e);
// return START_NOT_STICKY;
// }
// }
//
// return START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// Log.d(TAG, "Stopping observer.");
// isObserving = false;
// screenshotObserver.stop();
//
// super.onDestroy();
// }
//
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// throw new UnsupportedOperationException("Binding is not supported.");
// }
//
// static class ScreenshotContentObserver implements IOnScreenShotListener {
//
// private final Context context;
//
// ScreenshotContentObserver(Context context) {
// this.context = context.getApplicationContext();
// }
//
// @Override
// public void onScreenShot(Uri uri) {
// Log.d(TAG, "Screenshot added: " + uri);
// new OcrImageReader().submit(context, uri);
// }
//
// }
//
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ToxicBakery.app.screenshot_redaction.service.ScreenshotService; | package com.ToxicBakery.app.screenshot_redaction.receiver;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/service/ScreenshotService.java
// public class ScreenshotService extends Service {
//
// private static final String TAG = "ScreenshotService";
//
// private static final String[] REQUIRED_PERMISSIONS = {
// Manifest.permission.READ_EXTERNAL_STORAGE
// };
//
// private ScreenshotObserver screenshotObserver;
// private boolean isObserving;
//
// public static void startScreenshotService(@NonNull Context context) {
// if (PermissionCheck.hasPermissions(context, REQUIRED_PERMISSIONS)) {
// Intent intent = new Intent(context, ScreenshotService.class);
// context.startService(intent);
// }
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// if (!isObserving) {
// Log.d(TAG, "Starting observer.");
// try {
// ScreenshotContentObserver screenshotContentObserver = new ScreenshotContentObserver(getApplicationContext());
// screenshotObserver = new ScreenshotObserver(this, screenshotContentObserver);
// isObserving = true;
// } catch (UriObserver.ObserverException e) {
// Log.e(TAG, "Failed to start observer.", e);
// return START_NOT_STICKY;
// }
// }
//
// return START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// Log.d(TAG, "Stopping observer.");
// isObserving = false;
// screenshotObserver.stop();
//
// super.onDestroy();
// }
//
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// throw new UnsupportedOperationException("Binding is not supported.");
// }
//
// static class ScreenshotContentObserver implements IOnScreenShotListener {
//
// private final Context context;
//
// ScreenshotContentObserver(Context context) {
// this.context = context.getApplicationContext();
// }
//
// @Override
// public void onScreenShot(Uri uri) {
// Log.d(TAG, "Screenshot added: " + uri);
// new OcrImageReader().submit(context, uri);
// }
//
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/receiver/BootReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ToxicBakery.app.screenshot_redaction.service.ScreenshotService;
package com.ToxicBakery.app.screenshot_redaction.receiver;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { | ScreenshotService.startScreenshotService(context); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/widget/DictionarySelectionDialog.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/DictionaryProvider.java
// public class DictionaryProvider {
//
// private static final String DB_NAME = "DictionaryProvider.mapdb";
// private static final Scheduler SCHEDULER = Schedulers.from(
// new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()));
//
// private static DictionaryProvider instance;
//
// private final NamedDictionary[] dictionaries;
// private final Set<String> enabledDictionaries;
//
// private DictionaryProvider(@NonNull Context context) {
// dictionaries = new NamedDictionary[]{
// new NamedDictionary(context, DictionaryEnglish.getInstance(context)),
// new NamedDictionary(context, DictionaryEnglishNames.getInstance(context)),
// };
//
// File dbFile = new File(context.getFilesDir(), DB_NAME);
// DB db = DBMaker.fileDB(dbFile)
// .closeOnJvmShutdown()
// .asyncWriteEnable()
// .cacheLRUEnable()
// .make();
//
// boolean exists = db.exists(DB_NAME);
// enabledDictionaries = db.hashSet(DB_NAME);
//
// Observable.just(Pair.with(exists, dictionaries))
// .filter(new Func1<Pair<Boolean, NamedDictionary[]>, Boolean>() {
// @Override
// public Boolean call(Pair<Boolean, NamedDictionary[]> pair) {
// return !pair.getValue0();
// }
// })
// .flatMap(new Func1<Pair<Boolean, NamedDictionary[]>, Observable<NamedDictionary>>() {
// @Override
// public Observable<NamedDictionary> call(Pair<Boolean, NamedDictionary[]> pair) {
// return Observable.from(pair.getValue1());
// }
// })
// .subscribe(new Action1<NamedDictionary>() {
// @Override
// public void call(NamedDictionary namedDictionary) {
// enabledDictionaries.add(namedDictionary.getDictionary().getUUID());
// }
// });
// }
//
// public static DictionaryProvider getInstance(@NonNull Context context) {
// if (instance == null) {
// synchronized (DictionaryProvider.class) {
// if (instance == null) {
// instance = new DictionaryProvider(context.getApplicationContext());
// }
// }
// }
//
// return instance;
// }
//
// public Observable<Boolean> setDictionaryEnabled(@NonNull String uuid, boolean enabled) {
// return Observable.zip(
// Observable.just(uuid).repeat(),
// Observable.just(enabled).repeat(),
// Observable.from(dictionaries),
// RxTuples.<String, Boolean, NamedDictionary>toTriplet())
// .filter(new Func1<Triplet<String, Boolean, NamedDictionary>, Boolean>() {
// @Override
// public Boolean call(Triplet<String, Boolean, NamedDictionary> triplet) {
// String uuid = triplet.getValue0();
// return enabledDictionaries.contains(uuid);
// }
// })
// .map(new Func1<Triplet<String, Boolean, NamedDictionary>, Boolean>() {
// @Override
// public Boolean call(Triplet<String, Boolean, NamedDictionary> triplet) {
// String uuid = triplet.getValue0();
// Boolean enabled = triplet.getValue1();
// return enabled ? enabledDictionaries.add(uuid) : enabledDictionaries.remove(uuid);
// }
// })
// .subscribeOn(SCHEDULER);
// }
//
// public Observable<IDictionaryStatus> getDictionaries() {
// return Observable.from(dictionaries)
// .map(new Func1<NamedDictionary, IDictionaryStatus>() {
// @Override
// public IDictionaryStatus call(NamedDictionary namedDictionary) {
// String uuid = namedDictionary.getDictionary()
// .getUUID();
//
// boolean enabled = enabledDictionaries.contains(uuid);
// return new DictionaryStatus(namedDictionary, enabled);
// }
// })
// .subscribeOn(SCHEDULER)
// .asObservable();
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionaryStatus.java
// public interface IDictionaryStatus {
//
// IDictionary getDictionary();
//
// String getName();
//
// boolean isEnabled();
//
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.dictionary.DictionaryProvider;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionaryStatus;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.widget;
public class DictionarySelectionDialog extends DialogFragment implements DialogInterface.OnMultiChoiceClickListener {
public static final String TAG = "DictionarySelectionDialog";
| // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/DictionaryProvider.java
// public class DictionaryProvider {
//
// private static final String DB_NAME = "DictionaryProvider.mapdb";
// private static final Scheduler SCHEDULER = Schedulers.from(
// new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()));
//
// private static DictionaryProvider instance;
//
// private final NamedDictionary[] dictionaries;
// private final Set<String> enabledDictionaries;
//
// private DictionaryProvider(@NonNull Context context) {
// dictionaries = new NamedDictionary[]{
// new NamedDictionary(context, DictionaryEnglish.getInstance(context)),
// new NamedDictionary(context, DictionaryEnglishNames.getInstance(context)),
// };
//
// File dbFile = new File(context.getFilesDir(), DB_NAME);
// DB db = DBMaker.fileDB(dbFile)
// .closeOnJvmShutdown()
// .asyncWriteEnable()
// .cacheLRUEnable()
// .make();
//
// boolean exists = db.exists(DB_NAME);
// enabledDictionaries = db.hashSet(DB_NAME);
//
// Observable.just(Pair.with(exists, dictionaries))
// .filter(new Func1<Pair<Boolean, NamedDictionary[]>, Boolean>() {
// @Override
// public Boolean call(Pair<Boolean, NamedDictionary[]> pair) {
// return !pair.getValue0();
// }
// })
// .flatMap(new Func1<Pair<Boolean, NamedDictionary[]>, Observable<NamedDictionary>>() {
// @Override
// public Observable<NamedDictionary> call(Pair<Boolean, NamedDictionary[]> pair) {
// return Observable.from(pair.getValue1());
// }
// })
// .subscribe(new Action1<NamedDictionary>() {
// @Override
// public void call(NamedDictionary namedDictionary) {
// enabledDictionaries.add(namedDictionary.getDictionary().getUUID());
// }
// });
// }
//
// public static DictionaryProvider getInstance(@NonNull Context context) {
// if (instance == null) {
// synchronized (DictionaryProvider.class) {
// if (instance == null) {
// instance = new DictionaryProvider(context.getApplicationContext());
// }
// }
// }
//
// return instance;
// }
//
// public Observable<Boolean> setDictionaryEnabled(@NonNull String uuid, boolean enabled) {
// return Observable.zip(
// Observable.just(uuid).repeat(),
// Observable.just(enabled).repeat(),
// Observable.from(dictionaries),
// RxTuples.<String, Boolean, NamedDictionary>toTriplet())
// .filter(new Func1<Triplet<String, Boolean, NamedDictionary>, Boolean>() {
// @Override
// public Boolean call(Triplet<String, Boolean, NamedDictionary> triplet) {
// String uuid = triplet.getValue0();
// return enabledDictionaries.contains(uuid);
// }
// })
// .map(new Func1<Triplet<String, Boolean, NamedDictionary>, Boolean>() {
// @Override
// public Boolean call(Triplet<String, Boolean, NamedDictionary> triplet) {
// String uuid = triplet.getValue0();
// Boolean enabled = triplet.getValue1();
// return enabled ? enabledDictionaries.add(uuid) : enabledDictionaries.remove(uuid);
// }
// })
// .subscribeOn(SCHEDULER);
// }
//
// public Observable<IDictionaryStatus> getDictionaries() {
// return Observable.from(dictionaries)
// .map(new Func1<NamedDictionary, IDictionaryStatus>() {
// @Override
// public IDictionaryStatus call(NamedDictionary namedDictionary) {
// String uuid = namedDictionary.getDictionary()
// .getUUID();
//
// boolean enabled = enabledDictionaries.contains(uuid);
// return new DictionaryStatus(namedDictionary, enabled);
// }
// })
// .subscribeOn(SCHEDULER)
// .asObservable();
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionaryStatus.java
// public interface IDictionaryStatus {
//
// IDictionary getDictionary();
//
// String getName();
//
// boolean isEnabled();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/widget/DictionarySelectionDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.dictionary.DictionaryProvider;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionaryStatus;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.widget;
public class DictionarySelectionDialog extends DialogFragment implements DialogInterface.OnMultiChoiceClickListener {
public static final String TAG = "DictionarySelectionDialog";
| private DictionaryProvider dictionaryProvider; |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentTutorial.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/TutorialBus.java
// public class TutorialBus extends ADefaultBus<Integer> {
//
// private static volatile TutorialBus instance;
//
// public static TutorialBus getInstance() {
// if (instance == null) {
// synchronized (TutorialBus.class) {
// if (instance == null) {
// instance = new TutorialBus();
// }
// }
// }
//
// return instance;
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.TutorialBus; | package com.ToxicBakery.app.screenshot_redaction.fragment;
public class FragmentTutorial extends Fragment implements View.OnClickListener {
public static final int ARROW_RIGHT = 1;
private static final String EXTRA_TEXT = "EXTRA_TEXT";
private static final String EXTRA_IMAGE = "EXTRA_IMAGE";
| // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/TutorialBus.java
// public class TutorialBus extends ADefaultBus<Integer> {
//
// private static volatile TutorialBus instance;
//
// public static TutorialBus getInstance() {
// if (instance == null) {
// synchronized (TutorialBus.class) {
// if (instance == null) {
// instance = new TutorialBus();
// }
// }
// }
//
// return instance;
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentTutorial.java
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.TutorialBus;
package com.ToxicBakery.app.screenshot_redaction.fragment;
public class FragmentTutorial extends Fragment implements View.OnClickListener {
public static final int ARROW_RIGHT = 1;
private static final String EXTRA_TEXT = "EXTRA_TEXT";
private static final String EXTRA_IMAGE = "EXTRA_IMAGE";
| private TutorialBus tutorialBus = TutorialBus.getInstance(); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglishNames implements IDictionary {
private static final String TAG = "DictionaryEnglishNames";
private static DictionaryEnglishNames instance;
@VisibleForTesting | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglishNames implements IDictionary {
private static final String TAG = "DictionaryEnglishNames";
private static DictionaryEnglishNames instance;
@VisibleForTesting | final ICopyConfiguration copyConfiguration; |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglishNames implements IDictionary {
private static final String TAG = "DictionaryEnglishNames";
private static DictionaryEnglishNames instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
| // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglishNames implements IDictionary {
private static final String TAG = "DictionaryEnglishNames";
private static DictionaryEnglishNames instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
| private final CopyBus copyBus; |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglishNames implements IDictionary {
private static final String TAG = "DictionaryEnglishNames";
private static DictionaryEnglishNames instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
private final CopyBus copyBus;
private Set<String> words;
DictionaryEnglishNames(@NonNull Context context) { | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglishNames implements IDictionary {
private static final String TAG = "DictionaryEnglishNames";
private static DictionaryEnglishNames instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
private final CopyBus copyBus;
private Set<String> words;
DictionaryEnglishNames(@NonNull Context context) { | copyConfiguration = new WordListRawResourceCopyConfiguration(context, R.raw.wordlist_english_names); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglishNames implements IDictionary {
private static final String TAG = "DictionaryEnglishNames";
private static DictionaryEnglishNames instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
private final CopyBus copyBus;
private Set<String> words;
DictionaryEnglishNames(@NonNull Context context) {
copyConfiguration = new WordListRawResourceCopyConfiguration(context, R.raw.wordlist_english_names);
copyBus = CopyBus.getInstance();
listenCopy(); | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/IDictionary.java
// public interface IDictionary {
//
// /**
// * Determine if a word should be redacted.
// *
// * @param word the word in question
// * @return true if the word should be redacted
// */
// boolean shouldRedact(@NonNull String word);
//
// /**
// * The name of the dictionary.
// *
// * @return a string resource representation of the dictionary name.
// */
// @StringRes
// int getName();
//
// /**
// * A constant UUID of the dictionary.
// *
// * @return a constant UUID
// */
// @NonNull
// String getUUID();
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
public class DictionaryEnglishNames implements IDictionary {
private static final String TAG = "DictionaryEnglishNames";
private static DictionaryEnglishNames instance;
@VisibleForTesting
final ICopyConfiguration copyConfiguration;
private final CopyBus copyBus;
private Set<String> words;
DictionaryEnglishNames(@NonNull Context context) {
copyConfiguration = new WordListRawResourceCopyConfiguration(context, R.raw.wordlist_english_names);
copyBus = CopyBus.getInstance();
listenCopy(); | new CopyToSdCard().copy(copyConfiguration); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentSettings.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivityLicenses.java
// public class ActivityLicenses extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_licenses);
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, new FragmentLicenseList(), FragmentLicenseList.TAG)
// .commit();
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
// getSupportFragmentManager().popBackStackImmediate();
// } else {
// finish();
// }
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/widget/DictionarySelectionDialog.java
// public class DictionarySelectionDialog extends DialogFragment implements DialogInterface.OnMultiChoiceClickListener {
//
// public static final String TAG = "DictionarySelectionDialog";
//
// private DictionaryProvider dictionaryProvider;
// private CharSequence[] displayValues;
// private String[] entryValues;
// private boolean[] states;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// dictionaryProvider = DictionaryProvider.getInstance(getActivity());
//
// dictionaryProvider.getDictionaries()
// .subscribe(new DictionaryAction());
// }
//
// @NonNull
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// return new AlertDialog.Builder(getActivity())
// .setTitle(R.string.pref_dictionaries)
// .setMultiChoiceItems(displayValues, states, this)
// .setPositiveButton(android.R.string.ok, null)
// .create();
// }
//
// @Override
// public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// String uuid = entryValues[which];
// dictionaryProvider.setDictionaryEnabled(uuid, isChecked)
// .subscribe();
// }
//
// class DictionaryAction extends Subscriber<IDictionaryStatus> {
//
// final List<CharSequence> displayValuesList = new LinkedList<>();
// final List<String> entryValuesList = new LinkedList<>();
// final List<Boolean> statesList = new ArrayList<>();
//
// @Override
// public void onCompleted() {
// displayValues = displayValuesList.toArray(new CharSequence[displayValuesList.size()]);
// entryValues = entryValuesList.toArray(new String[entryValuesList.size()]);
// states = new boolean[statesList.size()];
//
// for (int i = 0; i < statesList.size(); i++) {
// states[i] = statesList.get(i);
// }
// }
//
// @Override
// public void onError(Throwable e) {
// throw new IllegalStateException(e);
// }
//
// @Override
// public void onNext(IDictionaryStatus dictionaryStatus) {
// IDictionary dictionary = dictionaryStatus.getDictionary();
// String displayName = dictionaryStatus.getName();
// String entryValue = dictionary.getUUID();
// boolean enabled = dictionaryStatus.isEnabled();
//
// displayValuesList.add(displayName);
// entryValuesList.add(entryValue);
// statesList.add(enabled);
// }
//
// }
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.ToxicBakery.app.screenshot_redaction.ActivityLicenses;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.widget.DictionarySelectionDialog; | package com.ToxicBakery.app.screenshot_redaction.fragment;
public class FragmentSettings extends PreferenceFragment implements Preference.OnPreferenceClickListener {
public static final String TAG = "FragmentSettings";
public static final String PREF_LICENSES = "pref_licenses";
public static final String PREF_DICTIONARIES = "pref_dictionaries";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
findPreference(PREF_LICENSES).setOnPreferenceClickListener(this);
findPreference(PREF_DICTIONARIES).setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceClick(Preference preference) {
switch (preference.getKey()) {
case PREF_LICENSES: | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivityLicenses.java
// public class ActivityLicenses extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_licenses);
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, new FragmentLicenseList(), FragmentLicenseList.TAG)
// .commit();
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
// getSupportFragmentManager().popBackStackImmediate();
// } else {
// finish();
// }
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/widget/DictionarySelectionDialog.java
// public class DictionarySelectionDialog extends DialogFragment implements DialogInterface.OnMultiChoiceClickListener {
//
// public static final String TAG = "DictionarySelectionDialog";
//
// private DictionaryProvider dictionaryProvider;
// private CharSequence[] displayValues;
// private String[] entryValues;
// private boolean[] states;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// dictionaryProvider = DictionaryProvider.getInstance(getActivity());
//
// dictionaryProvider.getDictionaries()
// .subscribe(new DictionaryAction());
// }
//
// @NonNull
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// return new AlertDialog.Builder(getActivity())
// .setTitle(R.string.pref_dictionaries)
// .setMultiChoiceItems(displayValues, states, this)
// .setPositiveButton(android.R.string.ok, null)
// .create();
// }
//
// @Override
// public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// String uuid = entryValues[which];
// dictionaryProvider.setDictionaryEnabled(uuid, isChecked)
// .subscribe();
// }
//
// class DictionaryAction extends Subscriber<IDictionaryStatus> {
//
// final List<CharSequence> displayValuesList = new LinkedList<>();
// final List<String> entryValuesList = new LinkedList<>();
// final List<Boolean> statesList = new ArrayList<>();
//
// @Override
// public void onCompleted() {
// displayValues = displayValuesList.toArray(new CharSequence[displayValuesList.size()]);
// entryValues = entryValuesList.toArray(new String[entryValuesList.size()]);
// states = new boolean[statesList.size()];
//
// for (int i = 0; i < statesList.size(); i++) {
// states[i] = statesList.get(i);
// }
// }
//
// @Override
// public void onError(Throwable e) {
// throw new IllegalStateException(e);
// }
//
// @Override
// public void onNext(IDictionaryStatus dictionaryStatus) {
// IDictionary dictionary = dictionaryStatus.getDictionary();
// String displayName = dictionaryStatus.getName();
// String entryValue = dictionary.getUUID();
// boolean enabled = dictionaryStatus.isEnabled();
//
// displayValuesList.add(displayName);
// entryValuesList.add(entryValue);
// statesList.add(enabled);
// }
//
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentSettings.java
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.ToxicBakery.app.screenshot_redaction.ActivityLicenses;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.widget.DictionarySelectionDialog;
package com.ToxicBakery.app.screenshot_redaction.fragment;
public class FragmentSettings extends PreferenceFragment implements Preference.OnPreferenceClickListener {
public static final String TAG = "FragmentSettings";
public static final String PREF_LICENSES = "pref_licenses";
public static final String PREF_DICTIONARIES = "pref_dictionaries";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
findPreference(PREF_LICENSES).setOnPreferenceClickListener(this);
findPreference(PREF_DICTIONARIES).setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceClick(Preference preference) {
switch (preference.getKey()) {
case PREF_LICENSES: | Intent intent = new Intent(getActivity(), ActivityLicenses.class); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentSettings.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivityLicenses.java
// public class ActivityLicenses extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_licenses);
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, new FragmentLicenseList(), FragmentLicenseList.TAG)
// .commit();
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
// getSupportFragmentManager().popBackStackImmediate();
// } else {
// finish();
// }
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/widget/DictionarySelectionDialog.java
// public class DictionarySelectionDialog extends DialogFragment implements DialogInterface.OnMultiChoiceClickListener {
//
// public static final String TAG = "DictionarySelectionDialog";
//
// private DictionaryProvider dictionaryProvider;
// private CharSequence[] displayValues;
// private String[] entryValues;
// private boolean[] states;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// dictionaryProvider = DictionaryProvider.getInstance(getActivity());
//
// dictionaryProvider.getDictionaries()
// .subscribe(new DictionaryAction());
// }
//
// @NonNull
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// return new AlertDialog.Builder(getActivity())
// .setTitle(R.string.pref_dictionaries)
// .setMultiChoiceItems(displayValues, states, this)
// .setPositiveButton(android.R.string.ok, null)
// .create();
// }
//
// @Override
// public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// String uuid = entryValues[which];
// dictionaryProvider.setDictionaryEnabled(uuid, isChecked)
// .subscribe();
// }
//
// class DictionaryAction extends Subscriber<IDictionaryStatus> {
//
// final List<CharSequence> displayValuesList = new LinkedList<>();
// final List<String> entryValuesList = new LinkedList<>();
// final List<Boolean> statesList = new ArrayList<>();
//
// @Override
// public void onCompleted() {
// displayValues = displayValuesList.toArray(new CharSequence[displayValuesList.size()]);
// entryValues = entryValuesList.toArray(new String[entryValuesList.size()]);
// states = new boolean[statesList.size()];
//
// for (int i = 0; i < statesList.size(); i++) {
// states[i] = statesList.get(i);
// }
// }
//
// @Override
// public void onError(Throwable e) {
// throw new IllegalStateException(e);
// }
//
// @Override
// public void onNext(IDictionaryStatus dictionaryStatus) {
// IDictionary dictionary = dictionaryStatus.getDictionary();
// String displayName = dictionaryStatus.getName();
// String entryValue = dictionary.getUUID();
// boolean enabled = dictionaryStatus.isEnabled();
//
// displayValuesList.add(displayName);
// entryValuesList.add(entryValue);
// statesList.add(enabled);
// }
//
// }
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.ToxicBakery.app.screenshot_redaction.ActivityLicenses;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.widget.DictionarySelectionDialog; | package com.ToxicBakery.app.screenshot_redaction.fragment;
public class FragmentSettings extends PreferenceFragment implements Preference.OnPreferenceClickListener {
public static final String TAG = "FragmentSettings";
public static final String PREF_LICENSES = "pref_licenses";
public static final String PREF_DICTIONARIES = "pref_dictionaries";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
findPreference(PREF_LICENSES).setOnPreferenceClickListener(this);
findPreference(PREF_DICTIONARIES).setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceClick(Preference preference) {
switch (preference.getKey()) {
case PREF_LICENSES:
Intent intent = new Intent(getActivity(), ActivityLicenses.class);
startActivity(intent);
return true;
case PREF_DICTIONARIES: | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivityLicenses.java
// public class ActivityLicenses extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_licenses);
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, new FragmentLicenseList(), FragmentLicenseList.TAG)
// .commit();
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
// getSupportFragmentManager().popBackStackImmediate();
// } else {
// finish();
// }
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/widget/DictionarySelectionDialog.java
// public class DictionarySelectionDialog extends DialogFragment implements DialogInterface.OnMultiChoiceClickListener {
//
// public static final String TAG = "DictionarySelectionDialog";
//
// private DictionaryProvider dictionaryProvider;
// private CharSequence[] displayValues;
// private String[] entryValues;
// private boolean[] states;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// dictionaryProvider = DictionaryProvider.getInstance(getActivity());
//
// dictionaryProvider.getDictionaries()
// .subscribe(new DictionaryAction());
// }
//
// @NonNull
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// return new AlertDialog.Builder(getActivity())
// .setTitle(R.string.pref_dictionaries)
// .setMultiChoiceItems(displayValues, states, this)
// .setPositiveButton(android.R.string.ok, null)
// .create();
// }
//
// @Override
// public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// String uuid = entryValues[which];
// dictionaryProvider.setDictionaryEnabled(uuid, isChecked)
// .subscribe();
// }
//
// class DictionaryAction extends Subscriber<IDictionaryStatus> {
//
// final List<CharSequence> displayValuesList = new LinkedList<>();
// final List<String> entryValuesList = new LinkedList<>();
// final List<Boolean> statesList = new ArrayList<>();
//
// @Override
// public void onCompleted() {
// displayValues = displayValuesList.toArray(new CharSequence[displayValuesList.size()]);
// entryValues = entryValuesList.toArray(new String[entryValuesList.size()]);
// states = new boolean[statesList.size()];
//
// for (int i = 0; i < statesList.size(); i++) {
// states[i] = statesList.get(i);
// }
// }
//
// @Override
// public void onError(Throwable e) {
// throw new IllegalStateException(e);
// }
//
// @Override
// public void onNext(IDictionaryStatus dictionaryStatus) {
// IDictionary dictionary = dictionaryStatus.getDictionary();
// String displayName = dictionaryStatus.getName();
// String entryValue = dictionary.getUUID();
// boolean enabled = dictionaryStatus.isEnabled();
//
// displayValuesList.add(displayName);
// entryValuesList.add(entryValue);
// statesList.add(enabled);
// }
//
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentSettings.java
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.ToxicBakery.app.screenshot_redaction.ActivityLicenses;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.widget.DictionarySelectionDialog;
package com.ToxicBakery.app.screenshot_redaction.fragment;
public class FragmentSettings extends PreferenceFragment implements Preference.OnPreferenceClickListener {
public static final String TAG = "FragmentSettings";
public static final String PREF_LICENSES = "pref_licenses";
public static final String PREF_DICTIONARIES = "pref_dictionaries";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
findPreference(PREF_LICENSES).setOnPreferenceClickListener(this);
findPreference(PREF_DICTIONARIES).setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceClick(Preference preference) {
switch (preference.getKey()) {
case PREF_LICENSES:
Intent intent = new Intent(getActivity(), ActivityLicenses.class);
startActivity(intent);
return true;
case PREF_DICTIONARIES: | new DictionarySelectionDialog().show(getFragmentManager(), DictionarySelectionDialog.TAG); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivitySettings.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentSettings.java
// public class FragmentSettings extends PreferenceFragment implements Preference.OnPreferenceClickListener {
//
// public static final String TAG = "FragmentSettings";
// public static final String PREF_LICENSES = "pref_licenses";
// public static final String PREF_DICTIONARIES = "pref_dictionaries";
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.settings);
//
// findPreference(PREF_LICENSES).setOnPreferenceClickListener(this);
// findPreference(PREF_DICTIONARIES).setOnPreferenceClickListener(this);
// }
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
// switch (preference.getKey()) {
// case PREF_LICENSES:
// Intent intent = new Intent(getActivity(), ActivityLicenses.class);
// startActivity(intent);
// return true;
// case PREF_DICTIONARIES:
// new DictionarySelectionDialog().show(getFragmentManager(), DictionarySelectionDialog.TAG);
// return true;
// }
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/util/PermissionCheck.java
// public class PermissionCheck {
//
// public static boolean hasPermissions(@NonNull Context context,
// @NonNull String[] requiredPermissions) {
//
// for (String requiredPermission : requiredPermissions) {
// int grant = PermissionChecker.checkSelfPermission(context, requiredPermission);
// if (grant != PermissionChecker.PERMISSION_GRANTED) {
// return false;
// }
// }
//
// return true;
// }
//
// }
| import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ToxicBakery.android.version.Is;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentSettings;
import com.ToxicBakery.app.screenshot_redaction.util.PermissionCheck;
import jonathanfinerty.once.Once;
import static com.ToxicBakery.android.version.SdkVersion.MARSHMALLOW; | package com.ToxicBakery.app.screenshot_redaction;
public class ActivitySettings extends AppCompatActivity {
private static final String KEY_SHOW_TUTORIAL = "KEY_SHOW_TUTORIAL";
private static final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.READ_EXTERNAL_STORAGE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction() | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentSettings.java
// public class FragmentSettings extends PreferenceFragment implements Preference.OnPreferenceClickListener {
//
// public static final String TAG = "FragmentSettings";
// public static final String PREF_LICENSES = "pref_licenses";
// public static final String PREF_DICTIONARIES = "pref_dictionaries";
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.settings);
//
// findPreference(PREF_LICENSES).setOnPreferenceClickListener(this);
// findPreference(PREF_DICTIONARIES).setOnPreferenceClickListener(this);
// }
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
// switch (preference.getKey()) {
// case PREF_LICENSES:
// Intent intent = new Intent(getActivity(), ActivityLicenses.class);
// startActivity(intent);
// return true;
// case PREF_DICTIONARIES:
// new DictionarySelectionDialog().show(getFragmentManager(), DictionarySelectionDialog.TAG);
// return true;
// }
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/util/PermissionCheck.java
// public class PermissionCheck {
//
// public static boolean hasPermissions(@NonNull Context context,
// @NonNull String[] requiredPermissions) {
//
// for (String requiredPermission : requiredPermissions) {
// int grant = PermissionChecker.checkSelfPermission(context, requiredPermission);
// if (grant != PermissionChecker.PERMISSION_GRANTED) {
// return false;
// }
// }
//
// return true;
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivitySettings.java
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ToxicBakery.android.version.Is;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentSettings;
import com.ToxicBakery.app.screenshot_redaction.util.PermissionCheck;
import jonathanfinerty.once.Once;
import static com.ToxicBakery.android.version.SdkVersion.MARSHMALLOW;
package com.ToxicBakery.app.screenshot_redaction;
public class ActivitySettings extends AppCompatActivity {
private static final String KEY_SHOW_TUTORIAL = "KEY_SHOW_TUTORIAL";
private static final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.READ_EXTERNAL_STORAGE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction() | .replace(R.id.container, new FragmentSettings(), FragmentSettings.TAG) |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivitySettings.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentSettings.java
// public class FragmentSettings extends PreferenceFragment implements Preference.OnPreferenceClickListener {
//
// public static final String TAG = "FragmentSettings";
// public static final String PREF_LICENSES = "pref_licenses";
// public static final String PREF_DICTIONARIES = "pref_dictionaries";
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.settings);
//
// findPreference(PREF_LICENSES).setOnPreferenceClickListener(this);
// findPreference(PREF_DICTIONARIES).setOnPreferenceClickListener(this);
// }
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
// switch (preference.getKey()) {
// case PREF_LICENSES:
// Intent intent = new Intent(getActivity(), ActivityLicenses.class);
// startActivity(intent);
// return true;
// case PREF_DICTIONARIES:
// new DictionarySelectionDialog().show(getFragmentManager(), DictionarySelectionDialog.TAG);
// return true;
// }
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/util/PermissionCheck.java
// public class PermissionCheck {
//
// public static boolean hasPermissions(@NonNull Context context,
// @NonNull String[] requiredPermissions) {
//
// for (String requiredPermission : requiredPermissions) {
// int grant = PermissionChecker.checkSelfPermission(context, requiredPermission);
// if (grant != PermissionChecker.PERMISSION_GRANTED) {
// return false;
// }
// }
//
// return true;
// }
//
// }
| import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ToxicBakery.android.version.Is;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentSettings;
import com.ToxicBakery.app.screenshot_redaction.util.PermissionCheck;
import jonathanfinerty.once.Once;
import static com.ToxicBakery.android.version.SdkVersion.MARSHMALLOW; | package com.ToxicBakery.app.screenshot_redaction;
public class ActivitySettings extends AppCompatActivity {
private static final String KEY_SHOW_TUTORIAL = "KEY_SHOW_TUTORIAL";
private static final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.READ_EXTERNAL_STORAGE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new FragmentSettings(), FragmentSettings.TAG)
.commit();
}
| // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentSettings.java
// public class FragmentSettings extends PreferenceFragment implements Preference.OnPreferenceClickListener {
//
// public static final String TAG = "FragmentSettings";
// public static final String PREF_LICENSES = "pref_licenses";
// public static final String PREF_DICTIONARIES = "pref_dictionaries";
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.settings);
//
// findPreference(PREF_LICENSES).setOnPreferenceClickListener(this);
// findPreference(PREF_DICTIONARIES).setOnPreferenceClickListener(this);
// }
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
// switch (preference.getKey()) {
// case PREF_LICENSES:
// Intent intent = new Intent(getActivity(), ActivityLicenses.class);
// startActivity(intent);
// return true;
// case PREF_DICTIONARIES:
// new DictionarySelectionDialog().show(getFragmentManager(), DictionarySelectionDialog.TAG);
// return true;
// }
// return false;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/util/PermissionCheck.java
// public class PermissionCheck {
//
// public static boolean hasPermissions(@NonNull Context context,
// @NonNull String[] requiredPermissions) {
//
// for (String requiredPermission : requiredPermissions) {
// int grant = PermissionChecker.checkSelfPermission(context, requiredPermission);
// if (grant != PermissionChecker.PERMISSION_GRANTED) {
// return false;
// }
// }
//
// return true;
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ActivitySettings.java
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ToxicBakery.android.version.Is;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentSettings;
import com.ToxicBakery.app.screenshot_redaction.util.PermissionCheck;
import jonathanfinerty.once.Once;
import static com.ToxicBakery.android.version.SdkVersion.MARSHMALLOW;
package com.ToxicBakery.app.screenshot_redaction;
public class ActivitySettings extends AppCompatActivity {
private static final String KEY_SHOW_TUTORIAL = "KEY_SHOW_TUTORIAL";
private static final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.READ_EXTERNAL_STORAGE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new FragmentSettings(), FragmentSettings.TAG)
.commit();
}
| final boolean hasPermissions = PermissionCheck.hasPermissions(this, REQUIRED_PERMISSIONS); |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNamesTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishNamesTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNamesTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishNamesTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule | public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class, false, true); |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNamesTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishNamesTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class, false, true);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception { | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNamesTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishNamesTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class, false, true);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception { | subscription = CopyBus.getInstance() |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNamesTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishNamesTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class, false, true);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception {
subscription = CopyBus.getInstance()
.register()
.first()
.subscribeOn(Schedulers.io()) | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNamesTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishNamesTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class, false, true);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception {
subscription = CopyBus.getInstance()
.register()
.first()
.subscribeOn(Schedulers.io()) | .subscribe(new Action1<CopyToSdCard.ICopyConfiguration>() { |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNamesTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishNamesTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class, false, true);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception {
subscription = CopyBus.getInstance()
.register()
.first()
.subscribeOn(Schedulers.io())
.subscribe(new Action1<CopyToSdCard.ICopyConfiguration>() {
@Override
public void call(CopyToSdCard.ICopyConfiguration iCopyConfiguration) {
semaphore.release();
}
});
DictionaryEnglishNames.getInstance(getContext());
}
@After
public void tearDown() throws Exception {
subscription.unsubscribe();
}
@SuppressWarnings("unused") | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/CopyBus.java
// public class CopyBus extends ADefaultBus<ICopyConfiguration> {
//
// private static volatile CopyBus instance;
//
// public static CopyBus getInstance() {
// if (instance == null) {
// synchronized (CopyBus.class) {
// if (instance == null) {
// instance = new CopyBus();
// }
// }
// }
//
// return instance;
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/CopyToSdCard.java
// public class CopyToSdCard {
//
// public void copy(@NonNull ICopyConfiguration copy) {
// Observable.just(copy)
// .observeOn(Schedulers.io())
// .subscribeOn(Schedulers.io())
// .subscribe(new CopyAction());
// }
//
// public interface ICopyConfiguration {
//
// InputStream getCopyStream() throws IOException;
//
// File getTarget() throws IOException;
//
// long getSize() throws IOException;
//
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/copy/WordListRawResourceCopyConfiguration.java
// public class WordListRawResourceCopyConfiguration implements CopyToSdCard.ICopyConfiguration {
//
// private static final String FOLDER = "wordlists";
//
// private final Context context;
// private final int rawRes;
// private final File baseDir;
//
// public WordListRawResourceCopyConfiguration(@NonNull Context context,
// @RawRes int rawRes) {
//
// this.context = context.getApplicationContext();
// this.rawRes = rawRes;
//
// baseDir = new File(context.getExternalFilesDir(null), FOLDER);
//
// try {
// FileUtils.forceMkdir(baseDir);
// } catch (IOException e) {
// throw new IllegalStateException("Failed to create required directory " + baseDir, e);
// }
// }
//
// @Override
// public InputStream getCopyStream() throws IOException {
// return context.getResources()
// .openRawResource(rawRes);
// }
//
// @Override
// public File getTarget() throws IOException {
// String resourceEntryName = context.getResources()
// .getResourceEntryName(rawRes);
//
// return new File(baseDir, resourceEntryName);
// }
//
// @Override
// public long getSize() throws IOException {
// InputStream inputStream = context.getResources()
// .openRawResource(rawRes);
//
// long fileSize = inputStream.available();
// inputStream.close();
//
// return fileSize;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o != null
// && o instanceof WordListRawResourceCopyConfiguration) {
//
// WordListRawResourceCopyConfiguration other = (WordListRawResourceCopyConfiguration) o;
// return rawRes == other.rawRes
// && baseDir.equals(other.baseDir);
// }
//
// return false;
// }
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNamesTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus;
import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard;
import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import rx.Subscription;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl;
@RunWith(AndroidJUnit4.class)
public class DictionaryEnglishNamesTest {
private final Semaphore semaphore = new Semaphore(0);
@Rule
public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class, false, true);
private Subscription subscription;
private Context getContext() {
return activityTestRule.getActivity();
}
@Before
public void setUp() throws Exception {
subscription = CopyBus.getInstance()
.register()
.first()
.subscribeOn(Schedulers.io())
.subscribe(new Action1<CopyToSdCard.ICopyConfiguration>() {
@Override
public void call(CopyToSdCard.ICopyConfiguration iCopyConfiguration) {
semaphore.release();
}
});
DictionaryEnglishNames.getInstance(getContext());
}
@After
public void tearDown() throws Exception {
subscription.unsubscribe();
}
@SuppressWarnings("unused") | public void onEvent(WordListRawResourceCopyConfiguration copyConfiguration) { |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/recycler/TutorialAdapter.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentInitialize.java
// public class FragmentInitialize extends Fragment implements View.OnClickListener {
//
// private static final String[] REQUIRED_PERMISSIONS = {
// Manifest.permission.READ_EXTERNAL_STORAGE
// };
//
// private static final int PERMISSION_REQUEST_CODE = 1;
//
// private Scene sceneComplete;
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_initialize, container, false);
//
// if (Is.greaterThanOrEqual(MARSHMALLOW)) {
// view.findViewById(R.id.tutorial_accept)
// .setOnClickListener(this);
//
// ViewGroup sceneRoot = (ViewGroup) view.findViewById(R.id.scene_root);
// sceneComplete = Scene.getSceneForLayout(sceneRoot, R.layout.scene_finished, getContext());
//
// if (hasPermissions()) {
// sceneComplete.enter();
// }
// } else {
// view.findViewById(R.id.tutorial_done)
// .setOnClickListener(this);
// }
//
// return view;
// }
//
// @Override
// public void setUserVisibleHint(boolean isVisibleToUser) {
// super.setUserVisibleHint(isVisibleToUser);
//
// if (isVisibleToUser) {
// if (Is.lessThan(MARSHMALLOW) || hasPermissions()) {
// performCopy();
// }
// }
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.tutorial_accept:
// if (hasPermissions()) {
// performCopy();
// animateFinished();
// } else {
// requestPermissions(REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE);
// }
// break;
// case R.id.tutorial_done:
// getActivity().finish();
// break;
// }
// }
//
// @Override
// public void onRequestPermissionsResult(int requestCode,
// @NonNull String[] permissions,
// @NonNull int[] grantResults) {
//
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//
// Observable.just(hasPermissions())
// .subscribe(new Action1<Boolean>() {
// @Override
// public void call(Boolean hasPermission) {
// if (hasPermission) {
// performCopy();
// animateFinished();
// }
// }
// });
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// void animateFinished() {
// Transition slideFromEnd = new Slide(Gravity.END);
// TransitionManager.go(sceneComplete, slideFromEnd);
//
// sceneComplete.getSceneRoot()
// .findViewById(R.id.tutorial_done)
// .setOnClickListener(this);
// }
//
// @MainThread
// void performCopy() {
// Context context = getContext();
// new CopyToSdCard().copy(new TessDataRawResourceCopyConfiguration(context, R.raw.eng));
// DictionaryEnglish.getInstance(context);
// DictionaryEnglishNames.getInstance(context);
// ScreenshotService.startScreenshotService(context);
// }
//
// @MainThread
// boolean hasPermissions() {
// return Is.lessThan(MARSHMALLOW)
// || PermissionCheck.hasPermissions(getContext(), REQUIRED_PERMISSIONS);
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentTutorial.java
// public class FragmentTutorial extends Fragment implements View.OnClickListener {
//
// public static final int ARROW_RIGHT = 1;
//
// private static final String EXTRA_TEXT = "EXTRA_TEXT";
// private static final String EXTRA_IMAGE = "EXTRA_IMAGE";
//
// private TutorialBus tutorialBus = TutorialBus.getInstance();
//
// public static FragmentTutorial createInstance(@StringRes int description,
// @DrawableRes int image) {
//
// Bundle bundle = new Bundle();
// bundle.putInt(EXTRA_TEXT, description);
// bundle.putInt(EXTRA_IMAGE, image);
//
// FragmentTutorial fragmentTutorial = new FragmentTutorial();
// fragmentTutorial.setArguments(bundle);
// return fragmentTutorial;
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Bundle bundle = getArguments();
// int description = bundle.getInt(EXTRA_TEXT);
// int image = bundle.getInt(EXTRA_IMAGE);
//
// View view = inflater.inflate(R.layout.fragment_tutorial, container, false);
//
// ((TextView) view.findViewById(R.id.tutorial_description)).setText(description);
// ((ImageView) view.findViewById(R.id.tutorial_image)).setImageResource(image);
//
// view.findViewById(R.id.tutorial_arrow_right)
// .setOnClickListener(this);
//
// return view;
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.tutorial_arrow_right:
// moveToNextPage();
// break;
// }
// }
//
// void moveToNextPage() {
// tutorialBus.post(ARROW_RIGHT);
// }
//
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentInitialize;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentTutorial; | package com.ToxicBakery.app.screenshot_redaction.recycler;
public class TutorialAdapter extends FragmentPagerAdapter {
private static final Fragment[] fragments = { | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentInitialize.java
// public class FragmentInitialize extends Fragment implements View.OnClickListener {
//
// private static final String[] REQUIRED_PERMISSIONS = {
// Manifest.permission.READ_EXTERNAL_STORAGE
// };
//
// private static final int PERMISSION_REQUEST_CODE = 1;
//
// private Scene sceneComplete;
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_initialize, container, false);
//
// if (Is.greaterThanOrEqual(MARSHMALLOW)) {
// view.findViewById(R.id.tutorial_accept)
// .setOnClickListener(this);
//
// ViewGroup sceneRoot = (ViewGroup) view.findViewById(R.id.scene_root);
// sceneComplete = Scene.getSceneForLayout(sceneRoot, R.layout.scene_finished, getContext());
//
// if (hasPermissions()) {
// sceneComplete.enter();
// }
// } else {
// view.findViewById(R.id.tutorial_done)
// .setOnClickListener(this);
// }
//
// return view;
// }
//
// @Override
// public void setUserVisibleHint(boolean isVisibleToUser) {
// super.setUserVisibleHint(isVisibleToUser);
//
// if (isVisibleToUser) {
// if (Is.lessThan(MARSHMALLOW) || hasPermissions()) {
// performCopy();
// }
// }
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.tutorial_accept:
// if (hasPermissions()) {
// performCopy();
// animateFinished();
// } else {
// requestPermissions(REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE);
// }
// break;
// case R.id.tutorial_done:
// getActivity().finish();
// break;
// }
// }
//
// @Override
// public void onRequestPermissionsResult(int requestCode,
// @NonNull String[] permissions,
// @NonNull int[] grantResults) {
//
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//
// Observable.just(hasPermissions())
// .subscribe(new Action1<Boolean>() {
// @Override
// public void call(Boolean hasPermission) {
// if (hasPermission) {
// performCopy();
// animateFinished();
// }
// }
// });
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// void animateFinished() {
// Transition slideFromEnd = new Slide(Gravity.END);
// TransitionManager.go(sceneComplete, slideFromEnd);
//
// sceneComplete.getSceneRoot()
// .findViewById(R.id.tutorial_done)
// .setOnClickListener(this);
// }
//
// @MainThread
// void performCopy() {
// Context context = getContext();
// new CopyToSdCard().copy(new TessDataRawResourceCopyConfiguration(context, R.raw.eng));
// DictionaryEnglish.getInstance(context);
// DictionaryEnglishNames.getInstance(context);
// ScreenshotService.startScreenshotService(context);
// }
//
// @MainThread
// boolean hasPermissions() {
// return Is.lessThan(MARSHMALLOW)
// || PermissionCheck.hasPermissions(getContext(), REQUIRED_PERMISSIONS);
// }
//
// }
//
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/fragment/FragmentTutorial.java
// public class FragmentTutorial extends Fragment implements View.OnClickListener {
//
// public static final int ARROW_RIGHT = 1;
//
// private static final String EXTRA_TEXT = "EXTRA_TEXT";
// private static final String EXTRA_IMAGE = "EXTRA_IMAGE";
//
// private TutorialBus tutorialBus = TutorialBus.getInstance();
//
// public static FragmentTutorial createInstance(@StringRes int description,
// @DrawableRes int image) {
//
// Bundle bundle = new Bundle();
// bundle.putInt(EXTRA_TEXT, description);
// bundle.putInt(EXTRA_IMAGE, image);
//
// FragmentTutorial fragmentTutorial = new FragmentTutorial();
// fragmentTutorial.setArguments(bundle);
// return fragmentTutorial;
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Bundle bundle = getArguments();
// int description = bundle.getInt(EXTRA_TEXT);
// int image = bundle.getInt(EXTRA_IMAGE);
//
// View view = inflater.inflate(R.layout.fragment_tutorial, container, false);
//
// ((TextView) view.findViewById(R.id.tutorial_description)).setText(description);
// ((ImageView) view.findViewById(R.id.tutorial_image)).setImageResource(image);
//
// view.findViewById(R.id.tutorial_arrow_right)
// .setOnClickListener(this);
//
// return view;
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.tutorial_arrow_right:
// moveToNextPage();
// break;
// }
// }
//
// void moveToNextPage() {
// tutorialBus.post(ARROW_RIGHT);
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/recycler/TutorialAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentInitialize;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentTutorial;
package com.ToxicBakery.app.screenshot_redaction.recycler;
public class TutorialAdapter extends FragmentPagerAdapter {
private static final Fragment[] fragments = { | FragmentTutorial.createInstance(R.string.tutorial_screenshot, R.drawable.tutorial_frame_screenshot), |
ToxicBakery/Screenshot-Redaction | app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/DictionaryProviderTest.java | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
| import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.ToxicBakery.app.screenshot_redaction.dictionary;
@RunWith(AndroidJUnit4.class)
public class DictionaryProviderTest {
@Rule | // Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/ActivityTest.java
// public class ActivityTest extends Activity {
//
// }
// Path: app/src/androidTest/java/com/ToxicBakery/app/screenshot_redaction/dictionary/DictionaryProviderTest.java
import android.content.Context;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ToxicBakery.app.screenshot_redaction.ActivityTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package com.ToxicBakery.app.screenshot_redaction.dictionary;
@RunWith(AndroidJUnit4.class)
public class DictionaryProviderTest {
@Rule | public ActivityTestRule<ActivityTest> activityTestRule = new ActivityTestRule<>(ActivityTest.class); |
ToxicBakery/Screenshot-Redaction | app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ocr/OcrImageResultStore.java | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/OcrImageResultBus.java
// public class OcrImageResultBus extends ADefaultBus<OcrImageResult> {
//
// private static volatile OcrImageResultBus instance;
//
// public static OcrImageResultBus getInstance() {
// if (instance == null) {
// synchronized (TutorialBus.class) {
// if (instance == null) {
// instance = new OcrImageResultBus();
// }
// }
// }
//
// return instance;
// }
//
// }
| import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.ToxicBakery.app.screenshot_redaction.bus.OcrImageResultBus;
import java.util.HashMap;
import java.util.Map; | package com.ToxicBakery.app.screenshot_redaction.ocr;
@SuppressWarnings("WeakerAccess")
public class OcrImageResultStore {
private static OcrImageResultStore instance;
private final Map<Uri, OcrImageResult> results; | // Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/bus/OcrImageResultBus.java
// public class OcrImageResultBus extends ADefaultBus<OcrImageResult> {
//
// private static volatile OcrImageResultBus instance;
//
// public static OcrImageResultBus getInstance() {
// if (instance == null) {
// synchronized (TutorialBus.class) {
// if (instance == null) {
// instance = new OcrImageResultBus();
// }
// }
// }
//
// return instance;
// }
//
// }
// Path: app/src/main/java/com/ToxicBakery/app/screenshot_redaction/ocr/OcrImageResultStore.java
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.ToxicBakery.app.screenshot_redaction.bus.OcrImageResultBus;
import java.util.HashMap;
import java.util.Map;
package com.ToxicBakery.app.screenshot_redaction.ocr;
@SuppressWarnings("WeakerAccess")
public class OcrImageResultStore {
private static OcrImageResultStore instance;
private final Map<Uri, OcrImageResult> results; | private final OcrImageResultBus ocrImageResultBus; |
vsfexperts/LaTeX | latex-renderer/src/main/java/de/vsfexperts/latex/renderer/SynchronousLatexRenderer.java | // Path: latex-renderer/src/main/java/de/vsfexperts/latex/storage/Archive.java
// public interface Archive {
//
// /**
// * Stores the contents of the file in the archive. The filename is used by the archive to identify the object.
// *
// * @param id
// * to identify archive
// * @param file
// * to be stored
// */
// void store(UUID id, File file) throws ArchiveException;
//
// /**
// * Deletes an archived object
// *
// * @param id
// * of archive
// * @param name
// * of object to delete
// */
// void delete(UUID id, String name) throws ArchiveException;
//
// /**
// * List content of archive
// *
// * @param id
// * @return List of objects
// */
// List<String> list(UUID id);
//
// /**
// * Returns an archived object
// *
// * @param id
// * of archive
// * @param name
// * of object
// * @return file pointing to storage location
// */
// Optional<File> get(UUID id, String name);
//
// }
//
// Path: latex-renderer/src/main/java/de/vsfexperts/latex/storage/LocalFileSystemStorage.java
// public class LocalFileSystemStorage {
//
// private final String baseDirectory;
//
// public LocalFileSystemStorage() {
// this(FileUtils.getTempDirectoryPath());
// }
//
// public LocalFileSystemStorage(final File baseDirectory) {
// this(baseDirectory.getAbsolutePath());
// }
//
// public LocalFileSystemStorage(final String baseDirectory) {
// this.baseDirectory = baseDirectory;
// }
//
// public File getBaseDirectory(final UUID jobId) throws FileSystemException {
// requireNonNull(jobId);
//
// final File jobDirectory = new File(getGlobalBaseDirectory(), jobId.toString());
//
// try {
// FileUtils.forceMkdir(jobDirectory);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
//
// return jobDirectory;
// }
//
// private File getGlobalBaseDirectory() throws FileSystemException {
// final File globalBaseDirectory = new File(baseDirectory);
// try {
// FileUtils.forceMkdir(globalBaseDirectory);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// return globalBaseDirectory;
// }
//
// public File createFile(final UUID jobId, final String filename, final String content) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// final File finalFile = new File(getBaseDirectory(jobId), filename);
// final File tempFile = new File(getBaseDirectory(jobId), filename + ".tmp");
//
// try {
// FileUtils.write(tempFile, content, Charset.forName("UTF-8"));
// FileUtils.moveFile(tempFile, finalFile);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
//
// return finalFile;
// }
//
// public void addFile(final UUID jobId, final File file) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(file);
//
// final File finalFile = new File(getBaseDirectory(jobId), file.getName());
// final File tempFile = new File(getBaseDirectory(jobId), file.getName() + ".tmp");
//
// try {
// FileUtils.copyFile(file, tempFile, true);
// FileUtils.moveFile(tempFile, finalFile);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// }
//
// public Optional<File> getFile(final UUID jobId, final String filename) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// final File file = new File(getBaseDirectory(jobId), filename);
//
// if (!file.exists()) {
// return Optional.empty();
// }
//
// return Optional.of(file);
// }
//
// public List<String> list(final UUID jobId) {
// requireNonNull(jobId);
// return Arrays.stream(getBaseDirectory(jobId).listFiles()).map(File::getName).collect(Collectors.toList());
// }
//
// public void delete(final UUID jobId, final String filename) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// try {
// FileUtils.forceDelete(new File(getBaseDirectory(jobId), filename));
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// }
//
// public void delete(final UUID jobId) throws FileSystemException {
// requireNonNull(jobId);
//
// try {
// FileUtils.forceDelete(getBaseDirectory(jobId));
// } catch (final Exception e) {
// throw new FileSystemException(e);
// }
// }
//
// public void deleteFiles(final UUID jobId, final Predicate<String> filenamePredicate) {
// final FileFilter filter = f -> f.isFile() && filenamePredicate.test(f.getName());
// Arrays.stream(getBaseDirectory(jobId).listFiles(filter)).forEach(File::delete);
// }
//
// public void clear() throws FileSystemException {
// try {
// FileUtils.cleanDirectory(getGlobalBaseDirectory());
// } catch (final Exception e) {
// throw new FileSystemException(e);
// }
// }
//
// }
| import java.util.concurrent.Executor;
import de.vsfexperts.latex.storage.Archive;
import de.vsfexperts.latex.storage.LocalFileSystemStorage; | package de.vsfexperts.latex.renderer;
/**
* Single threaded renderer. This renderer is using the current thread to render the file in a synchronous way.
*/
public class SynchronousLatexRenderer extends GenericLatexRenderer {
private static final DirectExecutor DIRECT_EXECUTOR = new DirectExecutor();
public SynchronousLatexRenderer() {
}
| // Path: latex-renderer/src/main/java/de/vsfexperts/latex/storage/Archive.java
// public interface Archive {
//
// /**
// * Stores the contents of the file in the archive. The filename is used by the archive to identify the object.
// *
// * @param id
// * to identify archive
// * @param file
// * to be stored
// */
// void store(UUID id, File file) throws ArchiveException;
//
// /**
// * Deletes an archived object
// *
// * @param id
// * of archive
// * @param name
// * of object to delete
// */
// void delete(UUID id, String name) throws ArchiveException;
//
// /**
// * List content of archive
// *
// * @param id
// * @return List of objects
// */
// List<String> list(UUID id);
//
// /**
// * Returns an archived object
// *
// * @param id
// * of archive
// * @param name
// * of object
// * @return file pointing to storage location
// */
// Optional<File> get(UUID id, String name);
//
// }
//
// Path: latex-renderer/src/main/java/de/vsfexperts/latex/storage/LocalFileSystemStorage.java
// public class LocalFileSystemStorage {
//
// private final String baseDirectory;
//
// public LocalFileSystemStorage() {
// this(FileUtils.getTempDirectoryPath());
// }
//
// public LocalFileSystemStorage(final File baseDirectory) {
// this(baseDirectory.getAbsolutePath());
// }
//
// public LocalFileSystemStorage(final String baseDirectory) {
// this.baseDirectory = baseDirectory;
// }
//
// public File getBaseDirectory(final UUID jobId) throws FileSystemException {
// requireNonNull(jobId);
//
// final File jobDirectory = new File(getGlobalBaseDirectory(), jobId.toString());
//
// try {
// FileUtils.forceMkdir(jobDirectory);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
//
// return jobDirectory;
// }
//
// private File getGlobalBaseDirectory() throws FileSystemException {
// final File globalBaseDirectory = new File(baseDirectory);
// try {
// FileUtils.forceMkdir(globalBaseDirectory);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// return globalBaseDirectory;
// }
//
// public File createFile(final UUID jobId, final String filename, final String content) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// final File finalFile = new File(getBaseDirectory(jobId), filename);
// final File tempFile = new File(getBaseDirectory(jobId), filename + ".tmp");
//
// try {
// FileUtils.write(tempFile, content, Charset.forName("UTF-8"));
// FileUtils.moveFile(tempFile, finalFile);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
//
// return finalFile;
// }
//
// public void addFile(final UUID jobId, final File file) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(file);
//
// final File finalFile = new File(getBaseDirectory(jobId), file.getName());
// final File tempFile = new File(getBaseDirectory(jobId), file.getName() + ".tmp");
//
// try {
// FileUtils.copyFile(file, tempFile, true);
// FileUtils.moveFile(tempFile, finalFile);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// }
//
// public Optional<File> getFile(final UUID jobId, final String filename) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// final File file = new File(getBaseDirectory(jobId), filename);
//
// if (!file.exists()) {
// return Optional.empty();
// }
//
// return Optional.of(file);
// }
//
// public List<String> list(final UUID jobId) {
// requireNonNull(jobId);
// return Arrays.stream(getBaseDirectory(jobId).listFiles()).map(File::getName).collect(Collectors.toList());
// }
//
// public void delete(final UUID jobId, final String filename) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// try {
// FileUtils.forceDelete(new File(getBaseDirectory(jobId), filename));
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// }
//
// public void delete(final UUID jobId) throws FileSystemException {
// requireNonNull(jobId);
//
// try {
// FileUtils.forceDelete(getBaseDirectory(jobId));
// } catch (final Exception e) {
// throw new FileSystemException(e);
// }
// }
//
// public void deleteFiles(final UUID jobId, final Predicate<String> filenamePredicate) {
// final FileFilter filter = f -> f.isFile() && filenamePredicate.test(f.getName());
// Arrays.stream(getBaseDirectory(jobId).listFiles(filter)).forEach(File::delete);
// }
//
// public void clear() throws FileSystemException {
// try {
// FileUtils.cleanDirectory(getGlobalBaseDirectory());
// } catch (final Exception e) {
// throw new FileSystemException(e);
// }
// }
//
// }
// Path: latex-renderer/src/main/java/de/vsfexperts/latex/renderer/SynchronousLatexRenderer.java
import java.util.concurrent.Executor;
import de.vsfexperts.latex.storage.Archive;
import de.vsfexperts.latex.storage.LocalFileSystemStorage;
package de.vsfexperts.latex.renderer;
/**
* Single threaded renderer. This renderer is using the current thread to render the file in a synchronous way.
*/
public class SynchronousLatexRenderer extends GenericLatexRenderer {
private static final DirectExecutor DIRECT_EXECUTOR = new DirectExecutor();
public SynchronousLatexRenderer() {
}
| public SynchronousLatexRenderer(final LocalFileSystemStorage storage, final Archive archive) { |
vsfexperts/LaTeX | latex-renderer/src/main/java/de/vsfexperts/latex/renderer/SynchronousLatexRenderer.java | // Path: latex-renderer/src/main/java/de/vsfexperts/latex/storage/Archive.java
// public interface Archive {
//
// /**
// * Stores the contents of the file in the archive. The filename is used by the archive to identify the object.
// *
// * @param id
// * to identify archive
// * @param file
// * to be stored
// */
// void store(UUID id, File file) throws ArchiveException;
//
// /**
// * Deletes an archived object
// *
// * @param id
// * of archive
// * @param name
// * of object to delete
// */
// void delete(UUID id, String name) throws ArchiveException;
//
// /**
// * List content of archive
// *
// * @param id
// * @return List of objects
// */
// List<String> list(UUID id);
//
// /**
// * Returns an archived object
// *
// * @param id
// * of archive
// * @param name
// * of object
// * @return file pointing to storage location
// */
// Optional<File> get(UUID id, String name);
//
// }
//
// Path: latex-renderer/src/main/java/de/vsfexperts/latex/storage/LocalFileSystemStorage.java
// public class LocalFileSystemStorage {
//
// private final String baseDirectory;
//
// public LocalFileSystemStorage() {
// this(FileUtils.getTempDirectoryPath());
// }
//
// public LocalFileSystemStorage(final File baseDirectory) {
// this(baseDirectory.getAbsolutePath());
// }
//
// public LocalFileSystemStorage(final String baseDirectory) {
// this.baseDirectory = baseDirectory;
// }
//
// public File getBaseDirectory(final UUID jobId) throws FileSystemException {
// requireNonNull(jobId);
//
// final File jobDirectory = new File(getGlobalBaseDirectory(), jobId.toString());
//
// try {
// FileUtils.forceMkdir(jobDirectory);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
//
// return jobDirectory;
// }
//
// private File getGlobalBaseDirectory() throws FileSystemException {
// final File globalBaseDirectory = new File(baseDirectory);
// try {
// FileUtils.forceMkdir(globalBaseDirectory);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// return globalBaseDirectory;
// }
//
// public File createFile(final UUID jobId, final String filename, final String content) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// final File finalFile = new File(getBaseDirectory(jobId), filename);
// final File tempFile = new File(getBaseDirectory(jobId), filename + ".tmp");
//
// try {
// FileUtils.write(tempFile, content, Charset.forName("UTF-8"));
// FileUtils.moveFile(tempFile, finalFile);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
//
// return finalFile;
// }
//
// public void addFile(final UUID jobId, final File file) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(file);
//
// final File finalFile = new File(getBaseDirectory(jobId), file.getName());
// final File tempFile = new File(getBaseDirectory(jobId), file.getName() + ".tmp");
//
// try {
// FileUtils.copyFile(file, tempFile, true);
// FileUtils.moveFile(tempFile, finalFile);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// }
//
// public Optional<File> getFile(final UUID jobId, final String filename) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// final File file = new File(getBaseDirectory(jobId), filename);
//
// if (!file.exists()) {
// return Optional.empty();
// }
//
// return Optional.of(file);
// }
//
// public List<String> list(final UUID jobId) {
// requireNonNull(jobId);
// return Arrays.stream(getBaseDirectory(jobId).listFiles()).map(File::getName).collect(Collectors.toList());
// }
//
// public void delete(final UUID jobId, final String filename) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// try {
// FileUtils.forceDelete(new File(getBaseDirectory(jobId), filename));
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// }
//
// public void delete(final UUID jobId) throws FileSystemException {
// requireNonNull(jobId);
//
// try {
// FileUtils.forceDelete(getBaseDirectory(jobId));
// } catch (final Exception e) {
// throw new FileSystemException(e);
// }
// }
//
// public void deleteFiles(final UUID jobId, final Predicate<String> filenamePredicate) {
// final FileFilter filter = f -> f.isFile() && filenamePredicate.test(f.getName());
// Arrays.stream(getBaseDirectory(jobId).listFiles(filter)).forEach(File::delete);
// }
//
// public void clear() throws FileSystemException {
// try {
// FileUtils.cleanDirectory(getGlobalBaseDirectory());
// } catch (final Exception e) {
// throw new FileSystemException(e);
// }
// }
//
// }
| import java.util.concurrent.Executor;
import de.vsfexperts.latex.storage.Archive;
import de.vsfexperts.latex.storage.LocalFileSystemStorage; | package de.vsfexperts.latex.renderer;
/**
* Single threaded renderer. This renderer is using the current thread to render the file in a synchronous way.
*/
public class SynchronousLatexRenderer extends GenericLatexRenderer {
private static final DirectExecutor DIRECT_EXECUTOR = new DirectExecutor();
public SynchronousLatexRenderer() {
}
| // Path: latex-renderer/src/main/java/de/vsfexperts/latex/storage/Archive.java
// public interface Archive {
//
// /**
// * Stores the contents of the file in the archive. The filename is used by the archive to identify the object.
// *
// * @param id
// * to identify archive
// * @param file
// * to be stored
// */
// void store(UUID id, File file) throws ArchiveException;
//
// /**
// * Deletes an archived object
// *
// * @param id
// * of archive
// * @param name
// * of object to delete
// */
// void delete(UUID id, String name) throws ArchiveException;
//
// /**
// * List content of archive
// *
// * @param id
// * @return List of objects
// */
// List<String> list(UUID id);
//
// /**
// * Returns an archived object
// *
// * @param id
// * of archive
// * @param name
// * of object
// * @return file pointing to storage location
// */
// Optional<File> get(UUID id, String name);
//
// }
//
// Path: latex-renderer/src/main/java/de/vsfexperts/latex/storage/LocalFileSystemStorage.java
// public class LocalFileSystemStorage {
//
// private final String baseDirectory;
//
// public LocalFileSystemStorage() {
// this(FileUtils.getTempDirectoryPath());
// }
//
// public LocalFileSystemStorage(final File baseDirectory) {
// this(baseDirectory.getAbsolutePath());
// }
//
// public LocalFileSystemStorage(final String baseDirectory) {
// this.baseDirectory = baseDirectory;
// }
//
// public File getBaseDirectory(final UUID jobId) throws FileSystemException {
// requireNonNull(jobId);
//
// final File jobDirectory = new File(getGlobalBaseDirectory(), jobId.toString());
//
// try {
// FileUtils.forceMkdir(jobDirectory);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
//
// return jobDirectory;
// }
//
// private File getGlobalBaseDirectory() throws FileSystemException {
// final File globalBaseDirectory = new File(baseDirectory);
// try {
// FileUtils.forceMkdir(globalBaseDirectory);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// return globalBaseDirectory;
// }
//
// public File createFile(final UUID jobId, final String filename, final String content) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// final File finalFile = new File(getBaseDirectory(jobId), filename);
// final File tempFile = new File(getBaseDirectory(jobId), filename + ".tmp");
//
// try {
// FileUtils.write(tempFile, content, Charset.forName("UTF-8"));
// FileUtils.moveFile(tempFile, finalFile);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
//
// return finalFile;
// }
//
// public void addFile(final UUID jobId, final File file) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(file);
//
// final File finalFile = new File(getBaseDirectory(jobId), file.getName());
// final File tempFile = new File(getBaseDirectory(jobId), file.getName() + ".tmp");
//
// try {
// FileUtils.copyFile(file, tempFile, true);
// FileUtils.moveFile(tempFile, finalFile);
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// }
//
// public Optional<File> getFile(final UUID jobId, final String filename) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// final File file = new File(getBaseDirectory(jobId), filename);
//
// if (!file.exists()) {
// return Optional.empty();
// }
//
// return Optional.of(file);
// }
//
// public List<String> list(final UUID jobId) {
// requireNonNull(jobId);
// return Arrays.stream(getBaseDirectory(jobId).listFiles()).map(File::getName).collect(Collectors.toList());
// }
//
// public void delete(final UUID jobId, final String filename) throws FileSystemException {
// requireNonNull(jobId);
// requireNonNull(filename);
//
// try {
// FileUtils.forceDelete(new File(getBaseDirectory(jobId), filename));
// } catch (final IOException e) {
// throw new FileSystemException(e);
// }
// }
//
// public void delete(final UUID jobId) throws FileSystemException {
// requireNonNull(jobId);
//
// try {
// FileUtils.forceDelete(getBaseDirectory(jobId));
// } catch (final Exception e) {
// throw new FileSystemException(e);
// }
// }
//
// public void deleteFiles(final UUID jobId, final Predicate<String> filenamePredicate) {
// final FileFilter filter = f -> f.isFile() && filenamePredicate.test(f.getName());
// Arrays.stream(getBaseDirectory(jobId).listFiles(filter)).forEach(File::delete);
// }
//
// public void clear() throws FileSystemException {
// try {
// FileUtils.cleanDirectory(getGlobalBaseDirectory());
// } catch (final Exception e) {
// throw new FileSystemException(e);
// }
// }
//
// }
// Path: latex-renderer/src/main/java/de/vsfexperts/latex/renderer/SynchronousLatexRenderer.java
import java.util.concurrent.Executor;
import de.vsfexperts.latex.storage.Archive;
import de.vsfexperts.latex.storage.LocalFileSystemStorage;
package de.vsfexperts.latex.renderer;
/**
* Single threaded renderer. This renderer is using the current thread to render the file in a synchronous way.
*/
public class SynchronousLatexRenderer extends GenericLatexRenderer {
private static final DirectExecutor DIRECT_EXECUTOR = new DirectExecutor();
public SynchronousLatexRenderer() {
}
| public SynchronousLatexRenderer(final LocalFileSystemStorage storage, final Archive archive) { |
vsfexperts/LaTeX | latex-template/src/main/java/de/vsfexperts/latex/template/LatexTemplate.java | // Path: latex-template/src/main/java/de/vsfexperts/latex/template/tools/LatexEscapeTool.java
// public class LatexEscapeTool {
//
// public String escape(final String input) {
// if (input == null) {
// return null;
// }
//
// String output = input;
//
// // replace 1st, otherwise the substitution of \ will be applied twice (to other substitutions)
// output = output.replace("\\", "\\textbackslash ");
//
// output = output.replace("€", "\\euro ");
// output = output.replace("<", "\\textless ");
// output = output.replace(">", "\\textgreater ");
// output = output.replace("§", "\\S ");
//
// // LaTeX special characters
// output = output.replace("&", "\\&");
// output = output.replace("%", "\\%");
// output = output.replace("$", "\\$");
// output = output.replace("#", "\\#");
// output = output.replace("_", "\\_");
// output = output.replace("{", "\\{");
// output = output.replace("}", "\\}");
// output = output.replace("~", "\\textasciitilde ");
// output = output.replace("^", "\\textasciicircum ");
//
// return output;
// }
// }
| import static java.util.Objects.requireNonNull;
import static org.apache.velocity.runtime.RuntimeConstants.INPUT_ENCODING;
import static org.apache.velocity.runtime.RuntimeConstants.OUTPUT_ENCODING;
import static org.apache.velocity.runtime.RuntimeConstants.RESOURCE_LOADER;
import static org.apache.velocity.runtime.RuntimeConstants.RUNTIME_LOG_LOGSYSTEM;
import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.log.CommonsLogLogChute;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.tools.generic.MathTool;
import de.vsfexperts.latex.template.tools.LatexEscapeTool; | final VelocityContext velocityContext = prepareContext(context);
return evaluateTemplate(velocityContext, velocityEngine);
}
private final VelocityEngine initializeEngine() {
final VelocityEngine engine = new VelocityEngine();
engine.setProperty(INPUT_ENCODING, "UTF-8");
engine.setProperty(OUTPUT_ENCODING, "UTF-8");
engine.setProperty(RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute());
customize(engine);
engine.init();
return engine;
}
protected void customize(final VelocityEngine engine) {
engine.setProperty(RESOURCE_LOADER, "classpath");
engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
}
private final VelocityContext prepareContext(final LatexContext context) {
final VelocityContext velocityContext = new VelocityContext(context.asMap());
customize(velocityContext);
return velocityContext;
}
protected void customize(final VelocityContext velocityContext) { | // Path: latex-template/src/main/java/de/vsfexperts/latex/template/tools/LatexEscapeTool.java
// public class LatexEscapeTool {
//
// public String escape(final String input) {
// if (input == null) {
// return null;
// }
//
// String output = input;
//
// // replace 1st, otherwise the substitution of \ will be applied twice (to other substitutions)
// output = output.replace("\\", "\\textbackslash ");
//
// output = output.replace("€", "\\euro ");
// output = output.replace("<", "\\textless ");
// output = output.replace(">", "\\textgreater ");
// output = output.replace("§", "\\S ");
//
// // LaTeX special characters
// output = output.replace("&", "\\&");
// output = output.replace("%", "\\%");
// output = output.replace("$", "\\$");
// output = output.replace("#", "\\#");
// output = output.replace("_", "\\_");
// output = output.replace("{", "\\{");
// output = output.replace("}", "\\}");
// output = output.replace("~", "\\textasciitilde ");
// output = output.replace("^", "\\textasciicircum ");
//
// return output;
// }
// }
// Path: latex-template/src/main/java/de/vsfexperts/latex/template/LatexTemplate.java
import static java.util.Objects.requireNonNull;
import static org.apache.velocity.runtime.RuntimeConstants.INPUT_ENCODING;
import static org.apache.velocity.runtime.RuntimeConstants.OUTPUT_ENCODING;
import static org.apache.velocity.runtime.RuntimeConstants.RESOURCE_LOADER;
import static org.apache.velocity.runtime.RuntimeConstants.RUNTIME_LOG_LOGSYSTEM;
import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.log.CommonsLogLogChute;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.tools.generic.MathTool;
import de.vsfexperts.latex.template.tools.LatexEscapeTool;
final VelocityContext velocityContext = prepareContext(context);
return evaluateTemplate(velocityContext, velocityEngine);
}
private final VelocityEngine initializeEngine() {
final VelocityEngine engine = new VelocityEngine();
engine.setProperty(INPUT_ENCODING, "UTF-8");
engine.setProperty(OUTPUT_ENCODING, "UTF-8");
engine.setProperty(RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute());
customize(engine);
engine.init();
return engine;
}
protected void customize(final VelocityEngine engine) {
engine.setProperty(RESOURCE_LOADER, "classpath");
engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
}
private final VelocityContext prepareContext(final LatexContext context) {
final VelocityContext velocityContext = new VelocityContext(context.asMap());
customize(velocityContext);
return velocityContext;
}
protected void customize(final VelocityContext velocityContext) { | velocityContext.put("e", new LatexEscapeTool()); |
vsfexperts/LaTeX | latex-template/src/test/java/de/vsfexperts/latex/template/LatexTemplateIT.java | // Path: latex-template/src/test/java/de/vsfexperts/latex/template/ClasspathUtils.java
// public static String getContent(final String classpathLocation) throws IOException {
// return IOUtils.toString(new ClassPathResource(classpathLocation).getInputStream(), Charset.forName("UTF-8"));
// }
| import static de.vsfexperts.latex.template.ClasspathUtils.getContent;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test; | package de.vsfexperts.latex.template;
public class LatexTemplateIT {
@Test
public void processTemplate() throws Exception { | // Path: latex-template/src/test/java/de/vsfexperts/latex/template/ClasspathUtils.java
// public static String getContent(final String classpathLocation) throws IOException {
// return IOUtils.toString(new ClassPathResource(classpathLocation).getInputStream(), Charset.forName("UTF-8"));
// }
// Path: latex-template/src/test/java/de/vsfexperts/latex/template/LatexTemplateIT.java
import static de.vsfexperts.latex.template.ClasspathUtils.getContent;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
package de.vsfexperts.latex.template;
public class LatexTemplateIT {
@Test
public void processTemplate() throws Exception { | final String template = getContent("/META-INF/templates/sampleTemplate.tex"); |
vsfexperts/LaTeX | latex-server/src/main/java/de/vsfexperts/latex/server/service/RenderController.java | // Path: latex-renderer/src/main/java/de/vsfexperts/latex/renderer/LatexRenderer.java
// public interface LatexRenderer {
//
// /**
// * Trigger a latex render job
// *
// * @param template
// * to process
// * @return id of render job
// */
// UUID render(String template);
//
// /**
// * Retrieve render output.
// *
// * @param jobId
// * to identify job
// * @return file referencing the generated pdf
// */
// Optional<File> getResult(UUID jobId);
//
// }
| import static org.springframework.http.HttpStatus.ACCEPTED;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.APPLICATION_PDF_VALUE;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Optional;
import java.util.UUID;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import de.vsfexperts.latex.renderer.LatexRenderer;
import io.micrometer.core.annotation.Timed; | package de.vsfexperts.latex.server.service;
@RestController
public class RenderController {
@Autowired | // Path: latex-renderer/src/main/java/de/vsfexperts/latex/renderer/LatexRenderer.java
// public interface LatexRenderer {
//
// /**
// * Trigger a latex render job
// *
// * @param template
// * to process
// * @return id of render job
// */
// UUID render(String template);
//
// /**
// * Retrieve render output.
// *
// * @param jobId
// * to identify job
// * @return file referencing the generated pdf
// */
// Optional<File> getResult(UUID jobId);
//
// }
// Path: latex-server/src/main/java/de/vsfexperts/latex/server/service/RenderController.java
import static org.springframework.http.HttpStatus.ACCEPTED;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.APPLICATION_PDF_VALUE;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Optional;
import java.util.UUID;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import de.vsfexperts.latex.renderer.LatexRenderer;
import io.micrometer.core.annotation.Timed;
package de.vsfexperts.latex.server.service;
@RestController
public class RenderController {
@Autowired | private LatexRenderer renderer; |
vsfexperts/LaTeX | latex-docker/src/test/java/de/vsfexperts/latex/renderer/ApiIT.java | // Path: latex-renderer/src/test/java/de/vsfexperts/latex/renderer/ClasspathUtils.java
// public static String getContent(final String classpathLocation) throws IOException {
// return IOUtils.toString(new ClassPathResource(classpathLocation).getInputStream(), Charset.forName("UTF-8"));
// }
| import static de.vsfexperts.latex.renderer.ClasspathUtils.getContent;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assume.assumeThat;
import static org.springframework.http.HttpStatus.ACCEPTED;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate; | package de.vsfexperts.latex.renderer;
public class ApiIT {
private static final Logger LOG = LoggerFactory.getLogger(ApiIT.class);
private static final String TEST_DOCUMENT = "/META-INF/sample.tex";
private static final String BASE_URL = "http://localhost:8080";
private static final int MAX_RETRIES = 5;
private RestTemplate rest;
@Before
public void setUp() {
final HttpMessageConverter<String> messageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
rest = new RestTemplate();
rest.getMessageConverters().add(0, messageConverter);
}
@Test
public void testDocumentSubmission() throws IOException { | // Path: latex-renderer/src/test/java/de/vsfexperts/latex/renderer/ClasspathUtils.java
// public static String getContent(final String classpathLocation) throws IOException {
// return IOUtils.toString(new ClassPathResource(classpathLocation).getInputStream(), Charset.forName("UTF-8"));
// }
// Path: latex-docker/src/test/java/de/vsfexperts/latex/renderer/ApiIT.java
import static de.vsfexperts.latex.renderer.ClasspathUtils.getContent;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assume.assumeThat;
import static org.springframework.http.HttpStatus.ACCEPTED;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
package de.vsfexperts.latex.renderer;
public class ApiIT {
private static final Logger LOG = LoggerFactory.getLogger(ApiIT.class);
private static final String TEST_DOCUMENT = "/META-INF/sample.tex";
private static final String BASE_URL = "http://localhost:8080";
private static final int MAX_RETRIES = 5;
private RestTemplate rest;
@Before
public void setUp() {
final HttpMessageConverter<String> messageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
rest = new RestTemplate();
rest.getMessageConverters().add(0, messageConverter);
}
@Test
public void testDocumentSubmission() throws IOException { | final String latexDocument = getContent(TEST_DOCUMENT); |
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/source/InputStreamSource.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Util.java
// public class Util {
// private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
//
// public static int getDP(Context context, int dp) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
// }
//
// public static byte[] toByteArray(InputStream inputStream) throws IOException {
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
// int n;
// while (-1 != (n = inputStream.read(buffer))) {
// os.write(buffer, 0, n);
// }
// return os.toByteArray();
// }
// }
| import android.content.Context;
import com.github.barteksc.pdfviewer.util.Util;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import java.io.IOException;
import java.io.InputStream; | /*
* Copyright (C) 2016 Bartosz Schiller.
*
* 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.github.barteksc.pdfviewer.source;
public class InputStreamSource implements DocumentSource {
private InputStream inputStream;
public InputStreamSource(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Util.java
// public class Util {
// private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
//
// public static int getDP(Context context, int dp) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
// }
//
// public static byte[] toByteArray(InputStream inputStream) throws IOException {
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
// int n;
// while (-1 != (n = inputStream.read(buffer))) {
// os.write(buffer, 0, n);
// }
// return os.toByteArray();
// }
// }
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/source/InputStreamSource.java
import android.content.Context;
import com.github.barteksc.pdfviewer.util.Util;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import java.io.IOException;
import java.io.InputStream;
/*
* Copyright (C) 2016 Bartosz Schiller.
*
* 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.github.barteksc.pdfviewer.source;
public class InputStreamSource implements DocumentSource {
private InputStream inputStream;
public InputStreamSource(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { | return core.newDocument(Util.toByteArray(inputStream), password); |
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/CacheManager.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java
// public class PagePart {
//
// private int page;
//
// private Bitmap renderedBitmap;
//
// private RectF pageRelativeBounds;
//
// private boolean thumbnail;
//
// private int cacheOrder;
//
// public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) {
// super();
// this.page = page;
// this.renderedBitmap = renderedBitmap;
// this.pageRelativeBounds = pageRelativeBounds;
// this.thumbnail = thumbnail;
// this.cacheOrder = cacheOrder;
// }
//
// public int getCacheOrder() {
// return cacheOrder;
// }
//
// public int getPage() {
// return page;
// }
//
// public Bitmap getRenderedBitmap() {
// return renderedBitmap;
// }
//
// public RectF getPageRelativeBounds() {
// return pageRelativeBounds;
// }
//
// public boolean isThumbnail() {
// return thumbnail;
// }
//
// public void setCacheOrder(int cacheOrder) {
// this.cacheOrder = cacheOrder;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof PagePart)) {
// return false;
// }
//
// PagePart part = (PagePart) obj;
// return part.getPage() == page
// && part.getPageRelativeBounds().left == pageRelativeBounds.left
// && part.getPageRelativeBounds().right == pageRelativeBounds.right
// && part.getPageRelativeBounds().top == pageRelativeBounds.top
// && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom;
// }
//
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static int CACHE_SIZE = 120;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static int THUMBNAILS_CACHE_SIZE = 8;
| import android.graphics.RectF;
import android.support.annotation.Nullable;
import com.github.barteksc.pdfviewer.model.PagePart;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import static com.github.barteksc.pdfviewer.util.Constants.Cache.CACHE_SIZE;
import static com.github.barteksc.pdfviewer.util.Constants.Cache.THUMBNAILS_CACHE_SIZE;
| /**
* Copyright 2016 Bartosz Schiller
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.github.barteksc.pdfviewer;
class CacheManager {
private final PriorityQueue<PagePart> passiveCache;
private final PriorityQueue<PagePart> activeCache;
private final List<PagePart> thumbnails;
private final Object passiveActiveLock = new Object();
private final PagePartComparator orderComparator = new PagePartComparator();
public CacheManager() {
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java
// public class PagePart {
//
// private int page;
//
// private Bitmap renderedBitmap;
//
// private RectF pageRelativeBounds;
//
// private boolean thumbnail;
//
// private int cacheOrder;
//
// public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) {
// super();
// this.page = page;
// this.renderedBitmap = renderedBitmap;
// this.pageRelativeBounds = pageRelativeBounds;
// this.thumbnail = thumbnail;
// this.cacheOrder = cacheOrder;
// }
//
// public int getCacheOrder() {
// return cacheOrder;
// }
//
// public int getPage() {
// return page;
// }
//
// public Bitmap getRenderedBitmap() {
// return renderedBitmap;
// }
//
// public RectF getPageRelativeBounds() {
// return pageRelativeBounds;
// }
//
// public boolean isThumbnail() {
// return thumbnail;
// }
//
// public void setCacheOrder(int cacheOrder) {
// this.cacheOrder = cacheOrder;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof PagePart)) {
// return false;
// }
//
// PagePart part = (PagePart) obj;
// return part.getPage() == page
// && part.getPageRelativeBounds().left == pageRelativeBounds.left
// && part.getPageRelativeBounds().right == pageRelativeBounds.right
// && part.getPageRelativeBounds().top == pageRelativeBounds.top
// && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom;
// }
//
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static int CACHE_SIZE = 120;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static int THUMBNAILS_CACHE_SIZE = 8;
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/CacheManager.java
import android.graphics.RectF;
import android.support.annotation.Nullable;
import com.github.barteksc.pdfviewer.model.PagePart;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import static com.github.barteksc.pdfviewer.util.Constants.Cache.CACHE_SIZE;
import static com.github.barteksc.pdfviewer.util.Constants.Cache.THUMBNAILS_CACHE_SIZE;
/**
* Copyright 2016 Bartosz Schiller
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.github.barteksc.pdfviewer;
class CacheManager {
private final PriorityQueue<PagePart> passiveCache;
private final PriorityQueue<PagePart> activeCache;
private final List<PagePart> thumbnails;
private final Object passiveActiveLock = new Object();
private final PagePartComparator orderComparator = new PagePartComparator();
public CacheManager() {
| activeCache = new PriorityQueue<>(CACHE_SIZE, orderComparator);
|
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/CacheManager.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java
// public class PagePart {
//
// private int page;
//
// private Bitmap renderedBitmap;
//
// private RectF pageRelativeBounds;
//
// private boolean thumbnail;
//
// private int cacheOrder;
//
// public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) {
// super();
// this.page = page;
// this.renderedBitmap = renderedBitmap;
// this.pageRelativeBounds = pageRelativeBounds;
// this.thumbnail = thumbnail;
// this.cacheOrder = cacheOrder;
// }
//
// public int getCacheOrder() {
// return cacheOrder;
// }
//
// public int getPage() {
// return page;
// }
//
// public Bitmap getRenderedBitmap() {
// return renderedBitmap;
// }
//
// public RectF getPageRelativeBounds() {
// return pageRelativeBounds;
// }
//
// public boolean isThumbnail() {
// return thumbnail;
// }
//
// public void setCacheOrder(int cacheOrder) {
// this.cacheOrder = cacheOrder;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof PagePart)) {
// return false;
// }
//
// PagePart part = (PagePart) obj;
// return part.getPage() == page
// && part.getPageRelativeBounds().left == pageRelativeBounds.left
// && part.getPageRelativeBounds().right == pageRelativeBounds.right
// && part.getPageRelativeBounds().top == pageRelativeBounds.top
// && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom;
// }
//
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static int CACHE_SIZE = 120;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static int THUMBNAILS_CACHE_SIZE = 8;
| import android.graphics.RectF;
import android.support.annotation.Nullable;
import com.github.barteksc.pdfviewer.model.PagePart;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import static com.github.barteksc.pdfviewer.util.Constants.Cache.CACHE_SIZE;
import static com.github.barteksc.pdfviewer.util.Constants.Cache.THUMBNAILS_CACHE_SIZE;
| // Then add part
activeCache.offer(part);
}
}
public void makeANewSet() {
synchronized (passiveActiveLock) {
passiveCache.addAll(activeCache);
activeCache.clear();
}
}
private void makeAFreeSpace() {
synchronized (passiveActiveLock) {
while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE &&
!passiveCache.isEmpty()) {
PagePart part = passiveCache.poll();
part.getRenderedBitmap().recycle();
}
while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE &&
!activeCache.isEmpty()) {
activeCache.poll().getRenderedBitmap().recycle();
}
}
}
public void cacheThumbnail(PagePart part) {
synchronized (thumbnails) {
// If cache too big, remove and recycle
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java
// public class PagePart {
//
// private int page;
//
// private Bitmap renderedBitmap;
//
// private RectF pageRelativeBounds;
//
// private boolean thumbnail;
//
// private int cacheOrder;
//
// public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) {
// super();
// this.page = page;
// this.renderedBitmap = renderedBitmap;
// this.pageRelativeBounds = pageRelativeBounds;
// this.thumbnail = thumbnail;
// this.cacheOrder = cacheOrder;
// }
//
// public int getCacheOrder() {
// return cacheOrder;
// }
//
// public int getPage() {
// return page;
// }
//
// public Bitmap getRenderedBitmap() {
// return renderedBitmap;
// }
//
// public RectF getPageRelativeBounds() {
// return pageRelativeBounds;
// }
//
// public boolean isThumbnail() {
// return thumbnail;
// }
//
// public void setCacheOrder(int cacheOrder) {
// this.cacheOrder = cacheOrder;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof PagePart)) {
// return false;
// }
//
// PagePart part = (PagePart) obj;
// return part.getPage() == page
// && part.getPageRelativeBounds().left == pageRelativeBounds.left
// && part.getPageRelativeBounds().right == pageRelativeBounds.right
// && part.getPageRelativeBounds().top == pageRelativeBounds.top
// && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom;
// }
//
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static int CACHE_SIZE = 120;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static int THUMBNAILS_CACHE_SIZE = 8;
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/CacheManager.java
import android.graphics.RectF;
import android.support.annotation.Nullable;
import com.github.barteksc.pdfviewer.model.PagePart;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import static com.github.barteksc.pdfviewer.util.Constants.Cache.CACHE_SIZE;
import static com.github.barteksc.pdfviewer.util.Constants.Cache.THUMBNAILS_CACHE_SIZE;
// Then add part
activeCache.offer(part);
}
}
public void makeANewSet() {
synchronized (passiveActiveLock) {
passiveCache.addAll(activeCache);
activeCache.clear();
}
}
private void makeAFreeSpace() {
synchronized (passiveActiveLock) {
while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE &&
!passiveCache.isEmpty()) {
PagePart part = passiveCache.poll();
part.getRenderedBitmap().recycle();
}
while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE &&
!activeCache.isEmpty()) {
activeCache.poll().getRenderedBitmap().recycle();
}
}
}
public void cacheThumbnail(PagePart part) {
synchronized (thumbnails) {
// If cache too big, remove and recycle
| while (thumbnails.size() >= THUMBNAILS_CACHE_SIZE) {
|
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java
// public enum SnapEdge {
// START, CENTER, END, NONE
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MAXIMUM_ZOOM = 10;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MINIMUM_ZOOM = 1;
| import android.graphics.PointF;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.util.SizeF;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM;
| ps.hide();
}
}
}
pdfView.performClick();
return true;
}
private boolean checkLinkTapped(float x, float y) {
PdfFile pdfFile = pdfView.pdfFile;
if (pdfFile == null) {
return false;
}
float mappedX = -pdfView.getCurrentXOffset() + x;
float mappedY = -pdfView.getCurrentYOffset() + y;
int page = pdfFile.getPageAtOffset(pdfView.isSwipeVertical() ? mappedY : mappedX, pdfView.getZoom());
SizeF pageSize = pdfFile.getScaledPageSize(page, pdfView.getZoom());
int pageX, pageY;
if (pdfView.isSwipeVertical()) {
pageX = (int) pdfFile.getSecondaryPageOffset(page, pdfView.getZoom());
pageY = (int) pdfFile.getPageOffset(page, pdfView.getZoom());
} else {
pageY = (int) pdfFile.getSecondaryPageOffset(page, pdfView.getZoom());
pageX = (int) pdfFile.getPageOffset(page, pdfView.getZoom());
}
for (PdfDocument.Link link : pdfFile.getPageLinks(page)) {
RectF mapped = pdfFile.mapRectToDevice(page, pageX, pageY, (int) pageSize.getWidth(),
(int) pageSize.getHeight(), link.getBounds());
mapped.sort();
if (mapped.contains(mappedX, mappedY)) {
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java
// public enum SnapEdge {
// START, CENTER, END, NONE
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MAXIMUM_ZOOM = 10;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MINIMUM_ZOOM = 1;
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.util.SizeF;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM;
ps.hide();
}
}
}
pdfView.performClick();
return true;
}
private boolean checkLinkTapped(float x, float y) {
PdfFile pdfFile = pdfView.pdfFile;
if (pdfFile == null) {
return false;
}
float mappedX = -pdfView.getCurrentXOffset() + x;
float mappedY = -pdfView.getCurrentYOffset() + y;
int page = pdfFile.getPageAtOffset(pdfView.isSwipeVertical() ? mappedY : mappedX, pdfView.getZoom());
SizeF pageSize = pdfFile.getScaledPageSize(page, pdfView.getZoom());
int pageX, pageY;
if (pdfView.isSwipeVertical()) {
pageX = (int) pdfFile.getSecondaryPageOffset(page, pdfView.getZoom());
pageY = (int) pdfFile.getPageOffset(page, pdfView.getZoom());
} else {
pageY = (int) pdfFile.getSecondaryPageOffset(page, pdfView.getZoom());
pageX = (int) pdfFile.getPageOffset(page, pdfView.getZoom());
}
for (PdfDocument.Link link : pdfFile.getPageLinks(page)) {
RectF mapped = pdfFile.mapRectToDevice(page, pageX, pageY, (int) pageSize.getWidth(),
(int) pageSize.getHeight(), link.getBounds());
mapped.sort();
if (mapped.contains(mappedX, mappedY)) {
| pdfView.callbacks.callLinkHandler(new LinkTapEvent(x, y, mappedX, mappedY, mapped, link));
|
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java
// public enum SnapEdge {
// START, CENTER, END, NONE
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MAXIMUM_ZOOM = 10;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MINIMUM_ZOOM = 1;
| import android.graphics.PointF;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.util.SizeF;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM;
| for (PdfDocument.Link link : pdfFile.getPageLinks(page)) {
RectF mapped = pdfFile.mapRectToDevice(page, pageX, pageY, (int) pageSize.getWidth(),
(int) pageSize.getHeight(), link.getBounds());
mapped.sort();
if (mapped.contains(mappedX, mappedY)) {
pdfView.callbacks.callLinkHandler(new LinkTapEvent(x, y, mappedX, mappedY, mapped, link));
return true;
}
}
return false;
}
private void startPageFling(MotionEvent downEvent, MotionEvent ev, float velocityX, float velocityY) {
if (!checkDoPageFling(velocityX, velocityY)) {
return;
}
int direction;
if (pdfView.isSwipeVertical()) {
direction = velocityY > 0 ? -1 : 1;
} else {
direction = velocityX > 0 ? -1 : 1;
}
// get the focused page during the down event to ensure only a single page is changed
float delta = pdfView.isSwipeVertical() ? ev.getY() - downEvent.getY() : ev.getX() - downEvent.getX();
float offsetX = pdfView.getCurrentXOffset() - delta * pdfView.getZoom();
float offsetY = pdfView.getCurrentYOffset() - delta * pdfView.getZoom();
int startingPage = pdfView.findFocusPage(offsetX, offsetY);
int targetPage = Math.max(0, Math.min(pdfView.getPageCount() - 1, startingPage + direction));
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java
// public enum SnapEdge {
// START, CENTER, END, NONE
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MAXIMUM_ZOOM = 10;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MINIMUM_ZOOM = 1;
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.util.SizeF;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM;
for (PdfDocument.Link link : pdfFile.getPageLinks(page)) {
RectF mapped = pdfFile.mapRectToDevice(page, pageX, pageY, (int) pageSize.getWidth(),
(int) pageSize.getHeight(), link.getBounds());
mapped.sort();
if (mapped.contains(mappedX, mappedY)) {
pdfView.callbacks.callLinkHandler(new LinkTapEvent(x, y, mappedX, mappedY, mapped, link));
return true;
}
}
return false;
}
private void startPageFling(MotionEvent downEvent, MotionEvent ev, float velocityX, float velocityY) {
if (!checkDoPageFling(velocityX, velocityY)) {
return;
}
int direction;
if (pdfView.isSwipeVertical()) {
direction = velocityY > 0 ? -1 : 1;
} else {
direction = velocityX > 0 ? -1 : 1;
}
// get the focused page during the down event to ensure only a single page is changed
float delta = pdfView.isSwipeVertical() ? ev.getY() - downEvent.getY() : ev.getX() - downEvent.getX();
float offsetX = pdfView.getCurrentXOffset() - delta * pdfView.getZoom();
float offsetY = pdfView.getCurrentYOffset() - delta * pdfView.getZoom();
int startingPage = pdfView.findFocusPage(offsetX, offsetY);
int targetPage = Math.max(0, Math.min(pdfView.getPageCount() - 1, startingPage + direction));
| SnapEdge edge = pdfView.findSnapEdge(targetPage);
|
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java
// public enum SnapEdge {
// START, CENTER, END, NONE
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MAXIMUM_ZOOM = 10;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MINIMUM_ZOOM = 1;
| import android.graphics.PointF;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.util.SizeF;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM;
|
private void onBoundedFling(float velocityX, float velocityY) {
int xOffset = (int) pdfView.getCurrentXOffset();
int yOffset = (int) pdfView.getCurrentYOffset();
PdfFile pdfFile = pdfView.pdfFile;
float pageStart = -pdfFile.getPageOffset(pdfView.getCurrentPage(), pdfView.getZoom());
float pageEnd = pageStart - pdfFile.getPageLength(pdfView.getCurrentPage(), pdfView.getZoom());
float minX, minY, maxX, maxY;
if (pdfView.isSwipeVertical()) {
minX = -(pdfView.toCurrentScale(pdfFile.getMaxPageWidth()) - pdfView.getWidth());
minY = pageEnd + pdfView.getHeight();
maxX = 0;
maxY = pageStart;
} else {
minX = pageEnd + pdfView.getWidth();
minY = -(pdfView.toCurrentScale(pdfFile.getMaxPageHeight()) - pdfView.getHeight());
maxX = pageStart;
maxY = 0;
}
animationManager.startFlingAnimation(xOffset, yOffset, (int) (velocityX), (int) (velocityY),
(int) minX, (int) maxX, (int) minY, (int) maxY);
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float dr = detector.getScaleFactor();
float wantedZoom = pdfView.getZoom() * dr;
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java
// public enum SnapEdge {
// START, CENTER, END, NONE
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MAXIMUM_ZOOM = 10;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MINIMUM_ZOOM = 1;
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.util.SizeF;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM;
private void onBoundedFling(float velocityX, float velocityY) {
int xOffset = (int) pdfView.getCurrentXOffset();
int yOffset = (int) pdfView.getCurrentYOffset();
PdfFile pdfFile = pdfView.pdfFile;
float pageStart = -pdfFile.getPageOffset(pdfView.getCurrentPage(), pdfView.getZoom());
float pageEnd = pageStart - pdfFile.getPageLength(pdfView.getCurrentPage(), pdfView.getZoom());
float minX, minY, maxX, maxY;
if (pdfView.isSwipeVertical()) {
minX = -(pdfView.toCurrentScale(pdfFile.getMaxPageWidth()) - pdfView.getWidth());
minY = pageEnd + pdfView.getHeight();
maxX = 0;
maxY = pageStart;
} else {
minX = pageEnd + pdfView.getWidth();
minY = -(pdfView.toCurrentScale(pdfFile.getMaxPageHeight()) - pdfView.getHeight());
maxX = pageStart;
maxY = 0;
}
animationManager.startFlingAnimation(xOffset, yOffset, (int) (velocityX), (int) (velocityY),
(int) minX, (int) maxX, (int) minY, (int) maxY);
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float dr = detector.getScaleFactor();
float wantedZoom = pdfView.getZoom() * dr;
| float minZoom = Math.min(MINIMUM_ZOOM, pdfView.getMinZoom());
|
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java
// public enum SnapEdge {
// START, CENTER, END, NONE
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MAXIMUM_ZOOM = 10;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MINIMUM_ZOOM = 1;
| import android.graphics.PointF;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.util.SizeF;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM;
| private void onBoundedFling(float velocityX, float velocityY) {
int xOffset = (int) pdfView.getCurrentXOffset();
int yOffset = (int) pdfView.getCurrentYOffset();
PdfFile pdfFile = pdfView.pdfFile;
float pageStart = -pdfFile.getPageOffset(pdfView.getCurrentPage(), pdfView.getZoom());
float pageEnd = pageStart - pdfFile.getPageLength(pdfView.getCurrentPage(), pdfView.getZoom());
float minX, minY, maxX, maxY;
if (pdfView.isSwipeVertical()) {
minX = -(pdfView.toCurrentScale(pdfFile.getMaxPageWidth()) - pdfView.getWidth());
minY = pageEnd + pdfView.getHeight();
maxX = 0;
maxY = pageStart;
} else {
minX = pageEnd + pdfView.getWidth();
minY = -(pdfView.toCurrentScale(pdfFile.getMaxPageHeight()) - pdfView.getHeight());
maxX = pageStart;
maxY = 0;
}
animationManager.startFlingAnimation(xOffset, yOffset, (int) (velocityX), (int) (velocityY),
(int) minX, (int) maxX, (int) minY, (int) maxY);
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float dr = detector.getScaleFactor();
float wantedZoom = pdfView.getZoom() * dr;
float minZoom = Math.min(MINIMUM_ZOOM, pdfView.getMinZoom());
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java
// public enum SnapEdge {
// START, CENTER, END, NONE
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MAXIMUM_ZOOM = 10;
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java
// public static float MINIMUM_ZOOM = 1;
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.util.SizeF;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM;
import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM;
private void onBoundedFling(float velocityX, float velocityY) {
int xOffset = (int) pdfView.getCurrentXOffset();
int yOffset = (int) pdfView.getCurrentYOffset();
PdfFile pdfFile = pdfView.pdfFile;
float pageStart = -pdfFile.getPageOffset(pdfView.getCurrentPage(), pdfView.getZoom());
float pageEnd = pageStart - pdfFile.getPageLength(pdfView.getCurrentPage(), pdfView.getZoom());
float minX, minY, maxX, maxY;
if (pdfView.isSwipeVertical()) {
minX = -(pdfView.toCurrentScale(pdfFile.getMaxPageWidth()) - pdfView.getWidth());
minY = pageEnd + pdfView.getHeight();
maxX = 0;
maxY = pageStart;
} else {
minX = pageEnd + pdfView.getWidth();
minY = -(pdfView.toCurrentScale(pdfFile.getMaxPageHeight()) - pdfView.getHeight());
maxX = pageStart;
maxY = 0;
}
animationManager.startFlingAnimation(xOffset, yOffset, (int) (velocityX), (int) (velocityY),
(int) minX, (int) maxX, (int) minY, (int) maxY);
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float dr = detector.getScaleFactor();
float wantedZoom = pdfView.getZoom() * dr;
float minZoom = Math.min(MINIMUM_ZOOM, pdfView.getMinZoom());
| float maxZoom = Math.min(MAXIMUM_ZOOM, pdfView.getMaxZoom());
|
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/RenderingHandler.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/exception/PageRenderingException.java
// public class PageRenderingException extends Exception {
// private final int page;
//
// public PageRenderingException(int page, Throwable cause) {
// super(cause);
// this.page = page;
// }
//
// public int getPage() {
// return page;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java
// public class PagePart {
//
// private int page;
//
// private Bitmap renderedBitmap;
//
// private RectF pageRelativeBounds;
//
// private boolean thumbnail;
//
// private int cacheOrder;
//
// public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) {
// super();
// this.page = page;
// this.renderedBitmap = renderedBitmap;
// this.pageRelativeBounds = pageRelativeBounds;
// this.thumbnail = thumbnail;
// this.cacheOrder = cacheOrder;
// }
//
// public int getCacheOrder() {
// return cacheOrder;
// }
//
// public int getPage() {
// return page;
// }
//
// public Bitmap getRenderedBitmap() {
// return renderedBitmap;
// }
//
// public RectF getPageRelativeBounds() {
// return pageRelativeBounds;
// }
//
// public boolean isThumbnail() {
// return thumbnail;
// }
//
// public void setCacheOrder(int cacheOrder) {
// this.cacheOrder = cacheOrder;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof PagePart)) {
// return false;
// }
//
// PagePart part = (PagePart) obj;
// return part.getPage() == page
// && part.getPageRelativeBounds().left == pageRelativeBounds.left
// && part.getPageRelativeBounds().right == pageRelativeBounds.right
// && part.getPageRelativeBounds().top == pageRelativeBounds.top
// && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom;
// }
//
// }
| import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.github.barteksc.pdfviewer.exception.PageRenderingException;
import com.github.barteksc.pdfviewer.model.PagePart;
| /**
* Copyright 2016 Bartosz Schiller
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.github.barteksc.pdfviewer;
/**
* A {@link Handler} that will process incoming {@link RenderingTask} messages
* and alert {@link PDFView#onBitmapRendered(PagePart)} when the portion of the
* PDF is ready to render.
*/
class RenderingHandler extends Handler {
/**
* {@link Message#what} kind of message this handler processes.
*/
static final int MSG_RENDER_TASK = 1;
private static final String TAG = RenderingHandler.class.getName();
private PDFView pdfView;
private RectF renderBounds = new RectF();
private Rect roundedRenderBounds = new Rect();
private Matrix renderMatrix = new Matrix();
private boolean running = false;
RenderingHandler(Looper looper, PDFView pdfView) {
super(looper);
this.pdfView = pdfView;
}
void addRenderingTask(int page, float width, float height, RectF bounds, boolean thumbnail, int cacheOrder, boolean bestQuality, boolean annotationRendering) {
RenderingTask task = new RenderingTask(width, height, bounds, page, thumbnail, cacheOrder, bestQuality, annotationRendering);
Message msg = obtainMessage(MSG_RENDER_TASK, task);
sendMessage(msg);
}
@Override
public void handleMessage(Message message) {
RenderingTask task = (RenderingTask) message.obj;
try {
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/exception/PageRenderingException.java
// public class PageRenderingException extends Exception {
// private final int page;
//
// public PageRenderingException(int page, Throwable cause) {
// super(cause);
// this.page = page;
// }
//
// public int getPage() {
// return page;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java
// public class PagePart {
//
// private int page;
//
// private Bitmap renderedBitmap;
//
// private RectF pageRelativeBounds;
//
// private boolean thumbnail;
//
// private int cacheOrder;
//
// public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) {
// super();
// this.page = page;
// this.renderedBitmap = renderedBitmap;
// this.pageRelativeBounds = pageRelativeBounds;
// this.thumbnail = thumbnail;
// this.cacheOrder = cacheOrder;
// }
//
// public int getCacheOrder() {
// return cacheOrder;
// }
//
// public int getPage() {
// return page;
// }
//
// public Bitmap getRenderedBitmap() {
// return renderedBitmap;
// }
//
// public RectF getPageRelativeBounds() {
// return pageRelativeBounds;
// }
//
// public boolean isThumbnail() {
// return thumbnail;
// }
//
// public void setCacheOrder(int cacheOrder) {
// this.cacheOrder = cacheOrder;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof PagePart)) {
// return false;
// }
//
// PagePart part = (PagePart) obj;
// return part.getPage() == page
// && part.getPageRelativeBounds().left == pageRelativeBounds.left
// && part.getPageRelativeBounds().right == pageRelativeBounds.right
// && part.getPageRelativeBounds().top == pageRelativeBounds.top
// && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom;
// }
//
// }
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/RenderingHandler.java
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.github.barteksc.pdfviewer.exception.PageRenderingException;
import com.github.barteksc.pdfviewer.model.PagePart;
/**
* Copyright 2016 Bartosz Schiller
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.github.barteksc.pdfviewer;
/**
* A {@link Handler} that will process incoming {@link RenderingTask} messages
* and alert {@link PDFView#onBitmapRendered(PagePart)} when the portion of the
* PDF is ready to render.
*/
class RenderingHandler extends Handler {
/**
* {@link Message#what} kind of message this handler processes.
*/
static final int MSG_RENDER_TASK = 1;
private static final String TAG = RenderingHandler.class.getName();
private PDFView pdfView;
private RectF renderBounds = new RectF();
private Rect roundedRenderBounds = new Rect();
private Matrix renderMatrix = new Matrix();
private boolean running = false;
RenderingHandler(Looper looper, PDFView pdfView) {
super(looper);
this.pdfView = pdfView;
}
void addRenderingTask(int page, float width, float height, RectF bounds, boolean thumbnail, int cacheOrder, boolean bestQuality, boolean annotationRendering) {
RenderingTask task = new RenderingTask(width, height, bounds, page, thumbnail, cacheOrder, bestQuality, annotationRendering);
Message msg = obtainMessage(MSG_RENDER_TASK, task);
sendMessage(msg);
}
@Override
public void handleMessage(Message message) {
RenderingTask task = (RenderingTask) message.obj;
try {
| final PagePart part = proceed(task);
|
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/RenderingHandler.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/exception/PageRenderingException.java
// public class PageRenderingException extends Exception {
// private final int page;
//
// public PageRenderingException(int page, Throwable cause) {
// super(cause);
// this.page = page;
// }
//
// public int getPage() {
// return page;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java
// public class PagePart {
//
// private int page;
//
// private Bitmap renderedBitmap;
//
// private RectF pageRelativeBounds;
//
// private boolean thumbnail;
//
// private int cacheOrder;
//
// public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) {
// super();
// this.page = page;
// this.renderedBitmap = renderedBitmap;
// this.pageRelativeBounds = pageRelativeBounds;
// this.thumbnail = thumbnail;
// this.cacheOrder = cacheOrder;
// }
//
// public int getCacheOrder() {
// return cacheOrder;
// }
//
// public int getPage() {
// return page;
// }
//
// public Bitmap getRenderedBitmap() {
// return renderedBitmap;
// }
//
// public RectF getPageRelativeBounds() {
// return pageRelativeBounds;
// }
//
// public boolean isThumbnail() {
// return thumbnail;
// }
//
// public void setCacheOrder(int cacheOrder) {
// this.cacheOrder = cacheOrder;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof PagePart)) {
// return false;
// }
//
// PagePart part = (PagePart) obj;
// return part.getPage() == page
// && part.getPageRelativeBounds().left == pageRelativeBounds.left
// && part.getPageRelativeBounds().right == pageRelativeBounds.right
// && part.getPageRelativeBounds().top == pageRelativeBounds.top
// && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom;
// }
//
// }
| import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.github.barteksc.pdfviewer.exception.PageRenderingException;
import com.github.barteksc.pdfviewer.model.PagePart;
| private boolean running = false;
RenderingHandler(Looper looper, PDFView pdfView) {
super(looper);
this.pdfView = pdfView;
}
void addRenderingTask(int page, float width, float height, RectF bounds, boolean thumbnail, int cacheOrder, boolean bestQuality, boolean annotationRendering) {
RenderingTask task = new RenderingTask(width, height, bounds, page, thumbnail, cacheOrder, bestQuality, annotationRendering);
Message msg = obtainMessage(MSG_RENDER_TASK, task);
sendMessage(msg);
}
@Override
public void handleMessage(Message message) {
RenderingTask task = (RenderingTask) message.obj;
try {
final PagePart part = proceed(task);
if (part != null) {
if (running) {
pdfView.post(new Runnable() {
@Override
public void run() {
pdfView.onBitmapRendered(part);
}
});
} else {
part.getRenderedBitmap().recycle();
}
}
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/exception/PageRenderingException.java
// public class PageRenderingException extends Exception {
// private final int page;
//
// public PageRenderingException(int page, Throwable cause) {
// super(cause);
// this.page = page;
// }
//
// public int getPage() {
// return page;
// }
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java
// public class PagePart {
//
// private int page;
//
// private Bitmap renderedBitmap;
//
// private RectF pageRelativeBounds;
//
// private boolean thumbnail;
//
// private int cacheOrder;
//
// public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) {
// super();
// this.page = page;
// this.renderedBitmap = renderedBitmap;
// this.pageRelativeBounds = pageRelativeBounds;
// this.thumbnail = thumbnail;
// this.cacheOrder = cacheOrder;
// }
//
// public int getCacheOrder() {
// return cacheOrder;
// }
//
// public int getPage() {
// return page;
// }
//
// public Bitmap getRenderedBitmap() {
// return renderedBitmap;
// }
//
// public RectF getPageRelativeBounds() {
// return pageRelativeBounds;
// }
//
// public boolean isThumbnail() {
// return thumbnail;
// }
//
// public void setCacheOrder(int cacheOrder) {
// this.cacheOrder = cacheOrder;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof PagePart)) {
// return false;
// }
//
// PagePart part = (PagePart) obj;
// return part.getPage() == page
// && part.getPageRelativeBounds().left == pageRelativeBounds.left
// && part.getPageRelativeBounds().right == pageRelativeBounds.right
// && part.getPageRelativeBounds().top == pageRelativeBounds.top
// && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom;
// }
//
// }
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/RenderingHandler.java
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.github.barteksc.pdfviewer.exception.PageRenderingException;
import com.github.barteksc.pdfviewer.model.PagePart;
private boolean running = false;
RenderingHandler(Looper looper, PDFView pdfView) {
super(looper);
this.pdfView = pdfView;
}
void addRenderingTask(int page, float width, float height, RectF bounds, boolean thumbnail, int cacheOrder, boolean bestQuality, boolean annotationRendering) {
RenderingTask task = new RenderingTask(width, height, bounds, page, thumbnail, cacheOrder, bestQuality, annotationRendering);
Message msg = obtainMessage(MSG_RENDER_TASK, task);
sendMessage(msg);
}
@Override
public void handleMessage(Message message) {
RenderingTask task = (RenderingTask) message.obj;
try {
final PagePart part = proceed(task);
if (part != null) {
if (running) {
pdfView.post(new Runnable() {
@Override
public void run() {
pdfView.onBitmapRendered(part);
}
});
} else {
part.getRenderedBitmap().recycle();
}
}
| } catch (final PageRenderingException ex) {
|
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/Callbacks.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/link/LinkHandler.java
// public interface LinkHandler {
//
// /**
// * Called when link was tapped by user
// *
// * @param event current event
// */
// void handleLinkEvent(LinkTapEvent event);
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
| import android.view.MotionEvent;
import com.github.barteksc.pdfviewer.link.LinkHandler;
import com.github.barteksc.pdfviewer.model.LinkTapEvent; | /**
* Copyright 2017 Bartosz Schiller
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.github.barteksc.pdfviewer.listener;
public class Callbacks {
/**
* Call back object to call when the PDF is loaded
*/
private OnLoadCompleteListener onLoadCompleteListener;
/**
* Call back object to call when document loading error occurs
*/
private OnErrorListener onErrorListener;
/**
* Call back object to call when the page load error occurs
*/
private OnPageErrorListener onPageErrorListener;
/**
* Call back object to call when the document is initially rendered
*/
private OnRenderListener onRenderListener;
/**
* Call back object to call when the page has changed
*/
private OnPageChangeListener onPageChangeListener;
/**
* Call back object to call when the page is scrolled
*/
private OnPageScrollListener onPageScrollListener;
/**
* Call back object to call when the above layer is to drawn
*/
private OnDrawListener onDrawListener;
private OnDrawListener onDrawAllListener;
/**
* Call back object to call when the user does a tap gesture
*/
private OnTapListener onTapListener;
/**
* Call back object to call when the user does a long tap gesture
*/
private OnLongPressListener onLongPressListener;
/**
* Call back object to call when clicking link
*/ | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/link/LinkHandler.java
// public interface LinkHandler {
//
// /**
// * Called when link was tapped by user
// *
// * @param event current event
// */
// void handleLinkEvent(LinkTapEvent event);
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/Callbacks.java
import android.view.MotionEvent;
import com.github.barteksc.pdfviewer.link.LinkHandler;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
/**
* Copyright 2017 Bartosz Schiller
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.github.barteksc.pdfviewer.listener;
public class Callbacks {
/**
* Call back object to call when the PDF is loaded
*/
private OnLoadCompleteListener onLoadCompleteListener;
/**
* Call back object to call when document loading error occurs
*/
private OnErrorListener onErrorListener;
/**
* Call back object to call when the page load error occurs
*/
private OnPageErrorListener onPageErrorListener;
/**
* Call back object to call when the document is initially rendered
*/
private OnRenderListener onRenderListener;
/**
* Call back object to call when the page has changed
*/
private OnPageChangeListener onPageChangeListener;
/**
* Call back object to call when the page is scrolled
*/
private OnPageScrollListener onPageScrollListener;
/**
* Call back object to call when the above layer is to drawn
*/
private OnDrawListener onDrawListener;
private OnDrawListener onDrawAllListener;
/**
* Call back object to call when the user does a tap gesture
*/
private OnTapListener onTapListener;
/**
* Call back object to call when the user does a long tap gesture
*/
private OnLongPressListener onLongPressListener;
/**
* Call back object to call when clicking link
*/ | private LinkHandler linkHandler; |
barteksc/AndroidPdfViewer | android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/Callbacks.java | // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/link/LinkHandler.java
// public interface LinkHandler {
//
// /**
// * Called when link was tapped by user
// *
// * @param event current event
// */
// void handleLinkEvent(LinkTapEvent event);
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
| import android.view.MotionEvent;
import com.github.barteksc.pdfviewer.link.LinkHandler;
import com.github.barteksc.pdfviewer.model.LinkTapEvent; | public void setOnDrawAll(OnDrawListener onDrawAllListener) {
this.onDrawAllListener = onDrawAllListener;
}
public OnDrawListener getOnDrawAll() {
return onDrawAllListener;
}
public void setOnTap(OnTapListener onTapListener) {
this.onTapListener = onTapListener;
}
public boolean callOnTap(MotionEvent event) {
return onTapListener != null && onTapListener.onTap(event);
}
public void setOnLongPress(OnLongPressListener onLongPressListener) {
this.onLongPressListener = onLongPressListener;
}
public void callOnLongPress(MotionEvent event) {
if (onLongPressListener != null) {
onLongPressListener.onLongPress(event);
}
}
public void setLinkHandler(LinkHandler linkHandler) {
this.linkHandler = linkHandler;
}
| // Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/link/LinkHandler.java
// public interface LinkHandler {
//
// /**
// * Called when link was tapped by user
// *
// * @param event current event
// */
// void handleLinkEvent(LinkTapEvent event);
// }
//
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java
// public class LinkTapEvent {
// private float originalX;
// private float originalY;
// private float documentX;
// private float documentY;
// private RectF mappedLinkRect;
// private PdfDocument.Link link;
//
// public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
// this.originalX = originalX;
// this.originalY = originalY;
// this.documentX = documentX;
// this.documentY = documentY;
// this.mappedLinkRect = mappedLinkRect;
// this.link = link;
// }
//
// public float getOriginalX() {
// return originalX;
// }
//
// public float getOriginalY() {
// return originalY;
// }
//
// public float getDocumentX() {
// return documentX;
// }
//
// public float getDocumentY() {
// return documentY;
// }
//
// public RectF getMappedLinkRect() {
// return mappedLinkRect;
// }
//
// public PdfDocument.Link getLink() {
// return link;
// }
// }
// Path: android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/Callbacks.java
import android.view.MotionEvent;
import com.github.barteksc.pdfviewer.link.LinkHandler;
import com.github.barteksc.pdfviewer.model.LinkTapEvent;
public void setOnDrawAll(OnDrawListener onDrawAllListener) {
this.onDrawAllListener = onDrawAllListener;
}
public OnDrawListener getOnDrawAll() {
return onDrawAllListener;
}
public void setOnTap(OnTapListener onTapListener) {
this.onTapListener = onTapListener;
}
public boolean callOnTap(MotionEvent event) {
return onTapListener != null && onTapListener.onTap(event);
}
public void setOnLongPress(OnLongPressListener onLongPressListener) {
this.onLongPressListener = onLongPressListener;
}
public void callOnLongPress(MotionEvent event) {
if (onLongPressListener != null) {
onLongPressListener.onLongPress(event);
}
}
public void setLinkHandler(LinkHandler linkHandler) {
this.linkHandler = linkHandler;
}
| public void callLinkHandler(LinkTapEvent event) { |
jkazama/sample-boot-scala | src/main/java/sample/model/constraints/CategoryEmpty.java | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
| import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import sample.util.JavaRegex; | package sample.model.constraints;
/**
* 各種カテゴリ/区分(必須)を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@Size
@Pattern(regexp = "")
public @interface CategoryEmpty {
String message() default "{error.domain.category}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 30;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
// Path: src/main/java/sample/model/constraints/CategoryEmpty.java
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import sample.util.JavaRegex;
package sample.model.constraints;
/**
* 各種カテゴリ/区分(必須)を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@Size
@Pattern(regexp = "")
public @interface CategoryEmpty {
String message() default "{error.domain.category}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 30;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | String regexp() default JavaRegex.rAscii; |
jkazama/sample-boot-scala | src/main/java/sample/model/constraints/Password.java | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
| import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.NotBlank;
import sample.util.JavaRegex; | package sample.model.constraints;
/**
* パスワード(必須)を表現する制約注釈。
* low: 実際の定義はプロジェクトに大きく依存するのでサンプルでは適当にしています。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Password {
String message() default "{error.domain.password}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 256;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
// Path: src/main/java/sample/model/constraints/Password.java
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.NotBlank;
import sample.util.JavaRegex;
package sample.model.constraints;
/**
* パスワード(必須)を表現する制約注釈。
* low: 実際の定義はプロジェクトに大きく依存するのでサンプルでは適当にしています。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Password {
String message() default "{error.domain.password}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 256;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | String regexp() default JavaRegex.rAscii; |
jkazama/sample-boot-scala | src/main/java/sample/model/constraints/OutlineEmpty.java | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
| import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import sample.util.JavaRegex; | package sample.model.constraints;
/**
* 概要を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@Size
@Pattern(regexp = "")
public @interface OutlineEmpty {
String message() default "{error.domain.outline}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 200;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
// Path: src/main/java/sample/model/constraints/OutlineEmpty.java
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import sample.util.JavaRegex;
package sample.model.constraints;
/**
* 概要を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@Size
@Pattern(regexp = "")
public @interface OutlineEmpty {
String message() default "{error.domain.outline}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 200;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | String regexp() default JavaRegex.rWord; |
jkazama/sample-boot-scala | src/main/java/sample/model/constraints/Description.java | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
| import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.NotBlank;
import sample.util.JavaRegex; | package sample.model.constraints;
/**
* 備考(必須)を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Description {
String message() default "{error.domain.description}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 400;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
// Path: src/main/java/sample/model/constraints/Description.java
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.NotBlank;
import sample.util.JavaRegex;
package sample.model.constraints;
/**
* 備考(必須)を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Description {
String message() default "{error.domain.description}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 400;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | String regexp() default JavaRegex.rWord; |
jkazama/sample-boot-scala | src/main/java/sample/model/constraints/Outline.java | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
| import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.NotBlank;
import sample.util.JavaRegex; | package sample.model.constraints;
/**
* 概要(必須)を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Outline {
String message() default "{error.domain.outline}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 200;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
// Path: src/main/java/sample/model/constraints/Outline.java
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.NotBlank;
import sample.util.JavaRegex;
package sample.model.constraints;
/**
* 概要(必須)を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Outline {
String message() default "{error.domain.outline}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 200;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | String regexp() default JavaRegex.rWord; |
jkazama/sample-boot-scala | src/main/java/sample/model/constraints/DescriptionEmpty.java | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
| import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import sample.util.JavaRegex; | package sample.model.constraints;
/**
* 備考を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@Size
@Pattern(regexp = "")
public @interface DescriptionEmpty {
String message() default "{error.domain.description}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 400;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
// Path: src/main/java/sample/model/constraints/DescriptionEmpty.java
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import sample.util.JavaRegex;
package sample.model.constraints;
/**
* 備考を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@Size
@Pattern(regexp = "")
public @interface DescriptionEmpty {
String message() default "{error.domain.description}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 400;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | String regexp() default JavaRegex.rWord; |
jkazama/sample-boot-scala | src/main/java/sample/model/constraints/Category.java | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
| import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.NotBlank;
import sample.util.JavaRegex; | package sample.model.constraints;
/**
* 各種カテゴリ/区分(必須)を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Category {
String message() default "{error.domain.category}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 30;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | // Path: src/main/java/sample/util/JavaRegex.java
// public interface JavaRegex {
// /** Ascii */
// String rAscii = "^\\p{ASCII}*$";
// /** 英字 */
// String rAlpha = "^[a-zA-Z]*$";
// /** 英字大文字 */
// String rAlphaUpper = "^[A-Z]*$";
// /** 英字小文字 */
// String rAlphaLower = "^[a-z]*$";
// /** 英数 */
// String rAlnum = "^[0-9a-zA-Z]*$";
// /** シンボル */
// String rSymbol = "^\\p{Punct}*$";
// /** 英数記号 */
// String rAlnumSymbol = "^[0-9a-zA-Z\\p{Punct}]*$";
// /** 数字 */
// String rNumber = "^[-]?[0-9]*$";
// /** 整数 */
// String rNumberNatural = "^[0-9]*$";
// /** 倍精度浮動小数点 */
// String rDecimal = "^[-]?(\\d+)(\\.\\d+)?$";
// // see UnicodeBlock
// /** ひらがな */
// String rHiragana = "^\\p{InHiragana}*$";
// /** カタカナ */
// String rKatakana = "^\\p{InKatakana}*$";
// /** 半角カタカナ */
// String rHankata = "^[。-゚]*$";
// /** 半角文字列 */
// String rHankaku = "^[\\p{InBasicLatin}。-゚]*$"; // ラテン文字 + 半角カタカナ
// /** 全角文字列 */
// String rZenkaku = "^[^\\p{InBasicLatin}。-゚]*$"; // 全角の定義を半角以外で割り切り
// /** 漢字 */
// String rKanji = "^[\\p{InCJKUnifiedIdeographs}々\\p{InCJKCompatibilityIdeographs}]*$";
// /** 文字 */
// String rWord = "^(?s).*$";
// /** コード */
// String rCode = "^[0-9a-zA-Z_-]*$"; // 英数 + アンダーバー + ハイフン
// }
// Path: src/main/java/sample/model/constraints/Category.java
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import javax.validation.*;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.NotBlank;
import sample.util.JavaRegex;
package sample.model.constraints;
/**
* 各種カテゴリ/区分(必須)を表現する制約注釈。
*/
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Category {
String message() default "{error.domain.category}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@OverridesAttribute(constraint = Size.class, name = "max")
int max() default 30;
@OverridesAttribute(constraint = Pattern.class, name = "regexp") | String regexp() default JavaRegex.rAscii; |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/bleach/CompositeBleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
| import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils; | package xyz.docbleach.api.bleach;
public class CompositeBleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositeBleach.class);
private final Collection<Bleach> bleaches = new ArrayList<>();
private final String name;
public CompositeBleach(Bleach... bleaches) {
Collections.addAll(this.bleaches, bleaches);
name = buildName(bleaches);
}
private String buildName(Bleach[] bleaches) {
StringBuilder myName = new StringBuilder("CompositeBleach: ");
for (Bleach b : bleaches) {
myName.append(b.getName()).append(" ");
}
return myName.toString().trim();
}
@Override
public boolean handlesMagic(InputStream stream) {
return bleaches.stream().anyMatch(bleach -> bleach.handlesMagic(stream));
}
@Override
public String getName() {
return name;
}
@Override | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
// Path: api/src/main/java/xyz/docbleach/api/bleach/CompositeBleach.java
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils;
package xyz.docbleach.api.bleach;
public class CompositeBleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositeBleach.class);
private final Collection<Bleach> bleaches = new ArrayList<>();
private final String name;
public CompositeBleach(Bleach... bleaches) {
Collections.addAll(this.bleaches, bleaches);
name = buildName(bleaches);
}
private String buildName(Bleach[] bleaches) {
StringBuilder myName = new StringBuilder("CompositeBleach: ");
for (Bleach b : bleaches) {
myName.append(b.getName()).append(" ");
}
return myName.toString().trim();
}
@Override
public boolean handlesMagic(InputStream stream) {
return bleaches.stream().anyMatch(bleach -> bleach.handlesMagic(stream));
}
@Override
public String getName() {
return name;
}
@Override | public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/bleach/CompositeBleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
| import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils; | package xyz.docbleach.api.bleach;
public class CompositeBleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositeBleach.class);
private final Collection<Bleach> bleaches = new ArrayList<>();
private final String name;
public CompositeBleach(Bleach... bleaches) {
Collections.addAll(this.bleaches, bleaches);
name = buildName(bleaches);
}
private String buildName(Bleach[] bleaches) {
StringBuilder myName = new StringBuilder("CompositeBleach: ");
for (Bleach b : bleaches) {
myName.append(b.getName()).append(" ");
}
return myName.toString().trim();
}
@Override
public boolean handlesMagic(InputStream stream) {
return bleaches.stream().anyMatch(bleach -> bleach.handlesMagic(stream));
}
@Override
public String getName() {
return name;
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
// Path: api/src/main/java/xyz/docbleach/api/bleach/CompositeBleach.java
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils;
package xyz.docbleach.api.bleach;
public class CompositeBleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositeBleach.class);
private final Collection<Bleach> bleaches = new ArrayList<>();
private final String name;
public CompositeBleach(Bleach... bleaches) {
Collections.addAll(this.bleaches, bleaches);
name = buildName(bleaches);
}
private String buildName(Bleach[] bleaches) {
StringBuilder myName = new StringBuilder("CompositeBleach: ");
for (Bleach b : bleaches) {
myName.append(b.getName()).append(" ");
}
return myName.toString().trim();
}
@Override
public boolean handlesMagic(InputStream stream) {
return bleaches.stream().anyMatch(bleach -> bleach.handlesMagic(stream));
}
@Override
public String getName() {
return name;
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) | throws BleachException { |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/bleach/CompositeBleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
| import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils; | package xyz.docbleach.api.bleach;
public class CompositeBleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositeBleach.class);
private final Collection<Bleach> bleaches = new ArrayList<>();
private final String name;
public CompositeBleach(Bleach... bleaches) {
Collections.addAll(this.bleaches, bleaches);
name = buildName(bleaches);
}
private String buildName(Bleach[] bleaches) {
StringBuilder myName = new StringBuilder("CompositeBleach: ");
for (Bleach b : bleaches) {
myName.append(b.getName()).append(" ");
}
return myName.toString().trim();
}
@Override
public boolean handlesMagic(InputStream stream) {
return bleaches.stream().anyMatch(bleach -> bleach.handlesMagic(stream));
}
@Override
public String getName() {
return name;
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
throws BleachException {
ByteArrayOutputStream os = null; | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
// Path: api/src/main/java/xyz/docbleach/api/bleach/CompositeBleach.java
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils;
package xyz.docbleach.api.bleach;
public class CompositeBleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositeBleach.class);
private final Collection<Bleach> bleaches = new ArrayList<>();
private final String name;
public CompositeBleach(Bleach... bleaches) {
Collections.addAll(this.bleaches, bleaches);
name = buildName(bleaches);
}
private String buildName(Bleach[] bleaches) {
StringBuilder myName = new StringBuilder("CompositeBleach: ");
for (Bleach b : bleaches) {
myName.append(b.getName()).append(" ");
}
return myName.toString().trim();
}
@Override
public boolean handlesMagic(InputStream stream) {
return bleaches.stream().anyMatch(bleach -> bleach.handlesMagic(stream));
}
@Override
public String getName() {
return name;
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
throws BleachException {
ByteArrayOutputStream os = null; | CloseShieldInputStream is = new CloseShieldInputStream(inputStream); |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/bleach/CompositeBleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
| import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils; | if (os != null && is == null) {
// We check if "is" is null to prevent useless object creation
ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());
is = new CloseShieldInputStream(new BufferedInputStream(bais, bais.available()));
try {
os.close();
} catch (IOException e) {
LOGGER.error("Error in CompositeBleach", e);
}
}
if (!b.handlesMagic(is)) {
continue;
}
LOGGER.trace("Using bleach: {}", b.getName());
os = new ByteArrayOutputStream();
b.sanitize(is, os, session);
try {
is.close();
is = null;
} catch (IOException e) {
LOGGER.error("Error in CompositeBleach", e);
}
}
try {
if (os == null) {
// no bleach is able to handle this file | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/CloseShieldInputStream.java
// public class CloseShieldInputStream extends FilterInputStream {
//
// public CloseShieldInputStream(InputStream inStream) {
// super(inStream);
// }
//
// @Override
// public void close() throws IOException {
// // no-action
// }
//
// public void _close() throws IOException {
// super.close();
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
// Path: api/src/main/java/xyz/docbleach/api/bleach/CompositeBleach.java
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.CloseShieldInputStream;
import xyz.docbleach.api.util.StreamUtils;
if (os != null && is == null) {
// We check if "is" is null to prevent useless object creation
ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());
is = new CloseShieldInputStream(new BufferedInputStream(bais, bais.available()));
try {
os.close();
} catch (IOException e) {
LOGGER.error("Error in CompositeBleach", e);
}
}
if (!b.handlesMagic(is)) {
continue;
}
LOGGER.trace("Using bleach: {}", b.getName());
os = new ByteArrayOutputStream();
b.sanitize(is, os, session);
try {
is.close();
is = null;
} catch (IOException e) {
LOGGER.error("Error in CompositeBleach", e);
}
}
try {
if (os == null) {
// no bleach is able to handle this file | StreamUtils.copy(is, outputStream); |
docbleach/DocBleach | module/module-pdf/src/test/java/xyz/docbleach/module/pdf/PdfBleachSessionTest.java | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
| import static org.mockito.Mockito.mock;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession; | package xyz.docbleach.module.pdf;
class PdfBleachSessionTest {
private PdfBleachSession instance; | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
// Path: module/module-pdf/src/test/java/xyz/docbleach/module/pdf/PdfBleachSessionTest.java
import static org.mockito.Mockito.mock;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
package xyz.docbleach.module.pdf;
class PdfBleachSessionTest {
private PdfBleachSession instance; | private BleachSession session; |
docbleach/DocBleach | module/module-pdf/src/test/java/xyz/docbleach/module/pdf/PdfBleachSessionTest.java | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
| import static org.mockito.Mockito.mock;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession; | package xyz.docbleach.module.pdf;
class PdfBleachSessionTest {
private PdfBleachSession instance;
private BleachSession session;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = new PdfBleachSession(session);
}
@Test
void recordingJavascriptThreatWorks() {
instance.recordJavascriptThreat("", ""); | // Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
//
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
// Path: module/module-pdf/src/test/java/xyz/docbleach/module/pdf/PdfBleachSessionTest.java
import static org.mockito.Mockito.mock;
import static xyz.docbleach.api.BleachTestBase.assertThreatsFound;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
package xyz.docbleach.module.pdf;
class PdfBleachSessionTest {
private PdfBleachSession instance;
private BleachSession session;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = new PdfBleachSession(session);
}
@Test
void recordingJavascriptThreatWorks() {
instance.recordJavascriptThreat("", ""); | assertThreatsFound(session, 1); |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/OLE2Bleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.function.Predicate;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException; | package xyz.docbleach.module.ole2;
/**
* Sanitizes an OLE2 file (.doc, .xls, .ppt) by copying its elements into a new OLE2 container.
* Information to be modified (template, ...) are changed on the fly, and entries to be removed are
* just not copied over. This way, using a simple Visitor, it is possible to add rules applied on
* each entry.
*/
public class OLE2Bleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(OLE2Bleach.class);
@Override
public boolean handlesMagic(InputStream stream) {
try {
return stream.available() > 4 && FileMagic.valueOf(stream) == FileMagic.OLE2;
} catch (Exception e) {
LOGGER.warn("An exception occured", e);
return false;
}
}
@Override
public String getName() {
return "OLE2 Bleach";
}
@Override | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/OLE2Bleach.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.function.Predicate;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
package xyz.docbleach.module.ole2;
/**
* Sanitizes an OLE2 file (.doc, .xls, .ppt) by copying its elements into a new OLE2 container.
* Information to be modified (template, ...) are changed on the fly, and entries to be removed are
* just not copied over. This way, using a simple Visitor, it is possible to add rules applied on
* each entry.
*/
public class OLE2Bleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(OLE2Bleach.class);
@Override
public boolean handlesMagic(InputStream stream) {
try {
return stream.available() > 4 && FileMagic.valueOf(stream) == FileMagic.OLE2;
} catch (Exception e) {
LOGGER.warn("An exception occured", e);
return false;
}
}
@Override
public String getName() {
return "OLE2 Bleach";
}
@Override | public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/OLE2Bleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.function.Predicate;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException; | package xyz.docbleach.module.ole2;
/**
* Sanitizes an OLE2 file (.doc, .xls, .ppt) by copying its elements into a new OLE2 container.
* Information to be modified (template, ...) are changed on the fly, and entries to be removed are
* just not copied over. This way, using a simple Visitor, it is possible to add rules applied on
* each entry.
*/
public class OLE2Bleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(OLE2Bleach.class);
@Override
public boolean handlesMagic(InputStream stream) {
try {
return stream.available() > 4 && FileMagic.valueOf(stream) == FileMagic.OLE2;
} catch (Exception e) {
LOGGER.warn("An exception occured", e);
return false;
}
}
@Override
public String getName() {
return "OLE2 Bleach";
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/OLE2Bleach.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.function.Predicate;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
package xyz.docbleach.module.ole2;
/**
* Sanitizes an OLE2 file (.doc, .xls, .ppt) by copying its elements into a new OLE2 container.
* Information to be modified (template, ...) are changed on the fly, and entries to be removed are
* just not copied over. This way, using a simple Visitor, it is possible to add rules applied on
* each entry.
*/
public class OLE2Bleach implements Bleach {
private static final Logger LOGGER = LoggerFactory.getLogger(OLE2Bleach.class);
@Override
public boolean handlesMagic(InputStream stream) {
try {
return stream.available() > 4 && FileMagic.valueOf(stream) == FileMagic.OLE2;
} catch (Exception e) {
LOGGER.warn("An exception occured", e);
return false;
}
}
@Override
public String getName() {
return "OLE2 Bleach";
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) | throws BleachException { |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.ole2;
public class SummaryInformationSanitiser extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(SummaryInformationSanitiser.class);
private static final String NORMAL_TEMPLATE = "Normal.dotm";
| // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java
import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
package xyz.docbleach.module.ole2;
public class SummaryInformationSanitiser extends EntryFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(SummaryInformationSanitiser.class);
private static final String NORMAL_TEMPLATE = "Normal.dotm";
| public SummaryInformationSanitiser(BleachSession session) { |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | try (DocumentInputStream dis = new DocumentInputStream(dsiEntry)) {
PropertySet ps = new PropertySet(dis);
// Useful for debugging purposes
// LOGGER.debug("PropertySet sections: {}", ps.getSections());
SummaryInformation dsi = new SummaryInformation(ps);
sanitizeSummaryInformation(session, dsi);
} catch (NoPropertySetStreamException
| UnexpectedPropertySetTypeException
| IOException e) {
LOGGER.error("An error occured while trying to sanitize the document entry", e);
}
}
protected void sanitizeSummaryInformation(BleachSession session, SummaryInformation dsi) {
sanitizeTemplate(session, dsi);
sanitizeComments(session, dsi);
}
protected void sanitizeComments(BleachSession session, SummaryInformation dsi) {
String comments = dsi.getComments();
if (comments == null || comments.isEmpty()) {
return;
}
LOGGER.trace("Removing the document's Comments (was '{}')", comments);
dsi.removeComments();
| // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java
import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
try (DocumentInputStream dis = new DocumentInputStream(dsiEntry)) {
PropertySet ps = new PropertySet(dis);
// Useful for debugging purposes
// LOGGER.debug("PropertySet sections: {}", ps.getSections());
SummaryInformation dsi = new SummaryInformation(ps);
sanitizeSummaryInformation(session, dsi);
} catch (NoPropertySetStreamException
| UnexpectedPropertySetTypeException
| IOException e) {
LOGGER.error("An error occured while trying to sanitize the document entry", e);
}
}
protected void sanitizeSummaryInformation(BleachSession session, SummaryInformation dsi) {
sanitizeTemplate(session, dsi);
sanitizeComments(session, dsi);
}
protected void sanitizeComments(BleachSession session, SummaryInformation dsi) {
String comments = dsi.getComments();
if (comments == null || comments.isEmpty()) {
return;
}
LOGGER.trace("Removing the document's Comments (was '{}')", comments);
dsi.removeComments();
| Threat threat = Threat.builder() |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | PropertySet ps = new PropertySet(dis);
// Useful for debugging purposes
// LOGGER.debug("PropertySet sections: {}", ps.getSections());
SummaryInformation dsi = new SummaryInformation(ps);
sanitizeSummaryInformation(session, dsi);
} catch (NoPropertySetStreamException
| UnexpectedPropertySetTypeException
| IOException e) {
LOGGER.error("An error occured while trying to sanitize the document entry", e);
}
}
protected void sanitizeSummaryInformation(BleachSession session, SummaryInformation dsi) {
sanitizeTemplate(session, dsi);
sanitizeComments(session, dsi);
}
protected void sanitizeComments(BleachSession session, SummaryInformation dsi) {
String comments = dsi.getComments();
if (comments == null || comments.isEmpty()) {
return;
}
LOGGER.trace("Removing the document's Comments (was '{}')", comments);
dsi.removeComments();
Threat threat = Threat.builder() | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java
import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
PropertySet ps = new PropertySet(dis);
// Useful for debugging purposes
// LOGGER.debug("PropertySet sections: {}", ps.getSections());
SummaryInformation dsi = new SummaryInformation(ps);
sanitizeSummaryInformation(session, dsi);
} catch (NoPropertySetStreamException
| UnexpectedPropertySetTypeException
| IOException e) {
LOGGER.error("An error occured while trying to sanitize the document entry", e);
}
}
protected void sanitizeSummaryInformation(BleachSession session, SummaryInformation dsi) {
sanitizeTemplate(session, dsi);
sanitizeComments(session, dsi);
}
protected void sanitizeComments(BleachSession session, SummaryInformation dsi) {
String comments = dsi.getComments();
if (comments == null || comments.isEmpty()) {
return;
}
LOGGER.trace("Removing the document's Comments (was '{}')", comments);
dsi.removeComments();
Threat threat = Threat.builder() | .type(ThreatType.UNRECOGNIZED_CONTENT) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | // Useful for debugging purposes
// LOGGER.debug("PropertySet sections: {}", ps.getSections());
SummaryInformation dsi = new SummaryInformation(ps);
sanitizeSummaryInformation(session, dsi);
} catch (NoPropertySetStreamException
| UnexpectedPropertySetTypeException
| IOException e) {
LOGGER.error("An error occured while trying to sanitize the document entry", e);
}
}
protected void sanitizeSummaryInformation(BleachSession session, SummaryInformation dsi) {
sanitizeTemplate(session, dsi);
sanitizeComments(session, dsi);
}
protected void sanitizeComments(BleachSession session, SummaryInformation dsi) {
String comments = dsi.getComments();
if (comments == null || comments.isEmpty()) {
return;
}
LOGGER.trace("Removing the document's Comments (was '{}')", comments);
dsi.removeComments();
Threat threat = Threat.builder()
.type(ThreatType.UNRECOGNIZED_CONTENT) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java
import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
// Useful for debugging purposes
// LOGGER.debug("PropertySet sections: {}", ps.getSections());
SummaryInformation dsi = new SummaryInformation(ps);
sanitizeSummaryInformation(session, dsi);
} catch (NoPropertySetStreamException
| UnexpectedPropertySetTypeException
| IOException e) {
LOGGER.error("An error occured while trying to sanitize the document entry", e);
}
}
protected void sanitizeSummaryInformation(BleachSession session, SummaryInformation dsi) {
sanitizeTemplate(session, dsi);
sanitizeComments(session, dsi);
}
protected void sanitizeComments(BleachSession session, SummaryInformation dsi) {
String comments = dsi.getComments();
if (comments == null || comments.isEmpty()) {
return;
}
LOGGER.trace("Removing the document's Comments (was '{}')", comments);
dsi.removeComments();
Threat threat = Threat.builder()
.type(ThreatType.UNRECOGNIZED_CONTENT) | .severity(ThreatSeverity.LOW) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | // LOGGER.debug("PropertySet sections: {}", ps.getSections());
SummaryInformation dsi = new SummaryInformation(ps);
sanitizeSummaryInformation(session, dsi);
} catch (NoPropertySetStreamException
| UnexpectedPropertySetTypeException
| IOException e) {
LOGGER.error("An error occured while trying to sanitize the document entry", e);
}
}
protected void sanitizeSummaryInformation(BleachSession session, SummaryInformation dsi) {
sanitizeTemplate(session, dsi);
sanitizeComments(session, dsi);
}
protected void sanitizeComments(BleachSession session, SummaryInformation dsi) {
String comments = dsi.getComments();
if (comments == null || comments.isEmpty()) {
return;
}
LOGGER.trace("Removing the document's Comments (was '{}')", comments);
dsi.removeComments();
Threat threat = Threat.builder()
.type(ThreatType.UNRECOGNIZED_CONTENT)
.severity(ThreatSeverity.LOW) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ole2/SummaryInformationSanitiser.java
import java.io.IOException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
// LOGGER.debug("PropertySet sections: {}", ps.getSections());
SummaryInformation dsi = new SummaryInformation(ps);
sanitizeSummaryInformation(session, dsi);
} catch (NoPropertySetStreamException
| UnexpectedPropertySetTypeException
| IOException e) {
LOGGER.error("An error occured while trying to sanitize the document entry", e);
}
}
protected void sanitizeSummaryInformation(BleachSession session, SummaryInformation dsi) {
sanitizeTemplate(session, dsi);
sanitizeComments(session, dsi);
}
protected void sanitizeComments(BleachSession session, SummaryInformation dsi) {
String comments = dsi.getComments();
if (comments == null || comments.isEmpty()) {
return;
}
LOGGER.trace("Removing the document's Comments (was '{}')", comments);
dsi.removeComments();
Threat threat = Threat.builder()
.type(ThreatType.UNRECOGNIZED_CONTENT)
.severity(ThreatSeverity.LOW) | .action(ThreatAction.REMOVE) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ooxml/OOXMLTagHelper.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.ZipPackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | // The evil tag has not been found, return
if (!external && !ddeauto) {
return;
}
LOGGER.debug((external ? "externalData tag" : "DDE ") + " has been spotted {}", part);
// Replace the tag by a comment
content = content.replaceAll(REGEXP_EXTERNAL_DATA, XML_COMMENT_BLEACHED);
// Replace DDEAUTO with nothing, DDE will not trigger
content = content.replaceAll(DDEAUTO, "");
// Replace ddeService & ddeTopic with cmd.exe exit
content =
content.replaceAll(
REGEXP_DDESERVICE_DATA, ATTRIBUTE_DDESERVICE_DATA + "=\"" + DDE_DATA_BLEACHED1 + "\"");
content =
content.replaceAll(
REGEXP_DDETOPIC_DATA, ATTRIBUTE_DDETOPIC_DATA + "=\"" + DDE_DATA_BLEACHED2 + "\"");
// Write the result
try (OutputStream os = part.getOutputStream()) {
os.write(content.getBytes());
os.close();
} catch (IOException ex) {
LOGGER.error("Error while writing the part content. The file may be corrupted.", ex);
return;
}
| // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ooxml/OOXMLTagHelper.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.ZipPackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
// The evil tag has not been found, return
if (!external && !ddeauto) {
return;
}
LOGGER.debug((external ? "externalData tag" : "DDE ") + " has been spotted {}", part);
// Replace the tag by a comment
content = content.replaceAll(REGEXP_EXTERNAL_DATA, XML_COMMENT_BLEACHED);
// Replace DDEAUTO with nothing, DDE will not trigger
content = content.replaceAll(DDEAUTO, "");
// Replace ddeService & ddeTopic with cmd.exe exit
content =
content.replaceAll(
REGEXP_DDESERVICE_DATA, ATTRIBUTE_DDESERVICE_DATA + "=\"" + DDE_DATA_BLEACHED1 + "\"");
content =
content.replaceAll(
REGEXP_DDETOPIC_DATA, ATTRIBUTE_DDETOPIC_DATA + "=\"" + DDE_DATA_BLEACHED2 + "\"");
// Write the result
try (OutputStream os = part.getOutputStream()) {
os.write(content.getBytes());
os.close();
} catch (IOException ex) {
LOGGER.error("Error while writing the part content. The file may be corrupted.", ex);
return;
}
| session.recordThreat(Threat.builder() |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ooxml/OOXMLTagHelper.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.ZipPackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | if (!external && !ddeauto) {
return;
}
LOGGER.debug((external ? "externalData tag" : "DDE ") + " has been spotted {}", part);
// Replace the tag by a comment
content = content.replaceAll(REGEXP_EXTERNAL_DATA, XML_COMMENT_BLEACHED);
// Replace DDEAUTO with nothing, DDE will not trigger
content = content.replaceAll(DDEAUTO, "");
// Replace ddeService & ddeTopic with cmd.exe exit
content =
content.replaceAll(
REGEXP_DDESERVICE_DATA, ATTRIBUTE_DDESERVICE_DATA + "=\"" + DDE_DATA_BLEACHED1 + "\"");
content =
content.replaceAll(
REGEXP_DDETOPIC_DATA, ATTRIBUTE_DDETOPIC_DATA + "=\"" + DDE_DATA_BLEACHED2 + "\"");
// Write the result
try (OutputStream os = part.getOutputStream()) {
os.write(content.getBytes());
os.close();
} catch (IOException ex) {
LOGGER.error("Error while writing the part content. The file may be corrupted.", ex);
return;
}
session.recordThreat(Threat.builder() | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ooxml/OOXMLTagHelper.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.ZipPackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
if (!external && !ddeauto) {
return;
}
LOGGER.debug((external ? "externalData tag" : "DDE ") + " has been spotted {}", part);
// Replace the tag by a comment
content = content.replaceAll(REGEXP_EXTERNAL_DATA, XML_COMMENT_BLEACHED);
// Replace DDEAUTO with nothing, DDE will not trigger
content = content.replaceAll(DDEAUTO, "");
// Replace ddeService & ddeTopic with cmd.exe exit
content =
content.replaceAll(
REGEXP_DDESERVICE_DATA, ATTRIBUTE_DDESERVICE_DATA + "=\"" + DDE_DATA_BLEACHED1 + "\"");
content =
content.replaceAll(
REGEXP_DDETOPIC_DATA, ATTRIBUTE_DDETOPIC_DATA + "=\"" + DDE_DATA_BLEACHED2 + "\"");
// Write the result
try (OutputStream os = part.getOutputStream()) {
os.write(content.getBytes());
os.close();
} catch (IOException ex) {
LOGGER.error("Error while writing the part content. The file may be corrupted.", ex);
return;
}
session.recordThreat(Threat.builder() | .type(external ? ThreatType.EXTERNAL_CONTENT : ThreatType.ACTIVE_CONTENT) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ooxml/OOXMLTagHelper.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.ZipPackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | return;
}
LOGGER.debug((external ? "externalData tag" : "DDE ") + " has been spotted {}", part);
// Replace the tag by a comment
content = content.replaceAll(REGEXP_EXTERNAL_DATA, XML_COMMENT_BLEACHED);
// Replace DDEAUTO with nothing, DDE will not trigger
content = content.replaceAll(DDEAUTO, "");
// Replace ddeService & ddeTopic with cmd.exe exit
content =
content.replaceAll(
REGEXP_DDESERVICE_DATA, ATTRIBUTE_DDESERVICE_DATA + "=\"" + DDE_DATA_BLEACHED1 + "\"");
content =
content.replaceAll(
REGEXP_DDETOPIC_DATA, ATTRIBUTE_DDETOPIC_DATA + "=\"" + DDE_DATA_BLEACHED2 + "\"");
// Write the result
try (OutputStream os = part.getOutputStream()) {
os.write(content.getBytes());
os.close();
} catch (IOException ex) {
LOGGER.error("Error while writing the part content. The file may be corrupted.", ex);
return;
}
session.recordThreat(Threat.builder()
.type(external ? ThreatType.EXTERNAL_CONTENT : ThreatType.ACTIVE_CONTENT) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ooxml/OOXMLTagHelper.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.ZipPackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
return;
}
LOGGER.debug((external ? "externalData tag" : "DDE ") + " has been spotted {}", part);
// Replace the tag by a comment
content = content.replaceAll(REGEXP_EXTERNAL_DATA, XML_COMMENT_BLEACHED);
// Replace DDEAUTO with nothing, DDE will not trigger
content = content.replaceAll(DDEAUTO, "");
// Replace ddeService & ddeTopic with cmd.exe exit
content =
content.replaceAll(
REGEXP_DDESERVICE_DATA, ATTRIBUTE_DDESERVICE_DATA + "=\"" + DDE_DATA_BLEACHED1 + "\"");
content =
content.replaceAll(
REGEXP_DDETOPIC_DATA, ATTRIBUTE_DDETOPIC_DATA + "=\"" + DDE_DATA_BLEACHED2 + "\"");
// Write the result
try (OutputStream os = part.getOutputStream()) {
os.write(content.getBytes());
os.close();
} catch (IOException ex) {
LOGGER.error("Error while writing the part content. The file may be corrupted.", ex);
return;
}
session.recordThreat(Threat.builder()
.type(external ? ThreatType.EXTERNAL_CONTENT : ThreatType.ACTIVE_CONTENT) | .severity(ThreatSeverity.HIGH) |
docbleach/DocBleach | module/module-office/src/main/java/xyz/docbleach/module/ooxml/OOXMLTagHelper.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.ZipPackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | }
LOGGER.debug((external ? "externalData tag" : "DDE ") + " has been spotted {}", part);
// Replace the tag by a comment
content = content.replaceAll(REGEXP_EXTERNAL_DATA, XML_COMMENT_BLEACHED);
// Replace DDEAUTO with nothing, DDE will not trigger
content = content.replaceAll(DDEAUTO, "");
// Replace ddeService & ddeTopic with cmd.exe exit
content =
content.replaceAll(
REGEXP_DDESERVICE_DATA, ATTRIBUTE_DDESERVICE_DATA + "=\"" + DDE_DATA_BLEACHED1 + "\"");
content =
content.replaceAll(
REGEXP_DDETOPIC_DATA, ATTRIBUTE_DDETOPIC_DATA + "=\"" + DDE_DATA_BLEACHED2 + "\"");
// Write the result
try (OutputStream os = part.getOutputStream()) {
os.write(content.getBytes());
os.close();
} catch (IOException ex) {
LOGGER.error("Error while writing the part content. The file may be corrupted.", ex);
return;
}
session.recordThreat(Threat.builder()
.type(external ? ThreatType.EXTERNAL_CONTENT : ThreatType.ACTIVE_CONTENT)
.severity(ThreatSeverity.HIGH) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatAction.java
// public enum ThreatAction {
// /**
// * No actions had to be taken, for instance if the threat is innocuous.
// */
// NOTHING,
//
// /**
// * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a
// * screenshot of the page
// */
// DISARM,
//
// /**
// * No actions were taken because of the configuration
// */
// IGNORE,
//
// /**
// * The threat has been removed.
// */
// REMOVE;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatSeverity.java
// public enum ThreatSeverity {
// LOW,
// MEDIUM,
// HIGH,
// EXTREME;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/ThreatType.java
// public enum ThreatType {
// /**
// * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO
// */
// ACTIVE_CONTENT,
//
// /**
// * Word Template linking to an external "thing", ...
// */
// EXTERNAL_CONTENT,
//
// /**
// * OLE Objects, ...
// */
// BINARY_CONTENT,
//
// /**
// * OLE Objects, strange image in a document ...
// */
// UNRECOGNIZED_CONTENT
// }
// Path: module/module-office/src/main/java/xyz/docbleach/module/ooxml/OOXMLTagHelper.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.ZipPackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType;
}
LOGGER.debug((external ? "externalData tag" : "DDE ") + " has been spotted {}", part);
// Replace the tag by a comment
content = content.replaceAll(REGEXP_EXTERNAL_DATA, XML_COMMENT_BLEACHED);
// Replace DDEAUTO with nothing, DDE will not trigger
content = content.replaceAll(DDEAUTO, "");
// Replace ddeService & ddeTopic with cmd.exe exit
content =
content.replaceAll(
REGEXP_DDESERVICE_DATA, ATTRIBUTE_DDESERVICE_DATA + "=\"" + DDE_DATA_BLEACHED1 + "\"");
content =
content.replaceAll(
REGEXP_DDETOPIC_DATA, ATTRIBUTE_DDETOPIC_DATA + "=\"" + DDE_DATA_BLEACHED2 + "\"");
// Write the result
try (OutputStream os = part.getOutputStream()) {
os.write(content.getBytes());
os.close();
} catch (IOException ex) {
LOGGER.error("Error while writing the part content. The file may be corrupted.", ex);
return;
}
session.recordThreat(Threat.builder()
.type(external ? ThreatType.EXTERNAL_CONTENT : ThreatType.ACTIVE_CONTENT)
.severity(ThreatSeverity.HIGH) | .action(ThreatAction.REMOVE) |
docbleach/DocBleach | api/src/test/java/xyz/docbleach/api/BleachTestBase.java | // Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
| import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import xyz.docbleach.api.threat.Threat; | package xyz.docbleach.api;
public abstract class BleachTestBase {
public static void assertThreatsFound(BleachSession session, int n) { | // Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import xyz.docbleach.api.threat.Threat;
package xyz.docbleach.api;
public abstract class BleachTestBase {
public static void assertThreatsFound(BleachSession session, int n) { | verify(session, times(n)).recordThreat(any(Threat.class)); |
docbleach/DocBleach | module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.StreamUtils; | package xyz.docbleach.module.pdf;
/**
* PDF parsing is a bit tricky: everything may or may not be linked to additional actions, so we
* need to treat each and every elements.
*/
public class PdfBleach implements Bleach {
private static final byte[] PDF_MAGIC = new byte[]{37, 80, 68, 70};
@Override
public boolean handlesMagic(InputStream stream) { | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
// Path: module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleach.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.StreamUtils;
package xyz.docbleach.module.pdf;
/**
* PDF parsing is a bit tricky: everything may or may not be linked to additional actions, so we
* need to treat each and every elements.
*/
public class PdfBleach implements Bleach {
private static final byte[] PDF_MAGIC = new byte[]{37, 80, 68, 70};
@Override
public boolean handlesMagic(InputStream stream) { | return StreamUtils.hasHeader(stream, PDF_MAGIC); |
docbleach/DocBleach | module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.StreamUtils; | package xyz.docbleach.module.pdf;
/**
* PDF parsing is a bit tricky: everything may or may not be linked to additional actions, so we
* need to treat each and every elements.
*/
public class PdfBleach implements Bleach {
private static final byte[] PDF_MAGIC = new byte[]{37, 80, 68, 70};
@Override
public boolean handlesMagic(InputStream stream) {
return StreamUtils.hasHeader(stream, PDF_MAGIC);
}
@Override
public String getName() {
return "PDF Bleach";
}
@Override | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
// Path: module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleach.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.StreamUtils;
package xyz.docbleach.module.pdf;
/**
* PDF parsing is a bit tricky: everything may or may not be linked to additional actions, so we
* need to treat each and every elements.
*/
public class PdfBleach implements Bleach {
private static final byte[] PDF_MAGIC = new byte[]{37, 80, 68, 70};
@Override
public boolean handlesMagic(InputStream stream) {
return StreamUtils.hasHeader(stream, PDF_MAGIC);
}
@Override
public String getName() {
return "PDF Bleach";
}
@Override | public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) |
docbleach/DocBleach | module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.StreamUtils; | package xyz.docbleach.module.pdf;
/**
* PDF parsing is a bit tricky: everything may or may not be linked to additional actions, so we
* need to treat each and every elements.
*/
public class PdfBleach implements Bleach {
private static final byte[] PDF_MAGIC = new byte[]{37, 80, 68, 70};
@Override
public boolean handlesMagic(InputStream stream) {
return StreamUtils.hasHeader(stream, PDF_MAGIC);
}
@Override
public String getName() {
return "PDF Bleach";
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/util/StreamUtils.java
// public class StreamUtils {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
//
// private StreamUtils() {
// throw new IllegalAccessError("Utility class");
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[100];
// int len;
// while ((len = is.read(buffer)) != -1) {
// os.write(buffer, 0, len);
// }
// }
//
// public static boolean hasHeader(InputStream stream, byte[] header) {
// byte[] fileMagic = new byte[header.length];
// int length;
//
// stream.mark(header.length);
//
// try {
// length = stream.read(fileMagic);
//
// if (stream instanceof PushbackInputStream) {
// PushbackInputStream pin = (PushbackInputStream) stream;
// pin.unread(fileMagic, 0, length);
// } else {
// stream.reset();
// }
// } catch (IOException e) {
// LOGGER.warn("An exception occured", e);
// return false;
// }
//
// return length == header.length && Arrays.equals(fileMagic, header);
// }
// }
// Path: module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleach.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.util.StreamUtils;
package xyz.docbleach.module.pdf;
/**
* PDF parsing is a bit tricky: everything may or may not be linked to additional actions, so we
* need to treat each and every elements.
*/
public class PdfBleach implements Bleach {
private static final byte[] PDF_MAGIC = new byte[]{37, 80, 68, 70};
@Override
public boolean handlesMagic(InputStream stream) {
return StreamUtils.hasHeader(stream, PDF_MAGIC);
}
@Override
public String getName() {
return "PDF Bleach";
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) | throws BleachException { |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/BleachSession.java | // Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.threat.Threat; | package xyz.docbleach.api;
/**
* A Bleach Session handles the data a bleach needs to store: list of the threats removed, for
* instance May be used in the future to store configuration (file's password, for instance) or
* callbacks
*/
public class BleachSession implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
private static final int MAX_ONGOING_TASKS = 10; | // Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.threat.Threat;
package xyz.docbleach.api;
/**
* A Bleach Session handles the data a bleach needs to store: list of the threats removed, for
* instance May be used in the future to store configuration (file's password, for instance) or
* callbacks
*/
public class BleachSession implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
private static final int MAX_ONGOING_TASKS = 10; | private final transient Bleach bleach; |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/BleachSession.java | // Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.threat.Threat; | package xyz.docbleach.api;
/**
* A Bleach Session handles the data a bleach needs to store: list of the threats removed, for
* instance May be used in the future to store configuration (file's password, for instance) or
* callbacks
*/
public class BleachSession implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
private static final int MAX_ONGOING_TASKS = 10;
private final transient Bleach bleach; | // Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.threat.Threat;
package xyz.docbleach.api;
/**
* A Bleach Session handles the data a bleach needs to store: list of the threats removed, for
* instance May be used in the future to store configuration (file's password, for instance) or
* callbacks
*/
public class BleachSession implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
private static final int MAX_ONGOING_TASKS = 10;
private final transient Bleach bleach; | private final Collection<Threat> threats = new ArrayList<>(); |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/BleachSession.java | // Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.threat.Threat; | package xyz.docbleach.api;
/**
* A Bleach Session handles the data a bleach needs to store: list of the threats removed, for
* instance May be used in the future to store configuration (file's password, for instance) or
* callbacks
*/
public class BleachSession implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
private static final int MAX_ONGOING_TASKS = 10;
private final transient Bleach bleach;
private final Collection<Threat> threats = new ArrayList<>();
/**
* Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
*/
private int ongoingTasks = 0;
public BleachSession(Bleach bleach) {
this.bleach = bleach;
}
/**
* The BleachSession is able to record threats encountered by the bleach.
*
* @param threat The removed threat object, containing the threat type and more information
*/
public void recordThreat(Threat threat) {
if (threat == null) {
return;
}
LOGGER.trace("Threat recorded: " + threat);
threats.add(threat);
}
public Collection<Threat> getThreats() {
return threats;
}
public int threatCount() {
return threats.size();
}
/**
* @return The bleach used in this session
*/
public Bleach getBleach() {
return bleach;
}
| // Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.threat.Threat;
package xyz.docbleach.api;
/**
* A Bleach Session handles the data a bleach needs to store: list of the threats removed, for
* instance May be used in the future to store configuration (file's password, for instance) or
* callbacks
*/
public class BleachSession implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
private static final int MAX_ONGOING_TASKS = 10;
private final transient Bleach bleach;
private final Collection<Threat> threats = new ArrayList<>();
/**
* Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
*/
private int ongoingTasks = 0;
public BleachSession(Bleach bleach) {
this.bleach = bleach;
}
/**
* The BleachSession is able to record threats encountered by the bleach.
*
* @param threat The removed threat object, containing the threat type and more information
*/
public void recordThreat(Threat threat) {
if (threat == null) {
return;
}
LOGGER.trace("Threat recorded: " + threat);
threats.add(threat);
}
public Collection<Threat> getThreats() {
return threats;
}
public int threatCount() {
return threats.size();
}
/**
* @return The bleach used in this session
*/
public Bleach getBleach() {
return bleach;
}
| public void sanitize(InputStream is, OutputStream os) throws BleachException { |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/BleachSession.java | // Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.threat.Threat; | package xyz.docbleach.api;
/**
* A Bleach Session handles the data a bleach needs to store: list of the threats removed, for
* instance May be used in the future to store configuration (file's password, for instance) or
* callbacks
*/
public class BleachSession implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
private static final int MAX_ONGOING_TASKS = 10;
private final transient Bleach bleach;
private final Collection<Threat> threats = new ArrayList<>();
/**
* Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
*/
private int ongoingTasks = 0;
public BleachSession(Bleach bleach) {
this.bleach = bleach;
}
/**
* The BleachSession is able to record threats encountered by the bleach.
*
* @param threat The removed threat object, containing the threat type and more information
*/
public void recordThreat(Threat threat) {
if (threat == null) {
return;
}
LOGGER.trace("Threat recorded: " + threat);
threats.add(threat);
}
public Collection<Threat> getThreats() {
return threats;
}
public int threatCount() {
return threats.size();
}
/**
* @return The bleach used in this session
*/
public Bleach getBleach() {
return bleach;
}
public void sanitize(InputStream is, OutputStream os) throws BleachException {
try {
if (ongoingTasks++ >= MAX_ONGOING_TASKS) { | // Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
// public interface Bleach {
//
// /**
// * Checks the magic header of the file and returns true if this bleach is able to sanitize this
// * InputStream. The stream has to {@link InputStream#markSupported support mark}.
// *
// * <p>The Bleach is responsible for the error handling to prevent exceptions.
// *
// * @param stream file from wich we will read the data
// * @return true if this bleach may handle this file, false otherwise
// */
// boolean handlesMagic(InputStream stream);
//
// /**
// * @return this bleach's name
// */
// String getName();
//
// /**
// * @param inputStream the file we want to sanitize
// * @param outputStream the sanitized file this bleach will write to
// * @param session the bleach session that stores threats
// * @throws BleachException Any fatal error that might occur during the bleach
// */
// void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
// throws BleachException;
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/RecursionBleachException.java
// public class RecursionBleachException extends BleachException {
//
// /**
// * @param depth The depth of the recursion
// */
// public RecursionBleachException(int depth) {
// super("Recursion exploit? There are already " + depth + " sanitation tasks.");
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/threat/Threat.java
// @AutoValue
// public abstract class Threat {
//
// public static Builder builder() {
// return new AutoValue_Threat.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder type(ThreatType value);
//
// public abstract Builder severity(ThreatSeverity value);
//
// public abstract Builder action(ThreatAction value);
//
// public abstract Builder location(String value);
//
// public abstract Builder details(String value);
//
// public abstract Threat build();
// }
//
// public abstract ThreatType type();
//
// public abstract ThreatSeverity severity();
//
// public abstract ThreatAction action();
//
// public abstract String location();
//
// public abstract String details();
// }
// Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.bleach.Bleach;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.exception.RecursionBleachException;
import xyz.docbleach.api.threat.Threat;
package xyz.docbleach.api;
/**
* A Bleach Session handles the data a bleach needs to store: list of the threats removed, for
* instance May be used in the future to store configuration (file's password, for instance) or
* callbacks
*/
public class BleachSession implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
private static final int MAX_ONGOING_TASKS = 10;
private final transient Bleach bleach;
private final Collection<Threat> threats = new ArrayList<>();
/**
* Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
*/
private int ongoingTasks = 0;
public BleachSession(Bleach bleach) {
this.bleach = bleach;
}
/**
* The BleachSession is able to record threats encountered by the bleach.
*
* @param threat The removed threat object, containing the threat type and more information
*/
public void recordThreat(Threat threat) {
if (threat == null) {
return;
}
LOGGER.trace("Threat recorded: " + threat);
threats.add(threat);
}
public Collection<Threat> getThreats() {
return threats;
}
public int threatCount() {
return threats.size();
}
/**
* @return The bleach used in this session
*/
public Bleach getBleach() {
return bleach;
}
public void sanitize(InputStream is, OutputStream os) throws BleachException {
try {
if (ongoingTasks++ >= MAX_ONGOING_TASKS) { | throw new RecursionBleachException(ongoingTasks); |
docbleach/DocBleach | module/module-office/src/test/java/xyz/docbleach/module/ole2/ObjectRemoverTest.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public abstract class BleachTestBase {
//
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
// }
| import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.BleachTestBase; | package xyz.docbleach.module.ole2;
class ObjectRemoverTest {
private ObjectRemover instance; | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public abstract class BleachTestBase {
//
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
// }
// Path: module/module-office/src/test/java/xyz/docbleach/module/ole2/ObjectRemoverTest.java
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.BleachTestBase;
package xyz.docbleach.module.ole2;
class ObjectRemoverTest {
private ObjectRemover instance; | private BleachSession session; |
docbleach/DocBleach | module/module-office/src/test/java/xyz/docbleach/module/ole2/ObjectRemoverTest.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public abstract class BleachTestBase {
//
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
// }
| import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.BleachTestBase; | package xyz.docbleach.module.ole2;
class ObjectRemoverTest {
private ObjectRemover instance;
private BleachSession session;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = spy(new ObjectRemover(session));
}
@Test
void testRemovesMacro() {
Entry entry = mock(Entry.class);
doReturn("\u0001CompObj").when(entry).getName();
assertFalse(instance.test(entry), "An object entry should not be copied over"); | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/test/java/xyz/docbleach/api/BleachTestBase.java
// public abstract class BleachTestBase {
//
// public static void assertThreatsFound(BleachSession session, int n) {
// verify(session, times(n)).recordThreat(any(Threat.class));
// }
// }
// Path: module/module-office/src/test/java/xyz/docbleach/module/ole2/ObjectRemoverTest.java
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.Entry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.BleachTestBase;
package xyz.docbleach.module.ole2;
class ObjectRemoverTest {
private ObjectRemover instance;
private BleachSession session;
@BeforeEach
void setUp() {
session = mock(BleachSession.class);
instance = spy(new ObjectRemover(session));
}
@Test
void testRemovesMacro() {
Entry entry = mock(Entry.class);
doReturn("\u0001CompObj").when(entry).getName();
assertFalse(instance.test(entry), "An object entry should not be copied over"); | BleachTestBase.assertThreatsFound(session, 1); |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/bleach/Bleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import java.io.InputStream;
import java.io.OutputStream;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException; | package xyz.docbleach.api.bleach;
public interface Bleach {
/**
* Checks the magic header of the file and returns true if this bleach is able to sanitize this
* InputStream. The stream has to {@link InputStream#markSupported support mark}.
*
* <p>The Bleach is responsible for the error handling to prevent exceptions.
*
* @param stream file from wich we will read the data
* @return true if this bleach may handle this file, false otherwise
*/
boolean handlesMagic(InputStream stream);
/**
* @return this bleach's name
*/
String getName();
/**
* @param inputStream the file we want to sanitize
* @param outputStream the sanitized file this bleach will write to
* @param session the bleach session that stores threats
* @throws BleachException Any fatal error that might occur during the bleach
*/ | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
import java.io.InputStream;
import java.io.OutputStream;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
package xyz.docbleach.api.bleach;
public interface Bleach {
/**
* Checks the magic header of the file and returns true if this bleach is able to sanitize this
* InputStream. The stream has to {@link InputStream#markSupported support mark}.
*
* <p>The Bleach is responsible for the error handling to prevent exceptions.
*
* @param stream file from wich we will read the data
* @return true if this bleach may handle this file, false otherwise
*/
boolean handlesMagic(InputStream stream);
/**
* @return this bleach's name
*/
String getName();
/**
* @param inputStream the file we want to sanitize
* @param outputStream the sanitized file this bleach will write to
* @param session the bleach session that stores threats
* @throws BleachException Any fatal error that might occur during the bleach
*/ | void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) |
docbleach/DocBleach | api/src/main/java/xyz/docbleach/api/bleach/Bleach.java | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
| import java.io.InputStream;
import java.io.OutputStream;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException; | package xyz.docbleach.api.bleach;
public interface Bleach {
/**
* Checks the magic header of the file and returns true if this bleach is able to sanitize this
* InputStream. The stream has to {@link InputStream#markSupported support mark}.
*
* <p>The Bleach is responsible for the error handling to prevent exceptions.
*
* @param stream file from wich we will read the data
* @return true if this bleach may handle this file, false otherwise
*/
boolean handlesMagic(InputStream stream);
/**
* @return this bleach's name
*/
String getName();
/**
* @param inputStream the file we want to sanitize
* @param outputStream the sanitized file this bleach will write to
* @param session the bleach session that stores threats
* @throws BleachException Any fatal error that might occur during the bleach
*/
void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) | // Path: api/src/main/java/xyz/docbleach/api/BleachSession.java
// public class BleachSession implements Serializable {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);
// private static final int MAX_ONGOING_TASKS = 10;
// private final transient Bleach bleach;
// private final Collection<Threat> threats = new ArrayList<>();
// /**
// * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)
// */
// private int ongoingTasks = 0;
//
// public BleachSession(Bleach bleach) {
// this.bleach = bleach;
// }
//
// /**
// * The BleachSession is able to record threats encountered by the bleach.
// *
// * @param threat The removed threat object, containing the threat type and more information
// */
// public void recordThreat(Threat threat) {
// if (threat == null) {
// return;
// }
// LOGGER.trace("Threat recorded: " + threat);
// threats.add(threat);
// }
//
// public Collection<Threat> getThreats() {
// return threats;
// }
//
// public int threatCount() {
// return threats.size();
// }
//
// /**
// * @return The bleach used in this session
// */
// public Bleach getBleach() {
// return bleach;
// }
//
// public void sanitize(InputStream is, OutputStream os) throws BleachException {
// try {
// if (ongoingTasks++ >= MAX_ONGOING_TASKS) {
// throw new RecursionBleachException(ongoingTasks);
// }
// if (!bleach.handlesMagic(is)) {
// return;
// }
// bleach.sanitize(is, os, this);
// } finally {
// ongoingTasks--;
// }
// }
// }
//
// Path: api/src/main/java/xyz/docbleach/api/exception/BleachException.java
// public class BleachException extends Exception {
//
// public BleachException(Throwable e) {
// super(e);
// }
//
// public BleachException(String message) {
// super(message);
// }
// }
// Path: api/src/main/java/xyz/docbleach/api/bleach/Bleach.java
import java.io.InputStream;
import java.io.OutputStream;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
package xyz.docbleach.api.bleach;
public interface Bleach {
/**
* Checks the magic header of the file and returns true if this bleach is able to sanitize this
* InputStream. The stream has to {@link InputStream#markSupported support mark}.
*
* <p>The Bleach is responsible for the error handling to prevent exceptions.
*
* @param stream file from wich we will read the data
* @return true if this bleach may handle this file, false otherwise
*/
boolean handlesMagic(InputStream stream);
/**
* @return this bleach's name
*/
String getName();
/**
* @param inputStream the file we want to sanitize
* @param outputStream the sanitized file this bleach will write to
* @param session the bleach session that stores threats
* @throws BleachException Any fatal error that might occur during the bleach
*/
void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session) | throws BleachException; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.