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
nortal/j-road
server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeBaseEndpoint.java
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // }
import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeHeader; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.SOAPUtil; import com.nortal.jroad.wsdl.XTeeWsdlDefinition; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.soap.AttachmentPart; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import org.springframework.ws.context.MessageContext; import org.springframework.ws.server.endpoint.MessageEndpoint; import org.springframework.ws.wsdl.wsdl11.provider.SuffixBasedMessagesProvider; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList;
/** * Copyright 2015 Nortal 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.nortal.jroad.endpoint; /** * Base class for X-Tee Spring web-service endpoints, extension classes must implement * {@link AbstractXTeeBaseEndpoint#invokeInternal(XTeeMessage request, XTeeMessage response)}. * * @author Roman Tekhov * @author Dmitri Danilkin * @author Lauri Lättemäe (lauri.lattemae@nortal.com) - protocol 4.0 */ public abstract class AbstractXTeeBaseEndpoint implements MessageEndpoint { protected boolean metaService = false;
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // } // Path: server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeBaseEndpoint.java import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeHeader; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.SOAPUtil; import com.nortal.jroad.wsdl.XTeeWsdlDefinition; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.soap.AttachmentPart; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import org.springframework.ws.context.MessageContext; import org.springframework.ws.server.endpoint.MessageEndpoint; import org.springframework.ws.wsdl.wsdl11.provider.SuffixBasedMessagesProvider; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Copyright 2015 Nortal 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.nortal.jroad.endpoint; /** * Base class for X-Tee Spring web-service endpoints, extension classes must implement * {@link AbstractXTeeBaseEndpoint#invokeInternal(XTeeMessage request, XTeeMessage response)}. * * @author Roman Tekhov * @author Dmitri Danilkin * @author Lauri Lättemäe (lauri.lattemae@nortal.com) - protocol 4.0 */ public abstract class AbstractXTeeBaseEndpoint implements MessageEndpoint { protected boolean metaService = false;
protected XRoadProtocolVersion version;
nortal/j-road
server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeBaseEndpoint.java
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // }
import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeHeader; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.SOAPUtil; import com.nortal.jroad.wsdl.XTeeWsdlDefinition; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.soap.AttachmentPart; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import org.springframework.ws.context.MessageContext; import org.springframework.ws.server.endpoint.MessageEndpoint; import org.springframework.ws.wsdl.wsdl11.provider.SuffixBasedMessagesProvider; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList;
if ((version = XRoadProtocolVersion.getValueByVersionCode(SOAPUtil.getTextContent(reqHeader))) != null) { return version; } } } // Extract protocol version by namespaces SOAPEnvelope soapEnv = requestMessage.getSOAPPart().getEnvelope(); Iterator<String> prefixes = soapEnv.getNamespacePrefixes(); while (prefixes.hasNext()) { String nsPrefix = prefixes.next(); String nsURI = soapEnv.getNamespaceURI(nsPrefix).toLowerCase(); if ((version = XRoadProtocolVersion.getValueByNamespaceURI(nsURI)) != null) { return version; } } throw new IllegalStateException("Unsupported protocol version"); } @SuppressWarnings("unchecked") protected void getResponse(Document query, SOAPMessage responseMessage, SOAPMessage requestMessage) throws Exception { XTeeHeader header = metaService ? null : parseXteeHeader(requestMessage); // Build request message List<XTeeAttachment> attachments = new ArrayList<XTeeAttachment>(); for (Iterator<AttachmentPart> i = requestMessage.getAttachments(); i.hasNext();) { AttachmentPart a = i.next(); attachments.add(new XTeeAttachment(a.getContentId(), a.getContentType(), a.getRawContentBytes())); }
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // } // Path: server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeBaseEndpoint.java import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeHeader; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.SOAPUtil; import com.nortal.jroad.wsdl.XTeeWsdlDefinition; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.soap.AttachmentPart; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import org.springframework.ws.context.MessageContext; import org.springframework.ws.server.endpoint.MessageEndpoint; import org.springframework.ws.wsdl.wsdl11.provider.SuffixBasedMessagesProvider; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; if ((version = XRoadProtocolVersion.getValueByVersionCode(SOAPUtil.getTextContent(reqHeader))) != null) { return version; } } } // Extract protocol version by namespaces SOAPEnvelope soapEnv = requestMessage.getSOAPPart().getEnvelope(); Iterator<String> prefixes = soapEnv.getNamespacePrefixes(); while (prefixes.hasNext()) { String nsPrefix = prefixes.next(); String nsURI = soapEnv.getNamespaceURI(nsPrefix).toLowerCase(); if ((version = XRoadProtocolVersion.getValueByNamespaceURI(nsURI)) != null) { return version; } } throw new IllegalStateException("Unsupported protocol version"); } @SuppressWarnings("unchecked") protected void getResponse(Document query, SOAPMessage responseMessage, SOAPMessage requestMessage) throws Exception { XTeeHeader header = metaService ? null : parseXteeHeader(requestMessage); // Build request message List<XTeeAttachment> attachments = new ArrayList<XTeeAttachment>(); for (Iterator<AttachmentPart> i = requestMessage.getAttachments(); i.hasNext();) { AttachmentPart a = i.next(); attachments.add(new XTeeAttachment(a.getContentId(), a.getContentType(), a.getRawContentBytes())); }
XTeeMessage<Document> request = new BeanXTeeMessage<Document>(header, query, attachments);
nortal/j-road
client-transport/src/main/java/com/nortal/jroad/client/service/configuration/DelegatingXRoadServiceConfiguration.java
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // }
import com.nortal.jroad.client.enums.XroadObjectType; import com.nortal.jroad.enums.XRoadProtocolVersion;
public String getFile() { return configuration.getFile(); } @Override public String getIdCode() { return configuration.getIdCode(); } @Override public String getMethod() { return configuration.getMethod(); } @Override public String getSecurityServer() { return configuration.getSecurityServer(); } @Override public String getVersion() { return configuration.getVersion(); } @Override public String getWsdlDatabase() { return configuration.getWsdlDatabase(); } @Override
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // Path: client-transport/src/main/java/com/nortal/jroad/client/service/configuration/DelegatingXRoadServiceConfiguration.java import com.nortal.jroad.client.enums.XroadObjectType; import com.nortal.jroad.enums.XRoadProtocolVersion; public String getFile() { return configuration.getFile(); } @Override public String getIdCode() { return configuration.getIdCode(); } @Override public String getMethod() { return configuration.getMethod(); } @Override public String getSecurityServer() { return configuration.getSecurityServer(); } @Override public String getVersion() { return configuration.getVersion(); } @Override public String getWsdlDatabase() { return configuration.getWsdlDatabase(); } @Override
public XRoadProtocolVersion getProtocolVersion() {
nortal/j-road
client-service/tor/src/main/java/com/nortal/jroad/client/tor/TorXTeeServiceImpl.java
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // } // // Path: common/src/main/java/com/nortal/jroad/util/AttachmentUtil.java // public class AttachmentUtil { // private static long salt = 0; // // public static String getUniqueCid() { // salt++; // return UUID.randomUUID().toString() + String.valueOf(salt); // } // // }
import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.activation.DataHandler; import javax.xml.namespace.QName; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.TransformerException; import org.springframework.stereotype.Service; import org.springframework.ws.WebServiceMessage; import org.springframework.ws.soap.saaj.SaajSoapMessage; import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.client.service.callback.CustomCallback; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.DownloadMimeDocument; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.DownloadMimeDocument.DownloadMime; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.DownloadMimeResponseDocument.DownloadMimeResponse; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.DownloadMimeType; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TORIKDocument; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TORIKDocument.TORIK; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TORIKResponseDocument; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TORIKResponseDocument.TORIKResponse; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TorikRequestType; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TorikRequestType.ParinguLiik; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeDocument; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeDocument.UploadMime; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeResponseDocument.UploadMimeResponse; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeType; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeType.Props; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeType.Props.Prop; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import com.nortal.jroad.model.XmlBeansXRoadMessage; import com.nortal.jroad.util.AttachmentUtil;
DownloadMimeType request = downloadMimeDocument.addNewRequest(); request.setTarget(target); XRoadMessage<DownloadMimeResponse> response = send(new XmlBeansXRoadMessage<DownloadMimeDocument.DownloadMime>(downloadMimeDocument), METHOD_DOWNLOAD_MIME, V1, new TorCallback(), null); return response; } @Override public UploadMimeResponse uploadMime(String target, String operation, String id, DataHandler fail) throws XRoadServiceConsumptionException { UploadMime uploadMimeDocument = UploadMimeDocument.UploadMime.Factory.newInstance(); UploadMimeType request = uploadMimeDocument.addNewRequest(); request.setTarget(target); request.setOperation(operation); Props props = request.addNewProps(); Prop prop = props.addNewProp(); prop.setKey(UPLOAD_ID); prop.setStringValue(id); XmlBeansXRoadMessage<UploadMimeDocument.UploadMime> XRoadMessage = new XmlBeansXRoadMessage<UploadMimeDocument.UploadMime>(uploadMimeDocument); List<XRoadAttachment> attachments = XRoadMessage.getAttachments();
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // } // // Path: common/src/main/java/com/nortal/jroad/util/AttachmentUtil.java // public class AttachmentUtil { // private static long salt = 0; // // public static String getUniqueCid() { // salt++; // return UUID.randomUUID().toString() + String.valueOf(salt); // } // // } // Path: client-service/tor/src/main/java/com/nortal/jroad/client/tor/TorXTeeServiceImpl.java import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.activation.DataHandler; import javax.xml.namespace.QName; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.TransformerException; import org.springframework.stereotype.Service; import org.springframework.ws.WebServiceMessage; import org.springframework.ws.soap.saaj.SaajSoapMessage; import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.client.service.callback.CustomCallback; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.DownloadMimeDocument; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.DownloadMimeDocument.DownloadMime; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.DownloadMimeResponseDocument.DownloadMimeResponse; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.DownloadMimeType; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TORIKDocument; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TORIKDocument.TORIK; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TORIKResponseDocument; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TORIKResponseDocument.TORIKResponse; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TorikRequestType; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.TorikRequestType.ParinguLiik; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeDocument; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeDocument.UploadMime; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeResponseDocument.UploadMimeResponse; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeType; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeType.Props; import com.nortal.jroad.client.tor.types.ee.x_road.emtav5.producer.UploadMimeType.Props.Prop; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import com.nortal.jroad.model.XmlBeansXRoadMessage; import com.nortal.jroad.util.AttachmentUtil; DownloadMimeType request = downloadMimeDocument.addNewRequest(); request.setTarget(target); XRoadMessage<DownloadMimeResponse> response = send(new XmlBeansXRoadMessage<DownloadMimeDocument.DownloadMime>(downloadMimeDocument), METHOD_DOWNLOAD_MIME, V1, new TorCallback(), null); return response; } @Override public UploadMimeResponse uploadMime(String target, String operation, String id, DataHandler fail) throws XRoadServiceConsumptionException { UploadMime uploadMimeDocument = UploadMimeDocument.UploadMime.Factory.newInstance(); UploadMimeType request = uploadMimeDocument.addNewRequest(); request.setTarget(target); request.setOperation(operation); Props props = request.addNewProps(); Prop prop = props.addNewProp(); prop.setKey(UPLOAD_ID); prop.setStringValue(id); XmlBeansXRoadMessage<UploadMimeDocument.UploadMime> XRoadMessage = new XmlBeansXRoadMessage<UploadMimeDocument.UploadMime>(uploadMimeDocument); List<XRoadAttachment> attachments = XRoadMessage.getAttachments();
String failCid = AttachmentUtil.getUniqueCid();
nortal/j-road
client-transport/src/main/java/com/nortal/jroad/client/service/callback/XRoadProtocolNamespaceStrategyV4.java
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/configuration/XRoadServiceConfiguration.java // public interface XRoadServiceConfiguration extends Serializable { // /** // * Returns an URL of institutions security server, typically in form of // * <code>http://minu_turvaserver/cgi-bin/consumer_proxy</code>. // */ // String getSecurityServer(); // // /** // * Returns name/prefix of the X-Tee database where the service-to-be-invoked resides. // */ // String getDatabase(); // // /** // * Returns name/prefix of the X-Tee database, which is actually specified in the WSDL of the service. // */ // String getWsdlDatabase(); // // /** Returns identifier of the person/entity who will be invoking the service */ // String getIdCode(); // // /** Returns name of file (or document) related to the service invokation. */ // String getFile(); // // /** Returns the service-to-be-invoked version. */ // String getVersion(); // // /** Returns the name of the (service's) <code>method</code> that will be called. */ // String getMethod(); // // /** // * Returns database xroad protocol version - by default v4 // */ // XRoadProtocolVersion getProtocolVersion(); // // String getClientXRoadInstance(); // // String getClientMemberClass(); // // String getClientMemberCode(); // // String getClientSubsystemCode(); // // String getServiceXRoadInstance(); // // String getServiceMemberClass(); // // String getServiceMemberCode(); // // String getServiceSubsystemCode(); // // XroadObjectType getClientObjectType(); // // XroadObjectType getServiceObjectType(); // } // // Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // }
import com.nortal.jroad.client.enums.XroadObjectType; import com.nortal.jroad.client.service.configuration.XRoadServiceConfiguration; import com.nortal.jroad.enums.XRoadProtocolVersion; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import org.apache.commons.lang.StringUtils;
package com.nortal.jroad.client.service.callback; /** * @author Aleksei Bogdanov (aleksei.bogdanov@nortal.com) * @author Lauri Lättemäe (lauri.lattemae@nortal.com) - protocol 4.0 */ public class XRoadProtocolNamespaceStrategyV4 extends MessageCallbackNamespaceStrategy { private XRoadProtocolVersion protocol = XRoadProtocolVersion.V4_0; @Override public void addNamespaces(SOAPEnvelope env) throws SOAPException { env.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema"); env.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance"); env.addNamespaceDeclaration(protocol.getNamespacePrefix(), protocol.getNamespaceUri()); env.addNamespaceDeclaration("id", "http://x-road.eu/xsd/identifiers"); } @Override
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/configuration/XRoadServiceConfiguration.java // public interface XRoadServiceConfiguration extends Serializable { // /** // * Returns an URL of institutions security server, typically in form of // * <code>http://minu_turvaserver/cgi-bin/consumer_proxy</code>. // */ // String getSecurityServer(); // // /** // * Returns name/prefix of the X-Tee database where the service-to-be-invoked resides. // */ // String getDatabase(); // // /** // * Returns name/prefix of the X-Tee database, which is actually specified in the WSDL of the service. // */ // String getWsdlDatabase(); // // /** Returns identifier of the person/entity who will be invoking the service */ // String getIdCode(); // // /** Returns name of file (or document) related to the service invokation. */ // String getFile(); // // /** Returns the service-to-be-invoked version. */ // String getVersion(); // // /** Returns the name of the (service's) <code>method</code> that will be called. */ // String getMethod(); // // /** // * Returns database xroad protocol version - by default v4 // */ // XRoadProtocolVersion getProtocolVersion(); // // String getClientXRoadInstance(); // // String getClientMemberClass(); // // String getClientMemberCode(); // // String getClientSubsystemCode(); // // String getServiceXRoadInstance(); // // String getServiceMemberClass(); // // String getServiceMemberCode(); // // String getServiceSubsystemCode(); // // XroadObjectType getClientObjectType(); // // XroadObjectType getServiceObjectType(); // } // // Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // Path: client-transport/src/main/java/com/nortal/jroad/client/service/callback/XRoadProtocolNamespaceStrategyV4.java import com.nortal.jroad.client.enums.XroadObjectType; import com.nortal.jroad.client.service.configuration.XRoadServiceConfiguration; import com.nortal.jroad.enums.XRoadProtocolVersion; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import org.apache.commons.lang.StringUtils; package com.nortal.jroad.client.service.callback; /** * @author Aleksei Bogdanov (aleksei.bogdanov@nortal.com) * @author Lauri Lättemäe (lauri.lattemae@nortal.com) - protocol 4.0 */ public class XRoadProtocolNamespaceStrategyV4 extends MessageCallbackNamespaceStrategy { private XRoadProtocolVersion protocol = XRoadProtocolVersion.V4_0; @Override public void addNamespaces(SOAPEnvelope env) throws SOAPException { env.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema"); env.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance"); env.addNamespaceDeclaration(protocol.getNamespacePrefix(), protocol.getNamespaceUri()); env.addNamespaceDeclaration("id", "http://x-road.eu/xsd/identifiers"); } @Override
public void addXTeeHeaderElements(SOAPEnvelope env, XRoadServiceConfiguration conf) throws SOAPException {
nortal/j-road
client-transport/src/test/java/com/nortal/jroad/client/service/extractor/StandardXRoadConsumerMessageExtractorTest.java
// Path: client-transport/src/main/java/com/nortal/jroad/model/XmlBeansXRoadMetadata.java // public class XmlBeansXRoadMetadata implements Serializable { // private static final long serialVersionUID = 1L; // // private String operationName; // private String operationNs; // // private String requestElementName; // private String requestElementNs; // // private String responseElementName; // private String responseElementNs; // // private String version; // // public XmlBeansXRoadMetadata(String operationName, // String operationNs, // String requestElementName, // String requestElementNs, // String responseElementName, // String responseElementNs, // String version) { // this.operationName = operationName; // this.operationNs = operationNs; // this.requestElementName = requestElementName; // this.requestElementNs = requestElementNs; // this.responseElementName = responseElementName; // this.responseElementNs = responseElementNs; // this.version = version; // } // // public String getOperationName() { // return operationName; // } // // public void setOperationName(String operationName) { // this.operationName = operationName; // } // // public String getOperationNs() { // return operationNs; // } // // public void setOperationNs(String operationNs) { // this.operationNs = operationNs; // } // // public String getResponseElementName() { // return responseElementName; // } // // public void setResponseElementName(String responseElementName) { // this.responseElementName = responseElementName; // } // // public String getRequestElementName() { // return requestElementName; // } // // public String getRequestElementNs() { // return requestElementNs; // } // // public String getResponseElementNs() { // return responseElementNs; // } // // public void setResponseElementNs(String responseElementNs) { // this.responseElementNs = responseElementNs; // } // // public String getVersion() { // return version; // } // // }
import com.nortal.jroad.model.XRoadMessage; import com.nortal.jroad.model.XmlBeansXRoadMetadata; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.ws.soap.saaj.SaajSoapMessage; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import java.io.IOException; import java.io.InputStream; import static org.junit.Assert.assertEquals;
private final static String RESULT_SINGLE_ROW_FORMAT = "<response xmlns:era=\"http://earest.x-road.eu/\" xmlns=\"f\">\n" + " <request xmlns=\"\">\n" + " <ParinguKoostamiseAeg>2017-10-06T15:51:00</ParinguKoostamiseAeg>\n" + " </request>\n" + " <response xmlns=\"\">\n" + " <ArestiVastused>\n" + " <Vastus>\n" + " <IsikuOigusedKohustused>\n" + " <Akt>\n" + " <AlgParinguUnikaalneID>A801201702209240</AlgParinguUnikaalneID>\n" + " <VolitatudKasutajad>\n" + " <VolitatudKasutaja>\n" + " <VolituseLaad/>\n" + " <VolituseFailiNimi>jyritamm</VolituseFailiNimi>\n" + " <VolituseFail>JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb" + "2cvUGFnZXMgMiAwIFIvTGFuZyhldC1FRSkgL1N0cnVjdFRyZWVSb290IDE1IDAgUi9NYXJrSW5mbzw8L01h" + "cmtlZCB0cnVlPj4+CjE1MDc2Nw0KJSVFT0YNCnhyZWYNCjAgMA0KdHJhaWxlcg0KPDwvU2l6ZSAyNy9Sb29" + "0IDEgMCBSL0luZm8gMTQgMCBSL0lEWzxBNDQzRkEyNkVCQzM3RTRDODczOUFEQkYxNUEyRTZDRj48QTQ0M0" + "ZBMjZFQkMzN0U0Qzg3MzlBREJGMTVBMkU2Q0YXSAvUHJldiAxNTA3NjcvWFJlZlN0bSAxNTA0NjM+Pg0Kc3" + "RhcnR4cmVmDQoxNTE0NjUNCiUlRU9G</VolituseFail>\n" + " </VolitatudKasutaja>\n" + " </VolitatudKasutajad>\n" + " </Akt>\n" + " </IsikuOigusedKohustused>\n" + " </Vastus>\n" + " </ArestiVastused>\n" + " </response>\n" + "</response>"; public static final StandardXRoadConsumerMessageExtractor EXTRACTOR =
// Path: client-transport/src/main/java/com/nortal/jroad/model/XmlBeansXRoadMetadata.java // public class XmlBeansXRoadMetadata implements Serializable { // private static final long serialVersionUID = 1L; // // private String operationName; // private String operationNs; // // private String requestElementName; // private String requestElementNs; // // private String responseElementName; // private String responseElementNs; // // private String version; // // public XmlBeansXRoadMetadata(String operationName, // String operationNs, // String requestElementName, // String requestElementNs, // String responseElementName, // String responseElementNs, // String version) { // this.operationName = operationName; // this.operationNs = operationNs; // this.requestElementName = requestElementName; // this.requestElementNs = requestElementNs; // this.responseElementName = responseElementName; // this.responseElementNs = responseElementNs; // this.version = version; // } // // public String getOperationName() { // return operationName; // } // // public void setOperationName(String operationName) { // this.operationName = operationName; // } // // public String getOperationNs() { // return operationNs; // } // // public void setOperationNs(String operationNs) { // this.operationNs = operationNs; // } // // public String getResponseElementName() { // return responseElementName; // } // // public void setResponseElementName(String responseElementName) { // this.responseElementName = responseElementName; // } // // public String getRequestElementName() { // return requestElementName; // } // // public String getRequestElementNs() { // return requestElementNs; // } // // public String getResponseElementNs() { // return responseElementNs; // } // // public void setResponseElementNs(String responseElementNs) { // this.responseElementNs = responseElementNs; // } // // public String getVersion() { // return version; // } // // } // Path: client-transport/src/test/java/com/nortal/jroad/client/service/extractor/StandardXRoadConsumerMessageExtractorTest.java import com.nortal.jroad.model.XRoadMessage; import com.nortal.jroad.model.XmlBeansXRoadMetadata; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.ws.soap.saaj.SaajSoapMessage; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import java.io.IOException; import java.io.InputStream; import static org.junit.Assert.assertEquals; private final static String RESULT_SINGLE_ROW_FORMAT = "<response xmlns:era=\"http://earest.x-road.eu/\" xmlns=\"f\">\n" + " <request xmlns=\"\">\n" + " <ParinguKoostamiseAeg>2017-10-06T15:51:00</ParinguKoostamiseAeg>\n" + " </request>\n" + " <response xmlns=\"\">\n" + " <ArestiVastused>\n" + " <Vastus>\n" + " <IsikuOigusedKohustused>\n" + " <Akt>\n" + " <AlgParinguUnikaalneID>A801201702209240</AlgParinguUnikaalneID>\n" + " <VolitatudKasutajad>\n" + " <VolitatudKasutaja>\n" + " <VolituseLaad/>\n" + " <VolituseFailiNimi>jyritamm</VolituseFailiNimi>\n" + " <VolituseFail>JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb" + "2cvUGFnZXMgMiAwIFIvTGFuZyhldC1FRSkgL1N0cnVjdFRyZWVSb290IDE1IDAgUi9NYXJrSW5mbzw8L01h" + "cmtlZCB0cnVlPj4+CjE1MDc2Nw0KJSVFT0YNCnhyZWYNCjAgMA0KdHJhaWxlcg0KPDwvU2l6ZSAyNy9Sb29" + "0IDEgMCBSL0luZm8gMTQgMCBSL0lEWzxBNDQzRkEyNkVCQzM3RTRDODczOUFEQkYxNUEyRTZDRj48QTQ0M0" + "ZBMjZFQkMzN0U0Qzg3MzlBREJGMTVBMkU2Q0YXSAvUHJldiAxNTA3NjcvWFJlZlN0bSAxNTA0NjM+Pg0Kc3" + "RhcnR4cmVmDQoxNTE0NjUNCiUlRU9G</VolituseFail>\n" + " </VolitatudKasutaja>\n" + " </VolitatudKasutajad>\n" + " </Akt>\n" + " </IsikuOigusedKohustused>\n" + " </Vastus>\n" + " </ArestiVastused>\n" + " </response>\n" + "</response>"; public static final StandardXRoadConsumerMessageExtractor EXTRACTOR =
new StandardXRoadConsumerMessageExtractor(new XmlBeansXRoadMetadata("operation",
nortal/j-road
client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/configuration/provider/XRoadServiceConfigurationProvider.java // public interface XRoadServiceConfigurationProvider { // XRoadServiceConfiguration createConfiguration(String database, String wsdldatabase, String method, String version); // } // // Path: client-transport/src/main/java/com/nortal/jroad/client/service/consumer/XRoadConsumer.java // public interface XRoadConsumer { // // /** // * Performs an invocation of some X-tee service. // * // * @param <I> input object type // * @param <O> output object type // * @param input Java object representing the request // * @param xTeeServiceConfiguration service configuration data // * @return Java object representing the response // */ // <I, O> XRoadMessage<O> sendRequest(XRoadMessage<I> input, XRoadServiceConfiguration xTeeServiceConfiguration) // throws XRoadServiceConsumptionException; // // /** // * Performs an invocation of some X-tee service. // * // * @param <I> input object type // * @param <O> output object type // * @param input Java object representing the request // * @param xTeeServiceConfiguration service configuration data // * @param callback Custom callback to invoke for sending the message // * @param extractor Custom extractor to invoke for extracting the message // * @return Java object representing the response // */ // <I, O> XRoadMessage<O> sendRequest(XRoadMessage<I> input, // XRoadServiceConfiguration xTeeServiceConfiguration, // CustomCallback callback, // CustomExtractor extractor) throws XRoadServiceConsumptionException; // // }
import javax.annotation.Resource; import com.nortal.jroad.client.service.configuration.provider.XRoadServiceConfigurationProvider; import com.nortal.jroad.client.service.consumer.XRoadConsumer;
package com.nortal.jroad.client.service; /** * @author Aleksei Bogdanov (aleksei.bogdanov@nortal.com) */ public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { @Resource
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/configuration/provider/XRoadServiceConfigurationProvider.java // public interface XRoadServiceConfigurationProvider { // XRoadServiceConfiguration createConfiguration(String database, String wsdldatabase, String method, String version); // } // // Path: client-transport/src/main/java/com/nortal/jroad/client/service/consumer/XRoadConsumer.java // public interface XRoadConsumer { // // /** // * Performs an invocation of some X-tee service. // * // * @param <I> input object type // * @param <O> output object type // * @param input Java object representing the request // * @param xTeeServiceConfiguration service configuration data // * @return Java object representing the response // */ // <I, O> XRoadMessage<O> sendRequest(XRoadMessage<I> input, XRoadServiceConfiguration xTeeServiceConfiguration) // throws XRoadServiceConsumptionException; // // /** // * Performs an invocation of some X-tee service. // * // * @param <I> input object type // * @param <O> output object type // * @param input Java object representing the request // * @param xTeeServiceConfiguration service configuration data // * @param callback Custom callback to invoke for sending the message // * @param extractor Custom extractor to invoke for extracting the message // * @return Java object representing the response // */ // <I, O> XRoadMessage<O> sendRequest(XRoadMessage<I> input, // XRoadServiceConfiguration xTeeServiceConfiguration, // CustomCallback callback, // CustomExtractor extractor) throws XRoadServiceConsumptionException; // // } // Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java import javax.annotation.Resource; import com.nortal.jroad.client.service.configuration.provider.XRoadServiceConfigurationProvider; import com.nortal.jroad.client.service.consumer.XRoadConsumer; package com.nortal.jroad.client.service; /** * @author Aleksei Bogdanov (aleksei.bogdanov@nortal.com) */ public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { @Resource
protected XRoadConsumer xRoadConsumer;
nortal/j-road
client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/configuration/provider/XRoadServiceConfigurationProvider.java // public interface XRoadServiceConfigurationProvider { // XRoadServiceConfiguration createConfiguration(String database, String wsdldatabase, String method, String version); // } // // Path: client-transport/src/main/java/com/nortal/jroad/client/service/consumer/XRoadConsumer.java // public interface XRoadConsumer { // // /** // * Performs an invocation of some X-tee service. // * // * @param <I> input object type // * @param <O> output object type // * @param input Java object representing the request // * @param xTeeServiceConfiguration service configuration data // * @return Java object representing the response // */ // <I, O> XRoadMessage<O> sendRequest(XRoadMessage<I> input, XRoadServiceConfiguration xTeeServiceConfiguration) // throws XRoadServiceConsumptionException; // // /** // * Performs an invocation of some X-tee service. // * // * @param <I> input object type // * @param <O> output object type // * @param input Java object representing the request // * @param xTeeServiceConfiguration service configuration data // * @param callback Custom callback to invoke for sending the message // * @param extractor Custom extractor to invoke for extracting the message // * @return Java object representing the response // */ // <I, O> XRoadMessage<O> sendRequest(XRoadMessage<I> input, // XRoadServiceConfiguration xTeeServiceConfiguration, // CustomCallback callback, // CustomExtractor extractor) throws XRoadServiceConsumptionException; // // }
import javax.annotation.Resource; import com.nortal.jroad.client.service.configuration.provider.XRoadServiceConfigurationProvider; import com.nortal.jroad.client.service.consumer.XRoadConsumer;
package com.nortal.jroad.client.service; /** * @author Aleksei Bogdanov (aleksei.bogdanov@nortal.com) */ public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { @Resource protected XRoadConsumer xRoadConsumer; @Resource
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/configuration/provider/XRoadServiceConfigurationProvider.java // public interface XRoadServiceConfigurationProvider { // XRoadServiceConfiguration createConfiguration(String database, String wsdldatabase, String method, String version); // } // // Path: client-transport/src/main/java/com/nortal/jroad/client/service/consumer/XRoadConsumer.java // public interface XRoadConsumer { // // /** // * Performs an invocation of some X-tee service. // * // * @param <I> input object type // * @param <O> output object type // * @param input Java object representing the request // * @param xTeeServiceConfiguration service configuration data // * @return Java object representing the response // */ // <I, O> XRoadMessage<O> sendRequest(XRoadMessage<I> input, XRoadServiceConfiguration xTeeServiceConfiguration) // throws XRoadServiceConsumptionException; // // /** // * Performs an invocation of some X-tee service. // * // * @param <I> input object type // * @param <O> output object type // * @param input Java object representing the request // * @param xTeeServiceConfiguration service configuration data // * @param callback Custom callback to invoke for sending the message // * @param extractor Custom extractor to invoke for extracting the message // * @return Java object representing the response // */ // <I, O> XRoadMessage<O> sendRequest(XRoadMessage<I> input, // XRoadServiceConfiguration xTeeServiceConfiguration, // CustomCallback callback, // CustomExtractor extractor) throws XRoadServiceConsumptionException; // // } // Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java import javax.annotation.Resource; import com.nortal.jroad.client.service.configuration.provider.XRoadServiceConfigurationProvider; import com.nortal.jroad.client.service.consumer.XRoadConsumer; package com.nortal.jroad.client.service; /** * @author Aleksei Bogdanov (aleksei.bogdanov@nortal.com) */ public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { @Resource protected XRoadConsumer xRoadConsumer; @Resource
protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider;
nortal/j-road
client-service/treasury/src/main/java/com/nortal/jroad/client/treasury/TreasuryXTeeServiceImpl.java
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFactory; import javax.xml.soap.SOAPMessage; import javax.xml.transform.TransformerException; import org.apache.xmlbeans.impl.util.Base64; import org.springframework.stereotype.Service; import org.springframework.ws.WebServiceMessage; import org.w3c.dom.Node; import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.client.service.callback.CustomCallback; import com.nortal.jroad.client.treasury.database.TreasuryXRoadDatabase; import com.nortal.jroad.client.treasury.types.ee.riik.xtee.treasury.producers.producer.treasury.SendDocumentRequestType; import com.nortal.jroad.client.treasury.types.ee.riik.xtee.treasury.producers.producer.treasury.SendDocumentResponseType; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import com.nortal.jroad.model.XmlBeansXRoadMessage; import com.nortal.jroad.util.SOAPUtil;
package com.nortal.jroad.client.treasury; /** * At the time of writing the implementation of this service on the treasury side does NOT conform to their WSDL nor the * X-tee specification in general, thus the client-side implementation also does NOT conform to the WSDL. Hopefully this * will change in the future, but until then PLEASE DO NOT USE this service as an example. Due to the fact, that there * is an element present outside "keha". Some hacking is required to make this work... * * @author Dmitri Danilkin * @author Lauri Lättemäe <lauri.lattemae@nortal.com> */ @Service("treasuryXTeeService") public class TreasuryXTeeServiceImpl extends XRoadDatabaseService implements TreasuryXTeeService { private static final String SEND_DOCUMENT = "sendDocument"; private static final String VERSION = "v1"; @Resource private TreasuryXRoadDatabase treasuryXRoadDatabase; public SendDocumentResponseType sendDocument(String uniqueId, String type, byte[] manus) throws XRoadServiceConsumptionException { SendDocumentRequestType kassaReq = SendDocumentRequestType.Factory.newInstance(); kassaReq.setUniqueId(uniqueId); kassaReq.setType(type); kassaReq.setManus("".getBytes());
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // } // Path: client-service/treasury/src/main/java/com/nortal/jroad/client/treasury/TreasuryXTeeServiceImpl.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFactory; import javax.xml.soap.SOAPMessage; import javax.xml.transform.TransformerException; import org.apache.xmlbeans.impl.util.Base64; import org.springframework.stereotype.Service; import org.springframework.ws.WebServiceMessage; import org.w3c.dom.Node; import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.client.service.callback.CustomCallback; import com.nortal.jroad.client.treasury.database.TreasuryXRoadDatabase; import com.nortal.jroad.client.treasury.types.ee.riik.xtee.treasury.producers.producer.treasury.SendDocumentRequestType; import com.nortal.jroad.client.treasury.types.ee.riik.xtee.treasury.producers.producer.treasury.SendDocumentResponseType; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import com.nortal.jroad.model.XmlBeansXRoadMessage; import com.nortal.jroad.util.SOAPUtil; package com.nortal.jroad.client.treasury; /** * At the time of writing the implementation of this service on the treasury side does NOT conform to their WSDL nor the * X-tee specification in general, thus the client-side implementation also does NOT conform to the WSDL. Hopefully this * will change in the future, but until then PLEASE DO NOT USE this service as an example. Due to the fact, that there * is an element present outside "keha". Some hacking is required to make this work... * * @author Dmitri Danilkin * @author Lauri Lättemäe <lauri.lattemae@nortal.com> */ @Service("treasuryXTeeService") public class TreasuryXTeeServiceImpl extends XRoadDatabaseService implements TreasuryXTeeService { private static final String SEND_DOCUMENT = "sendDocument"; private static final String VERSION = "v1"; @Resource private TreasuryXRoadDatabase treasuryXRoadDatabase; public SendDocumentResponseType sendDocument(String uniqueId, String type, byte[] manus) throws XRoadServiceConsumptionException { SendDocumentRequestType kassaReq = SendDocumentRequestType.Factory.newInstance(); kassaReq.setUniqueId(uniqueId); kassaReq.setType(type); kassaReq.setManus("".getBytes());
List<XRoadAttachment> attachments = new ArrayList<XRoadAttachment>();
nortal/j-road
example/src/main/java/com/nortal/jroad/example/client/NaidisXRoadServiceImpl.java
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/jaxb/ByteArrayDataSource.java // public class ByteArrayDataSource implements DataSource { // private byte[] data; // private String contentType; // // public ByteArrayDataSource(String contentType, byte[] data) { // this.contentType = contentType; // this.data = data; // } // // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(data); // } // // public OutputStream getOutputStream() throws IOException { // throw new UnsupportedOperationException(); // } // // public String getContentType() { // return contentType; // } // // public String getName() { // return "ByteArrayDataSource"; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXRoadMessage.java // public class BeanXRoadMessage<T> implements XRoadMessage<T> { // private List<XRoadAttachment> attachments; // private XRoadHeader header; // private T content; // // public BeanXRoadMessage(XRoadHeader header, T content, List<XRoadAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XRoadAttachment> getAttachments() { // return attachments; // } // // public XRoadHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XRoadAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XRoadHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // }
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.example.client.database.NaidisXRoadDatabase; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoResponse; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoResponse; import com.nortal.jroad.jaxb.ByteArrayDataSource; import com.nortal.jroad.model.BeanXRoadMessage; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import java.util.Arrays; import javax.activation.DataHandler; import javax.annotation.Resource; import org.springframework.stereotype.Service;
package com.nortal.jroad.example.client; /** * @author Lauri Lättemäe (lauri.lattemae@nortal.com) */ @Service("naidisXRoadService") public class NaidisXRoadServiceImpl extends XRoadDatabaseService implements NaidisXRoadService { @Resource private NaidisXRoadDatabase naidisXRoadDatabase; @Override public AttachmentEchoResponse sendAttachment(String contentType, byte[] content) throws XRoadServiceConsumptionException {
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/jaxb/ByteArrayDataSource.java // public class ByteArrayDataSource implements DataSource { // private byte[] data; // private String contentType; // // public ByteArrayDataSource(String contentType, byte[] data) { // this.contentType = contentType; // this.data = data; // } // // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(data); // } // // public OutputStream getOutputStream() throws IOException { // throw new UnsupportedOperationException(); // } // // public String getContentType() { // return contentType; // } // // public String getName() { // return "ByteArrayDataSource"; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXRoadMessage.java // public class BeanXRoadMessage<T> implements XRoadMessage<T> { // private List<XRoadAttachment> attachments; // private XRoadHeader header; // private T content; // // public BeanXRoadMessage(XRoadHeader header, T content, List<XRoadAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XRoadAttachment> getAttachments() { // return attachments; // } // // public XRoadHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XRoadAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XRoadHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // } // Path: example/src/main/java/com/nortal/jroad/example/client/NaidisXRoadServiceImpl.java import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.example.client.database.NaidisXRoadDatabase; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoResponse; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoResponse; import com.nortal.jroad.jaxb.ByteArrayDataSource; import com.nortal.jroad.model.BeanXRoadMessage; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import java.util.Arrays; import javax.activation.DataHandler; import javax.annotation.Resource; import org.springframework.stereotype.Service; package com.nortal.jroad.example.client; /** * @author Lauri Lättemäe (lauri.lattemae@nortal.com) */ @Service("naidisXRoadService") public class NaidisXRoadServiceImpl extends XRoadDatabaseService implements NaidisXRoadService { @Resource private NaidisXRoadDatabase naidisXRoadDatabase; @Override public AttachmentEchoResponse sendAttachment(String contentType, byte[] content) throws XRoadServiceConsumptionException {
DataHandler reqHandler = new DataHandler(new ByteArrayDataSource(contentType, content));
nortal/j-road
example/src/main/java/com/nortal/jroad/example/client/NaidisXRoadServiceImpl.java
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/jaxb/ByteArrayDataSource.java // public class ByteArrayDataSource implements DataSource { // private byte[] data; // private String contentType; // // public ByteArrayDataSource(String contentType, byte[] data) { // this.contentType = contentType; // this.data = data; // } // // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(data); // } // // public OutputStream getOutputStream() throws IOException { // throw new UnsupportedOperationException(); // } // // public String getContentType() { // return contentType; // } // // public String getName() { // return "ByteArrayDataSource"; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXRoadMessage.java // public class BeanXRoadMessage<T> implements XRoadMessage<T> { // private List<XRoadAttachment> attachments; // private XRoadHeader header; // private T content; // // public BeanXRoadMessage(XRoadHeader header, T content, List<XRoadAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XRoadAttachment> getAttachments() { // return attachments; // } // // public XRoadHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XRoadAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XRoadHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // }
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.example.client.database.NaidisXRoadDatabase; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoResponse; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoResponse; import com.nortal.jroad.jaxb.ByteArrayDataSource; import com.nortal.jroad.model.BeanXRoadMessage; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import java.util.Arrays; import javax.activation.DataHandler; import javax.annotation.Resource; import org.springframework.stereotype.Service;
package com.nortal.jroad.example.client; /** * @author Lauri Lättemäe (lauri.lattemae@nortal.com) */ @Service("naidisXRoadService") public class NaidisXRoadServiceImpl extends XRoadDatabaseService implements NaidisXRoadService { @Resource private NaidisXRoadDatabase naidisXRoadDatabase; @Override public AttachmentEchoResponse sendAttachment(String contentType, byte[] content) throws XRoadServiceConsumptionException { DataHandler reqHandler = new DataHandler(new ByteArrayDataSource(contentType, content)); AttachmentEchoRequest request = AttachmentEchoRequest.Factory.newInstance(); request.addNewNest().setAttachmentHandler(reqHandler); return naidisXRoadDatabase.attachmentEchoV1(request); } @Override public String sendEcho(String text) throws XRoadServiceConsumptionException { EchoRequest req = EchoRequest.Factory.newInstance(); req.setText(text); return naidisXRoadDatabase.echoV1(req).getText(); } @Override public String sendEchoMime(String text) throws XRoadServiceConsumptionException { EchoRequest echoReq = EchoRequest.Factory.newInstance(); echoReq.setText(text);
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/jaxb/ByteArrayDataSource.java // public class ByteArrayDataSource implements DataSource { // private byte[] data; // private String contentType; // // public ByteArrayDataSource(String contentType, byte[] data) { // this.contentType = contentType; // this.data = data; // } // // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(data); // } // // public OutputStream getOutputStream() throws IOException { // throw new UnsupportedOperationException(); // } // // public String getContentType() { // return contentType; // } // // public String getName() { // return "ByteArrayDataSource"; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXRoadMessage.java // public class BeanXRoadMessage<T> implements XRoadMessage<T> { // private List<XRoadAttachment> attachments; // private XRoadHeader header; // private T content; // // public BeanXRoadMessage(XRoadHeader header, T content, List<XRoadAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XRoadAttachment> getAttachments() { // return attachments; // } // // public XRoadHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XRoadAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XRoadHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // } // Path: example/src/main/java/com/nortal/jroad/example/client/NaidisXRoadServiceImpl.java import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.example.client.database.NaidisXRoadDatabase; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoResponse; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoResponse; import com.nortal.jroad.jaxb.ByteArrayDataSource; import com.nortal.jroad.model.BeanXRoadMessage; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import java.util.Arrays; import javax.activation.DataHandler; import javax.annotation.Resource; import org.springframework.stereotype.Service; package com.nortal.jroad.example.client; /** * @author Lauri Lättemäe (lauri.lattemae@nortal.com) */ @Service("naidisXRoadService") public class NaidisXRoadServiceImpl extends XRoadDatabaseService implements NaidisXRoadService { @Resource private NaidisXRoadDatabase naidisXRoadDatabase; @Override public AttachmentEchoResponse sendAttachment(String contentType, byte[] content) throws XRoadServiceConsumptionException { DataHandler reqHandler = new DataHandler(new ByteArrayDataSource(contentType, content)); AttachmentEchoRequest request = AttachmentEchoRequest.Factory.newInstance(); request.addNewNest().setAttachmentHandler(reqHandler); return naidisXRoadDatabase.attachmentEchoV1(request); } @Override public String sendEcho(String text) throws XRoadServiceConsumptionException { EchoRequest req = EchoRequest.Factory.newInstance(); req.setText(text); return naidisXRoadDatabase.echoV1(req).getText(); } @Override public String sendEchoMime(String text) throws XRoadServiceConsumptionException { EchoRequest echoReq = EchoRequest.Factory.newInstance(); echoReq.setText(text);
BeanXRoadMessage<EchoRequest> req =
nortal/j-road
example/src/main/java/com/nortal/jroad/example/client/NaidisXRoadServiceImpl.java
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/jaxb/ByteArrayDataSource.java // public class ByteArrayDataSource implements DataSource { // private byte[] data; // private String contentType; // // public ByteArrayDataSource(String contentType, byte[] data) { // this.contentType = contentType; // this.data = data; // } // // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(data); // } // // public OutputStream getOutputStream() throws IOException { // throw new UnsupportedOperationException(); // } // // public String getContentType() { // return contentType; // } // // public String getName() { // return "ByteArrayDataSource"; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXRoadMessage.java // public class BeanXRoadMessage<T> implements XRoadMessage<T> { // private List<XRoadAttachment> attachments; // private XRoadHeader header; // private T content; // // public BeanXRoadMessage(XRoadHeader header, T content, List<XRoadAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XRoadAttachment> getAttachments() { // return attachments; // } // // public XRoadHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XRoadAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XRoadHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // }
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.example.client.database.NaidisXRoadDatabase; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoResponse; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoResponse; import com.nortal.jroad.jaxb.ByteArrayDataSource; import com.nortal.jroad.model.BeanXRoadMessage; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import java.util.Arrays; import javax.activation.DataHandler; import javax.annotation.Resource; import org.springframework.stereotype.Service;
package com.nortal.jroad.example.client; /** * @author Lauri Lättemäe (lauri.lattemae@nortal.com) */ @Service("naidisXRoadService") public class NaidisXRoadServiceImpl extends XRoadDatabaseService implements NaidisXRoadService { @Resource private NaidisXRoadDatabase naidisXRoadDatabase; @Override public AttachmentEchoResponse sendAttachment(String contentType, byte[] content) throws XRoadServiceConsumptionException { DataHandler reqHandler = new DataHandler(new ByteArrayDataSource(contentType, content)); AttachmentEchoRequest request = AttachmentEchoRequest.Factory.newInstance(); request.addNewNest().setAttachmentHandler(reqHandler); return naidisXRoadDatabase.attachmentEchoV1(request); } @Override public String sendEcho(String text) throws XRoadServiceConsumptionException { EchoRequest req = EchoRequest.Factory.newInstance(); req.setText(text); return naidisXRoadDatabase.echoV1(req).getText(); } @Override public String sendEchoMime(String text) throws XRoadServiceConsumptionException { EchoRequest echoReq = EchoRequest.Factory.newInstance(); echoReq.setText(text); BeanXRoadMessage<EchoRequest> req = new BeanXRoadMessage<EchoRequest>(null, echoReq,
// Path: client-transport/src/main/java/com/nortal/jroad/client/service/XRoadDatabaseService.java // public abstract class XRoadDatabaseService extends BaseXRoadDatabaseService { // // @Resource // protected XRoadConsumer xRoadConsumer; // @Resource // protected XRoadServiceConfigurationProvider xRoadServiceConfigurationProvider; // // @Override // protected XRoadConsumer getXRoadConsumer() { // return xRoadConsumer; // } // // @Override // protected XRoadServiceConfigurationProvider getXRoadServiceConfigurationProvider() { // return xRoadServiceConfigurationProvider; // } // } // // Path: common/src/main/java/com/nortal/jroad/jaxb/ByteArrayDataSource.java // public class ByteArrayDataSource implements DataSource { // private byte[] data; // private String contentType; // // public ByteArrayDataSource(String contentType, byte[] data) { // this.contentType = contentType; // this.data = data; // } // // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(data); // } // // public OutputStream getOutputStream() throws IOException { // throw new UnsupportedOperationException(); // } // // public String getContentType() { // return contentType; // } // // public String getName() { // return "ByteArrayDataSource"; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXRoadMessage.java // public class BeanXRoadMessage<T> implements XRoadMessage<T> { // private List<XRoadAttachment> attachments; // private XRoadHeader header; // private T content; // // public BeanXRoadMessage(XRoadHeader header, T content, List<XRoadAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XRoadAttachment> getAttachments() { // return attachments; // } // // public XRoadHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XRoadAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XRoadHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java // public class XRoadAttachment implements InputStreamSource { // private String cid; // private DataHandler dataHandler; // // public XRoadAttachment(String cid, String contentType, byte[] data) { // this.cid = cid; // this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data)); // } // // public XRoadAttachment(String cid, DataHandler dataHandler) { // this.cid = cid; // this.dataHandler = dataHandler; // } // // public InputStream getInputStream() throws IOException { // return dataHandler.getInputStream(); // } // // @Override // public String toString() { // return "cid:" + cid; // } // // public String getCid() { // return cid; // } // // public byte[] getData() throws IOException { // return FileCopyUtils.copyToByteArray(dataHandler.getInputStream()); // } // // public String getContentType() { // return dataHandler.getContentType(); // } // // public DataHandler getDataHandler() { // return dataHandler; // } // // } // Path: example/src/main/java/com/nortal/jroad/example/client/NaidisXRoadServiceImpl.java import com.nortal.jroad.client.exception.XRoadServiceConsumptionException; import com.nortal.jroad.client.service.XRoadDatabaseService; import com.nortal.jroad.example.client.database.NaidisXRoadDatabase; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.AttachmentEchoResponse; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoRequest; import com.nortal.jroad.example.client.types.eu.x_road.naidis.EchoResponse; import com.nortal.jroad.jaxb.ByteArrayDataSource; import com.nortal.jroad.model.BeanXRoadMessage; import com.nortal.jroad.model.XRoadAttachment; import com.nortal.jroad.model.XRoadMessage; import java.util.Arrays; import javax.activation.DataHandler; import javax.annotation.Resource; import org.springframework.stereotype.Service; package com.nortal.jroad.example.client; /** * @author Lauri Lättemäe (lauri.lattemae@nortal.com) */ @Service("naidisXRoadService") public class NaidisXRoadServiceImpl extends XRoadDatabaseService implements NaidisXRoadService { @Resource private NaidisXRoadDatabase naidisXRoadDatabase; @Override public AttachmentEchoResponse sendAttachment(String contentType, byte[] content) throws XRoadServiceConsumptionException { DataHandler reqHandler = new DataHandler(new ByteArrayDataSource(contentType, content)); AttachmentEchoRequest request = AttachmentEchoRequest.Factory.newInstance(); request.addNewNest().setAttachmentHandler(reqHandler); return naidisXRoadDatabase.attachmentEchoV1(request); } @Override public String sendEcho(String text) throws XRoadServiceConsumptionException { EchoRequest req = EchoRequest.Factory.newInstance(); req.setText(text); return naidisXRoadDatabase.echoV1(req).getText(); } @Override public String sendEchoMime(String text) throws XRoadServiceConsumptionException { EchoRequest echoReq = EchoRequest.Factory.newInstance(); echoReq.setText(text); BeanXRoadMessage<EchoRequest> req = new BeanXRoadMessage<EchoRequest>(null, echoReq,
Arrays.asList(new XRoadAttachment("cid", "text/plain", text.getBytes())));
nortal/j-road
common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java
// Path: common/src/main/java/com/nortal/jroad/jaxb/ByteArrayDataSource.java // public class ByteArrayDataSource implements DataSource { // private byte[] data; // private String contentType; // // public ByteArrayDataSource(String contentType, byte[] data) { // this.contentType = contentType; // this.data = data; // } // // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(data); // } // // public OutputStream getOutputStream() throws IOException { // throw new UnsupportedOperationException(); // } // // public String getContentType() { // return contentType; // } // // public String getName() { // return "ByteArrayDataSource"; // } // }
import java.io.IOException; import java.io.InputStream; import javax.activation.DataHandler; import org.springframework.core.io.InputStreamSource; import org.springframework.util.FileCopyUtils; import com.nortal.jroad.jaxb.ByteArrayDataSource;
/** * Copyright 2015 Nortal 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.nortal.jroad.model; /** * XTee messages are sometimes allowed to contain MIME attachments, which this class encapsulates. Each attachment has * MIME content-type, data (content) and unique ID. This class implements {@link InputStreamSource} for a nice fit into * Spring-WS and provides easy access to attachment content. Attachments are the preferred way of transporting large * amounts of data because transmitting attachments requires much less bandwidth and resources (base64 etc) than * transmitting the same data within SOAP messages without attachments. * * @author Dmitri Danilkin */ public class XRoadAttachment implements InputStreamSource { private String cid; private DataHandler dataHandler; public XRoadAttachment(String cid, String contentType, byte[] data) { this.cid = cid;
// Path: common/src/main/java/com/nortal/jroad/jaxb/ByteArrayDataSource.java // public class ByteArrayDataSource implements DataSource { // private byte[] data; // private String contentType; // // public ByteArrayDataSource(String contentType, byte[] data) { // this.contentType = contentType; // this.data = data; // } // // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(data); // } // // public OutputStream getOutputStream() throws IOException { // throw new UnsupportedOperationException(); // } // // public String getContentType() { // return contentType; // } // // public String getName() { // return "ByteArrayDataSource"; // } // } // Path: common/src/main/java/com/nortal/jroad/model/XRoadAttachment.java import java.io.IOException; import java.io.InputStream; import javax.activation.DataHandler; import org.springframework.core.io.InputStreamSource; import org.springframework.util.FileCopyUtils; import com.nortal.jroad.jaxb.ByteArrayDataSource; /** * Copyright 2015 Nortal 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.nortal.jroad.model; /** * XTee messages are sometimes allowed to contain MIME attachments, which this class encapsulates. Each attachment has * MIME content-type, data (content) and unique ID. This class implements {@link InputStreamSource} for a nice fit into * Spring-WS and provides easy access to attachment content. Attachments are the preferred way of transporting large * amounts of data because transmitting attachments requires much less bandwidth and resources (base64 etc) than * transmitting the same data within SOAP messages without attachments. * * @author Dmitri Danilkin */ public class XRoadAttachment implements InputStreamSource { private String cid; private DataHandler dataHandler; public XRoadAttachment(String cid, String contentType, byte[] data) { this.cid = cid;
this.dataHandler = new DataHandler(new ByteArrayDataSource(contentType, data));
nortal/j-road
server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeJAXBEndpoint.java
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/util/AttachmentUtil.java // public class AttachmentUtil { // private static long salt = 0; // // public static String getUniqueCid() { // salt++; // return UUID.randomUUID().toString() + String.valueOf(salt); // } // // }
import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.AttachmentUtil; import com.nortal.jroad.util.SOAPUtil; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.annotation.Resource; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.attachment.AttachmentMarshaller; import javax.xml.bind.attachment.AttachmentUnmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node;
this.paringKehaClass = paringKehaClass; } protected Class<T> getParingKehaClass() { return paringKehaClass; } protected void updateUnmarshaller(Unmarshaller unmarshaller) throws Exception { // define schema validation, etc here in child endpoint classes } protected void updateMarshaller(Marshaller marshaller) throws Exception { // define your schema validation, etc here in child endpoint classes } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected void invokeInternal(final XTeeMessage<Document> request, final XTeeMessage<Element> response) throws Exception { if (getParingKehaClass() == null) { throw new IllegalStateException("Query body class ('requestClass') is unset/unspecified!"); } JAXBContext requestJc = getJAXBContextInstance(); Unmarshaller requestUnmarshaller = requestJc.createUnmarshaller(); requestUnmarshaller.setAttachmentUnmarshaller(new XTeeAttachmentUnmarshaller(request)); updateUnmarshaller(requestUnmarshaller); Document requestOnly = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/util/AttachmentUtil.java // public class AttachmentUtil { // private static long salt = 0; // // public static String getUniqueCid() { // salt++; // return UUID.randomUUID().toString() + String.valueOf(salt); // } // // } // Path: server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeJAXBEndpoint.java import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.AttachmentUtil; import com.nortal.jroad.util.SOAPUtil; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.annotation.Resource; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.attachment.AttachmentMarshaller; import javax.xml.bind.attachment.AttachmentUnmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; this.paringKehaClass = paringKehaClass; } protected Class<T> getParingKehaClass() { return paringKehaClass; } protected void updateUnmarshaller(Unmarshaller unmarshaller) throws Exception { // define schema validation, etc here in child endpoint classes } protected void updateMarshaller(Marshaller marshaller) throws Exception { // define your schema validation, etc here in child endpoint classes } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected void invokeInternal(final XTeeMessage<Document> request, final XTeeMessage<Element> response) throws Exception { if (getParingKehaClass() == null) { throw new IllegalStateException("Query body class ('requestClass') is unset/unspecified!"); } JAXBContext requestJc = getJAXBContextInstance(); Unmarshaller requestUnmarshaller = requestJc.createUnmarshaller(); requestUnmarshaller.setAttachmentUnmarshaller(new XTeeAttachmentUnmarshaller(request)); updateUnmarshaller(requestUnmarshaller); Document requestOnly = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
if (XRoadProtocolVersion.V2_0 == version) {
nortal/j-road
server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeJAXBEndpoint.java
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/util/AttachmentUtil.java // public class AttachmentUtil { // private static long salt = 0; // // public static String getUniqueCid() { // salt++; // return UUID.randomUUID().toString() + String.valueOf(salt); // } // // }
import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.AttachmentUtil; import com.nortal.jroad.util.SOAPUtil; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.annotation.Resource; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.attachment.AttachmentMarshaller; import javax.xml.bind.attachment.AttachmentUnmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node;
} protected void updateMarshaller(Marshaller marshaller) throws Exception { // define your schema validation, etc here in child endpoint classes } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected void invokeInternal(final XTeeMessage<Document> request, final XTeeMessage<Element> response) throws Exception { if (getParingKehaClass() == null) { throw new IllegalStateException("Query body class ('requestClass') is unset/unspecified!"); } JAXBContext requestJc = getJAXBContextInstance(); Unmarshaller requestUnmarshaller = requestJc.createUnmarshaller(); requestUnmarshaller.setAttachmentUnmarshaller(new XTeeAttachmentUnmarshaller(request)); updateUnmarshaller(requestUnmarshaller); Document requestOnly = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); if (XRoadProtocolVersion.V2_0 == version) { requestOnly.appendChild(requestOnly.importNode((Node) XPathFactory.newInstance().newXPath().evaluate("//*[local-name()='keha']", request.getContent(), XPathConstants.NODE), true)); } else { requestOnly.appendChild(requestOnly.importNode(SOAPUtil.getFirstNonTextChild(request.getContent()), true)); }
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/util/AttachmentUtil.java // public class AttachmentUtil { // private static long salt = 0; // // public static String getUniqueCid() { // salt++; // return UUID.randomUUID().toString() + String.valueOf(salt); // } // // } // Path: server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeJAXBEndpoint.java import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.AttachmentUtil; import com.nortal.jroad.util.SOAPUtil; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.annotation.Resource; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.attachment.AttachmentMarshaller; import javax.xml.bind.attachment.AttachmentUnmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; } protected void updateMarshaller(Marshaller marshaller) throws Exception { // define your schema validation, etc here in child endpoint classes } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected void invokeInternal(final XTeeMessage<Document> request, final XTeeMessage<Element> response) throws Exception { if (getParingKehaClass() == null) { throw new IllegalStateException("Query body class ('requestClass') is unset/unspecified!"); } JAXBContext requestJc = getJAXBContextInstance(); Unmarshaller requestUnmarshaller = requestJc.createUnmarshaller(); requestUnmarshaller.setAttachmentUnmarshaller(new XTeeAttachmentUnmarshaller(request)); updateUnmarshaller(requestUnmarshaller); Document requestOnly = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); if (XRoadProtocolVersion.V2_0 == version) { requestOnly.appendChild(requestOnly.importNode((Node) XPathFactory.newInstance().newXPath().evaluate("//*[local-name()='keha']", request.getContent(), XPathConstants.NODE), true)); } else { requestOnly.appendChild(requestOnly.importNode(SOAPUtil.getFirstNonTextChild(request.getContent()), true)); }
XTeeMessage<T> jaxbRequestMessage = new BeanXTeeMessage<T>(request.getHeader(),
nortal/j-road
server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeJAXBEndpoint.java
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/util/AttachmentUtil.java // public class AttachmentUtil { // private static long salt = 0; // // public static String getUniqueCid() { // salt++; // return UUID.randomUUID().toString() + String.valueOf(salt); // } // // }
import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.AttachmentUtil; import com.nortal.jroad.util.SOAPUtil; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.annotation.Resource; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.attachment.AttachmentMarshaller; import javax.xml.bind.attachment.AttachmentUnmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node;
} } private static class XTeeAttachmentMarshaller extends AttachmentMarshaller { private final List<XTeeAttachment> attachments; private long salt = 0; public XTeeAttachmentMarshaller(final XTeeMessage<?> message) { this.attachments = message.getAttachments(); } @Override public String addMtomAttachment(final byte[] arg0, final int arg1, final int arg2, final String arg3, final String arg4, final String arg5) { throw new UnsupportedOperationException("MTOM Support is disabled!"); } @Override public String addMtomAttachment(final DataHandler arg0, final String arg1, final String arg2) { throw new UnsupportedOperationException("MTOM Support is disabled!"); } @Override public String addSwaRefAttachment(final DataHandler handler) { salt++;
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // // Path: common/src/main/java/com/nortal/jroad/model/BeanXTeeMessage.java // @Deprecated // public class BeanXTeeMessage<T> implements XTeeMessage<T> { // private List<XTeeAttachment> attachments; // private XTeeHeader header; // private T content; // // public BeanXTeeMessage(XTeeHeader header, T content, List<XTeeAttachment> attachments) { // this.attachments = attachments; // this.header = header; // this.content = content; // } // // public List<XTeeAttachment> getAttachments() { // return attachments; // } // // public XTeeHeader getHeader() { // return header; // } // // public T getContent() { // return content; // } // // public void setContent(T content) { // this.content = content; // } // // public void setAttachments(List<XTeeAttachment> attachments) { // this.attachments = attachments; // } // // public void setHeader(XTeeHeader header) { // this.header = header; // } // } // // Path: common/src/main/java/com/nortal/jroad/util/AttachmentUtil.java // public class AttachmentUtil { // private static long salt = 0; // // public static String getUniqueCid() { // salt++; // return UUID.randomUUID().toString() + String.valueOf(salt); // } // // } // Path: server/src/main/java/com/nortal/jroad/endpoint/AbstractXTeeJAXBEndpoint.java import com.nortal.jroad.enums.XRoadProtocolVersion; import com.nortal.jroad.model.BeanXTeeMessage; import com.nortal.jroad.model.XTeeAttachment; import com.nortal.jroad.model.XTeeMessage; import com.nortal.jroad.util.AttachmentUtil; import com.nortal.jroad.util.SOAPUtil; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.annotation.Resource; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.attachment.AttachmentMarshaller; import javax.xml.bind.attachment.AttachmentUnmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; } } private static class XTeeAttachmentMarshaller extends AttachmentMarshaller { private final List<XTeeAttachment> attachments; private long salt = 0; public XTeeAttachmentMarshaller(final XTeeMessage<?> message) { this.attachments = message.getAttachments(); } @Override public String addMtomAttachment(final byte[] arg0, final int arg1, final int arg2, final String arg3, final String arg4, final String arg5) { throw new UnsupportedOperationException("MTOM Support is disabled!"); } @Override public String addMtomAttachment(final DataHandler arg0, final String arg1, final String arg2) { throw new UnsupportedOperationException("MTOM Support is disabled!"); } @Override public String addSwaRefAttachment(final DataHandler handler) { salt++;
String contentId = AttachmentUtil.getUniqueCid();
nortal/j-road
client-transport/src/main/java/com/nortal/jroad/client/service/configuration/XRoadServiceConfiguration.java
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // }
import com.nortal.jroad.client.enums.XroadObjectType; import com.nortal.jroad.enums.XRoadProtocolVersion; import java.io.Serializable;
package com.nortal.jroad.client.service.configuration; /** * @author Aleksei Bogdanov (aleksei.bogdanov@nortal.com) * @author Lauri Lättemäe (lauri.lattemae@nortal.com) - protocol 4.0 */ // TODO Lauri: konfi võiks kuidagi paremini lahendatud olla public interface XRoadServiceConfiguration extends Serializable { /** * Returns an URL of institutions security server, typically in form of * <code>http://minu_turvaserver/cgi-bin/consumer_proxy</code>. */ String getSecurityServer(); /** * Returns name/prefix of the X-Tee database where the service-to-be-invoked resides. */ String getDatabase(); /** * Returns name/prefix of the X-Tee database, which is actually specified in the WSDL of the service. */ String getWsdlDatabase(); /** Returns identifier of the person/entity who will be invoking the service */ String getIdCode(); /** Returns name of file (or document) related to the service invokation. */ String getFile(); /** Returns the service-to-be-invoked version. */ String getVersion(); /** Returns the name of the (service's) <code>method</code> that will be called. */ String getMethod(); /** * Returns database xroad protocol version - by default v4 */
// Path: common/src/main/java/com/nortal/jroad/enums/XRoadProtocolVersion.java // public enum XRoadProtocolVersion { // // V2_0("2.0", "xtee", "http://x-tee.riik.ee/xsd/xtee.xsd"), // V3_0("3.0", "xrd", "http://x-rd.net/xsd/xroad.xsd"), // V3_1("3.1", "xrd", "http://x-road.ee/xsd/x-road.xsd"), // V4_0("4.0", "xrd", "http://x-road.eu/xsd/xroad.xsd"); // // private final String code; // private final String namespacePrefix; // private final String namespaceUri; // // private XRoadProtocolVersion(String code, String namespacePrefix, String namespaceUri) { // this.code = code; // this.namespaceUri = namespaceUri; // this.namespacePrefix = namespacePrefix; // } // // public String getCode() { // return code; // } // // public String getNamespacePrefix() { // return namespacePrefix; // } // // public String getNamespaceUri() { // return namespaceUri; // } // // public static XRoadProtocolVersion getValueByVersionCode(String code) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getCode().equals(code)) { // return version; // } // } // return null; // } // // public static XRoadProtocolVersion getValueByNamespaceURI(String uri) { // for (XRoadProtocolVersion version : XRoadProtocolVersion.values()) { // if (version.getNamespaceUri().startsWith(uri)) { // return version; // } // } // return null; // } // // } // Path: client-transport/src/main/java/com/nortal/jroad/client/service/configuration/XRoadServiceConfiguration.java import com.nortal.jroad.client.enums.XroadObjectType; import com.nortal.jroad.enums.XRoadProtocolVersion; import java.io.Serializable; package com.nortal.jroad.client.service.configuration; /** * @author Aleksei Bogdanov (aleksei.bogdanov@nortal.com) * @author Lauri Lättemäe (lauri.lattemae@nortal.com) - protocol 4.0 */ // TODO Lauri: konfi võiks kuidagi paremini lahendatud olla public interface XRoadServiceConfiguration extends Serializable { /** * Returns an URL of institutions security server, typically in form of * <code>http://minu_turvaserver/cgi-bin/consumer_proxy</code>. */ String getSecurityServer(); /** * Returns name/prefix of the X-Tee database where the service-to-be-invoked resides. */ String getDatabase(); /** * Returns name/prefix of the X-Tee database, which is actually specified in the WSDL of the service. */ String getWsdlDatabase(); /** Returns identifier of the person/entity who will be invoking the service */ String getIdCode(); /** Returns name of file (or document) related to the service invokation. */ String getFile(); /** Returns the service-to-be-invoked version. */ String getVersion(); /** Returns the name of the (service's) <code>method</code> that will be called. */ String getMethod(); /** * Returns database xroad protocol version - by default v4 */
XRoadProtocolVersion getProtocolVersion();
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/HttpParserTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/DefaultSocketData.java // public class DefaultSocketData implements SocketData // { // // protected final byte[] data; // // // public DefaultSocketData(byte[] data) { // this.data = data.clone(); // } // // public InputStream getData() { // return new ByteArrayInputStream(data); // } // // @Override // public String toString() { // return StringUtils.convertDataToString(data); // } // }
import static org.junit.Assert.assertEquals; import net.javacrumbs.mocksocket.connection.data.DefaultSocketData; import org.junit.Test;
/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class HttpParserTest { @Test public void testCharset() throws Exception { String data = "GET http://localhost HTTP/1.1\n" + "Content-type: text/plain;charset=ISO-8859-2\n" + "Content-Length: 9\n" + "\n" + "ěščřžýáíé";
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/DefaultSocketData.java // public class DefaultSocketData implements SocketData // { // // protected final byte[] data; // // // public DefaultSocketData(byte[] data) { // this.data = data.clone(); // } // // public InputStream getData() { // return new ByteArrayInputStream(data); // } // // @Override // public String toString() { // return StringUtils.convertDataToString(data); // } // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/HttpParserTest.java import static org.junit.Assert.assertEquals; import net.javacrumbs.mocksocket.connection.data.DefaultSocketData; import org.junit.Test; /* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class HttpParserTest { @Test public void testCharset() throws Exception { String data = "GET http://localhost HTTP/1.1\n" + "Content-type: text/plain;charset=ISO-8859-2\n" + "Content-Length: 9\n" + "\n" + "ěščřžýáíé";
HttpRequest parser = new HttpParser(new DefaultSocketData(data.getBytes("ISO-8859-2")));
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall()
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall()
.andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404))
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall()
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall()
.andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404))
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall()
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall()
.andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404))
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall() .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404)) .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200));
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall() .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404)) .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200));
assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall() .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404)) .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200));
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall() .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404)) .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200));
assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall() .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404)) .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200)); assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain")))); assertThat(recordedConnections().get(0), method(is("GET")));
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class SampleTest { private static final String ADDRESS = "http://localhost/"; @After public void reset() { HttpMockSocket.reset(); } @Test public void testHttpClientMethod() throws ClientProtocolException, IOException { expectCall() .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404)) .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200)); assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain")))); assertThat(recordedConnections().get(0), method(is("GET")));
assertThat(request(0).getMethod(), is("GET"));
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test;
expectCall() .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404)) .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200)); assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain")))); assertThat(recordedConnections().get(0), method(is("GET"))); assertThat(request(0).getMethod(), is("GET")); assertThat(request(0).getAddress(), is("localhost:80")); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); getResponse.getEntity().writeTo(outstream); assertThat(new String(outstream.toByteArray()), is("Text")); httpget.abort(); HttpPost httppost = new HttpPost(ADDRESS); HttpResponse postResponse = httpclient.execute(httppost); assertThat(postResponse.getStatusLine().getStatusCode(), is(404)); httppost.abort(); } @Test public void testHttpClientUri() throws ClientProtocolException, IOException { expectCall()
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test; expectCall() .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404)) .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200)); assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain")))); assertThat(recordedConnections().get(0), method(is("GET"))); assertThat(request(0).getMethod(), is("GET")); assertThat(request(0).getAddress(), is("localhost:80")); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); getResponse.getEntity().writeTo(outstream); assertThat(new String(outstream.toByteArray()), is("Text")); httpget.abort(); HttpPost httppost = new HttpPost(ADDRESS); HttpResponse postResponse = httpclient.execute(httppost); assertThat(postResponse.getStatusLine().getStatusCode(), is(404)); httppost.abort(); } @Test public void testHttpClientUri() throws ClientProtocolException, IOException { expectCall()
.andWhenRequest(uri(is("/test/something.do"))).thenReturn(response().withStatus(404))
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test;
.andWhenRequest(uri(is("/test/other.do"))).thenReturn(response().withContent("Text")).thenReturn(response().withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); doGet(httpclient); doGet(httpclient); HttpPost httppost = new HttpPost(ADDRESS+"test/something.do"); HttpResponse postResponse = httpclient.execute(httppost); assertThat(postResponse.getStatusLine().getStatusCode(), is(404)); httppost.abort(); } private void doGet(HttpClient httpclient) throws IOException, ClientProtocolException { HttpGet httpget = new HttpGet(ADDRESS+"test/other.do"); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200)); assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain")))); assertThat(recordedConnections().get(0), method(is("GET"))); assertThat(request(0).getMethod(), is("GET")); assertThat(request(0).getAddress(), is("localhost:80")); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); getResponse.getEntity().writeTo(outstream); assertThat(new String(outstream.toByteArray()), is("Text")); httpget.abort(); }
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> method(Matcher<String> methodMatcher) { // return new CombinableMatcher<RequestSocketData>(new MethodMatcher(methodMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpRequest request(int index) // { // return new HttpParser(recordedConnections().get(index)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static HttpResponseGenerator response() // { // return new HttpResponseGenerator(); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> uri(Matcher<String> uriMatcher) { // return new CombinableMatcher<RequestSocketData>(new UriMatcher(uriMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.method; import static net.javacrumbs.mocksocket.http.HttpMockSocket.request; import static net.javacrumbs.mocksocket.http.HttpMockSocket.response; import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.After; import org.junit.Test; .andWhenRequest(uri(is("/test/other.do"))).thenReturn(response().withContent("Text")).thenReturn(response().withContent("Text")); HttpClient httpclient = new DefaultHttpClient(); doGet(httpclient); doGet(httpclient); HttpPost httppost = new HttpPost(ADDRESS+"test/something.do"); HttpResponse postResponse = httpclient.execute(httppost); assertThat(postResponse.getStatusLine().getStatusCode(), is(404)); httppost.abort(); } private void doGet(HttpClient httpclient) throws IOException, ClientProtocolException { HttpGet httpget = new HttpGet(ADDRESS+"test/other.do"); httpget.addHeader("Accept","text/plain"); HttpResponse getResponse = httpclient.execute(httpget); assertThat(getResponse.getStatusLine().getStatusCode(), is(200)); assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain")))); assertThat(recordedConnections().get(0), method(is("GET"))); assertThat(request(0).getMethod(), is("GET")); assertThat(request(0).getAddress(), is("localhost:80")); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); getResponse.getEntity().writeTo(outstream); assertThat(new String(outstream.toByteArray()), is("Text")); httpget.abort(); }
@Test(expected=MockSocketException.class)
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/StringUtils.java // public class StringUtils { // private static boolean printDataAsString = true; // // private static String defaultEncoding = "UTF-8"; // // public static synchronized boolean isPrintDataAsString() { // return printDataAsString; // } // // /** // * Should be data printed as string or as byte array. // * @param printDataAsString // */ // public static synchronized void setPrintDataAsString(boolean printDataAsString) { // StringUtils.printDataAsString = printDataAsString; // } // // public static synchronized String getDefaultEncoding() { // return defaultEncoding; // } // // public static synchronized void setDefaultEncoding(String defaultEncoding) { // StringUtils.defaultEncoding = defaultEncoding; // } // // public static String convertDataToString(byte[] data) { // if (printDataAsString) // { // try { // return new String(data, defaultEncoding); // } catch (UnsupportedEncodingException e) { // return new String(data); // } // } // else // { // return Arrays.toString(data); // } // } // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import net.javacrumbs.mocksocket.connection.StringUtils;
/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.data; public class OutputSocketData implements RequestSocketData { private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); private final String address; public OutputSocketData(String address) { this.address = address; } public InputStream getData() { return new ByteArrayInputStream(getDataAsBytes()); } protected byte[] getDataAsBytes() { return outputStream.toByteArray(); } public OutputStream getOutputStream() { return outputStream; } public String getAddress() { return address; } @Override public String toString() {
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/StringUtils.java // public class StringUtils { // private static boolean printDataAsString = true; // // private static String defaultEncoding = "UTF-8"; // // public static synchronized boolean isPrintDataAsString() { // return printDataAsString; // } // // /** // * Should be data printed as string or as byte array. // * @param printDataAsString // */ // public static synchronized void setPrintDataAsString(boolean printDataAsString) { // StringUtils.printDataAsString = printDataAsString; // } // // public static synchronized String getDefaultEncoding() { // return defaultEncoding; // } // // public static synchronized void setDefaultEncoding(String defaultEncoding) { // StringUtils.defaultEncoding = defaultEncoding; // } // // public static String convertDataToString(byte[] data) { // if (printDataAsString) // { // try { // return new String(data, defaultEncoding); // } catch (UnsupportedEncodingException e) { // return new String(data); // } // } // else // { // return Arrays.toString(data); // } // } // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import net.javacrumbs.mocksocket.connection.StringUtils; /* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.data; public class OutputSocketData implements RequestSocketData { private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); private final String address; public OutputSocketData(String address) { this.address = address; } public InputStream getData() { return new ByteArrayInputStream(getDataAsBytes()); } protected byte[] getDataAsBytes() { return outputStream.toByteArray(); } public OutputStream getOutputStream() { return outputStream; } public String getAddress() { return address; } @Override public String toString() {
return StringUtils.convertDataToString(getDataAsBytes());
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/matchers/DataMatcher.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java // public class Utils { // private Utils() // { // //empty // } // // public static final byte[] toByteArray(InputStream stream) // { // try // { // return IOUtils.toByteArray(stream); // } // catch (IOException e) // { // throw new MockSocketException("Can not read data.",e); // } // finally // { // IOUtils.closeQuietly(stream); // } // } // }
import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.util.Utils; import org.hamcrest.Description; import org.hamcrest.Matcher;
/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.matchers; public class DataMatcher extends AbstractSocketMatcher<SocketData> { public DataMatcher(Matcher<byte[]> wrappedMatcher) { super(wrappedMatcher); } public void describeTo(Description description) { description.appendText("data ").appendDescriptionOf(getWrappedMatcher()); } public boolean matches(Object item) { if (item instanceof SocketData) {
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java // public class Utils { // private Utils() // { // //empty // } // // public static final byte[] toByteArray(InputStream stream) // { // try // { // return IOUtils.toByteArray(stream); // } // catch (IOException e) // { // throw new MockSocketException("Can not read data.",e); // } // finally // { // IOUtils.closeQuietly(stream); // } // } // } // Path: core/src/main/java/net/javacrumbs/mocksocket/matchers/DataMatcher.java import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.util.Utils; import org.hamcrest.Description; import org.hamcrest.Matcher; /* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.matchers; public class DataMatcher extends AbstractSocketMatcher<SocketData> { public DataMatcher(Matcher<byte[]> wrappedMatcher) { super(wrappedMatcher); } public void describeTo(Description description) { description.appendText("data ").appendDescriptionOf(getWrappedMatcher()); } public boolean matches(Object item) { if (item instanceof SocketData) {
return getWrappedMatcher().matches(Utils.toByteArray(((SocketData) item).getData()));
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/HttpMatchersTest.java
// Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> content(Matcher<String> contentMatcher) { // return new CombinableMatcher<RequestSocketData>(new ContentMatcher(contentMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> status(Matcher<Integer> statusMatcher) { // return new CombinableMatcher<RequestSocketData>(new StatusMatcher(statusMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // }
import static net.javacrumbs.mocksocket.http.HttpMockSocket.content; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.status; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayInputStream; import java.io.InputStream; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import org.junit.Test;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class HttpMatchersTest { private static final RequestSocketData REQUEST = new RequestSocketData() { public InputStream getData() { return new ByteArrayInputStream("HTTP/1.0 200 OK\nLast-Modified: Wed, 10 Mar 2010 19:11:49 GMT\n\nTest".getBytes()); } public String getAddress() { return "localhost:1111"; } }; @Test public void testMatchStatus() {
// Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> content(Matcher<String> contentMatcher) { // return new CombinableMatcher<RequestSocketData>(new ContentMatcher(contentMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> status(Matcher<Integer> statusMatcher) { // return new CombinableMatcher<RequestSocketData>(new StatusMatcher(statusMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/HttpMatchersTest.java import static net.javacrumbs.mocksocket.http.HttpMockSocket.content; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.status; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayInputStream; import java.io.InputStream; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import org.junit.Test; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class HttpMatchersTest { private static final RequestSocketData REQUEST = new RequestSocketData() { public InputStream getData() { return new ByteArrayInputStream("HTTP/1.0 200 OK\nLast-Modified: Wed, 10 Mar 2010 19:11:49 GMT\n\nTest".getBytes()); } public String getAddress() { return "localhost:1111"; } }; @Test public void testMatchStatus() {
assertThat(REQUEST, status(is(200)));
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/HttpMatchersTest.java
// Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> content(Matcher<String> contentMatcher) { // return new CombinableMatcher<RequestSocketData>(new ContentMatcher(contentMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> status(Matcher<Integer> statusMatcher) { // return new CombinableMatcher<RequestSocketData>(new StatusMatcher(statusMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // }
import static net.javacrumbs.mocksocket.http.HttpMockSocket.content; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.status; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayInputStream; import java.io.InputStream; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import org.junit.Test;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class HttpMatchersTest { private static final RequestSocketData REQUEST = new RequestSocketData() { public InputStream getData() { return new ByteArrayInputStream("HTTP/1.0 200 OK\nLast-Modified: Wed, 10 Mar 2010 19:11:49 GMT\n\nTest".getBytes()); } public String getAddress() { return "localhost:1111"; } }; @Test public void testMatchStatus() { assertThat(REQUEST, status(is(200))); } @Test(expected=AssertionError.class) public void testDoNotMatchStatus() { assertThat(REQUEST, status(is(300))); } @Test public void testMatchHeader() {
// Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> content(Matcher<String> contentMatcher) { // return new CombinableMatcher<RequestSocketData>(new ContentMatcher(contentMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> status(Matcher<Integer> statusMatcher) { // return new CombinableMatcher<RequestSocketData>(new StatusMatcher(statusMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/HttpMatchersTest.java import static net.javacrumbs.mocksocket.http.HttpMockSocket.content; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.status; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayInputStream; import java.io.InputStream; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import org.junit.Test; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class HttpMatchersTest { private static final RequestSocketData REQUEST = new RequestSocketData() { public InputStream getData() { return new ByteArrayInputStream("HTTP/1.0 200 OK\nLast-Modified: Wed, 10 Mar 2010 19:11:49 GMT\n\nTest".getBytes()); } public String getAddress() { return "localhost:1111"; } }; @Test public void testMatchStatus() { assertThat(REQUEST, status(is(200))); } @Test(expected=AssertionError.class) public void testDoNotMatchStatus() { assertThat(REQUEST, status(is(300))); } @Test public void testMatchHeader() {
assertThat(REQUEST, header("Last-Modified", is("Wed, 10 Mar 2010 19:11:49 GMT")));
lukas-krecan/mock-socket
http/src/test/java/net/javacrumbs/mocksocket/http/HttpMatchersTest.java
// Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> content(Matcher<String> contentMatcher) { // return new CombinableMatcher<RequestSocketData>(new ContentMatcher(contentMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> status(Matcher<Integer> statusMatcher) { // return new CombinableMatcher<RequestSocketData>(new StatusMatcher(statusMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // }
import static net.javacrumbs.mocksocket.http.HttpMockSocket.content; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.status; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayInputStream; import java.io.InputStream; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import org.junit.Test;
}; @Test public void testMatchStatus() { assertThat(REQUEST, status(is(200))); } @Test(expected=AssertionError.class) public void testDoNotMatchStatus() { assertThat(REQUEST, status(is(300))); } @Test public void testMatchHeader() { assertThat(REQUEST, header("Last-Modified", is("Wed, 10 Mar 2010 19:11:49 GMT"))); } @Test(expected=AssertionError.class) public void testDoMatchHeader() { assertThat(REQUEST, header("Last-Modified", is("Tue, 10 Mar 2010 19:11:49 GMT"))); } @Test(expected=AssertionError.class) public void testDoMatchHeaderNotPresent() { assertThat(REQUEST, header("Expires", is("Tue, 10 Mar 2010 19:11:49 GMT"))); } @Test public void testMatchContent() {
// Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> content(Matcher<String> contentMatcher) { // return new CombinableMatcher<RequestSocketData>(new ContentMatcher(contentMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> header(String header, Matcher<String> headerMatcher) { // return new CombinableMatcher<RequestSocketData>(new HeaderMatcher(header, headerMatcher)); // } // // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java // public static CombinableMatcher<RequestSocketData> status(Matcher<Integer> statusMatcher) { // return new CombinableMatcher<RequestSocketData>(new StatusMatcher(statusMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // Path: http/src/test/java/net/javacrumbs/mocksocket/http/HttpMatchersTest.java import static net.javacrumbs.mocksocket.http.HttpMockSocket.content; import static net.javacrumbs.mocksocket.http.HttpMockSocket.header; import static net.javacrumbs.mocksocket.http.HttpMockSocket.status; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayInputStream; import java.io.InputStream; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import org.junit.Test; }; @Test public void testMatchStatus() { assertThat(REQUEST, status(is(200))); } @Test(expected=AssertionError.class) public void testDoNotMatchStatus() { assertThat(REQUEST, status(is(300))); } @Test public void testMatchHeader() { assertThat(REQUEST, header("Last-Modified", is("Wed, 10 Mar 2010 19:11:49 GMT"))); } @Test(expected=AssertionError.class) public void testDoMatchHeader() { assertThat(REQUEST, header("Last-Modified", is("Tue, 10 Mar 2010 19:11:49 GMT"))); } @Test(expected=AssertionError.class) public void testDoMatchHeaderNotPresent() { assertThat(REQUEST, header("Expires", is("Tue, 10 Mar 2010 19:11:49 GMT"))); } @Test public void testMatchContent() {
assertThat(REQUEST, content(is("Test")));
lukas-krecan/mock-socket
core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // }
import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils;
/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket; public class SampleTest { @Test public void testResponse() throws Exception { byte[] mockData = new byte[]{1,2,3,4};
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // } // Path: core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils; /* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket; public class SampleTest { @Test public void testResponse() throws Exception { byte[] mockData = new byte[]{1,2,3,4};
expectCall().andReturn(data(mockData));
lukas-krecan/mock-socket
core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // }
import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils;
/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket; public class SampleTest { @Test public void testResponse() throws Exception { byte[] mockData = new byte[]{1,2,3,4};
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // } // Path: core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils; /* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket; public class SampleTest { @Test public void testResponse() throws Exception { byte[] mockData = new byte[]{1,2,3,4};
expectCall().andReturn(data(mockData));
lukas-krecan/mock-socket
core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // }
import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils;
expectCall().andReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testMultiple() throws Exception { byte[] mockData1 = new byte[]{1,2,3,4}; byte[] mockData2 = new byte[]{1,2,3,4}; expectCall().andReturn(data(mockData1)).andReturn(data(mockData2)); Socket socket1 = SocketFactory.getDefault().createSocket("example.org", 1234); byte[] data1 = IOUtils.toByteArray(socket1.getInputStream()); socket1.close(); assertThat(data1, is(mockData1)); Socket socket2 = SocketFactory.getDefault().createSocket("example.org", 1234); byte[] data2 = IOUtils.toByteArray(socket2.getInputStream()); socket2.close(); assertThat(data2, is(mockData2)); } @Test public void testConditionalAddress() throws Exception { byte[] mockData = new byte[]{1,2,3,4};
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // } // Path: core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils; expectCall().andReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testMultiple() throws Exception { byte[] mockData1 = new byte[]{1,2,3,4}; byte[] mockData2 = new byte[]{1,2,3,4}; expectCall().andReturn(data(mockData1)).andReturn(data(mockData2)); Socket socket1 = SocketFactory.getDefault().createSocket("example.org", 1234); byte[] data1 = IOUtils.toByteArray(socket1.getInputStream()); socket1.close(); assertThat(data1, is(mockData1)); Socket socket2 = SocketFactory.getDefault().createSocket("example.org", 1234); byte[] data2 = IOUtils.toByteArray(socket2.getInputStream()); socket2.close(); assertThat(data2, is(mockData2)); } @Test public void testConditionalAddress() throws Exception { byte[] mockData = new byte[]{1,2,3,4};
expectCall().andWhenRequest(address(is("example.org:1234"))).thenReturn(data(mockData));
lukas-krecan/mock-socket
core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // }
import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils;
public void testConditionalAddress() throws Exception { byte[] mockData = new byte[]{1,2,3,4}; expectCall().andWhenRequest(address(is("example.org:1234"))).thenReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testConditionalData() throws Exception { byte[] dataToWrite = new byte[]{5,4,3,2}; byte[] mockData = new byte[]{1,2,3,4}; expectCall().andWhenRequest(data(is(dataToWrite))).thenReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testRequest() throws Exception { //prepare mock byte[] dataToWrite = new byte[]{5,4,3,2};
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // } // Path: core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils; public void testConditionalAddress() throws Exception { byte[] mockData = new byte[]{1,2,3,4}; expectCall().andWhenRequest(address(is("example.org:1234"))).thenReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testConditionalData() throws Exception { byte[] dataToWrite = new byte[]{5,4,3,2}; byte[] mockData = new byte[]{1,2,3,4}; expectCall().andWhenRequest(data(is(dataToWrite))).thenReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testRequest() throws Exception { //prepare mock byte[] dataToWrite = new byte[]{5,4,3,2};
expectCall().andReturn(emptyResponse());
lukas-krecan/mock-socket
core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // }
import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils;
assertThat(data, is(mockData)); } @Test public void testConditionalData() throws Exception { byte[] dataToWrite = new byte[]{5,4,3,2}; byte[] mockData = new byte[]{1,2,3,4}; expectCall().andWhenRequest(data(is(dataToWrite))).thenReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testRequest() throws Exception { //prepare mock byte[] dataToWrite = new byte[]{5,4,3,2}; expectCall().andReturn(emptyResponse()); //do test Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); socket.close(); //verify data sent
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // } // Path: core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils; assertThat(data, is(mockData)); } @Test public void testConditionalData() throws Exception { byte[] dataToWrite = new byte[]{5,4,3,2}; byte[] mockData = new byte[]{1,2,3,4}; expectCall().andWhenRequest(data(is(dataToWrite))).thenReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testRequest() throws Exception { //prepare mock byte[] dataToWrite = new byte[]{5,4,3,2}; expectCall().andReturn(emptyResponse()); //do test Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); socket.close(); //verify data sent
assertThat(recordedConnections().get(0), data(is(dataToWrite)));
lukas-krecan/mock-socket
core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // }
import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils;
expectCall().andWhenRequest(data(is(dataToWrite))).thenReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testRequest() throws Exception { //prepare mock byte[] dataToWrite = new byte[]{5,4,3,2}; expectCall().andReturn(emptyResponse()); //do test Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); socket.close(); //verify data sent assertThat(recordedConnections().get(0), data(is(dataToWrite))); assertThat(recordedConnections().get(0), address(is("example.org:1234"))); } @After public void tearDown() {
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static Matcher<RequestSocketData> address(Matcher<String> addressMatcher) // { // return new CombinableMatcher<RequestSocketData>(new AddressMatcher(addressMatcher)); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData data(byte[] data) // { // return new DefaultSocketData(data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static SocketData emptyResponse() // { // return new DefaultSocketData(new byte[0]); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static UniversalMockRecorder expectCall() { // return StaticConnectionFactory.expectCall(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static List<RequestSocketData> recordedConnections() // { // return StaticConnectionFactory.getRequestRecorder().requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java // public static void reset() // { // StaticConnectionFactory.reset(); // } // Path: core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java import org.junit.After; import org.junit.Test; import static net.javacrumbs.mocksocket.MockSocket.address; import static net.javacrumbs.mocksocket.MockSocket.data; import static net.javacrumbs.mocksocket.MockSocket.emptyResponse; import static net.javacrumbs.mocksocket.MockSocket.expectCall; import static net.javacrumbs.mocksocket.MockSocket.recordedConnections; import static net.javacrumbs.mocksocket.MockSocket.reset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.Socket; import javax.net.SocketFactory; import org.apache.commons.io.IOUtils; expectCall().andWhenRequest(data(is(dataToWrite))).thenReturn(data(mockData)); Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); byte[] data = IOUtils.toByteArray(socket.getInputStream()); socket.close(); assertThat(data, is(mockData)); } @Test public void testRequest() throws Exception { //prepare mock byte[] dataToWrite = new byte[]{5,4,3,2}; expectCall().andReturn(emptyResponse()); //do test Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234); IOUtils.write(dataToWrite, socket.getOutputStream()); socket.close(); //verify data sent assertThat(recordedConnections().get(0), data(is(dataToWrite))); assertThat(recordedConnections().get(0), address(is("example.org:1234"))); } @After public void tearDown() {
reset();
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/StaticConnectionFactory.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/socket/MockSocketImplFactory.java // public class MockSocketImplFactory implements SocketImplFactory { // private final ConnectionFactory connectionFactory; // // public MockSocketImplFactory(ConnectionFactory connectionFactory) { // this.connectionFactory = connectionFactory; // } // // public SocketImpl createSocketImpl() { // return new ConnectionFactoryMockSocketImpl(connectionFactory); // } // // }
import java.io.IOException; import java.net.Socket; import java.net.SocketImplFactory; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.socket.MockSocketImplFactory;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection; /** * Stores connections in a static field. It is NOT threads safe so you can not execute multiple tests in parallel. * You also can not use it if there is a {@link SocketImplFactory} already set. * @author Lukas Krecan * @see Socket#setSocketImplFactory(SocketImplFactory) */ public class StaticConnectionFactory implements ConnectionFactory { private static ConnectionFactory connectionFactory; static { bootstrap(); } static void bootstrap() { try {
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/socket/MockSocketImplFactory.java // public class MockSocketImplFactory implements SocketImplFactory { // private final ConnectionFactory connectionFactory; // // public MockSocketImplFactory(ConnectionFactory connectionFactory) { // this.connectionFactory = connectionFactory; // } // // public SocketImpl createSocketImpl() { // return new ConnectionFactoryMockSocketImpl(connectionFactory); // } // // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/StaticConnectionFactory.java import java.io.IOException; import java.net.Socket; import java.net.SocketImplFactory; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.socket.MockSocketImplFactory; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection; /** * Stores connections in a static field. It is NOT threads safe so you can not execute multiple tests in parallel. * You also can not use it if there is a {@link SocketImplFactory} already set. * @author Lukas Krecan * @see Socket#setSocketImplFactory(SocketImplFactory) */ public class StaticConnectionFactory implements ConnectionFactory { private static ConnectionFactory connectionFactory; static { bootstrap(); } static void bootstrap() { try {
Socket.setSocketImplFactory(new MockSocketImplFactory(new StaticConnectionFactory()));
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/StaticConnectionFactory.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/socket/MockSocketImplFactory.java // public class MockSocketImplFactory implements SocketImplFactory { // private final ConnectionFactory connectionFactory; // // public MockSocketImplFactory(ConnectionFactory connectionFactory) { // this.connectionFactory = connectionFactory; // } // // public SocketImpl createSocketImpl() { // return new ConnectionFactoryMockSocketImpl(connectionFactory); // } // // }
import java.io.IOException; import java.net.Socket; import java.net.SocketImplFactory; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.socket.MockSocketImplFactory;
UniversalMockConnectionFactory mockConnection = new UniversalMockConnectionFactory(); useConnectionFactory(mockConnection); return mockConnection; } else { throw new IllegalArgumentException("Can not call expectCall twice. You have to call reset before each test. If you need simulate multiple requests, please call andReturn several times."); } } public synchronized static void reset() { connectionFactory = null; } public static void useConnectionFactory(ConnectionFactory connectionFactory) { StaticConnectionFactory.connectionFactory = connectionFactory; } protected synchronized static ConnectionFactory getConnectionFactory() { return connectionFactory; } public synchronized static RequestRecorder getRequestRecorder() { if (connectionFactory instanceof RequestRecorder) { return (RequestRecorder)connectionFactory; } else if (connectionFactory!=null) {
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/socket/MockSocketImplFactory.java // public class MockSocketImplFactory implements SocketImplFactory { // private final ConnectionFactory connectionFactory; // // public MockSocketImplFactory(ConnectionFactory connectionFactory) { // this.connectionFactory = connectionFactory; // } // // public SocketImpl createSocketImpl() { // return new ConnectionFactoryMockSocketImpl(connectionFactory); // } // // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/StaticConnectionFactory.java import java.io.IOException; import java.net.Socket; import java.net.SocketImplFactory; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.socket.MockSocketImplFactory; UniversalMockConnectionFactory mockConnection = new UniversalMockConnectionFactory(); useConnectionFactory(mockConnection); return mockConnection; } else { throw new IllegalArgumentException("Can not call expectCall twice. You have to call reset before each test. If you need simulate multiple requests, please call andReturn several times."); } } public synchronized static void reset() { connectionFactory = null; } public static void useConnectionFactory(ConnectionFactory connectionFactory) { StaticConnectionFactory.connectionFactory = connectionFactory; } protected synchronized static ConnectionFactory getConnectionFactory() { return connectionFactory; } public synchronized static RequestRecorder getRequestRecorder() { if (connectionFactory instanceof RequestRecorder) { return (RequestRecorder)connectionFactory; } else if (connectionFactory!=null) {
throw new MockSocketException("Connection factory "+connectionFactory.getClass()+" is not instance of "+RequestRecorder.class);
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/UniversalMockRecorder.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockResultRecorder.java // public interface MatcherBasedMockResultRecorder { // // /** // * When the condition is met, return this data. // * @param data // * @return // */ // MatcherBasedMockRecorder thenReturn(SocketData data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/sequential/SequentialMockRecorder.java // public interface SequentialMockRecorder { // public SequentialMockRecorder andReturn(SocketData data); // }
import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.connection.matcher.MatcherBasedMockResultRecorder; import net.javacrumbs.mocksocket.connection.sequential.SequentialMockRecorder; import org.hamcrest.Matcher;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection; /** * Can record both sequential and matcher based mocks. * @author Lukas Krecan * */ public interface UniversalMockRecorder { public SequentialMockRecorder andReturn(SocketData data);
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockResultRecorder.java // public interface MatcherBasedMockResultRecorder { // // /** // * When the condition is met, return this data. // * @param data // * @return // */ // MatcherBasedMockRecorder thenReturn(SocketData data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/sequential/SequentialMockRecorder.java // public interface SequentialMockRecorder { // public SequentialMockRecorder andReturn(SocketData data); // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/UniversalMockRecorder.java import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.connection.matcher.MatcherBasedMockResultRecorder; import net.javacrumbs.mocksocket.connection.sequential.SequentialMockRecorder; import org.hamcrest.Matcher; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection; /** * Can record both sequential and matcher based mocks. * @author Lukas Krecan * */ public interface UniversalMockRecorder { public SequentialMockRecorder andReturn(SocketData data);
public MatcherBasedMockResultRecorder andWhenRequest(Matcher<RequestSocketData> matcher);
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/UniversalMockRecorder.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockResultRecorder.java // public interface MatcherBasedMockResultRecorder { // // /** // * When the condition is met, return this data. // * @param data // * @return // */ // MatcherBasedMockRecorder thenReturn(SocketData data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/sequential/SequentialMockRecorder.java // public interface SequentialMockRecorder { // public SequentialMockRecorder andReturn(SocketData data); // }
import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.connection.matcher.MatcherBasedMockResultRecorder; import net.javacrumbs.mocksocket.connection.sequential.SequentialMockRecorder; import org.hamcrest.Matcher;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection; /** * Can record both sequential and matcher based mocks. * @author Lukas Krecan * */ public interface UniversalMockRecorder { public SequentialMockRecorder andReturn(SocketData data);
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockResultRecorder.java // public interface MatcherBasedMockResultRecorder { // // /** // * When the condition is met, return this data. // * @param data // * @return // */ // MatcherBasedMockRecorder thenReturn(SocketData data); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/sequential/SequentialMockRecorder.java // public interface SequentialMockRecorder { // public SequentialMockRecorder andReturn(SocketData data); // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/UniversalMockRecorder.java import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.connection.matcher.MatcherBasedMockResultRecorder; import net.javacrumbs.mocksocket.connection.sequential.SequentialMockRecorder; import org.hamcrest.Matcher; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection; /** * Can record both sequential and matcher based mocks. * @author Lukas Krecan * */ public interface UniversalMockRecorder { public SequentialMockRecorder andReturn(SocketData data);
public MatcherBasedMockResultRecorder andWhenRequest(Matcher<RequestSocketData> matcher);
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockConnectionFactory.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java // public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { // // private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); // private int actualConnection = -1; // // public synchronized Connection createConnection(String address) { // actualConnection++; // requestData.add(createRequestSocket(address)); // // return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); // } // // protected OutputSocketData createRequestSocket(String address) { // return new OutputSocketData(address); // } // // protected abstract InputStream createInputStream(); // // protected synchronized OutputSocketData getRequestSocketData() { // return requestData.get(actualConnection); // } // // public synchronized List<RequestSocketData> requestData() { // return new ArrayList<RequestSocketData>(requestData); // } // // protected synchronized int getActualConnection() { // return actualConnection; // } // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java // public interface RequestRecorder { // public List<RequestSocketData> requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // }
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory; import net.javacrumbs.mocksocket.connection.RequestRecorder; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import org.hamcrest.Matcher;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.matcher; /** * Mock connection that is based on {@link Matcher}s. * @author Lukas Krecan * */ public class MatcherBasedMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, MatcherBasedMockResultRecorder, MatcherBasedMockRecorder { private final List<MatcherWithData> matchers = new ArrayList<MatcherWithData>(); protected InputStream createInputStream() { return new RedirectingInputStream(getRequestSocketData()); }
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java // public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { // // private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); // private int actualConnection = -1; // // public synchronized Connection createConnection(String address) { // actualConnection++; // requestData.add(createRequestSocket(address)); // // return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); // } // // protected OutputSocketData createRequestSocket(String address) { // return new OutputSocketData(address); // } // // protected abstract InputStream createInputStream(); // // protected synchronized OutputSocketData getRequestSocketData() { // return requestData.get(actualConnection); // } // // public synchronized List<RequestSocketData> requestData() { // return new ArrayList<RequestSocketData>(requestData); // } // // protected synchronized int getActualConnection() { // return actualConnection; // } // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java // public interface RequestRecorder { // public List<RequestSocketData> requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockConnectionFactory.java import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory; import net.javacrumbs.mocksocket.connection.RequestRecorder; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import org.hamcrest.Matcher; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.matcher; /** * Mock connection that is based on {@link Matcher}s. * @author Lukas Krecan * */ public class MatcherBasedMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, MatcherBasedMockResultRecorder, MatcherBasedMockRecorder { private final List<MatcherWithData> matchers = new ArrayList<MatcherWithData>(); protected InputStream createInputStream() { return new RedirectingInputStream(getRequestSocketData()); }
public MatcherBasedMockRecorder thenReturn(SocketData data) {
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockConnectionFactory.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java // public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { // // private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); // private int actualConnection = -1; // // public synchronized Connection createConnection(String address) { // actualConnection++; // requestData.add(createRequestSocket(address)); // // return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); // } // // protected OutputSocketData createRequestSocket(String address) { // return new OutputSocketData(address); // } // // protected abstract InputStream createInputStream(); // // protected synchronized OutputSocketData getRequestSocketData() { // return requestData.get(actualConnection); // } // // public synchronized List<RequestSocketData> requestData() { // return new ArrayList<RequestSocketData>(requestData); // } // // protected synchronized int getActualConnection() { // return actualConnection; // } // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java // public interface RequestRecorder { // public List<RequestSocketData> requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // }
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory; import net.javacrumbs.mocksocket.connection.RequestRecorder; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import org.hamcrest.Matcher;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.matcher; /** * Mock connection that is based on {@link Matcher}s. * @author Lukas Krecan * */ public class MatcherBasedMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, MatcherBasedMockResultRecorder, MatcherBasedMockRecorder { private final List<MatcherWithData> matchers = new ArrayList<MatcherWithData>(); protected InputStream createInputStream() { return new RedirectingInputStream(getRequestSocketData()); } public MatcherBasedMockRecorder thenReturn(SocketData data) { matchers.get(matchers.size()-1).addData(data); return this; }
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java // public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { // // private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); // private int actualConnection = -1; // // public synchronized Connection createConnection(String address) { // actualConnection++; // requestData.add(createRequestSocket(address)); // // return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); // } // // protected OutputSocketData createRequestSocket(String address) { // return new OutputSocketData(address); // } // // protected abstract InputStream createInputStream(); // // protected synchronized OutputSocketData getRequestSocketData() { // return requestData.get(actualConnection); // } // // public synchronized List<RequestSocketData> requestData() { // return new ArrayList<RequestSocketData>(requestData); // } // // protected synchronized int getActualConnection() { // return actualConnection; // } // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java // public interface RequestRecorder { // public List<RequestSocketData> requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockConnectionFactory.java import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory; import net.javacrumbs.mocksocket.connection.RequestRecorder; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import org.hamcrest.Matcher; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.matcher; /** * Mock connection that is based on {@link Matcher}s. * @author Lukas Krecan * */ public class MatcherBasedMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, MatcherBasedMockResultRecorder, MatcherBasedMockRecorder { private final List<MatcherWithData> matchers = new ArrayList<MatcherWithData>(); protected InputStream createInputStream() { return new RedirectingInputStream(getRequestSocketData()); } public MatcherBasedMockRecorder thenReturn(SocketData data) { matchers.get(matchers.size()-1).addData(data); return this; }
public MatcherBasedMockResultRecorder andWhenRequest(Matcher<RequestSocketData> matcher) {
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockConnectionFactory.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java // public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { // // private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); // private int actualConnection = -1; // // public synchronized Connection createConnection(String address) { // actualConnection++; // requestData.add(createRequestSocket(address)); // // return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); // } // // protected OutputSocketData createRequestSocket(String address) { // return new OutputSocketData(address); // } // // protected abstract InputStream createInputStream(); // // protected synchronized OutputSocketData getRequestSocketData() { // return requestData.get(actualConnection); // } // // public synchronized List<RequestSocketData> requestData() { // return new ArrayList<RequestSocketData>(requestData); // } // // protected synchronized int getActualConnection() { // return actualConnection; // } // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java // public interface RequestRecorder { // public List<RequestSocketData> requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // }
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory; import net.javacrumbs.mocksocket.connection.RequestRecorder; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import org.hamcrest.Matcher;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.matcher; /** * Mock connection that is based on {@link Matcher}s. * @author Lukas Krecan * */ public class MatcherBasedMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, MatcherBasedMockResultRecorder, MatcherBasedMockRecorder { private final List<MatcherWithData> matchers = new ArrayList<MatcherWithData>(); protected InputStream createInputStream() { return new RedirectingInputStream(getRequestSocketData()); } public MatcherBasedMockRecorder thenReturn(SocketData data) { matchers.get(matchers.size()-1).addData(data); return this; } public MatcherBasedMockResultRecorder andWhenRequest(Matcher<RequestSocketData> matcher) { matchers.add(new MatcherWithData(matcher)); return this; } /** * Input stream that redirects to actual InputStread based on OutputStreamData. Has to be done this way since InputStram could be created before * OutputStream data are written. * @author Lukas Krecan * */ class RedirectingInputStream extends InputStream { private final RequestSocketData requestSocketData; private InputStream wrappedInputStream; public RedirectingInputStream(RequestSocketData requestSocketData) { this.requestSocketData = requestSocketData; } @Override public int read() throws IOException { if (wrappedInputStream==null) { wrappedInputStream = findInputStream(); } return wrappedInputStream.read(); }
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java // public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { // // private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); // private int actualConnection = -1; // // public synchronized Connection createConnection(String address) { // actualConnection++; // requestData.add(createRequestSocket(address)); // // return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); // } // // protected OutputSocketData createRequestSocket(String address) { // return new OutputSocketData(address); // } // // protected abstract InputStream createInputStream(); // // protected synchronized OutputSocketData getRequestSocketData() { // return requestData.get(actualConnection); // } // // public synchronized List<RequestSocketData> requestData() { // return new ArrayList<RequestSocketData>(requestData); // } // // protected synchronized int getActualConnection() { // return actualConnection; // } // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java // public interface RequestRecorder { // public List<RequestSocketData> requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockConnectionFactory.java import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory; import net.javacrumbs.mocksocket.connection.RequestRecorder; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import org.hamcrest.Matcher; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.matcher; /** * Mock connection that is based on {@link Matcher}s. * @author Lukas Krecan * */ public class MatcherBasedMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, MatcherBasedMockResultRecorder, MatcherBasedMockRecorder { private final List<MatcherWithData> matchers = new ArrayList<MatcherWithData>(); protected InputStream createInputStream() { return new RedirectingInputStream(getRequestSocketData()); } public MatcherBasedMockRecorder thenReturn(SocketData data) { matchers.get(matchers.size()-1).addData(data); return this; } public MatcherBasedMockResultRecorder andWhenRequest(Matcher<RequestSocketData> matcher) { matchers.add(new MatcherWithData(matcher)); return this; } /** * Input stream that redirects to actual InputStread based on OutputStreamData. Has to be done this way since InputStram could be created before * OutputStream data are written. * @author Lukas Krecan * */ class RedirectingInputStream extends InputStream { private final RequestSocketData requestSocketData; private InputStream wrappedInputStream; public RedirectingInputStream(RequestSocketData requestSocketData) { this.requestSocketData = requestSocketData; } @Override public int read() throws IOException { if (wrappedInputStream==null) { wrappedInputStream = findInputStream(); } return wrappedInputStream.read(); }
private InputStream findInputStream() throws IOException, MockSocketException {
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java // public class OutputSocketData implements RequestSocketData { // // private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // private final String address; // // public OutputSocketData(String address) { // this.address = address; // } // // public InputStream getData() { // return new ByteArrayInputStream(getDataAsBytes()); // } // // protected byte[] getDataAsBytes() // { // return outputStream.toByteArray(); // } // // public OutputStream getOutputStream() { // return outputStream; // } // // public String getAddress() { // return address; // } // // @Override // public String toString() { // return StringUtils.convertDataToString(getDataAsBytes()); // } // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // }
import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.connection.data.OutputSocketData; import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection; /** * Common code for creating MockConnections. * @author Lukas Krecan * */ public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); private int actualConnection = -1; public synchronized Connection createConnection(String address) { actualConnection++; requestData.add(createRequestSocket(address)); return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); } protected OutputSocketData createRequestSocket(String address) { return new OutputSocketData(address); } protected abstract InputStream createInputStream(); protected synchronized OutputSocketData getRequestSocketData() { return requestData.get(actualConnection); }
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java // public class OutputSocketData implements RequestSocketData { // // private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // private final String address; // // public OutputSocketData(String address) { // this.address = address; // } // // public InputStream getData() { // return new ByteArrayInputStream(getDataAsBytes()); // } // // protected byte[] getDataAsBytes() // { // return outputStream.toByteArray(); // } // // public OutputStream getOutputStream() { // return outputStream; // } // // public String getAddress() { // return address; // } // // @Override // public String toString() { // return StringUtils.convertDataToString(getDataAsBytes()); // } // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java // public interface RequestSocketData extends SocketData{ // // public String getAddress(); // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.connection.data.OutputSocketData; import net.javacrumbs.mocksocket.connection.data.RequestSocketData; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection; /** * Common code for creating MockConnections. * @author Lukas Krecan * */ public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); private int actualConnection = -1; public synchronized Connection createConnection(String address) { actualConnection++; requestData.add(createRequestSocket(address)); return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); } protected OutputSocketData createRequestSocket(String address) { return new OutputSocketData(address); } protected abstract InputStream createInputStream(); protected synchronized OutputSocketData getRequestSocketData() { return requestData.get(actualConnection); }
public synchronized List<RequestSocketData> requestData() {
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/sequential/SequentialMockConnectionFactory.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java // public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { // // private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); // private int actualConnection = -1; // // public synchronized Connection createConnection(String address) { // actualConnection++; // requestData.add(createRequestSocket(address)); // // return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); // } // // protected OutputSocketData createRequestSocket(String address) { // return new OutputSocketData(address); // } // // protected abstract InputStream createInputStream(); // // protected synchronized OutputSocketData getRequestSocketData() { // return requestData.get(actualConnection); // } // // public synchronized List<RequestSocketData> requestData() { // return new ArrayList<RequestSocketData>(requestData); // } // // protected synchronized int getActualConnection() { // return actualConnection; // } // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java // public interface RequestRecorder { // public List<RequestSocketData> requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // }
import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory; import net.javacrumbs.mocksocket.connection.RequestRecorder; import net.javacrumbs.mocksocket.connection.data.SocketData;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.sequential; /** * Mock connection. Can simulate multiple requests to the same address. * @author Lukas Krecan * */ public class SequentialMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, SequentialMockRecorder{ private final List<SocketData> responseData = new ArrayList<SocketData>(); public SequentialMockConnectionFactory() { } public SequentialMockRecorder andReturn(SocketData data) { this.responseData.add(data); return this; } protected InputStream createInputStream() { int actualConnection = getActualConnection(); if (responseData.size()>actualConnection ) { return responseData.get(actualConnection).getData(); } else {
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java // public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory { // // private final List<OutputSocketData> requestData = new ArrayList<OutputSocketData>(); // private int actualConnection = -1; // // public synchronized Connection createConnection(String address) { // actualConnection++; // requestData.add(createRequestSocket(address)); // // return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream()); // } // // protected OutputSocketData createRequestSocket(String address) { // return new OutputSocketData(address); // } // // protected abstract InputStream createInputStream(); // // protected synchronized OutputSocketData getRequestSocketData() { // return requestData.get(actualConnection); // } // // public synchronized List<RequestSocketData> requestData() { // return new ArrayList<RequestSocketData>(requestData); // } // // protected synchronized int getActualConnection() { // return actualConnection; // } // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java // public interface RequestRecorder { // public List<RequestSocketData> requestData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/sequential/SequentialMockConnectionFactory.java import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.javacrumbs.mocksocket.MockSocketException; import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory; import net.javacrumbs.mocksocket.connection.RequestRecorder; import net.javacrumbs.mocksocket.connection.data.SocketData; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.sequential; /** * Mock connection. Can simulate multiple requests to the same address. * @author Lukas Krecan * */ public class SequentialMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, SequentialMockRecorder{ private final List<SocketData> responseData = new ArrayList<SocketData>(); public SequentialMockConnectionFactory() { } public SequentialMockRecorder andReturn(SocketData data) { this.responseData.add(data); return this; } protected InputStream createInputStream() { int actualConnection = getActualConnection(); if (responseData.size()>actualConnection ) { return responseData.get(actualConnection).getData(); } else {
throw new MockSocketException("No more connections expected. Requests recorded so far are: "+requestData());
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/socket/MockSocketImplFactory.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/ConnectionFactory.java // public interface ConnectionFactory { // // Connection createConnection(String address); // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/ConnectionFactoryMockSocketImpl.java // public class ConnectionFactoryMockSocketImpl extends AbstractMockSocketImpl { // private final ConnectionFactory connectionFactory; // private Connection connection; // // public ConnectionFactoryMockSocketImpl(ConnectionFactory connectionFactory) { // this.connectionFactory = connectionFactory; // } // // @Override // protected void onConnect(String address) { // connection = connectionFactory.createConnection(address); // } // // @Override // protected InputStream getInputStream() throws IOException { // assertConnection(); // return connection.getInputStream(); // } // // @Override // protected OutputStream getOutputStream() throws IOException { // assertConnection(); // return connection.getOutputStream(); // } // // private void assertConnection() { // if (connection == null) // { // throw new IllegalStateException("Connection is not open"); // } // // } // // }
import java.net.SocketImpl; import java.net.SocketImplFactory; import net.javacrumbs.mocksocket.connection.ConnectionFactory; import net.javacrumbs.mocksocket.connection.ConnectionFactoryMockSocketImpl;
/** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.socket; public class MockSocketImplFactory implements SocketImplFactory { private final ConnectionFactory connectionFactory; public MockSocketImplFactory(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public SocketImpl createSocketImpl() {
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/ConnectionFactory.java // public interface ConnectionFactory { // // Connection createConnection(String address); // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/ConnectionFactoryMockSocketImpl.java // public class ConnectionFactoryMockSocketImpl extends AbstractMockSocketImpl { // private final ConnectionFactory connectionFactory; // private Connection connection; // // public ConnectionFactoryMockSocketImpl(ConnectionFactory connectionFactory) { // this.connectionFactory = connectionFactory; // } // // @Override // protected void onConnect(String address) { // connection = connectionFactory.createConnection(address); // } // // @Override // protected InputStream getInputStream() throws IOException { // assertConnection(); // return connection.getInputStream(); // } // // @Override // protected OutputStream getOutputStream() throws IOException { // assertConnection(); // return connection.getOutputStream(); // } // // private void assertConnection() { // if (connection == null) // { // throw new IllegalStateException("Connection is not open"); // } // // } // // } // Path: core/src/main/java/net/javacrumbs/mocksocket/socket/MockSocketImplFactory.java import java.net.SocketImpl; import java.net.SocketImplFactory; import net.javacrumbs.mocksocket.connection.ConnectionFactory; import net.javacrumbs.mocksocket.connection.ConnectionFactoryMockSocketImpl; /** * Copyright 2009-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.socket; public class MockSocketImplFactory implements SocketImplFactory { private final ConnectionFactory connectionFactory; public MockSocketImplFactory(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public SocketImpl createSocketImpl() {
return new ConnectionFactoryMockSocketImpl(connectionFactory);
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/connection/data/DefaultSocketData.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/StringUtils.java // public class StringUtils { // private static boolean printDataAsString = true; // // private static String defaultEncoding = "UTF-8"; // // public static synchronized boolean isPrintDataAsString() { // return printDataAsString; // } // // /** // * Should be data printed as string or as byte array. // * @param printDataAsString // */ // public static synchronized void setPrintDataAsString(boolean printDataAsString) { // StringUtils.printDataAsString = printDataAsString; // } // // public static synchronized String getDefaultEncoding() { // return defaultEncoding; // } // // public static synchronized void setDefaultEncoding(String defaultEncoding) { // StringUtils.defaultEncoding = defaultEncoding; // } // // public static String convertDataToString(byte[] data) { // if (printDataAsString) // { // try { // return new String(data, defaultEncoding); // } catch (UnsupportedEncodingException e) { // return new String(data); // } // } // else // { // return Arrays.toString(data); // } // } // }
import java.io.ByteArrayInputStream; import java.io.InputStream; import net.javacrumbs.mocksocket.connection.StringUtils;
/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.data; /** * Wraps socket data. * @author Lukas Krecan * */ public class DefaultSocketData implements SocketData { protected final byte[] data; public DefaultSocketData(byte[] data) { this.data = data.clone(); } public InputStream getData() { return new ByteArrayInputStream(data); } @Override public String toString() {
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/StringUtils.java // public class StringUtils { // private static boolean printDataAsString = true; // // private static String defaultEncoding = "UTF-8"; // // public static synchronized boolean isPrintDataAsString() { // return printDataAsString; // } // // /** // * Should be data printed as string or as byte array. // * @param printDataAsString // */ // public static synchronized void setPrintDataAsString(boolean printDataAsString) { // StringUtils.printDataAsString = printDataAsString; // } // // public static synchronized String getDefaultEncoding() { // return defaultEncoding; // } // // public static synchronized void setDefaultEncoding(String defaultEncoding) { // StringUtils.defaultEncoding = defaultEncoding; // } // // public static String convertDataToString(byte[] data) { // if (printDataAsString) // { // try { // return new String(data, defaultEncoding); // } catch (UnsupportedEncodingException e) { // return new String(data); // } // } // else // { // return Arrays.toString(data); // } // } // } // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/DefaultSocketData.java import java.io.ByteArrayInputStream; import java.io.InputStream; import net.javacrumbs.mocksocket.connection.StringUtils; /* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.connection.data; /** * Wraps socket data. * @author Lukas Krecan * */ public class DefaultSocketData implements SocketData { protected final byte[] data; public DefaultSocketData(byte[] data) { this.data = data.clone(); } public InputStream getData() { return new ByteArrayInputStream(data); } @Override public String toString() {
return StringUtils.convertDataToString(data);
lukas-krecan/mock-socket
core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // }
import java.io.IOException; import java.io.InputStream; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.commons.io.IOUtils;
/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.util; public class Utils { private Utils() { //empty } public static final byte[] toByteArray(InputStream stream) { try { return IOUtils.toByteArray(stream); } catch (IOException e) {
// Path: core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java // public class MockSocketException extends RuntimeException { // private static final long serialVersionUID = -6476984055059688027L; // // public MockSocketException(String message, Throwable cause) { // super(message, cause); // } // // public MockSocketException(String message) { // super(message); // } // // public MockSocketException(Throwable cause) { // super(cause); // } // // // } // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java import java.io.IOException; import java.io.InputStream; import net.javacrumbs.mocksocket.MockSocketException; import org.apache.commons.io.IOUtils; /* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.util; public class Utils { private Utils() { //empty } public static final byte[] toByteArray(InputStream stream) { try { return IOUtils.toByteArray(stream); } catch (IOException e) {
throw new MockSocketException("Can not read data.",e);
lukas-krecan/mock-socket
http/src/main/java/net/javacrumbs/mocksocket/http/HttpParser.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java // public class OutputSocketData implements RequestSocketData { // // private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // private final String address; // // public OutputSocketData(String address) { // this.address = address; // } // // public InputStream getData() { // return new ByteArrayInputStream(getDataAsBytes()); // } // // protected byte[] getDataAsBytes() // { // return outputStream.toByteArray(); // } // // public OutputStream getOutputStream() { // return outputStream; // } // // public String getAddress() { // return address; // } // // @Override // public String toString() { // return StringUtils.convertDataToString(getDataAsBytes()); // } // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java // public class Utils { // private Utils() // { // //empty // } // // public static final byte[] toByteArray(InputStream stream) // { // try // { // return IOUtils.toByteArray(stream); // } // catch (IOException e) // { // throw new MockSocketException("Can not read data.",e); // } // finally // { // IOUtils.closeQuietly(stream); // } // } // }
import org.eclipse.jetty.testing.HttpTester; import org.eclipse.jetty.util.ByteArrayOutputStream2; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import net.javacrumbs.mocksocket.connection.data.OutputSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.util.Utils; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.View;
/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class HttpParser implements HttpRequest { private final HttpTester httpTester;
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java // public class OutputSocketData implements RequestSocketData { // // private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // private final String address; // // public OutputSocketData(String address) { // this.address = address; // } // // public InputStream getData() { // return new ByteArrayInputStream(getDataAsBytes()); // } // // protected byte[] getDataAsBytes() // { // return outputStream.toByteArray(); // } // // public OutputStream getOutputStream() { // return outputStream; // } // // public String getAddress() { // return address; // } // // @Override // public String toString() { // return StringUtils.convertDataToString(getDataAsBytes()); // } // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java // public class Utils { // private Utils() // { // //empty // } // // public static final byte[] toByteArray(InputStream stream) // { // try // { // return IOUtils.toByteArray(stream); // } // catch (IOException e) // { // throw new MockSocketException("Can not read data.",e); // } // finally // { // IOUtils.closeQuietly(stream); // } // } // } // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpParser.java import org.eclipse.jetty.testing.HttpTester; import org.eclipse.jetty.util.ByteArrayOutputStream2; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import net.javacrumbs.mocksocket.connection.data.OutputSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.util.Utils; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.View; /* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.mocksocket.http; public class HttpParser implements HttpRequest { private final HttpTester httpTester;
private final SocketData socketData;
lukas-krecan/mock-socket
http/src/main/java/net/javacrumbs/mocksocket/http/HttpParser.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java // public class OutputSocketData implements RequestSocketData { // // private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // private final String address; // // public OutputSocketData(String address) { // this.address = address; // } // // public InputStream getData() { // return new ByteArrayInputStream(getDataAsBytes()); // } // // protected byte[] getDataAsBytes() // { // return outputStream.toByteArray(); // } // // public OutputStream getOutputStream() { // return outputStream; // } // // public String getAddress() { // return address; // } // // @Override // public String toString() { // return StringUtils.convertDataToString(getDataAsBytes()); // } // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java // public class Utils { // private Utils() // { // //empty // } // // public static final byte[] toByteArray(InputStream stream) // { // try // { // return IOUtils.toByteArray(stream); // } // catch (IOException e) // { // throw new MockSocketException("Can not read data.",e); // } // finally // { // IOUtils.closeQuietly(stream); // } // } // }
import org.eclipse.jetty.testing.HttpTester; import org.eclipse.jetty.util.ByteArrayOutputStream2; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import net.javacrumbs.mocksocket.connection.data.OutputSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.util.Utils; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.View;
@SuppressWarnings("unchecked") public List<String> getHeaderNames() { return Collections.list(httpTester.getHeaderNames()); } public long getLongHeader(String name) throws NumberFormatException { return httpTester.getLongHeader(name); } public String getHeader(String name) { return httpTester.getHeader(name); } @SuppressWarnings("unchecked") public List<String> getHeaderValues(String name) { return Collections.list(httpTester.getHeaderValues(name)); } public String getContent() { return httpTester.getContent(); } public InputStream getData() { return socketData.getData(); } /** * Returns address to which the request was sent to or null. */ public String getAddress() {
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java // public class OutputSocketData implements RequestSocketData { // // private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // private final String address; // // public OutputSocketData(String address) { // this.address = address; // } // // public InputStream getData() { // return new ByteArrayInputStream(getDataAsBytes()); // } // // protected byte[] getDataAsBytes() // { // return outputStream.toByteArray(); // } // // public OutputStream getOutputStream() { // return outputStream; // } // // public String getAddress() { // return address; // } // // @Override // public String toString() { // return StringUtils.convertDataToString(getDataAsBytes()); // } // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java // public class Utils { // private Utils() // { // //empty // } // // public static final byte[] toByteArray(InputStream stream) // { // try // { // return IOUtils.toByteArray(stream); // } // catch (IOException e) // { // throw new MockSocketException("Can not read data.",e); // } // finally // { // IOUtils.closeQuietly(stream); // } // } // } // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpParser.java import org.eclipse.jetty.testing.HttpTester; import org.eclipse.jetty.util.ByteArrayOutputStream2; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import net.javacrumbs.mocksocket.connection.data.OutputSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.util.Utils; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.View; @SuppressWarnings("unchecked") public List<String> getHeaderNames() { return Collections.list(httpTester.getHeaderNames()); } public long getLongHeader(String name) throws NumberFormatException { return httpTester.getLongHeader(name); } public String getHeader(String name) { return httpTester.getHeader(name); } @SuppressWarnings("unchecked") public List<String> getHeaderValues(String name) { return Collections.list(httpTester.getHeaderValues(name)); } public String getContent() { return httpTester.getContent(); } public InputStream getData() { return socketData.getData(); } /** * Returns address to which the request was sent to or null. */ public String getAddress() {
if (socketData instanceof OutputSocketData)
lukas-krecan/mock-socket
http/src/main/java/net/javacrumbs/mocksocket/http/HttpParser.java
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java // public class OutputSocketData implements RequestSocketData { // // private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // private final String address; // // public OutputSocketData(String address) { // this.address = address; // } // // public InputStream getData() { // return new ByteArrayInputStream(getDataAsBytes()); // } // // protected byte[] getDataAsBytes() // { // return outputStream.toByteArray(); // } // // public OutputStream getOutputStream() { // return outputStream; // } // // public String getAddress() { // return address; // } // // @Override // public String toString() { // return StringUtils.convertDataToString(getDataAsBytes()); // } // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java // public class Utils { // private Utils() // { // //empty // } // // public static final byte[] toByteArray(InputStream stream) // { // try // { // return IOUtils.toByteArray(stream); // } // catch (IOException e) // { // throw new MockSocketException("Can not read data.",e); // } // finally // { // IOUtils.closeQuietly(stream); // } // } // }
import org.eclipse.jetty.testing.HttpTester; import org.eclipse.jetty.util.ByteArrayOutputStream2; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import net.javacrumbs.mocksocket.connection.data.OutputSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.util.Utils; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.View;
} public InputStream getData() { return socketData.getData(); } /** * Returns address to which the request was sent to or null. */ public String getAddress() { if (socketData instanceof OutputSocketData) { return ((OutputSocketData) socketData).getAddress(); } else { return null; } } /** * HttpTester that can parse byte[]. * @author Lukas Krecan * */ private static class ExtendedHttpTester extends HttpTester { private String _charset; public String parse(InputStream data) throws IOException {
// Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java // public class OutputSocketData implements RequestSocketData { // // private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // private final String address; // // public OutputSocketData(String address) { // this.address = address; // } // // public InputStream getData() { // return new ByteArrayInputStream(getDataAsBytes()); // } // // protected byte[] getDataAsBytes() // { // return outputStream.toByteArray(); // } // // public OutputStream getOutputStream() { // return outputStream; // } // // public String getAddress() { // return address; // } // // @Override // public String toString() { // return StringUtils.convertDataToString(getDataAsBytes()); // } // // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java // public interface SocketData { // // public InputStream getData(); // } // // Path: core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java // public class Utils { // private Utils() // { // //empty // } // // public static final byte[] toByteArray(InputStream stream) // { // try // { // return IOUtils.toByteArray(stream); // } // catch (IOException e) // { // throw new MockSocketException("Can not read data.",e); // } // finally // { // IOUtils.closeQuietly(stream); // } // } // } // Path: http/src/main/java/net/javacrumbs/mocksocket/http/HttpParser.java import org.eclipse.jetty.testing.HttpTester; import org.eclipse.jetty.util.ByteArrayOutputStream2; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import net.javacrumbs.mocksocket.connection.data.OutputSocketData; import net.javacrumbs.mocksocket.connection.data.SocketData; import net.javacrumbs.mocksocket.util.Utils; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.View; } public InputStream getData() { return socketData.getData(); } /** * Returns address to which the request was sent to or null. */ public String getAddress() { if (socketData instanceof OutputSocketData) { return ((OutputSocketData) socketData).getAddress(); } else { return null; } } /** * HttpTester that can parse byte[]. * @author Lukas Krecan * */ private static class ExtendedHttpTester extends HttpTester { private String _charset; public String parse(InputStream data) throws IOException {
Buffer buf = new ByteArrayBuffer(Utils.toByteArray(data));
pierre/ning-service-skeleton
base/src/main/java/com/ning/jetty/base/modules/ServerModuleBuilder.java
// Path: core/src/main/java/com/ning/jetty/core/modules/ServerModule.java // public class ServerModule extends ServletModule // { // protected Multibinder<HealthCheck> healthChecksBinder; // // @Override // public void configureServlets() // { // installJackson(); // installJMX(); // installStats(); // } // // protected void installJackson() // { // final ObjectMapper mapper = getJacksonProvider().get(); // // bind(ObjectMapper.class).toInstance(mapper); // bind(JacksonJsonProvider.class) // .toInstance(new JacksonJsonProvider(mapper, new Annotations[]{Annotations.JACKSON, Annotations.JAXB})); // } // // /** // * Override this method to provide your own Jackson provider. // * // * @return ObjectMapper provider for Jackson // */ // protected Provider<ObjectMapper> getJacksonProvider() // { // return new Provider<ObjectMapper>() // { // @Override // public ObjectMapper get() // { // final ObjectMapper mapper = new ObjectMapper(); // mapper.registerModule(new JodaModule()); // mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // return mapper; // } // }; // } // // protected void installJMX() // { // final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); // binder().bind(MBeanServer.class).toInstance(mBeanServer); // // install(new MBeanModule()); // } // // protected void installStats() // { // // Codahale's metrics // install(new InstrumentationModule()); // // // Healthchecks // healthChecksBinder = Multibinder.newSetBinder(binder(), HealthCheck.class); // install(new AdminServletModule("/1.0/healthcheck", "/1.0/metrics", "/1.0/ping", "/1.0/threads")); // // // Metrics/Jersey integration // install(new TimedResourceModule()); // } // }
import java.util.Map; import com.ning.jetty.core.modules.ServerModule; import com.google.common.collect.Maps; import com.google.inject.Module; import com.yammer.metrics.core.HealthCheck; import org.skife.config.ConfigSource; import org.skife.config.SimplePropertyConfigSource; import javax.servlet.Filter; import javax.servlet.http.HttpServlet; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
public ServerModuleBuilder addServlet(final String urlPattern, final Class<? extends HttpServlet> filterKey) { this.servlets.put(urlPattern, filterKey); return this; } public ServerModuleBuilder addServletRegex(final String urlPattern, final Class<? extends HttpServlet> filterKey) { this.servletsRegex.put(urlPattern, filterKey); return this; } public ServerModuleBuilder addJerseyServlet(final String urlPattern, final Class<? extends HttpServlet> filterKey) { this.jaxRSServlets.put(urlPattern, filterKey); return this; } public ServerModuleBuilder addJerseyServletRegex(final String urlPattern, final Class<? extends HttpServlet> filterKey) { this.jaxRSServletsRegex.put(urlPattern, filterKey); return this; } public void setJaxRSImplementation(final JaxRSImplementation jaxRSImplementation) { this.jaxRSImplementation = jaxRSImplementation; }
// Path: core/src/main/java/com/ning/jetty/core/modules/ServerModule.java // public class ServerModule extends ServletModule // { // protected Multibinder<HealthCheck> healthChecksBinder; // // @Override // public void configureServlets() // { // installJackson(); // installJMX(); // installStats(); // } // // protected void installJackson() // { // final ObjectMapper mapper = getJacksonProvider().get(); // // bind(ObjectMapper.class).toInstance(mapper); // bind(JacksonJsonProvider.class) // .toInstance(new JacksonJsonProvider(mapper, new Annotations[]{Annotations.JACKSON, Annotations.JAXB})); // } // // /** // * Override this method to provide your own Jackson provider. // * // * @return ObjectMapper provider for Jackson // */ // protected Provider<ObjectMapper> getJacksonProvider() // { // return new Provider<ObjectMapper>() // { // @Override // public ObjectMapper get() // { // final ObjectMapper mapper = new ObjectMapper(); // mapper.registerModule(new JodaModule()); // mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // return mapper; // } // }; // } // // protected void installJMX() // { // final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); // binder().bind(MBeanServer.class).toInstance(mBeanServer); // // install(new MBeanModule()); // } // // protected void installStats() // { // // Codahale's metrics // install(new InstrumentationModule()); // // // Healthchecks // healthChecksBinder = Multibinder.newSetBinder(binder(), HealthCheck.class); // install(new AdminServletModule("/1.0/healthcheck", "/1.0/metrics", "/1.0/ping", "/1.0/threads")); // // // Metrics/Jersey integration // install(new TimedResourceModule()); // } // } // Path: base/src/main/java/com/ning/jetty/base/modules/ServerModuleBuilder.java import java.util.Map; import com.ning.jetty.core.modules.ServerModule; import com.google.common.collect.Maps; import com.google.inject.Module; import com.yammer.metrics.core.HealthCheck; import org.skife.config.ConfigSource; import org.skife.config.SimplePropertyConfigSource; import javax.servlet.Filter; import javax.servlet.http.HttpServlet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public ServerModuleBuilder addServlet(final String urlPattern, final Class<? extends HttpServlet> filterKey) { this.servlets.put(urlPattern, filterKey); return this; } public ServerModuleBuilder addServletRegex(final String urlPattern, final Class<? extends HttpServlet> filterKey) { this.servletsRegex.put(urlPattern, filterKey); return this; } public ServerModuleBuilder addJerseyServlet(final String urlPattern, final Class<? extends HttpServlet> filterKey) { this.jaxRSServlets.put(urlPattern, filterKey); return this; } public ServerModuleBuilder addJerseyServletRegex(final String urlPattern, final Class<? extends HttpServlet> filterKey) { this.jaxRSServletsRegex.put(urlPattern, filterKey); return this; } public void setJaxRSImplementation(final JaxRSImplementation jaxRSImplementation) { this.jaxRSImplementation = jaxRSImplementation; }
public ServerModule build()
pierre/ning-service-skeleton
jdbi/src/main/java/com/ning/jetty/jdbi/guice/providers/DBIProvider.java
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // }
import java.util.concurrent.TimeUnit; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.TimingCollector; import org.skife.jdbi.v2.tweak.SQLLog; import com.google.inject.Inject; import com.google.inject.Provider; import com.jolbox.bonecp.BoneCPConfig; import com.jolbox.bonecp.BoneCPDataSource; import com.ning.jetty.jdbi.config.DaoConfig; import com.yammer.metrics.core.MetricsRegistry; import com.yammer.metrics.jdbi.InstrumentedTimingCollector; import com.yammer.metrics.jdbi.strategies.BasicSqlNameStrategy;
/* * Copyright 2010-2011 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.guice.providers; public class DBIProvider implements Provider<DBI> { private final MetricsRegistry metricsRegistry;
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // Path: jdbi/src/main/java/com/ning/jetty/jdbi/guice/providers/DBIProvider.java import java.util.concurrent.TimeUnit; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.TimingCollector; import org.skife.jdbi.v2.tweak.SQLLog; import com.google.inject.Inject; import com.google.inject.Provider; import com.jolbox.bonecp.BoneCPConfig; import com.jolbox.bonecp.BoneCPDataSource; import com.ning.jetty.jdbi.config.DaoConfig; import com.yammer.metrics.core.MetricsRegistry; import com.yammer.metrics.jdbi.InstrumentedTimingCollector; import com.yammer.metrics.jdbi.strategies.BasicSqlNameStrategy; /* * Copyright 2010-2011 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.guice.providers; public class DBIProvider implements Provider<DBI> { private final MetricsRegistry metricsRegistry;
private final DaoConfig config;
pierre/ning-service-skeleton
core/src/main/java/com/ning/jetty/core/server/HttpServer.java
// Path: core/src/main/java/com/ning/jetty/core/CoreConfig.java // public interface CoreConfig // { // @Config("com.ning.core.server.ip") // @Default("127.0.0.1") // String getServerHost(); // // @Config("com.ning.core.server.port") // @Default("8080") // int getServerPort(); // // @Config("com.ning.core.server.server.ssl.enabled") // @Default("false") // boolean isSSLEnabled(); // // @Config("com.ning.core.server.server.ssl.port") // @Default("8443") // int getServerSslPort(); // // @Config("com.ning.core.server.jetty.stats") // @Default("true") // boolean isJettyStatsOn(); // // @Config("com.ning.core.server.jetty.ssl.keystore") // @DefaultNull // String getSSLkeystoreLocation(); // // @Config("com.ning.core.server.jetty.ssl.keystore.password") // @DefaultNull // String getSSLkeystorePassword(); // // @Config("com.ning.core.server.jetty.maxThreads") // @Default("2000") // int getMaxThreads(); // // @Config("com.ning.core.server.jetty.minThreads") // @Default("2") // int getMinThreads(); // // @Config("com.ning.core.server.jetty.logPath") // @Default(".logs") // String getLogPath(); // // @Config("com.ning.core.server.jetty.resourceBase") // @DefaultNull // String getResourceBase(); // } // // Path: core/src/main/java/com/ning/jetty/core/listeners/SetupJULBridge.java // public class SetupJULBridge implements ServletContextListener // { // @Override // public void contextInitialized(final ServletContextEvent event) // { // // We first remove the default handler(s) // final Logger rootLogger = LogManager.getLogManager().getLogger(""); // final Handler[] handlers = rootLogger.getHandlers(); // // if (!ArrayUtils.isEmpty(handlers)) { // for (final Handler handler : handlers) { // rootLogger.removeHandler(handler); // } // } // // And then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j // SLF4JBridgeHandler.install(); // } // // @Override // public void contextDestroyed(final ServletContextEvent event) // { // SLF4JBridgeHandler.uninstall(); // } // }
import com.ning.jetty.core.CoreConfig; import com.ning.jetty.core.listeners.SetupJULBridge; import com.google.common.base.Preconditions; import com.google.common.io.Resources; import com.google.inject.servlet.GuiceFilter; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.NCSARequestLog; import org.eclipse.jetty.server.RequestLog; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.RequestLogHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.xml.XmlConfiguration; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.management.MBeanServer; import javax.servlet.DispatcherType; import java.lang.management.ManagementFactory; import java.util.EnumSet; import java.util.EventListener; import java.util.Map;
/* * Copyright 2010-2011 Ning, Inc. * * Ning 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 com.ning.jetty.core.server; /** * Embed Jetty */ public class HttpServer { private final Server server; public HttpServer() { this.server = new Server(); server.setSendServerVersion(false); } public HttpServer(final String jettyXml) throws Exception { this(); configure(jettyXml); } public void configure(final String jettyXml) throws Exception { final XmlConfiguration configuration = new XmlConfiguration(Resources.getResource(jettyXml)); configuration.configure(server); }
// Path: core/src/main/java/com/ning/jetty/core/CoreConfig.java // public interface CoreConfig // { // @Config("com.ning.core.server.ip") // @Default("127.0.0.1") // String getServerHost(); // // @Config("com.ning.core.server.port") // @Default("8080") // int getServerPort(); // // @Config("com.ning.core.server.server.ssl.enabled") // @Default("false") // boolean isSSLEnabled(); // // @Config("com.ning.core.server.server.ssl.port") // @Default("8443") // int getServerSslPort(); // // @Config("com.ning.core.server.jetty.stats") // @Default("true") // boolean isJettyStatsOn(); // // @Config("com.ning.core.server.jetty.ssl.keystore") // @DefaultNull // String getSSLkeystoreLocation(); // // @Config("com.ning.core.server.jetty.ssl.keystore.password") // @DefaultNull // String getSSLkeystorePassword(); // // @Config("com.ning.core.server.jetty.maxThreads") // @Default("2000") // int getMaxThreads(); // // @Config("com.ning.core.server.jetty.minThreads") // @Default("2") // int getMinThreads(); // // @Config("com.ning.core.server.jetty.logPath") // @Default(".logs") // String getLogPath(); // // @Config("com.ning.core.server.jetty.resourceBase") // @DefaultNull // String getResourceBase(); // } // // Path: core/src/main/java/com/ning/jetty/core/listeners/SetupJULBridge.java // public class SetupJULBridge implements ServletContextListener // { // @Override // public void contextInitialized(final ServletContextEvent event) // { // // We first remove the default handler(s) // final Logger rootLogger = LogManager.getLogManager().getLogger(""); // final Handler[] handlers = rootLogger.getHandlers(); // // if (!ArrayUtils.isEmpty(handlers)) { // for (final Handler handler : handlers) { // rootLogger.removeHandler(handler); // } // } // // And then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j // SLF4JBridgeHandler.install(); // } // // @Override // public void contextDestroyed(final ServletContextEvent event) // { // SLF4JBridgeHandler.uninstall(); // } // } // Path: core/src/main/java/com/ning/jetty/core/server/HttpServer.java import com.ning.jetty.core.CoreConfig; import com.ning.jetty.core.listeners.SetupJULBridge; import com.google.common.base.Preconditions; import com.google.common.io.Resources; import com.google.inject.servlet.GuiceFilter; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.NCSARequestLog; import org.eclipse.jetty.server.RequestLog; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.RequestLogHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.xml.XmlConfiguration; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.management.MBeanServer; import javax.servlet.DispatcherType; import java.lang.management.ManagementFactory; import java.util.EnumSet; import java.util.EventListener; import java.util.Map; /* * Copyright 2010-2011 Ning, Inc. * * Ning 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 com.ning.jetty.core.server; /** * Embed Jetty */ public class HttpServer { private final Server server; public HttpServer() { this.server = new Server(); server.setSendServerVersion(false); } public HttpServer(final String jettyXml) throws Exception { this(); configure(jettyXml); } public void configure(final String jettyXml) throws Exception { final XmlConfiguration configuration = new XmlConfiguration(Resources.getResource(jettyXml)); configuration.configure(server); }
public void configure(final CoreConfig config, final Iterable<EventListener> eventListeners, final Map<FilterHolder, String> filterHolders)
pierre/ning-service-skeleton
core/src/main/java/com/ning/jetty/core/server/HttpServer.java
// Path: core/src/main/java/com/ning/jetty/core/CoreConfig.java // public interface CoreConfig // { // @Config("com.ning.core.server.ip") // @Default("127.0.0.1") // String getServerHost(); // // @Config("com.ning.core.server.port") // @Default("8080") // int getServerPort(); // // @Config("com.ning.core.server.server.ssl.enabled") // @Default("false") // boolean isSSLEnabled(); // // @Config("com.ning.core.server.server.ssl.port") // @Default("8443") // int getServerSslPort(); // // @Config("com.ning.core.server.jetty.stats") // @Default("true") // boolean isJettyStatsOn(); // // @Config("com.ning.core.server.jetty.ssl.keystore") // @DefaultNull // String getSSLkeystoreLocation(); // // @Config("com.ning.core.server.jetty.ssl.keystore.password") // @DefaultNull // String getSSLkeystorePassword(); // // @Config("com.ning.core.server.jetty.maxThreads") // @Default("2000") // int getMaxThreads(); // // @Config("com.ning.core.server.jetty.minThreads") // @Default("2") // int getMinThreads(); // // @Config("com.ning.core.server.jetty.logPath") // @Default(".logs") // String getLogPath(); // // @Config("com.ning.core.server.jetty.resourceBase") // @DefaultNull // String getResourceBase(); // } // // Path: core/src/main/java/com/ning/jetty/core/listeners/SetupJULBridge.java // public class SetupJULBridge implements ServletContextListener // { // @Override // public void contextInitialized(final ServletContextEvent event) // { // // We first remove the default handler(s) // final Logger rootLogger = LogManager.getLogManager().getLogger(""); // final Handler[] handlers = rootLogger.getHandlers(); // // if (!ArrayUtils.isEmpty(handlers)) { // for (final Handler handler : handlers) { // rootLogger.removeHandler(handler); // } // } // // And then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j // SLF4JBridgeHandler.install(); // } // // @Override // public void contextDestroyed(final ServletContextEvent event) // { // SLF4JBridgeHandler.uninstall(); // } // }
import com.ning.jetty.core.CoreConfig; import com.ning.jetty.core.listeners.SetupJULBridge; import com.google.common.base.Preconditions; import com.google.common.io.Resources; import com.google.inject.servlet.GuiceFilter; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.NCSARequestLog; import org.eclipse.jetty.server.RequestLog; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.RequestLogHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.xml.XmlConfiguration; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.management.MBeanServer; import javax.servlet.DispatcherType; import java.lang.management.ManagementFactory; import java.util.EnumSet; import java.util.EventListener; import java.util.Map;
final SslSelectChannelConnector sslConnector = new SslSelectChannelConnector(); sslConnector.setName("https"); sslConnector.setStatsOn(isStatsOn); sslConnector.setPort(localSslPort); final SslContextFactory sslContextFactory = sslConnector.getSslContextFactory(); sslContextFactory.setKeyStorePath(sslKeyStorePath); sslContextFactory.setKeyStorePassword(sslKeyStorePassword); server.addConnector(sslConnector); } private void configureThreadPool(final CoreConfig config) { final QueuedThreadPool threadPool = new QueuedThreadPool(config.getMaxThreads()); threadPool.setMinThreads(config.getMinThreads()); threadPool.setName("http-worker"); server.setThreadPool(threadPool); } private ServletContextHandler createServletContextHandler(final String resourceBase, final Iterable<EventListener> eventListeners, final Map<FilterHolder, String> filterHolders) { final ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.NO_SESSIONS); context.setContextPath("/"); if (resourceBase != null) { // Required if you want a webapp directory. See ContextHandler#getResource and http://docs.codehaus.org/display/JETTY/Embedding+Jetty final String webapp = this.getClass().getClassLoader().getResource(resourceBase).toExternalForm(); context.setResourceBase(webapp); } // Jersey insists on using java.util.logging (JUL)
// Path: core/src/main/java/com/ning/jetty/core/CoreConfig.java // public interface CoreConfig // { // @Config("com.ning.core.server.ip") // @Default("127.0.0.1") // String getServerHost(); // // @Config("com.ning.core.server.port") // @Default("8080") // int getServerPort(); // // @Config("com.ning.core.server.server.ssl.enabled") // @Default("false") // boolean isSSLEnabled(); // // @Config("com.ning.core.server.server.ssl.port") // @Default("8443") // int getServerSslPort(); // // @Config("com.ning.core.server.jetty.stats") // @Default("true") // boolean isJettyStatsOn(); // // @Config("com.ning.core.server.jetty.ssl.keystore") // @DefaultNull // String getSSLkeystoreLocation(); // // @Config("com.ning.core.server.jetty.ssl.keystore.password") // @DefaultNull // String getSSLkeystorePassword(); // // @Config("com.ning.core.server.jetty.maxThreads") // @Default("2000") // int getMaxThreads(); // // @Config("com.ning.core.server.jetty.minThreads") // @Default("2") // int getMinThreads(); // // @Config("com.ning.core.server.jetty.logPath") // @Default(".logs") // String getLogPath(); // // @Config("com.ning.core.server.jetty.resourceBase") // @DefaultNull // String getResourceBase(); // } // // Path: core/src/main/java/com/ning/jetty/core/listeners/SetupJULBridge.java // public class SetupJULBridge implements ServletContextListener // { // @Override // public void contextInitialized(final ServletContextEvent event) // { // // We first remove the default handler(s) // final Logger rootLogger = LogManager.getLogManager().getLogger(""); // final Handler[] handlers = rootLogger.getHandlers(); // // if (!ArrayUtils.isEmpty(handlers)) { // for (final Handler handler : handlers) { // rootLogger.removeHandler(handler); // } // } // // And then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j // SLF4JBridgeHandler.install(); // } // // @Override // public void contextDestroyed(final ServletContextEvent event) // { // SLF4JBridgeHandler.uninstall(); // } // } // Path: core/src/main/java/com/ning/jetty/core/server/HttpServer.java import com.ning.jetty.core.CoreConfig; import com.ning.jetty.core.listeners.SetupJULBridge; import com.google.common.base.Preconditions; import com.google.common.io.Resources; import com.google.inject.servlet.GuiceFilter; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.NCSARequestLog; import org.eclipse.jetty.server.RequestLog; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.RequestLogHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.xml.XmlConfiguration; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.management.MBeanServer; import javax.servlet.DispatcherType; import java.lang.management.ManagementFactory; import java.util.EnumSet; import java.util.EventListener; import java.util.Map; final SslSelectChannelConnector sslConnector = new SslSelectChannelConnector(); sslConnector.setName("https"); sslConnector.setStatsOn(isStatsOn); sslConnector.setPort(localSslPort); final SslContextFactory sslContextFactory = sslConnector.getSslContextFactory(); sslContextFactory.setKeyStorePath(sslKeyStorePath); sslContextFactory.setKeyStorePassword(sslKeyStorePassword); server.addConnector(sslConnector); } private void configureThreadPool(final CoreConfig config) { final QueuedThreadPool threadPool = new QueuedThreadPool(config.getMaxThreads()); threadPool.setMinThreads(config.getMinThreads()); threadPool.setName("http-worker"); server.setThreadPool(threadPool); } private ServletContextHandler createServletContextHandler(final String resourceBase, final Iterable<EventListener> eventListeners, final Map<FilterHolder, String> filterHolders) { final ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.NO_SESSIONS); context.setContextPath("/"); if (resourceBase != null) { // Required if you want a webapp directory. See ContextHandler#getResource and http://docs.codehaus.org/display/JETTY/Embedding+Jetty final String webapp = this.getClass().getClassLoader().getResource(resourceBase).toExternalForm(); context.setResourceBase(webapp); } // Jersey insists on using java.util.logging (JUL)
final EventListener listener = new SetupJULBridge();
pierre/ning-service-skeleton
jdbi/src/main/java/com/ning/jetty/jdbi/log/Slf4jLogging.java
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // // Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/LogLevel.java // public enum LogLevel // { // DEBUG, // TRACE, // INFO, // WARN, // ERROR // }
import javax.inject.Inject; import org.skife.jdbi.v2.logging.FormattedLog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ning.jetty.jdbi.config.DaoConfig; import com.ning.jetty.jdbi.config.LogLevel;
/* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.log; public class Slf4jLogging extends FormattedLog { private static final Logger logger = LoggerFactory.getLogger(Slf4jLogging.class);
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // // Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/LogLevel.java // public enum LogLevel // { // DEBUG, // TRACE, // INFO, // WARN, // ERROR // } // Path: jdbi/src/main/java/com/ning/jetty/jdbi/log/Slf4jLogging.java import javax.inject.Inject; import org.skife.jdbi.v2.logging.FormattedLog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ning.jetty.jdbi.config.DaoConfig; import com.ning.jetty.jdbi.config.LogLevel; /* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.log; public class Slf4jLogging extends FormattedLog { private static final Logger logger = LoggerFactory.getLogger(Slf4jLogging.class);
private final DaoConfig config;
pierre/ning-service-skeleton
jdbi/src/main/java/com/ning/jetty/jdbi/log/Slf4jLogging.java
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // // Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/LogLevel.java // public enum LogLevel // { // DEBUG, // TRACE, // INFO, // WARN, // ERROR // }
import javax.inject.Inject; import org.skife.jdbi.v2.logging.FormattedLog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ning.jetty.jdbi.config.DaoConfig; import com.ning.jetty.jdbi.config.LogLevel;
/* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.log; public class Slf4jLogging extends FormattedLog { private static final Logger logger = LoggerFactory.getLogger(Slf4jLogging.class); private final DaoConfig config; @Inject public Slf4jLogging(final DaoConfig config) { this.config = config; } /** * Used to ask implementations if logging is enabled. * * @return true if statement logging is enabled */ @Override protected boolean isEnabled() { return true; } /** * Log the statement passed in * * @param msg the message to log */ @Override protected void log(final String msg) {
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // // Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/LogLevel.java // public enum LogLevel // { // DEBUG, // TRACE, // INFO, // WARN, // ERROR // } // Path: jdbi/src/main/java/com/ning/jetty/jdbi/log/Slf4jLogging.java import javax.inject.Inject; import org.skife.jdbi.v2.logging.FormattedLog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ning.jetty.jdbi.config.DaoConfig; import com.ning.jetty.jdbi.config.LogLevel; /* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.log; public class Slf4jLogging extends FormattedLog { private static final Logger logger = LoggerFactory.getLogger(Slf4jLogging.class); private final DaoConfig config; @Inject public Slf4jLogging(final DaoConfig config) { this.config = config; } /** * Used to ask implementations if logging is enabled. * * @return true if statement logging is enabled */ @Override protected boolean isEnabled() { return true; } /** * Log the statement passed in * * @param msg the message to log */ @Override protected void log(final String msg) {
if (config.getLogLevel().equals(LogLevel.DEBUG)) {
pierre/ning-service-skeleton
jdbi/src/test/java/com/ning/jetty/jdbi/guice/providers/TestDBIProvider.java
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // // Path: jdbi/src/main/java/com/ning/jetty/jdbi/log/Slf4jLogging.java // public class Slf4jLogging extends FormattedLog { // private static final Logger logger = LoggerFactory.getLogger(Slf4jLogging.class); // // private final DaoConfig config; // // @Inject // public Slf4jLogging(final DaoConfig config) { // this.config = config; // } // // /** // * Used to ask implementations if logging is enabled. // * // * @return true if statement logging is enabled // */ // @Override // protected boolean isEnabled() { // return true; // } // // /** // * Log the statement passed in // * // * @param msg the message to log // */ // @Override // protected void log(final String msg) { // if (config.getLogLevel().equals(LogLevel.DEBUG)) { // logger.debug(msg); // } else if (config.getLogLevel().equals(LogLevel.TRACE)) { // logger.trace(msg); // } else if (config.getLogLevel().equals(LogLevel.INFO)) { // logger.info(msg); // } else if (config.getLogLevel().equals(LogLevel.WARN)) { // logger.warn(msg); // } else if (config.getLogLevel().equals(LogLevel.ERROR)) { // logger.error(msg); // } // } // }
import com.ning.jetty.jdbi.log.Slf4jLogging; import com.yammer.metrics.core.MetricsRegistry; import java.util.Properties; import org.skife.config.ConfigurationObjectFactory; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.tweak.SQLLog; import org.testng.Assert; import org.testng.annotations.Test; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.ning.jetty.jdbi.config.DaoConfig;
/* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.guice.providers; public class TestDBIProvider { @Test(groups = "fast") public void testInjection() throws Exception { final Injector injector = Guice.createInjector(Stage.PRODUCTION, new Module() { @Override public void configure(final Binder binder) { binder.bind(MetricsRegistry.class).toInstance(new MetricsRegistry());
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // // Path: jdbi/src/main/java/com/ning/jetty/jdbi/log/Slf4jLogging.java // public class Slf4jLogging extends FormattedLog { // private static final Logger logger = LoggerFactory.getLogger(Slf4jLogging.class); // // private final DaoConfig config; // // @Inject // public Slf4jLogging(final DaoConfig config) { // this.config = config; // } // // /** // * Used to ask implementations if logging is enabled. // * // * @return true if statement logging is enabled // */ // @Override // protected boolean isEnabled() { // return true; // } // // /** // * Log the statement passed in // * // * @param msg the message to log // */ // @Override // protected void log(final String msg) { // if (config.getLogLevel().equals(LogLevel.DEBUG)) { // logger.debug(msg); // } else if (config.getLogLevel().equals(LogLevel.TRACE)) { // logger.trace(msg); // } else if (config.getLogLevel().equals(LogLevel.INFO)) { // logger.info(msg); // } else if (config.getLogLevel().equals(LogLevel.WARN)) { // logger.warn(msg); // } else if (config.getLogLevel().equals(LogLevel.ERROR)) { // logger.error(msg); // } // } // } // Path: jdbi/src/test/java/com/ning/jetty/jdbi/guice/providers/TestDBIProvider.java import com.ning.jetty.jdbi.log.Slf4jLogging; import com.yammer.metrics.core.MetricsRegistry; import java.util.Properties; import org.skife.config.ConfigurationObjectFactory; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.tweak.SQLLog; import org.testng.Assert; import org.testng.annotations.Test; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.ning.jetty.jdbi.config.DaoConfig; /* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.guice.providers; public class TestDBIProvider { @Test(groups = "fast") public void testInjection() throws Exception { final Injector injector = Guice.createInjector(Stage.PRODUCTION, new Module() { @Override public void configure(final Binder binder) { binder.bind(MetricsRegistry.class).toInstance(new MetricsRegistry());
binder.bind(DaoConfig.class).toInstance(new ConfigurationObjectFactory(new Properties()).build(DaoConfig.class));
pierre/ning-service-skeleton
jdbi/src/test/java/com/ning/jetty/jdbi/guice/providers/TestDBIProvider.java
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // // Path: jdbi/src/main/java/com/ning/jetty/jdbi/log/Slf4jLogging.java // public class Slf4jLogging extends FormattedLog { // private static final Logger logger = LoggerFactory.getLogger(Slf4jLogging.class); // // private final DaoConfig config; // // @Inject // public Slf4jLogging(final DaoConfig config) { // this.config = config; // } // // /** // * Used to ask implementations if logging is enabled. // * // * @return true if statement logging is enabled // */ // @Override // protected boolean isEnabled() { // return true; // } // // /** // * Log the statement passed in // * // * @param msg the message to log // */ // @Override // protected void log(final String msg) { // if (config.getLogLevel().equals(LogLevel.DEBUG)) { // logger.debug(msg); // } else if (config.getLogLevel().equals(LogLevel.TRACE)) { // logger.trace(msg); // } else if (config.getLogLevel().equals(LogLevel.INFO)) { // logger.info(msg); // } else if (config.getLogLevel().equals(LogLevel.WARN)) { // logger.warn(msg); // } else if (config.getLogLevel().equals(LogLevel.ERROR)) { // logger.error(msg); // } // } // }
import com.ning.jetty.jdbi.log.Slf4jLogging; import com.yammer.metrics.core.MetricsRegistry; import java.util.Properties; import org.skife.config.ConfigurationObjectFactory; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.tweak.SQLLog; import org.testng.Assert; import org.testng.annotations.Test; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.ning.jetty.jdbi.config.DaoConfig;
/* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.guice.providers; public class TestDBIProvider { @Test(groups = "fast") public void testInjection() throws Exception { final Injector injector = Guice.createInjector(Stage.PRODUCTION, new Module() { @Override public void configure(final Binder binder) { binder.bind(MetricsRegistry.class).toInstance(new MetricsRegistry()); binder.bind(DaoConfig.class).toInstance(new ConfigurationObjectFactory(new Properties()).build(DaoConfig.class));
// Path: jdbi/src/main/java/com/ning/jetty/jdbi/config/DaoConfig.java // public interface DaoConfig // { // @Description("The jdbc url for the database") // @Config("com.ning.jetty.jdbi.url") // @Default("jdbc:mysql://127.0.0.1:3306/information_schema") // String getJdbcUrl(); // // @Description("The jdbc user name for the database") // @Config("com.ning.jetty.jdbi.user") // @Default("root") // String getUsername(); // // @Description("The jdbc password for the database") // @Config("com.ning.jetty.jdbi.password") // @Default("root") // String getPassword(); // // @Description("The minimum allowed number of idle connections to the database") // @Config("com.ning.jetty.jdbi.minIdle") // @Default("1") // int getMinIdle(); // // @Description("The maximum allowed number of active connections to the database") // @Config("com.ning.jetty.jdbi.maxActive") // @Default("10") // int getMaxActive(); // // @Description("How long to wait before a connection attempt to the database is considered timed out") // @Config("com.ning.jetty.jdbi.connectionTimeout") // @Default("10s") // TimeSpan getConnectionTimeout(); // // @Description("The time for a connection to remain unused before it is closed off") // @Config("com.ning.jetty.jdbi.idleMaxAge") // @Default("60m") // TimeSpan getIdleMaxAge(); // // @Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " + // "currently in use will not be affected until they are returned to the pool") // @Config("com.ning.jetty.jdbi.maxConnectionAge") // @Default("0m") // TimeSpan getMaxConnectionAge(); // // @Description("Time for a connection to remain idle before sending a test query to the DB") // @Config("com.ning.jetty.jdbi.idleConnectionTestPeriod") // @Default("5m") // TimeSpan getIdleConnectionTestPeriod(); // // @Description("Log level for SQL queries") // @Config("com.ning.jetty.jdbi.logLevel") // @Default("DEBUG") // LogLevel getLogLevel(); // } // // Path: jdbi/src/main/java/com/ning/jetty/jdbi/log/Slf4jLogging.java // public class Slf4jLogging extends FormattedLog { // private static final Logger logger = LoggerFactory.getLogger(Slf4jLogging.class); // // private final DaoConfig config; // // @Inject // public Slf4jLogging(final DaoConfig config) { // this.config = config; // } // // /** // * Used to ask implementations if logging is enabled. // * // * @return true if statement logging is enabled // */ // @Override // protected boolean isEnabled() { // return true; // } // // /** // * Log the statement passed in // * // * @param msg the message to log // */ // @Override // protected void log(final String msg) { // if (config.getLogLevel().equals(LogLevel.DEBUG)) { // logger.debug(msg); // } else if (config.getLogLevel().equals(LogLevel.TRACE)) { // logger.trace(msg); // } else if (config.getLogLevel().equals(LogLevel.INFO)) { // logger.info(msg); // } else if (config.getLogLevel().equals(LogLevel.WARN)) { // logger.warn(msg); // } else if (config.getLogLevel().equals(LogLevel.ERROR)) { // logger.error(msg); // } // } // } // Path: jdbi/src/test/java/com/ning/jetty/jdbi/guice/providers/TestDBIProvider.java import com.ning.jetty.jdbi.log.Slf4jLogging; import com.yammer.metrics.core.MetricsRegistry; import java.util.Properties; import org.skife.config.ConfigurationObjectFactory; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.tweak.SQLLog; import org.testng.Assert; import org.testng.annotations.Test; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.ning.jetty.jdbi.config.DaoConfig; /* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.jetty.jdbi.guice.providers; public class TestDBIProvider { @Test(groups = "fast") public void testInjection() throws Exception { final Injector injector = Guice.createInjector(Stage.PRODUCTION, new Module() { @Override public void configure(final Binder binder) { binder.bind(MetricsRegistry.class).toInstance(new MetricsRegistry()); binder.bind(DaoConfig.class).toInstance(new ConfigurationObjectFactory(new Properties()).build(DaoConfig.class));
binder.bind(SQLLog.class).to(Slf4jLogging.class).asEagerSingleton();
hllorens/cognitionis-nlp-libraries
nlp-files/src/main/java/com/cognitionis/nlp_files/annotation_scorers/Score.java
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/StringUtils.java // public class StringUtils { // // /** // * Returns if a char is ASCII (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isASCII(char c) { // return (((int) c >> 7) == 0); // } // // /** // * Returns if a char is ISO-8859-1 (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isISO_8859_1(char c) { // return (((int) c) < 256); // } // // /** // * Returns if a char is of an encoding // * @param c // * @return // */ // public static boolean existsInEncoding(char c, String encoding) { // try { // String s = "" + c; // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // /** // * Returns if a string is of an encoding // * @param s // * @return // */ // public static boolean existsInEncoding(String s, String encoding) { // try { // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // public static int countOccurrencesOf(String source, char pattern) { // int count = 0; // if (source != null) { // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + 1; // count++; // } // return count; // } else { // return 0; // } // } // // public static int countOccurrencesOf(String source, String pattern) { // int count = 0; // if (source != null) { // final int len = pattern.length(); // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + len; // count++; // } // return count; // } else { // return 0; // } // } // // public static String twoDecPosS(double d) { // Double a; // String twoDec; // int negative_inc = 0; // int decimal_pos = 0; // // a = (((int) Math.round((d) * 100.0)) / 100.0); // twoDec = a.toString(); // // decimal_pos = twoDec.lastIndexOf('.'); // if (decimal_pos == -1) { // twoDec += "."; // decimal_pos = twoDec.length(); // } // twoDec += "00"; // // twoDec = twoDec.substring(0, decimal_pos + 3); // // return twoDec; // } // // public static <T> T[] concatArray(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // // }
import java.util.*; import com.cognitionis.utils_basickit.StringUtils;
} public double getAccuracyTokenLevel(String e) { return ((double) (tp.get(e) + tn.get(e)) / (tp.get(e) + tn.get(e) + fp.get(e) + fn.get(e))); } // IMPORTANT: ONLY FOR TEXT TYPE EVALUATION (SPAN) --> SPAN SLOPPY // NOT FOR ATTRIBUTES (IE, CLASS) public double getPrecisionRelaxed(String e) { return Precision(corr.get(e).doubleValue() + inco.get(e).doubleValue(), getACT(e)); } public double getRecallRelaxed(String e) { return Recall(corr.get(e).doubleValue() + inco.get(e).doubleValue(), getPOS(e)); } public double getF1Relaxed(String e) { double p = getPrecisionRelaxed(e); double r = getRecallRelaxed(e); return F1(p, r); } public void print() throws Exception { print("simple"); } public void print(String option) throws Exception { //System.out.println("KEYFILE: " + this.keyfile); for (String e : elem_judgements.keySet()) { System.out.println("\t>" + e.toUpperCase() + "< (POS=" + getPOS(e) + ",ACT=" + getACT(e) + "):\tPrecision=" + oneDecPos(getPrecision(e)) + "%\tRecall=" + oneDecPos(getRecall(e)) + "%\tF1=" + oneDecPos(getF1(e)) + "%\t- corr=" + corr.get(e) + ";inco=" + inco.get(e) + ";spur=" + spur.get(e) + ";miss=" + miss.get(e) + ";");
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/StringUtils.java // public class StringUtils { // // /** // * Returns if a char is ASCII (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isASCII(char c) { // return (((int) c >> 7) == 0); // } // // /** // * Returns if a char is ISO-8859-1 (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isISO_8859_1(char c) { // return (((int) c) < 256); // } // // /** // * Returns if a char is of an encoding // * @param c // * @return // */ // public static boolean existsInEncoding(char c, String encoding) { // try { // String s = "" + c; // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // /** // * Returns if a string is of an encoding // * @param s // * @return // */ // public static boolean existsInEncoding(String s, String encoding) { // try { // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // public static int countOccurrencesOf(String source, char pattern) { // int count = 0; // if (source != null) { // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + 1; // count++; // } // return count; // } else { // return 0; // } // } // // public static int countOccurrencesOf(String source, String pattern) { // int count = 0; // if (source != null) { // final int len = pattern.length(); // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + len; // count++; // } // return count; // } else { // return 0; // } // } // // public static String twoDecPosS(double d) { // Double a; // String twoDec; // int negative_inc = 0; // int decimal_pos = 0; // // a = (((int) Math.round((d) * 100.0)) / 100.0); // twoDec = a.toString(); // // decimal_pos = twoDec.lastIndexOf('.'); // if (decimal_pos == -1) { // twoDec += "."; // decimal_pos = twoDec.length(); // } // twoDec += "00"; // // twoDec = twoDec.substring(0, decimal_pos + 3); // // return twoDec; // } // // public static <T> T[] concatArray(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // // } // Path: nlp-files/src/main/java/com/cognitionis/nlp_files/annotation_scorers/Score.java import java.util.*; import com.cognitionis.utils_basickit.StringUtils; } public double getAccuracyTokenLevel(String e) { return ((double) (tp.get(e) + tn.get(e)) / (tp.get(e) + tn.get(e) + fp.get(e) + fn.get(e))); } // IMPORTANT: ONLY FOR TEXT TYPE EVALUATION (SPAN) --> SPAN SLOPPY // NOT FOR ATTRIBUTES (IE, CLASS) public double getPrecisionRelaxed(String e) { return Precision(corr.get(e).doubleValue() + inco.get(e).doubleValue(), getACT(e)); } public double getRecallRelaxed(String e) { return Recall(corr.get(e).doubleValue() + inco.get(e).doubleValue(), getPOS(e)); } public double getF1Relaxed(String e) { double p = getPrecisionRelaxed(e); double r = getRecallRelaxed(e); return F1(p, r); } public void print() throws Exception { print("simple"); } public void print(String option) throws Exception { //System.out.println("KEYFILE: " + this.keyfile); for (String e : elem_judgements.keySet()) { System.out.println("\t>" + e.toUpperCase() + "< (POS=" + getPOS(e) + ",ACT=" + getACT(e) + "):\tPrecision=" + oneDecPos(getPrecision(e)) + "%\tRecall=" + oneDecPos(getRecall(e)) + "%\tF1=" + oneDecPos(getF1(e)) + "%\t- corr=" + corr.get(e) + ";inco=" + inco.get(e) + ";spur=" + spur.get(e) + ";miss=" + miss.get(e) + ";");
System.out.println("\t TempEval2(token level score)\tPrecision=" + StringUtils.twoDecPosS(getPrecisionTokenLevel(e)) + "\tRecall=" + StringUtils.twoDecPosS(getRecallTokenLevel(e)) + "\tF1=" + StringUtils.twoDecPosS(getF1TokenLevel(e)) + " \t- accuracy=" + twoDecPos(getAccuracyTokenLevel(e)));
hllorens/cognitionis-nlp-libraries
nlp-files/src/main/java/com/cognitionis/nlp_files/TokenizedFile.java
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/StringUtils.java // public class StringUtils { // // /** // * Returns if a char is ASCII (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isASCII(char c) { // return (((int) c >> 7) == 0); // } // // /** // * Returns if a char is ISO-8859-1 (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isISO_8859_1(char c) { // return (((int) c) < 256); // } // // /** // * Returns if a char is of an encoding // * @param c // * @return // */ // public static boolean existsInEncoding(char c, String encoding) { // try { // String s = "" + c; // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // /** // * Returns if a string is of an encoding // * @param s // * @return // */ // public static boolean existsInEncoding(String s, String encoding) { // try { // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // public static int countOccurrencesOf(String source, char pattern) { // int count = 0; // if (source != null) { // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + 1; // count++; // } // return count; // } else { // return 0; // } // } // // public static int countOccurrencesOf(String source, String pattern) { // int count = 0; // if (source != null) { // final int len = pattern.length(); // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + len; // count++; // } // return count; // } else { // return 0; // } // } // // public static String twoDecPosS(double d) { // Double a; // String twoDec; // int negative_inc = 0; // int decimal_pos = 0; // // a = (((int) Math.round((d) * 100.0)) / 100.0); // twoDec = a.toString(); // // decimal_pos = twoDec.lastIndexOf('.'); // if (decimal_pos == -1) { // twoDec += "."; // decimal_pos = twoDec.length(); // } // twoDec += "00"; // // twoDec = twoDec.substring(0, decimal_pos + 3); // // return twoDec; // } // // public static <T> T[] concatArray(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // // }
import com.cognitionis.utils_basickit.StringUtils; import java.io.*; import java.nio.file.*; import static java.nio.file.StandardCopyOption.*; import java.util.*;
while ((pipesline = pipesreader.readLine()) != null) { linen++; //System.err.println(pipesline); if (pipesline.trim().length() > 1) { pipesarr = pipesline.split(this.field_separator_re); String token = pipesarr[tokcolumn]; int token_offset = -1; String paired_token = ""; int cn = 0; while (true) { if (readmodel) { cmodel_prev = cmodel; if ((cmodel = (char) modelreader.read()) == -1) { if (cn == token.length()) { break; // save last token end of file } else { throw new Exception("Premature end of model file"); } } offset++; } else { readmodel = true; } char cpipes = '\0'; if (cn >= token.length()) { if (usingNotUTF8tool) {
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/StringUtils.java // public class StringUtils { // // /** // * Returns if a char is ASCII (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isASCII(char c) { // return (((int) c >> 7) == 0); // } // // /** // * Returns if a char is ISO-8859-1 (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isISO_8859_1(char c) { // return (((int) c) < 256); // } // // /** // * Returns if a char is of an encoding // * @param c // * @return // */ // public static boolean existsInEncoding(char c, String encoding) { // try { // String s = "" + c; // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // /** // * Returns if a string is of an encoding // * @param s // * @return // */ // public static boolean existsInEncoding(String s, String encoding) { // try { // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // public static int countOccurrencesOf(String source, char pattern) { // int count = 0; // if (source != null) { // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + 1; // count++; // } // return count; // } else { // return 0; // } // } // // public static int countOccurrencesOf(String source, String pattern) { // int count = 0; // if (source != null) { // final int len = pattern.length(); // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + len; // count++; // } // return count; // } else { // return 0; // } // } // // public static String twoDecPosS(double d) { // Double a; // String twoDec; // int negative_inc = 0; // int decimal_pos = 0; // // a = (((int) Math.round((d) * 100.0)) / 100.0); // twoDec = a.toString(); // // decimal_pos = twoDec.lastIndexOf('.'); // if (decimal_pos == -1) { // twoDec += "."; // decimal_pos = twoDec.length(); // } // twoDec += "00"; // // twoDec = twoDec.substring(0, decimal_pos + 3); // // return twoDec; // } // // public static <T> T[] concatArray(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // // } // Path: nlp-files/src/main/java/com/cognitionis/nlp_files/TokenizedFile.java import com.cognitionis.utils_basickit.StringUtils; import java.io.*; import java.nio.file.*; import static java.nio.file.StandardCopyOption.*; import java.util.*; while ((pipesline = pipesreader.readLine()) != null) { linen++; //System.err.println(pipesline); if (pipesline.trim().length() > 1) { pipesarr = pipesline.split(this.field_separator_re); String token = pipesarr[tokcolumn]; int token_offset = -1; String paired_token = ""; int cn = 0; while (true) { if (readmodel) { cmodel_prev = cmodel; if ((cmodel = (char) modelreader.read()) == -1) { if (cn == token.length()) { break; // save last token end of file } else { throw new Exception("Premature end of model file"); } } offset++; } else { readmodel = true; } char cpipes = '\0'; if (cn >= token.length()) { if (usingNotUTF8tool) {
if (StringUtils.isISO_8859_1(cmodel)) {
hllorens/cognitionis-nlp-libraries
nlp-lang-models/src/main/java/com/cognitionis/nlp_lang_models/TextCategorizer.java
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/FileUtils.java // public static boolean URL_exists(String URLName) { // boolean result = false; // try { // if (System.getProperty("DEBUG") != null // && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // System.err.println("EXISTS? " + ensureURL(URLName)); // } // final URL url = new URL(ensureURL(URLName)); // final URLConnection con = url.openConnection(); // this will return // // an // // {Http,Jar}UrlConnection // // depending // if (url.getProtocol().equals("http")) { // final HttpURLConnection con_http = (HttpURLConnection) con; // HttpURLConnection.setFollowRedirects(false); // // HttpURLConnection.setInstanceFollowRedirects(false); // this // // might be needed // con_http.setRequestMethod("HEAD"); // if (con_http.getResponseCode() == HttpURLConnection.HTTP_OK) { // result = true; // } // } else { // con.connect(); // still does not work and requires external // // resources // result = true; // } // } catch (final Exception e) { // if (System.getProperty("DEBUG") != null // && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // System.err.println("Errors found (FileUtils): URL (" + URLName // + ") not found: " + e.getMessage() + "\n"); // e.printStackTrace(System.err); // } // return false; // } // return result; // }
import java.io.*; import java.util.*; import com.cognitionis.utils_basickit.*; import static com.cognitionis.utils_basickit.FileUtils.URL_exists;
package com.cognitionis.nlp_lang_models; /** * * @author Héctor Llorens * @since 2011 * * This is an implementation of the famous Tenkle Text Categorization algorithm * based on character n-grams * Best known as TextCat * */ public class TextCategorizer { private final static int MIN_WORDS_4_CATEGORIZE = 5; private final static String DEFAULT_CATEGORY = "en"; // English private String conf_file_path = "/resources/lang_models/text_categorization/"; private String conf_file_name = "indoeuropean.conf"; //private String conf_file_path = "indoeuropean.conf"; private ArrayList<TextCategorizerFingerprint> categories = new ArrayList(); public TextCategorizer() { loadFingerprints(); } public TextCategorizer(String conf_file_path) { this.conf_file_path = conf_file_path; loadFingerprints(); } private void loadFingerprints() { this.categories.clear(); try { // For our beloved Windows String extra = ""; // TODO check if this is really needed if (File.separator.equals("\\")) { extra = "\\"; } String app_path = FileUtils.getApplicationPath(TextCategorizer.class);
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/FileUtils.java // public static boolean URL_exists(String URLName) { // boolean result = false; // try { // if (System.getProperty("DEBUG") != null // && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // System.err.println("EXISTS? " + ensureURL(URLName)); // } // final URL url = new URL(ensureURL(URLName)); // final URLConnection con = url.openConnection(); // this will return // // an // // {Http,Jar}UrlConnection // // depending // if (url.getProtocol().equals("http")) { // final HttpURLConnection con_http = (HttpURLConnection) con; // HttpURLConnection.setFollowRedirects(false); // // HttpURLConnection.setInstanceFollowRedirects(false); // this // // might be needed // con_http.setRequestMethod("HEAD"); // if (con_http.getResponseCode() == HttpURLConnection.HTTP_OK) { // result = true; // } // } else { // con.connect(); // still does not work and requires external // // resources // result = true; // } // } catch (final Exception e) { // if (System.getProperty("DEBUG") != null // && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // System.err.println("Errors found (FileUtils): URL (" + URLName // + ") not found: " + e.getMessage() + "\n"); // e.printStackTrace(System.err); // } // return false; // } // return result; // } // Path: nlp-lang-models/src/main/java/com/cognitionis/nlp_lang_models/TextCategorizer.java import java.io.*; import java.util.*; import com.cognitionis.utils_basickit.*; import static com.cognitionis.utils_basickit.FileUtils.URL_exists; package com.cognitionis.nlp_lang_models; /** * * @author Héctor Llorens * @since 2011 * * This is an implementation of the famous Tenkle Text Categorization algorithm * based on character n-grams * Best known as TextCat * */ public class TextCategorizer { private final static int MIN_WORDS_4_CATEGORIZE = 5; private final static String DEFAULT_CATEGORY = "en"; // English private String conf_file_path = "/resources/lang_models/text_categorization/"; private String conf_file_name = "indoeuropean.conf"; //private String conf_file_path = "indoeuropean.conf"; private ArrayList<TextCategorizerFingerprint> categories = new ArrayList(); public TextCategorizer() { loadFingerprints(); } public TextCategorizer(String conf_file_path) { this.conf_file_path = conf_file_path; loadFingerprints(); } private void loadFingerprints() { this.categories.clear(); try { // For our beloved Windows String extra = ""; // TODO check if this is really needed if (File.separator.equals("\\")) { extra = "\\"; } String app_path = FileUtils.getApplicationPath(TextCategorizer.class);
if (!URL_exists(app_path+conf_file_path)) { // Check for external resoucre (outside classes)
hllorens/cognitionis-nlp-libraries
feature-builder/src/main/java/com/cognitionis/feature_builder/Timen.java
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/XmlAttribs.java // public class XmlAttribs { // // // public static HashMap<String, String> parseAttrs(String attrs) { // // if separated by blanks or consists of only one argument with a quoted value use XML // if(attrs.matches(".*=\"[^\"]*\"\\s+.*") || attrs.matches("[^=]*=\"[^\"]*\"")){ // return parseXMLattrs(attrs); // }else{ // otherwise use ";" separator that handles both quoted and un quoted values // return parseSemiColonAttrs(attrs); // } // } // // public static HashMap<String, String> parseXMLattrs(String attrs) { // HashMap<String, String> parsed_attrs=null; // try{ // attrs=attrs.trim().replaceAll("\\s+", " "); // if(attrs.endsWith("\"")){attrs=attrs.substring(0, attrs.length()-1);} // String[] attrs_arr = attrs.split("\" "); // parsed_attrs = new HashMap<String, String>(); // for (int i = 0; i < attrs_arr.length; i++) { // if (attrs_arr[i].matches("[^=]+=\"[^=]+")) { // parsed_attrs.put(attrs_arr[i].substring(0, attrs_arr[i].indexOf("=\"")), attrs_arr[i].substring(attrs_arr[i].indexOf("=\"") + 2)); // } // } // } catch (Exception e) { // System.err.println("Errors found (XmlAttribs):\n\t" + e.toString() + "\n"); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return null; // } // return parsed_attrs; // } // // public static HashMap<String, String> parseSemiColonAttrs(String attrs) { // HashMap<String, String> parsed_attrs=null; // try{ // String[] attrs_arr = attrs.trim().replaceAll("\\s+", " ").split(";"); // parsed_attrs = new HashMap<String, String>(); // for (int i = 0; i < attrs_arr.length; i++) { // if (attrs_arr[i].matches("[^=]+=[^=]+")) { // String name=attrs_arr[i].substring(0, attrs_arr[i].indexOf('=')); // String value=attrs_arr[i].substring(attrs_arr[i].indexOf('=') + 1); // if (value.matches("\".*\"")) { // value = value.substring(1, value.length() - 1); // } // parsed_attrs.put(name, value); // } // } // } catch (Exception e) { // System.err.println("Errors found (XmlAttribs):\n\t" + e.toString() + "\n"); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return null; // } // return parsed_attrs; // } // // // // // }
import java.io.*; import java.util.*; import com.cognitionis.nlp_files.*; import com.cognitionis.utils_basickit.XmlAttribs;
} throw new Exception("Some of the required columns (element,word/token,POS) not found: " + notFoundCol); } String pipeslineant = "--prior first line--"; try { String line; String[] linearr; HashMap<String, String> tempexAttribsHash = null; while ((line = pipesreader.readLine()) != null) { numline++; linearr = line.split("\\|"); if (linearr.length >= pipesfile.getPipesDescArrCount()) { if (linearr[iob2col].matches("B-.*")) { if (!word.equals("")) { outfile.write(id + "|" + word + "|" + tense + "|"+DCTs.get(file)[0]+"\n"); id = ""; word = ""; tense = ""; } word = linearr[tokencol]; tense = linearr[tensecol]; file = linearr[filecol]; if (linearr[attrscol].matches(".*=.*=.*") && !linearr[attrscol].contains(";")) {
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/XmlAttribs.java // public class XmlAttribs { // // // public static HashMap<String, String> parseAttrs(String attrs) { // // if separated by blanks or consists of only one argument with a quoted value use XML // if(attrs.matches(".*=\"[^\"]*\"\\s+.*") || attrs.matches("[^=]*=\"[^\"]*\"")){ // return parseXMLattrs(attrs); // }else{ // otherwise use ";" separator that handles both quoted and un quoted values // return parseSemiColonAttrs(attrs); // } // } // // public static HashMap<String, String> parseXMLattrs(String attrs) { // HashMap<String, String> parsed_attrs=null; // try{ // attrs=attrs.trim().replaceAll("\\s+", " "); // if(attrs.endsWith("\"")){attrs=attrs.substring(0, attrs.length()-1);} // String[] attrs_arr = attrs.split("\" "); // parsed_attrs = new HashMap<String, String>(); // for (int i = 0; i < attrs_arr.length; i++) { // if (attrs_arr[i].matches("[^=]+=\"[^=]+")) { // parsed_attrs.put(attrs_arr[i].substring(0, attrs_arr[i].indexOf("=\"")), attrs_arr[i].substring(attrs_arr[i].indexOf("=\"") + 2)); // } // } // } catch (Exception e) { // System.err.println("Errors found (XmlAttribs):\n\t" + e.toString() + "\n"); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return null; // } // return parsed_attrs; // } // // public static HashMap<String, String> parseSemiColonAttrs(String attrs) { // HashMap<String, String> parsed_attrs=null; // try{ // String[] attrs_arr = attrs.trim().replaceAll("\\s+", " ").split(";"); // parsed_attrs = new HashMap<String, String>(); // for (int i = 0; i < attrs_arr.length; i++) { // if (attrs_arr[i].matches("[^=]+=[^=]+")) { // String name=attrs_arr[i].substring(0, attrs_arr[i].indexOf('=')); // String value=attrs_arr[i].substring(attrs_arr[i].indexOf('=') + 1); // if (value.matches("\".*\"")) { // value = value.substring(1, value.length() - 1); // } // parsed_attrs.put(name, value); // } // } // } catch (Exception e) { // System.err.println("Errors found (XmlAttribs):\n\t" + e.toString() + "\n"); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return null; // } // return parsed_attrs; // } // // // // // } // Path: feature-builder/src/main/java/com/cognitionis/feature_builder/Timen.java import java.io.*; import java.util.*; import com.cognitionis.nlp_files.*; import com.cognitionis.utils_basickit.XmlAttribs; } throw new Exception("Some of the required columns (element,word/token,POS) not found: " + notFoundCol); } String pipeslineant = "--prior first line--"; try { String line; String[] linearr; HashMap<String, String> tempexAttribsHash = null; while ((line = pipesreader.readLine()) != null) { numline++; linearr = line.split("\\|"); if (linearr.length >= pipesfile.getPipesDescArrCount()) { if (linearr[iob2col].matches("B-.*")) { if (!word.equals("")) { outfile.write(id + "|" + word + "|" + tense + "|"+DCTs.get(file)[0]+"\n"); id = ""; word = ""; tense = ""; } word = linearr[tokencol]; tense = linearr[tensecol]; file = linearr[filecol]; if (linearr[attrscol].matches(".*=.*=.*") && !linearr[attrscol].contains(";")) {
tempexAttribsHash = XmlAttribs.parseXMLattrs(linearr[attrscol]);
hllorens/cognitionis-nlp-libraries
knowledgek/src/main/java/com/cognitionis/knowledgek/NUMEK/NUMEK.java
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/StringUtils.java // public class StringUtils { // // /** // * Returns if a char is ASCII (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isASCII(char c) { // return (((int) c >> 7) == 0); // } // // /** // * Returns if a char is ISO-8859-1 (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isISO_8859_1(char c) { // return (((int) c) < 256); // } // // /** // * Returns if a char is of an encoding // * @param c // * @return // */ // public static boolean existsInEncoding(char c, String encoding) { // try { // String s = "" + c; // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // /** // * Returns if a string is of an encoding // * @param s // * @return // */ // public static boolean existsInEncoding(String s, String encoding) { // try { // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // public static int countOccurrencesOf(String source, char pattern) { // int count = 0; // if (source != null) { // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + 1; // count++; // } // return count; // } else { // return 0; // } // } // // public static int countOccurrencesOf(String source, String pattern) { // int count = 0; // if (source != null) { // final int len = pattern.length(); // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + len; // count++; // } // return count; // } else { // return 0; // } // } // // public static String twoDecPosS(double d) { // Double a; // String twoDec; // int negative_inc = 0; // int decimal_pos = 0; // // a = (((int) Math.round((d) * 100.0)) / 100.0); // twoDec = a.toString(); // // decimal_pos = twoDec.lastIndexOf('.'); // if (decimal_pos == -1) { // twoDec += "."; // decimal_pos = twoDec.length(); // } // twoDec += "00"; // // twoDec = twoDec.substring(0, decimal_pos + 3); // // return twoDec; // } // // public static <T> T[] concatArray(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // // }
import com.cognitionis.utils_basickit.StringUtils; import java.util.*;
} else { if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { System.err.println("Warining: error normalizing fraction (" + snumber + ") it has been set to 0.0 by default."); } return 0.0; } } // UK English "and" is hundreds/thousands and tens/units separator // UK/US English "-" is tens and units separator // 1506 --> one thousand five hundred and six // English units are always singular. Plural (milions) are only informal/indefinite (e.g., there were millions of people) // FREELING ERRORS IN NUMEK: Eleven_hundred_ten_thousand_and_six = 1110006 (tens Hundreds are correct in English "informal") public String text2number(String snumber) { //Double number = new Double(0.0); // NO BECAUSE DO NOT SAVE OBJECTS BY REFERENCE... Number number = new Number(); try { snumber = snumber.trim().toLowerCase().replaceAll("\\s+(st|nd|rd|th|o|a)$", ""); // a twenty year period exception snumber = snumber.replaceAll("^(?:a|an)\\s+((?:"+units_re+"|"+tens_re+"|"+irregular_tens_re+").*)$", "$1"); Integer magnitude = 0; // order of magnitude Integer max_magn = MAX_NUMBERS_ORDER; String[] elements = snumber.split("(\\s*-\\s*|\\s+" + numdelim + "\\s+|\\s+)"); //System.out.println(snumber + " - numelems: "+elements.length); // already numeric expression if (locale.getLanguage().equalsIgnoreCase("es")) { snumber = snumber.replaceFirst(",", ".");
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/StringUtils.java // public class StringUtils { // // /** // * Returns if a char is ASCII (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isASCII(char c) { // return (((int) c >> 7) == 0); // } // // /** // * Returns if a char is ISO-8859-1 (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isISO_8859_1(char c) { // return (((int) c) < 256); // } // // /** // * Returns if a char is of an encoding // * @param c // * @return // */ // public static boolean existsInEncoding(char c, String encoding) { // try { // String s = "" + c; // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // /** // * Returns if a string is of an encoding // * @param s // * @return // */ // public static boolean existsInEncoding(String s, String encoding) { // try { // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // public static int countOccurrencesOf(String source, char pattern) { // int count = 0; // if (source != null) { // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + 1; // count++; // } // return count; // } else { // return 0; // } // } // // public static int countOccurrencesOf(String source, String pattern) { // int count = 0; // if (source != null) { // final int len = pattern.length(); // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + len; // count++; // } // return count; // } else { // return 0; // } // } // // public static String twoDecPosS(double d) { // Double a; // String twoDec; // int negative_inc = 0; // int decimal_pos = 0; // // a = (((int) Math.round((d) * 100.0)) / 100.0); // twoDec = a.toString(); // // decimal_pos = twoDec.lastIndexOf('.'); // if (decimal_pos == -1) { // twoDec += "."; // decimal_pos = twoDec.length(); // } // twoDec += "00"; // // twoDec = twoDec.substring(0, decimal_pos + 3); // // return twoDec; // } // // public static <T> T[] concatArray(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // // } // Path: knowledgek/src/main/java/com/cognitionis/knowledgek/NUMEK/NUMEK.java import com.cognitionis.utils_basickit.StringUtils; import java.util.*; } else { if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { System.err.println("Warining: error normalizing fraction (" + snumber + ") it has been set to 0.0 by default."); } return 0.0; } } // UK English "and" is hundreds/thousands and tens/units separator // UK/US English "-" is tens and units separator // 1506 --> one thousand five hundred and six // English units are always singular. Plural (milions) are only informal/indefinite (e.g., there were millions of people) // FREELING ERRORS IN NUMEK: Eleven_hundred_ten_thousand_and_six = 1110006 (tens Hundreds are correct in English "informal") public String text2number(String snumber) { //Double number = new Double(0.0); // NO BECAUSE DO NOT SAVE OBJECTS BY REFERENCE... Number number = new Number(); try { snumber = snumber.trim().toLowerCase().replaceAll("\\s+(st|nd|rd|th|o|a)$", ""); // a twenty year period exception snumber = snumber.replaceAll("^(?:a|an)\\s+((?:"+units_re+"|"+tens_re+"|"+irregular_tens_re+").*)$", "$1"); Integer magnitude = 0; // order of magnitude Integer max_magn = MAX_NUMBERS_ORDER; String[] elements = snumber.split("(\\s*-\\s*|\\s+" + numdelim + "\\s+|\\s+)"); //System.out.println(snumber + " - numelems: "+elements.length); // already numeric expression if (locale.getLanguage().equalsIgnoreCase("es")) { snumber = snumber.replaceFirst(",", ".");
if (StringUtils.countOccurrencesOf(snumber, '.') > 1) {
hllorens/cognitionis-nlp-libraries
utils-basickit/src/main/java/com/cognitionis/utils_basickit/statistics/T_test.java
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/StringUtils.java // public class StringUtils { // // /** // * Returns if a char is ASCII (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isASCII(char c) { // return (((int) c >> 7) == 0); // } // // /** // * Returns if a char is ISO-8859-1 (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isISO_8859_1(char c) { // return (((int) c) < 256); // } // // /** // * Returns if a char is of an encoding // * @param c // * @return // */ // public static boolean existsInEncoding(char c, String encoding) { // try { // String s = "" + c; // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // /** // * Returns if a string is of an encoding // * @param s // * @return // */ // public static boolean existsInEncoding(String s, String encoding) { // try { // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // public static int countOccurrencesOf(String source, char pattern) { // int count = 0; // if (source != null) { // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + 1; // count++; // } // return count; // } else { // return 0; // } // } // // public static int countOccurrencesOf(String source, String pattern) { // int count = 0; // if (source != null) { // final int len = pattern.length(); // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + len; // count++; // } // return count; // } else { // return 0; // } // } // // public static String twoDecPosS(double d) { // Double a; // String twoDec; // int negative_inc = 0; // int decimal_pos = 0; // // a = (((int) Math.round((d) * 100.0)) / 100.0); // twoDec = a.toString(); // // decimal_pos = twoDec.lastIndexOf('.'); // if (decimal_pos == -1) { // twoDec += "."; // decimal_pos = twoDec.length(); // } // twoDec += "00"; // // twoDec = twoDec.substring(0, decimal_pos + 3); // // return twoDec; // } // // public static <T> T[] concatArray(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // // }
import com.cognitionis.utils_basickit.StringUtils;
for (int fold = 0; fold < 10; fold++) { mean += data[fold]; } mean /= count; double variance = 0.0; for (int fold = 0; fold < 10; fold++) { variance += Math.pow(data[fold] - mean, 2); } variance /= count; double stdev = Math.sqrt(variance); // paired t-test t = (mean - 0.0) / (stdev / Math.sqrt(count)); if (t >= 1.38) { two_tail = 0.2; significant = true; } if (t >= 1.83) { two_tail = 0.1; } if (t >= 2.26) { two_tail = 0.05; } if (t >= 3.25) { two_tail = 0.001; }
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/StringUtils.java // public class StringUtils { // // /** // * Returns if a char is ASCII (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isASCII(char c) { // return (((int) c >> 7) == 0); // } // // /** // * Returns if a char is ISO-8859-1 (fastest than the generic function: existsInEncoding(char c, String encoding)) // * @param c // * @return // */ // public static boolean isISO_8859_1(char c) { // return (((int) c) < 256); // } // // /** // * Returns if a char is of an encoding // * @param c // * @return // */ // public static boolean existsInEncoding(char c, String encoding) { // try { // String s = "" + c; // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // /** // * Returns if a string is of an encoding // * @param s // * @return // */ // public static boolean existsInEncoding(String s, String encoding) { // try { // byte bytes[] = s.getBytes(encoding); // String s2 = new String(bytes, encoding); // return (s2.equals(s)); // } catch (Exception e) { // System.err.println("Errors found (StringUtils):\n\t" + e.toString()); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return false; // } // } // // public static int countOccurrencesOf(String source, char pattern) { // int count = 0; // if (source != null) { // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + 1; // count++; // } // return count; // } else { // return 0; // } // } // // public static int countOccurrencesOf(String source, String pattern) { // int count = 0; // if (source != null) { // final int len = pattern.length(); // int found = -1; // int start = 0; // // // while ((found = source.indexOf(pattern, start)) != -1) { // start = found + len; // count++; // } // return count; // } else { // return 0; // } // } // // public static String twoDecPosS(double d) { // Double a; // String twoDec; // int negative_inc = 0; // int decimal_pos = 0; // // a = (((int) Math.round((d) * 100.0)) / 100.0); // twoDec = a.toString(); // // decimal_pos = twoDec.lastIndexOf('.'); // if (decimal_pos == -1) { // twoDec += "."; // decimal_pos = twoDec.length(); // } // twoDec += "00"; // // twoDec = twoDec.substring(0, decimal_pos + 3); // // return twoDec; // } // // public static <T> T[] concatArray(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // // } // Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/statistics/T_test.java import com.cognitionis.utils_basickit.StringUtils; for (int fold = 0; fold < 10; fold++) { mean += data[fold]; } mean /= count; double variance = 0.0; for (int fold = 0; fold < 10; fold++) { variance += Math.pow(data[fold] - mean, 2); } variance /= count; double stdev = Math.sqrt(variance); // paired t-test t = (mean - 0.0) / (stdev / Math.sqrt(count)); if (t >= 1.38) { two_tail = 0.2; significant = true; } if (t >= 1.83) { two_tail = 0.1; } if (t >= 2.26) { two_tail = 0.05; } if (t >= 3.25) { two_tail = 0.001; }
output = "mean=" + StringUtils.twoDecPosS(mean) + " stdev=" + StringUtils.twoDecPosS(stdev) + " t=" + StringUtils.twoDecPosS(t) + " two_tail=" + two_tail + " one_tail=" + StringUtils.twoDecPosS(two_tail / 2) + " confidence>95=" + significant;
hllorens/cognitionis-nlp-libraries
nlp-files/src/main/java/com/cognitionis/nlp_files/annotation_scorers/Judgement.java
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/XmlAttribs.java // public class XmlAttribs { // // // public static HashMap<String, String> parseAttrs(String attrs) { // // if separated by blanks or consists of only one argument with a quoted value use XML // if(attrs.matches(".*=\"[^\"]*\"\\s+.*") || attrs.matches("[^=]*=\"[^\"]*\"")){ // return parseXMLattrs(attrs); // }else{ // otherwise use ";" separator that handles both quoted and un quoted values // return parseSemiColonAttrs(attrs); // } // } // // public static HashMap<String, String> parseXMLattrs(String attrs) { // HashMap<String, String> parsed_attrs=null; // try{ // attrs=attrs.trim().replaceAll("\\s+", " "); // if(attrs.endsWith("\"")){attrs=attrs.substring(0, attrs.length()-1);} // String[] attrs_arr = attrs.split("\" "); // parsed_attrs = new HashMap<String, String>(); // for (int i = 0; i < attrs_arr.length; i++) { // if (attrs_arr[i].matches("[^=]+=\"[^=]+")) { // parsed_attrs.put(attrs_arr[i].substring(0, attrs_arr[i].indexOf("=\"")), attrs_arr[i].substring(attrs_arr[i].indexOf("=\"") + 2)); // } // } // } catch (Exception e) { // System.err.println("Errors found (XmlAttribs):\n\t" + e.toString() + "\n"); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return null; // } // return parsed_attrs; // } // // public static HashMap<String, String> parseSemiColonAttrs(String attrs) { // HashMap<String, String> parsed_attrs=null; // try{ // String[] attrs_arr = attrs.trim().replaceAll("\\s+", " ").split(";"); // parsed_attrs = new HashMap<String, String>(); // for (int i = 0; i < attrs_arr.length; i++) { // if (attrs_arr[i].matches("[^=]+=[^=]+")) { // String name=attrs_arr[i].substring(0, attrs_arr[i].indexOf('=')); // String value=attrs_arr[i].substring(attrs_arr[i].indexOf('=') + 1); // if (value.matches("\".*\"")) { // value = value.substring(1, value.length() - 1); // } // parsed_attrs.put(name, value); // } // } // } catch (Exception e) { // System.err.println("Errors found (XmlAttribs):\n\t" + e.toString() + "\n"); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return null; // } // return parsed_attrs; // } // // // // // }
import com.cognitionis.utils_basickit.XmlAttribs; import java.util.*;
package com.cognitionis.nlp_files.annotation_scorers; /** * * @author Héctor Llorens * @since 2011 */ public class Judgement implements Comparable<Judgement> { // public and static to be accessed from outside in switchs if needed public static enum judgements {corr,inco,spur,miss;} // Correct, Incorrect, Spurious, Missing private int judgement; private String element; private HashMap <String,String> attribs; private HashMap <String,String> alt_annot_attribs; private HashMap <String,Integer> alt_annot_attribs_scores; private int numline; // private String keylines; private String annotlines; public Judgement(int j, String elem, String attrs, int nline, String keyline, String annotline){ try{ if(elem==null || keyline==null || annotline==null){ throw new Exception("Null element, keyline or annotline"); } //judgements.valueOf(j); // Check judgement judgements jdm=judgements.values()[j]; // Check judgement judgement=j; element=elem;
// Path: utils-basickit/src/main/java/com/cognitionis/utils_basickit/XmlAttribs.java // public class XmlAttribs { // // // public static HashMap<String, String> parseAttrs(String attrs) { // // if separated by blanks or consists of only one argument with a quoted value use XML // if(attrs.matches(".*=\"[^\"]*\"\\s+.*") || attrs.matches("[^=]*=\"[^\"]*\"")){ // return parseXMLattrs(attrs); // }else{ // otherwise use ";" separator that handles both quoted and un quoted values // return parseSemiColonAttrs(attrs); // } // } // // public static HashMap<String, String> parseXMLattrs(String attrs) { // HashMap<String, String> parsed_attrs=null; // try{ // attrs=attrs.trim().replaceAll("\\s+", " "); // if(attrs.endsWith("\"")){attrs=attrs.substring(0, attrs.length()-1);} // String[] attrs_arr = attrs.split("\" "); // parsed_attrs = new HashMap<String, String>(); // for (int i = 0; i < attrs_arr.length; i++) { // if (attrs_arr[i].matches("[^=]+=\"[^=]+")) { // parsed_attrs.put(attrs_arr[i].substring(0, attrs_arr[i].indexOf("=\"")), attrs_arr[i].substring(attrs_arr[i].indexOf("=\"") + 2)); // } // } // } catch (Exception e) { // System.err.println("Errors found (XmlAttribs):\n\t" + e.toString() + "\n"); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return null; // } // return parsed_attrs; // } // // public static HashMap<String, String> parseSemiColonAttrs(String attrs) { // HashMap<String, String> parsed_attrs=null; // try{ // String[] attrs_arr = attrs.trim().replaceAll("\\s+", " ").split(";"); // parsed_attrs = new HashMap<String, String>(); // for (int i = 0; i < attrs_arr.length; i++) { // if (attrs_arr[i].matches("[^=]+=[^=]+")) { // String name=attrs_arr[i].substring(0, attrs_arr[i].indexOf('=')); // String value=attrs_arr[i].substring(attrs_arr[i].indexOf('=') + 1); // if (value.matches("\".*\"")) { // value = value.substring(1, value.length() - 1); // } // parsed_attrs.put(name, value); // } // } // } catch (Exception e) { // System.err.println("Errors found (XmlAttribs):\n\t" + e.toString() + "\n"); // if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) { // e.printStackTrace(System.err); // System.exit(1); // } // return null; // } // return parsed_attrs; // } // // // // // } // Path: nlp-files/src/main/java/com/cognitionis/nlp_files/annotation_scorers/Judgement.java import com.cognitionis.utils_basickit.XmlAttribs; import java.util.*; package com.cognitionis.nlp_files.annotation_scorers; /** * * @author Héctor Llorens * @since 2011 */ public class Judgement implements Comparable<Judgement> { // public and static to be accessed from outside in switchs if needed public static enum judgements {corr,inco,spur,miss;} // Correct, Incorrect, Spurious, Missing private int judgement; private String element; private HashMap <String,String> attribs; private HashMap <String,String> alt_annot_attribs; private HashMap <String,Integer> alt_annot_attribs_scores; private int numline; // private String keylines; private String annotlines; public Judgement(int j, String elem, String attrs, int nline, String keyline, String annotline){ try{ if(elem==null || keyline==null || annotline==null){ throw new Exception("Null element, keyline or annotline"); } //judgements.valueOf(j); // Check judgement judgements jdm=judgements.values()[j]; // Check judgement judgement=j; element=elem;
attribs=XmlAttribs.parseXMLattrs(attrs);
rdlester/hermes
hermes/animation/Tileset.java
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // }
import hermes.Hermes; import processing.core.PImage;
package hermes.animation; public class Tileset { private PImage _tileImage; //a tile set aka a tile map aka a sprite sheet private int _tileWidth; //width of tiles in the sheet, in pixels private int _tileHeight;//height of tiles in the sheet, in pixels private PImage[][] _slicedTiles; //we preprocess the images by cutting them up and storing them in this grid /** * * @param tileImage PImage of tileset to cut up * @param tileWidth width of tiles in the set, in pixels * @param tileHeight height of tiles in the set, in pixels */ @SuppressWarnings("static-access") public Tileset(PImage tileImage, int tileWidth, int tileHeight) { _tileImage = tileImage; _tileWidth = tileWidth; _tileHeight = tileHeight; //initialize array, figure out how many rows and cols (note: _slicedTiles[y][x]) _slicedTiles = new PImage[tileImage.height / _tileHeight][tileImage.width / _tileWidth]; //cut the image into slices for (int row = 0; row < _tileImage.height / _tileHeight; row++) { for (int col = 0; col < _tileImage.width / _tileWidth; col++) { //Create a new image slice that corresponds to the size of the tiles in this set
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // } // Path: hermes/animation/Tileset.java import hermes.Hermes; import processing.core.PImage; package hermes.animation; public class Tileset { private PImage _tileImage; //a tile set aka a tile map aka a sprite sheet private int _tileWidth; //width of tiles in the sheet, in pixels private int _tileHeight;//height of tiles in the sheet, in pixels private PImage[][] _slicedTiles; //we preprocess the images by cutting them up and storing them in this grid /** * * @param tileImage PImage of tileset to cut up * @param tileWidth width of tiles in the set, in pixels * @param tileHeight height of tiles in the set, in pixels */ @SuppressWarnings("static-access") public Tileset(PImage tileImage, int tileWidth, int tileHeight) { _tileImage = tileImage; _tileWidth = tileWidth; _tileHeight = tileHeight; //initialize array, figure out how many rows and cols (note: _slicedTiles[y][x]) _slicedTiles = new PImage[tileImage.height / _tileHeight][tileImage.width / _tileWidth]; //cut the image into slices for (int row = 0; row < _tileImage.height / _tileHeight; row++) { for (int col = 0; col < _tileImage.width / _tileWidth; col++) { //Create a new image slice that corresponds to the size of the tiles in this set
PImage slice = Hermes.getPApplet().createImage(_tileWidth, _tileHeight, Hermes.getPApplet().ARGB);
rdlester/hermes
hermes/animation/AnimatedSprite.java
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // }
import hermes.Hermes; import java.util.ArrayList; import processing.core.*;
} if (_millisecondsPerFrameOnDeckFlag) { _currentMillisecondsPerFrame = _millisecondsPerFrameOnDeck; //update the millisecondsPerFrame used based on the onDeck buffer _millisecondsPerFrameOnDeckFlag = false; //reset flag } if (_initialFrameOnDeckFlag) { _initialFrame = _initialFrameOnDeck; //update the initialFrame to use based on the onDeck buffer _initialFrameOnDeckFlag = false; //reset flag } if (_lastFrameOnDeckFlag) { _lastFrame = _lastFrameOnDeck; //update the lastFrame to use based on the onDeck buffer _lastFrameOnDeckFlag = false; //reset flag } if (_playDirectionLeftToRightOnDeckFlag) { _playDirectionLeftToRight = _playDirectionLeftToRightOnDeck; //update the play direction based on the onDeck buffer _playDirectionLeftToRightOnDeckFlag = false; //reset flag } if (!_playingOnDeck) { _playing = _playingOnDeck; } } ////////2) if(_playing) {
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // } // Path: hermes/animation/AnimatedSprite.java import hermes.Hermes; import java.util.ArrayList; import processing.core.*; } if (_millisecondsPerFrameOnDeckFlag) { _currentMillisecondsPerFrame = _millisecondsPerFrameOnDeck; //update the millisecondsPerFrame used based on the onDeck buffer _millisecondsPerFrameOnDeckFlag = false; //reset flag } if (_initialFrameOnDeckFlag) { _initialFrame = _initialFrameOnDeck; //update the initialFrame to use based on the onDeck buffer _initialFrameOnDeckFlag = false; //reset flag } if (_lastFrameOnDeckFlag) { _lastFrame = _lastFrameOnDeck; //update the lastFrame to use based on the onDeck buffer _lastFrameOnDeckFlag = false; //reset flag } if (_playDirectionLeftToRightOnDeckFlag) { _playDirectionLeftToRight = _playDirectionLeftToRightOnDeck; //update the play direction based on the onDeck buffer _playDirectionLeftToRightOnDeckFlag = false; //reset flag } if (!_playingOnDeck) { _playing = _playingOnDeck; } } ////////2) if(_playing) {
int currentTime = Hermes.getPApplet().millis();
rdlester/hermes
hermes/animation/Animation.java
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // }
import hermes.Hermes; import java.util.ArrayList; import processing.core.*;
package hermes.animation; /** * <p>This class is used to store the PImages that make up a single animation and some properties * that aid in playing that animation. These properties values should be thought of as "default" * for this particular Animation, values that you know will work well or be used the most often. </p> * * <p>The key properties are:</p> * <ul> * <li>millisecondsPerFrame - specifies the rate at which the frames should be advanced. In other words, * how long a given frame appears on screen before advancing to the next. * * <li>interruptible - This is used to determine what happens when an AnimatedSprite's setActiveAnimation is called while this Animation is playing. * By default, this is set to true on construction. * <p>If set to true, the AnimatedSprite will immediately switch to the new Animation.</p> * <p>If set to false, this Animation will play to completion before changing * If numberOfTimesToPlay is set to INFINITE_LOOPS, it will play to the end of the cycle before switching. * Otherwise, the Animation will play through the remaining cycles it has left before switching. * Upon completion of playback, if setActiveAnimation has been called one or more times, the * AnimatedSprite's activeAnimation will be set to the one specified by the most recent call.</p> * * * <li><p>numberOfTimesToPlay - Specifies how many times this animation will play. * It can be set to any positive integer value, or INFINITE_LOOPS for looping the Animation * infinitely. By default, this is set to INFINITE_LOOPS on construction. * If the animation completes playing through its numberOfTimesToPlay and no calls * to AnimatedSprite's setActiveAnimation were made, the Animation will display its defaultFrame. * * <li><p>defaultFrame - the index of the frame that completed animations will rest on. By default * this is set to 0 (the first frame in the Animation) on construction. * </ul> */ public class Animation implements AnimationConstants { private int _millisecondsPerFrame; //in milliseconds private boolean _isInterruptible = true; //this specifies if the Animation can be escaped at on any frame private int _numberOfTimesToPlay = INFINITE_LOOPS; private int _defaultFrame = 0; ArrayList<PImage> _frames; //Collection of each frame used in the Animation /** * Builds an Animation from several image files on disk (where each is an individual frame in the Animation), and adds it to the Sprite's collection of Animations * * <p>The method loads files with numbers starting from 0 to (numberOfImagesToLoad-1) and assumes numerical contiguity * <br>ex. Explosion0.jpg, Explosion1.jpg, Explosion2.jpg would have method call: * <br>addAnimationFromSequenceOfImages("Explosion", 3, ".jpg");</P> * * <p>Works with all image filetypes supported by PImage: .gif, .jgp, tga, .png</p> * * @param imageSequenceNamePrefix file prefix of all of the images to be loaded into this Animation ex. "Explosion" * @param numberOfImagesToLoad total number of images to load (note: your names should be indexed starting from 0) * @param fileType file extension including the 'dot' - supports: ".gif" ".jgp" ".tga" ".png" * @param millisecondsPerFrame amount of time each frame in the Animation is displayed, in milliseconds */ public Animation(String imageSequenceNamePrefix, int numberOfImagesToLoad, String fileType, int millisecondsPerFrame) { //asserts to check for valid inputs assert supportImageType(fileType): "addAnimation Error: Images of filetype: "+fileType+"not supported.\n Suported types: .gif, .jgp, tga, .png"; _millisecondsPerFrame = millisecondsPerFrame; ArrayList<PImage> currentAnimation = new ArrayList<PImage>(); // make an ArrayList to store Animation being built //populates current Animation with the files named: <imageSequenceNamePrefix>i<fileType> //ex. Explosion4.jpg for (int i = 0; i < numberOfImagesToLoad; i++) {
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // } // Path: hermes/animation/Animation.java import hermes.Hermes; import java.util.ArrayList; import processing.core.*; package hermes.animation; /** * <p>This class is used to store the PImages that make up a single animation and some properties * that aid in playing that animation. These properties values should be thought of as "default" * for this particular Animation, values that you know will work well or be used the most often. </p> * * <p>The key properties are:</p> * <ul> * <li>millisecondsPerFrame - specifies the rate at which the frames should be advanced. In other words, * how long a given frame appears on screen before advancing to the next. * * <li>interruptible - This is used to determine what happens when an AnimatedSprite's setActiveAnimation is called while this Animation is playing. * By default, this is set to true on construction. * <p>If set to true, the AnimatedSprite will immediately switch to the new Animation.</p> * <p>If set to false, this Animation will play to completion before changing * If numberOfTimesToPlay is set to INFINITE_LOOPS, it will play to the end of the cycle before switching. * Otherwise, the Animation will play through the remaining cycles it has left before switching. * Upon completion of playback, if setActiveAnimation has been called one or more times, the * AnimatedSprite's activeAnimation will be set to the one specified by the most recent call.</p> * * * <li><p>numberOfTimesToPlay - Specifies how many times this animation will play. * It can be set to any positive integer value, or INFINITE_LOOPS for looping the Animation * infinitely. By default, this is set to INFINITE_LOOPS on construction. * If the animation completes playing through its numberOfTimesToPlay and no calls * to AnimatedSprite's setActiveAnimation were made, the Animation will display its defaultFrame. * * <li><p>defaultFrame - the index of the frame that completed animations will rest on. By default * this is set to 0 (the first frame in the Animation) on construction. * </ul> */ public class Animation implements AnimationConstants { private int _millisecondsPerFrame; //in milliseconds private boolean _isInterruptible = true; //this specifies if the Animation can be escaped at on any frame private int _numberOfTimesToPlay = INFINITE_LOOPS; private int _defaultFrame = 0; ArrayList<PImage> _frames; //Collection of each frame used in the Animation /** * Builds an Animation from several image files on disk (where each is an individual frame in the Animation), and adds it to the Sprite's collection of Animations * * <p>The method loads files with numbers starting from 0 to (numberOfImagesToLoad-1) and assumes numerical contiguity * <br>ex. Explosion0.jpg, Explosion1.jpg, Explosion2.jpg would have method call: * <br>addAnimationFromSequenceOfImages("Explosion", 3, ".jpg");</P> * * <p>Works with all image filetypes supported by PImage: .gif, .jgp, tga, .png</p> * * @param imageSequenceNamePrefix file prefix of all of the images to be loaded into this Animation ex. "Explosion" * @param numberOfImagesToLoad total number of images to load (note: your names should be indexed starting from 0) * @param fileType file extension including the 'dot' - supports: ".gif" ".jgp" ".tga" ".png" * @param millisecondsPerFrame amount of time each frame in the Animation is displayed, in milliseconds */ public Animation(String imageSequenceNamePrefix, int numberOfImagesToLoad, String fileType, int millisecondsPerFrame) { //asserts to check for valid inputs assert supportImageType(fileType): "addAnimation Error: Images of filetype: "+fileType+"not supported.\n Suported types: .gif, .jgp, tga, .png"; _millisecondsPerFrame = millisecondsPerFrame; ArrayList<PImage> currentAnimation = new ArrayList<PImage>(); // make an ArrayList to store Animation being built //populates current Animation with the files named: <imageSequenceNamePrefix>i<fileType> //ex. Explosion4.jpg for (int i = 0; i < numberOfImagesToLoad; i++) {
PImage currentImage = Hermes.getPApplet().loadImage(imageSequenceNamePrefix + i + fileType);
rdlester/hermes
hermesTest/shapeTests/RectangleTest.java
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // }
import static org.junit.Assert.*; import hermes.Hermes; import hermes.hshape.*; import org.junit.*; import processing.core.*;
package hermesTest.shapeTests; /** * unit tests for Hermes.shape.HRectangle * @author Sam * */ public class HRectangleTest { @Before public void setup() { PApplet applet = new PApplet(); applet.g = new PGraphics();
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // } // Path: hermesTest/shapeTests/RectangleTest.java import static org.junit.Assert.*; import hermes.Hermes; import hermes.hshape.*; import org.junit.*; import processing.core.*; package hermesTest.shapeTests; /** * unit tests for Hermes.shape.HRectangle * @author Sam * */ public class HRectangleTest { @Before public void setup() { PApplet applet = new PApplet(); applet.g = new PGraphics();
Hermes.setPApplet(applet);
rdlester/hermes
hermes/physics/InverseSquareInteractor.java
// Path: hermes/HermesMath.java // public static PVector reverse(PVector vector) { // vector.x = -vector.x; // vector.y = -vector.y; // vector.z = -vector.z; // return vector; // }
import static hermes.HermesMath.reverse; import hermes.*; import processing.core.PVector;
package hermes.physics; /** * <p> * A general inverse square-law force interactor. * Each being in the interaction will receive an equal and opposite force <b>F = k * q1 * q2 / r^2</b> * where <b>k</b> is a factor set in the constructor, <b>q1</b> and <b>q2</b> are determined by <code>beingFactor</code> * for the first and second beings respectively, and <b>r</b> is the distance between the beings. It can also be given a maximum range. * */ public abstract class InverseSquareInteractor extends Interactor<MassedBeing, MassedBeing> { private float _maxRangeSquared; // the maximum interaction range private float _k; // the gravity constant /** * Sets up a <code>ColoumbInteractor</code> with a range limit. * @param factor the force constant factor (k in the Coloumb equation) * @param maxRange the maximum range of the interaction. Beings separated by a distance greater than this range will not interact. */ public InverseSquareInteractor(float factor, float maxRange) { _k = factor; _maxRangeSquared = maxRange * maxRange; } /** * Sets up a <code>ColoumbInteractor</code> with no range limit. * @param factor the force constant factor (k in the Coloumb equation) */ public InverseSquareInteractor(float factor) { _k = factor; _maxRangeSquared = Float.POSITIVE_INFINITY; } public boolean detect(MassedBeing being1, MassedBeing being2) { if(being1 == being2) // no self-interaction return false; PVector r = PVector.sub(being1.getPosition(), being2.getPosition()); float d_squared = r.dot(r); // check if the distance is within the maximum range return d_squared <= _maxRangeSquared && d_squared != 0; } public void handle(MassedBeing being1, MassedBeing being2) { // F = k * q1 * q2 / r^2 PVector r = PVector.sub(being2.getPosition(), being1.getPosition()); double d_squared = (double)r.dot(r); double F = _k * beingFactor(being1) * beingFactor(being2) / d_squared; r.normalize(); PVector force = PVector.mult(r, (float)F); being2.addForce(force);
// Path: hermes/HermesMath.java // public static PVector reverse(PVector vector) { // vector.x = -vector.x; // vector.y = -vector.y; // vector.z = -vector.z; // return vector; // } // Path: hermes/physics/InverseSquareInteractor.java import static hermes.HermesMath.reverse; import hermes.*; import processing.core.PVector; package hermes.physics; /** * <p> * A general inverse square-law force interactor. * Each being in the interaction will receive an equal and opposite force <b>F = k * q1 * q2 / r^2</b> * where <b>k</b> is a factor set in the constructor, <b>q1</b> and <b>q2</b> are determined by <code>beingFactor</code> * for the first and second beings respectively, and <b>r</b> is the distance between the beings. It can also be given a maximum range. * */ public abstract class InverseSquareInteractor extends Interactor<MassedBeing, MassedBeing> { private float _maxRangeSquared; // the maximum interaction range private float _k; // the gravity constant /** * Sets up a <code>ColoumbInteractor</code> with a range limit. * @param factor the force constant factor (k in the Coloumb equation) * @param maxRange the maximum range of the interaction. Beings separated by a distance greater than this range will not interact. */ public InverseSquareInteractor(float factor, float maxRange) { _k = factor; _maxRangeSquared = maxRange * maxRange; } /** * Sets up a <code>ColoumbInteractor</code> with no range limit. * @param factor the force constant factor (k in the Coloumb equation) */ public InverseSquareInteractor(float factor) { _k = factor; _maxRangeSquared = Float.POSITIVE_INFINITY; } public boolean detect(MassedBeing being1, MassedBeing being2) { if(being1 == being2) // no self-interaction return false; PVector r = PVector.sub(being1.getPosition(), being2.getPosition()); float d_squared = r.dot(r); // check if the distance is within the maximum range return d_squared <= _maxRangeSquared && d_squared != 0; } public void handle(MassedBeing being1, MassedBeing being2) { // F = k * q1 * q2 / r^2 PVector r = PVector.sub(being2.getPosition(), being1.getPosition()); double d_squared = (double)r.dot(r); double F = _k * beingFactor(being1) * beingFactor(being2) / d_squared; r.normalize(); PVector force = PVector.mult(r, (float)F); being2.addForce(force);
being1.addForce(reverse(force));
rdlester/hermes
hermesTest/shapeTests/CircleTest.java
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // }
import static org.junit.Assert.*; import hermes.Hermes; import hermes.hshape.*; import processing.core.*; import org.junit.*;
package hermesTest.shapeTests; public class HCircleTest { @Before public void setup() { PApplet applet = new PApplet(); applet.g = new PGraphics();
// Path: hermes/Hermes.java // public class Hermes { // // private static PApplet _parentApplet = null; //Storage of sketch's PApplet. // private static float _timeScale = 1.0f; // the time scale used by Hermes motion and physics calculations // // /** // * Sets the time scale for calculating motion and physics. This is seconds/unit, so a value of 2 will mean // * each 2 seconds correspond to one time unit. // * @param scale // */ // public static void setTimeScale(float scale) { // _timeScale = scale; // } // // /** // * Returns the Hermes time scale. // * @return the time scale // */ // public static float getTimeScale() { // return _timeScale; // } // // /** // * Returns the <code>PApplet</code> that Hermes is running in. // */ // public static PApplet getPApplet() { // synchronized(_parentApplet) { // return _parentApplet; // } // } // // /** // * Set the PApplet that all utilities use. Called <code>Hermes.setPApplet(this)</code> before doing anything else! // */ // public static void setPApplet(PApplet parentApplet) { // _parentApplet = parentApplet; // } // // /** // * Causes the calling thread to sleep, catches InterruptedException. // * @param time the time (in milliseconds) to sleep // */ // public static void unsafeSleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) {} // } // // } // Path: hermesTest/shapeTests/CircleTest.java import static org.junit.Assert.*; import hermes.Hermes; import hermes.hshape.*; import processing.core.*; import org.junit.*; package hermesTest.shapeTests; public class HCircleTest { @Before public void setup() { PApplet applet = new PApplet(); applet.g = new PGraphics();
Hermes.setPApplet(applet);
Nescafemix/hintcase
HintCaseAssets/src/main/java/com/joanfuentes/hintcaseassets/shapeanimators/FadeInShapeAnimator.java
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/ShapeAnimator.java // public abstract class ShapeAnimator { // public static final int DEFAULT_ANIMATION_DURATION_IN_MILLISECONDS = 300; // public static final ShapeAnimator NO_ANIMATOR = null; // public static final OnFinishListener NO_CALLBACK = null; // protected int durationInMilliseconds; // protected long startDelayInMilliseconds; // // public ShapeAnimator() { // durationInMilliseconds = DEFAULT_ANIMATION_DURATION_IN_MILLISECONDS; // } // // public ShapeAnimator(int durationInMilliseconds) { // this.durationInMilliseconds = durationInMilliseconds; // } // // abstract public ValueAnimator getAnimator(View view, Shape shape, OnFinishListener onFinishListener); // // public ValueAnimator getAnimator(View view, Shape shape) { // return getAnimator(view, shape, NO_CALLBACK); // } // // public interface OnFinishListener { // void onFinish(); // } // // public ShapeAnimator setStartDelay(long startDelayInMilliseconds) { // this.startDelayInMilliseconds = startDelayInMilliseconds; // return this; // } // } // // Path: HintCase/src/main/java/com/joanfuentes/hintcase/Shape.java // public abstract class Shape { // private static final int DEFAULT_COLOR = 0xFFFFFF; // private static final int DEFAULT_ALPHA = 0; // private int left; // private int top; // private int right; // private int bottom; // private float centerX; // private float centerY; // private float width; // private float height; // private Paint shapePaint; // // public Shape() { // shapePaint = getInitializedTypePaint(); // } // // private Paint getInitializedTypePaint() { // Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // paint.setColor(DEFAULT_COLOR); // paint.setAlpha(DEFAULT_ALPHA); // paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); // return paint; // } // // public int getLeft() { // return left; // } // // public void setLeft(int left) { // this.left = left; // } // // public int getTop() { // return top; // } // // public void setTop(int top) { // this.top = top; // } // // public int getRight() { // return right; // } // // public void setRight(int right) { // this.right = right; // } // // public int getBottom() { // return bottom; // } // // public void setBottom(int bottom) { // this.bottom = bottom; // } // // public float getCenterX() { // return centerX; // } // // public void setCenterX(float centerX) { // this.centerX = centerX; // } // // public float getCenterY() { // return centerY; // } // // public void setCenterY(float centerY) { // this.centerY = centerY; // } // // public float getWidth() { // return width; // } // // public void setWidth(float width) { // this.width = width; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public Paint getShapePaint() { // return shapePaint; // } // // abstract public void setMinimumValue(); // abstract public void setShapeInfo(View targetView, ViewGroup parent, int offset, Context context); // abstract public boolean isTouchEventInsideTheHint(MotionEvent event); // abstract public void draw(Canvas canvas); // }
import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.view.View; import com.joanfuentes.hintcase.ShapeAnimator; import com.joanfuentes.hintcase.Shape;
package com.joanfuentes.hintcaseassets.shapeanimators; public class FadeInShapeAnimator extends ShapeAnimator { public FadeInShapeAnimator() { super(); } public FadeInShapeAnimator(int durationInMilliseconds) { super(durationInMilliseconds); } @Override
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/ShapeAnimator.java // public abstract class ShapeAnimator { // public static final int DEFAULT_ANIMATION_DURATION_IN_MILLISECONDS = 300; // public static final ShapeAnimator NO_ANIMATOR = null; // public static final OnFinishListener NO_CALLBACK = null; // protected int durationInMilliseconds; // protected long startDelayInMilliseconds; // // public ShapeAnimator() { // durationInMilliseconds = DEFAULT_ANIMATION_DURATION_IN_MILLISECONDS; // } // // public ShapeAnimator(int durationInMilliseconds) { // this.durationInMilliseconds = durationInMilliseconds; // } // // abstract public ValueAnimator getAnimator(View view, Shape shape, OnFinishListener onFinishListener); // // public ValueAnimator getAnimator(View view, Shape shape) { // return getAnimator(view, shape, NO_CALLBACK); // } // // public interface OnFinishListener { // void onFinish(); // } // // public ShapeAnimator setStartDelay(long startDelayInMilliseconds) { // this.startDelayInMilliseconds = startDelayInMilliseconds; // return this; // } // } // // Path: HintCase/src/main/java/com/joanfuentes/hintcase/Shape.java // public abstract class Shape { // private static final int DEFAULT_COLOR = 0xFFFFFF; // private static final int DEFAULT_ALPHA = 0; // private int left; // private int top; // private int right; // private int bottom; // private float centerX; // private float centerY; // private float width; // private float height; // private Paint shapePaint; // // public Shape() { // shapePaint = getInitializedTypePaint(); // } // // private Paint getInitializedTypePaint() { // Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // paint.setColor(DEFAULT_COLOR); // paint.setAlpha(DEFAULT_ALPHA); // paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); // return paint; // } // // public int getLeft() { // return left; // } // // public void setLeft(int left) { // this.left = left; // } // // public int getTop() { // return top; // } // // public void setTop(int top) { // this.top = top; // } // // public int getRight() { // return right; // } // // public void setRight(int right) { // this.right = right; // } // // public int getBottom() { // return bottom; // } // // public void setBottom(int bottom) { // this.bottom = bottom; // } // // public float getCenterX() { // return centerX; // } // // public void setCenterX(float centerX) { // this.centerX = centerX; // } // // public float getCenterY() { // return centerY; // } // // public void setCenterY(float centerY) { // this.centerY = centerY; // } // // public float getWidth() { // return width; // } // // public void setWidth(float width) { // this.width = width; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public Paint getShapePaint() { // return shapePaint; // } // // abstract public void setMinimumValue(); // abstract public void setShapeInfo(View targetView, ViewGroup parent, int offset, Context context); // abstract public boolean isTouchEventInsideTheHint(MotionEvent event); // abstract public void draw(Canvas canvas); // } // Path: HintCaseAssets/src/main/java/com/joanfuentes/hintcaseassets/shapeanimators/FadeInShapeAnimator.java import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.view.View; import com.joanfuentes.hintcase.ShapeAnimator; import com.joanfuentes.hintcase.Shape; package com.joanfuentes.hintcaseassets.shapeanimators; public class FadeInShapeAnimator extends ShapeAnimator { public FadeInShapeAnimator() { super(); } public FadeInShapeAnimator(int durationInMilliseconds) { super(durationInMilliseconds); } @Override
public ValueAnimator getAnimator(View view, Shape shape,
Nescafemix/hintcase
HintCase/src/main/java/com/joanfuentes/hintcase/HintCase.java
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/utils/DimenUtils.java // public class DimenUtils { // public static int getStatusBarHeight(Context context) { // int statusBarHeight = 0; // Resources resources = context.getResources(); // int id = resources.getIdentifier("status_bar_height", "dimen", "android"); // if (id > 0) { // statusBarHeight = resources.getDimensionPixelSize(id); // } // return statusBarHeight; // } // // public static int getActionBarHeight(Context context) { // int actionBarHeight = 0; // TypedValue tv = new TypedValue(); // if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { // actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, // context.getResources().getDisplayMetrics()); // } // return actionBarHeight; // } // // public static int dipToPixels(Context context, float valueInDP) { // DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDP, displayMetrics); // } // // public static Point getNavigationBarSizeIfExistAtTheBottom(Context context) { // Point appUsableSize = getAppUsableScreenSize(context); // Point realScreenSize = getRealScreenSize(context); // Point navigationPoint; // boolean navigationBarIsPresent = appUsableSize.y < realScreenSize.y; // if (navigationBarIsPresent) { // navigationPoint = new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y); // } else { // navigationPoint = new Point(); // } // return navigationPoint; // } // // public static Point getNavigationBarSizeIfExistOnTheRight(Context context) { // Point appUsableSize = getAppUsableScreenSize(context); // Point realScreenSize = getRealScreenSize(context); // Point navigationPoint; // boolean navigationBarIsPresent = appUsableSize.x < realScreenSize.x; // if (navigationBarIsPresent) { // navigationPoint = new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y); // } else { // navigationPoint = new Point(); // } // return navigationPoint; // } // // public static Point getAppUsableScreenSize(Context context) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // return size; // } // // public static Point getRealScreenSize(Context context) { // Point size = new Point(); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // display.getRealSize(size); // } else { // View decorView = null; // if(context instanceof Activity) { // decorView = ((Activity) context).getWindow().getDecorView(); // } else if(context instanceof ContextThemeWrapper) { // Context baseContext = ((ContextThemeWrapper) context).getBaseContext(); // if(baseContext instanceof Activity) { // decorView = ((Activity) baseContext).getWindow().getDecorView(); // } // } // if(decorView != null) { // size.x = decorView.getWidth(); // size.y = decorView.getHeight(); // } // } // return size; // } // }
import android.app.Activity; import android.content.Context; import android.support.annotation.DimenRes; import android.view.View; import com.joanfuentes.hintcase.utils.DimenUtils;
private HintCaseView hintCaseView; private Context context; public Shape getShape() { return this.hintCaseView.getShape(); } public void hide() { this.hintCaseView.performHide(); this.hintCaseView = null; } public interface OnClosedListener { void onClosed(); } public HintCase(View view) { this.context = view.getContext(); this.hintCaseView = new HintCaseView(context, this); this.hintCaseView.setTargetInfo(null, new RectangularShape(), NO_OFFSET_IN_PX, TARGET_IS_NOT_CLICKABLE); this.hintCaseView.setParentView(view); } public View getView() { return this.hintCaseView; } public HintCase setTarget(View target) {
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/utils/DimenUtils.java // public class DimenUtils { // public static int getStatusBarHeight(Context context) { // int statusBarHeight = 0; // Resources resources = context.getResources(); // int id = resources.getIdentifier("status_bar_height", "dimen", "android"); // if (id > 0) { // statusBarHeight = resources.getDimensionPixelSize(id); // } // return statusBarHeight; // } // // public static int getActionBarHeight(Context context) { // int actionBarHeight = 0; // TypedValue tv = new TypedValue(); // if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { // actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, // context.getResources().getDisplayMetrics()); // } // return actionBarHeight; // } // // public static int dipToPixels(Context context, float valueInDP) { // DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDP, displayMetrics); // } // // public static Point getNavigationBarSizeIfExistAtTheBottom(Context context) { // Point appUsableSize = getAppUsableScreenSize(context); // Point realScreenSize = getRealScreenSize(context); // Point navigationPoint; // boolean navigationBarIsPresent = appUsableSize.y < realScreenSize.y; // if (navigationBarIsPresent) { // navigationPoint = new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y); // } else { // navigationPoint = new Point(); // } // return navigationPoint; // } // // public static Point getNavigationBarSizeIfExistOnTheRight(Context context) { // Point appUsableSize = getAppUsableScreenSize(context); // Point realScreenSize = getRealScreenSize(context); // Point navigationPoint; // boolean navigationBarIsPresent = appUsableSize.x < realScreenSize.x; // if (navigationBarIsPresent) { // navigationPoint = new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y); // } else { // navigationPoint = new Point(); // } // return navigationPoint; // } // // public static Point getAppUsableScreenSize(Context context) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // return size; // } // // public static Point getRealScreenSize(Context context) { // Point size = new Point(); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // display.getRealSize(size); // } else { // View decorView = null; // if(context instanceof Activity) { // decorView = ((Activity) context).getWindow().getDecorView(); // } else if(context instanceof ContextThemeWrapper) { // Context baseContext = ((ContextThemeWrapper) context).getBaseContext(); // if(baseContext instanceof Activity) { // decorView = ((Activity) baseContext).getWindow().getDecorView(); // } // } // if(decorView != null) { // size.x = decorView.getWidth(); // size.y = decorView.getHeight(); // } // } // return size; // } // } // Path: HintCase/src/main/java/com/joanfuentes/hintcase/HintCase.java import android.app.Activity; import android.content.Context; import android.support.annotation.DimenRes; import android.view.View; import com.joanfuentes.hintcase.utils.DimenUtils; private HintCaseView hintCaseView; private Context context; public Shape getShape() { return this.hintCaseView.getShape(); } public void hide() { this.hintCaseView.performHide(); this.hintCaseView = null; } public interface OnClosedListener { void onClosed(); } public HintCase(View view) { this.context = view.getContext(); this.hintCaseView = new HintCaseView(context, this); this.hintCaseView.setTargetInfo(null, new RectangularShape(), NO_OFFSET_IN_PX, TARGET_IS_NOT_CLICKABLE); this.hintCaseView.setParentView(view); } public View getView() { return this.hintCaseView; } public HintCase setTarget(View target) {
int offsetInPx = DimenUtils.dipToPixels(context, HintCase.DEFAULT_SHAPE_OFFSET_IN_DP);
Nescafemix/hintcase
HintCase/src/main/java/com/joanfuentes/hintcase/HintCaseView.java
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/utils/DimenUtils.java // public class DimenUtils { // public static int getStatusBarHeight(Context context) { // int statusBarHeight = 0; // Resources resources = context.getResources(); // int id = resources.getIdentifier("status_bar_height", "dimen", "android"); // if (id > 0) { // statusBarHeight = resources.getDimensionPixelSize(id); // } // return statusBarHeight; // } // // public static int getActionBarHeight(Context context) { // int actionBarHeight = 0; // TypedValue tv = new TypedValue(); // if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { // actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, // context.getResources().getDisplayMetrics()); // } // return actionBarHeight; // } // // public static int dipToPixels(Context context, float valueInDP) { // DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDP, displayMetrics); // } // // public static Point getNavigationBarSizeIfExistAtTheBottom(Context context) { // Point appUsableSize = getAppUsableScreenSize(context); // Point realScreenSize = getRealScreenSize(context); // Point navigationPoint; // boolean navigationBarIsPresent = appUsableSize.y < realScreenSize.y; // if (navigationBarIsPresent) { // navigationPoint = new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y); // } else { // navigationPoint = new Point(); // } // return navigationPoint; // } // // public static Point getNavigationBarSizeIfExistOnTheRight(Context context) { // Point appUsableSize = getAppUsableScreenSize(context); // Point realScreenSize = getRealScreenSize(context); // Point navigationPoint; // boolean navigationBarIsPresent = appUsableSize.x < realScreenSize.x; // if (navigationBarIsPresent) { // navigationPoint = new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y); // } else { // navigationPoint = new Point(); // } // return navigationPoint; // } // // public static Point getAppUsableScreenSize(Context context) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // return size; // } // // public static Point getRealScreenSize(Context context) { // Point size = new Point(); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // display.getRealSize(size); // } else { // View decorView = null; // if(context instanceof Activity) { // decorView = ((Activity) context).getWindow().getDecorView(); // } else if(context instanceof ContextThemeWrapper) { // Context baseContext = ((ContextThemeWrapper) context).getBaseContext(); // if(baseContext instanceof Activity) { // decorView = ((Activity) baseContext).getWindow().getDecorView(); // } // } // if(decorView != null) { // size.x = decorView.getWidth(); // size.y = decorView.getHeight(); // } // } // return size; // } // }
import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.support.annotation.NonNull; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.joanfuentes.hintcase.utils.DimenUtils; import java.util.ArrayList; import java.util.List;
private HintCase hintCase; private boolean isTargetClickable; private Point navigationBarSizeIfExistAtTheBottom; private Point navigationBarSizeIfExistOnTheRight; private boolean wasPressedOnShape; public View getHintBlockView() { return hintBlockView; } public HintCaseView(Context context, HintCase hintCase) { super(context); init(hintCase); } private void init(HintCase hintCase) { setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); this.hintCase = hintCase; closeOnTouch = true; showExtraContentHolderAnimators = new ArrayList<>(); hideExtraContentHolderAnimators = new ArrayList<>(); hintBlock = NO_BLOCK_INFO; hintBlockView = NO_BLOCK_INFO_VIEW; extraBlocks = new ArrayList<>(); extraBlockViews = new ArrayList<>(); backgroundColor = DEFAULT_BACKGROUND_COLOR; offsetInPx = HintCase.NO_OFFSET_IN_PX; hintBlockPosition = DEFAULT_HINT_BLOCK_POSITION; basePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/utils/DimenUtils.java // public class DimenUtils { // public static int getStatusBarHeight(Context context) { // int statusBarHeight = 0; // Resources resources = context.getResources(); // int id = resources.getIdentifier("status_bar_height", "dimen", "android"); // if (id > 0) { // statusBarHeight = resources.getDimensionPixelSize(id); // } // return statusBarHeight; // } // // public static int getActionBarHeight(Context context) { // int actionBarHeight = 0; // TypedValue tv = new TypedValue(); // if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { // actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, // context.getResources().getDisplayMetrics()); // } // return actionBarHeight; // } // // public static int dipToPixels(Context context, float valueInDP) { // DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDP, displayMetrics); // } // // public static Point getNavigationBarSizeIfExistAtTheBottom(Context context) { // Point appUsableSize = getAppUsableScreenSize(context); // Point realScreenSize = getRealScreenSize(context); // Point navigationPoint; // boolean navigationBarIsPresent = appUsableSize.y < realScreenSize.y; // if (navigationBarIsPresent) { // navigationPoint = new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y); // } else { // navigationPoint = new Point(); // } // return navigationPoint; // } // // public static Point getNavigationBarSizeIfExistOnTheRight(Context context) { // Point appUsableSize = getAppUsableScreenSize(context); // Point realScreenSize = getRealScreenSize(context); // Point navigationPoint; // boolean navigationBarIsPresent = appUsableSize.x < realScreenSize.x; // if (navigationBarIsPresent) { // navigationPoint = new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y); // } else { // navigationPoint = new Point(); // } // return navigationPoint; // } // // public static Point getAppUsableScreenSize(Context context) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // return size; // } // // public static Point getRealScreenSize(Context context) { // Point size = new Point(); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // display.getRealSize(size); // } else { // View decorView = null; // if(context instanceof Activity) { // decorView = ((Activity) context).getWindow().getDecorView(); // } else if(context instanceof ContextThemeWrapper) { // Context baseContext = ((ContextThemeWrapper) context).getBaseContext(); // if(baseContext instanceof Activity) { // decorView = ((Activity) baseContext).getWindow().getDecorView(); // } // } // if(decorView != null) { // size.x = decorView.getWidth(); // size.y = decorView.getHeight(); // } // } // return size; // } // } // Path: HintCase/src/main/java/com/joanfuentes/hintcase/HintCaseView.java import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.support.annotation.NonNull; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.joanfuentes.hintcase.utils.DimenUtils; import java.util.ArrayList; import java.util.List; private HintCase hintCase; private boolean isTargetClickable; private Point navigationBarSizeIfExistAtTheBottom; private Point navigationBarSizeIfExistOnTheRight; private boolean wasPressedOnShape; public View getHintBlockView() { return hintBlockView; } public HintCaseView(Context context, HintCase hintCase) { super(context); init(hintCase); } private void init(HintCase hintCase) { setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); this.hintCase = hintCase; closeOnTouch = true; showExtraContentHolderAnimators = new ArrayList<>(); hideExtraContentHolderAnimators = new ArrayList<>(); hintBlock = NO_BLOCK_INFO; hintBlockView = NO_BLOCK_INFO_VIEW; extraBlocks = new ArrayList<>(); extraBlockViews = new ArrayList<>(); backgroundColor = DEFAULT_BACKGROUND_COLOR; offsetInPx = HintCase.NO_OFFSET_IN_PX; hintBlockPosition = DEFAULT_HINT_BLOCK_POSITION; basePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
navigationBarSizeIfExistAtTheBottom = DimenUtils.getNavigationBarSizeIfExistAtTheBottom(getContext());
Nescafemix/hintcase
HintCaseAssets/src/main/java/com/joanfuentes/hintcaseassets/shapeanimators/FadeOutShapeAnimator.java
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/ShapeAnimator.java // public abstract class ShapeAnimator { // public static final int DEFAULT_ANIMATION_DURATION_IN_MILLISECONDS = 300; // public static final ShapeAnimator NO_ANIMATOR = null; // public static final OnFinishListener NO_CALLBACK = null; // protected int durationInMilliseconds; // protected long startDelayInMilliseconds; // // public ShapeAnimator() { // durationInMilliseconds = DEFAULT_ANIMATION_DURATION_IN_MILLISECONDS; // } // // public ShapeAnimator(int durationInMilliseconds) { // this.durationInMilliseconds = durationInMilliseconds; // } // // abstract public ValueAnimator getAnimator(View view, Shape shape, OnFinishListener onFinishListener); // // public ValueAnimator getAnimator(View view, Shape shape) { // return getAnimator(view, shape, NO_CALLBACK); // } // // public interface OnFinishListener { // void onFinish(); // } // // public ShapeAnimator setStartDelay(long startDelayInMilliseconds) { // this.startDelayInMilliseconds = startDelayInMilliseconds; // return this; // } // } // // Path: HintCase/src/main/java/com/joanfuentes/hintcase/Shape.java // public abstract class Shape { // private static final int DEFAULT_COLOR = 0xFFFFFF; // private static final int DEFAULT_ALPHA = 0; // private int left; // private int top; // private int right; // private int bottom; // private float centerX; // private float centerY; // private float width; // private float height; // private Paint shapePaint; // // public Shape() { // shapePaint = getInitializedTypePaint(); // } // // private Paint getInitializedTypePaint() { // Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // paint.setColor(DEFAULT_COLOR); // paint.setAlpha(DEFAULT_ALPHA); // paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); // return paint; // } // // public int getLeft() { // return left; // } // // public void setLeft(int left) { // this.left = left; // } // // public int getTop() { // return top; // } // // public void setTop(int top) { // this.top = top; // } // // public int getRight() { // return right; // } // // public void setRight(int right) { // this.right = right; // } // // public int getBottom() { // return bottom; // } // // public void setBottom(int bottom) { // this.bottom = bottom; // } // // public float getCenterX() { // return centerX; // } // // public void setCenterX(float centerX) { // this.centerX = centerX; // } // // public float getCenterY() { // return centerY; // } // // public void setCenterY(float centerY) { // this.centerY = centerY; // } // // public float getWidth() { // return width; // } // // public void setWidth(float width) { // this.width = width; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public Paint getShapePaint() { // return shapePaint; // } // // abstract public void setMinimumValue(); // abstract public void setShapeInfo(View targetView, ViewGroup parent, int offset, Context context); // abstract public boolean isTouchEventInsideTheHint(MotionEvent event); // abstract public void draw(Canvas canvas); // }
import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.view.View; import com.joanfuentes.hintcase.ShapeAnimator; import com.joanfuentes.hintcase.Shape;
package com.joanfuentes.hintcaseassets.shapeanimators; public class FadeOutShapeAnimator extends ShapeAnimator { public FadeOutShapeAnimator() { super(); } public FadeOutShapeAnimator(int durationInMilliseconds) { super(durationInMilliseconds); } @Override
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/ShapeAnimator.java // public abstract class ShapeAnimator { // public static final int DEFAULT_ANIMATION_DURATION_IN_MILLISECONDS = 300; // public static final ShapeAnimator NO_ANIMATOR = null; // public static final OnFinishListener NO_CALLBACK = null; // protected int durationInMilliseconds; // protected long startDelayInMilliseconds; // // public ShapeAnimator() { // durationInMilliseconds = DEFAULT_ANIMATION_DURATION_IN_MILLISECONDS; // } // // public ShapeAnimator(int durationInMilliseconds) { // this.durationInMilliseconds = durationInMilliseconds; // } // // abstract public ValueAnimator getAnimator(View view, Shape shape, OnFinishListener onFinishListener); // // public ValueAnimator getAnimator(View view, Shape shape) { // return getAnimator(view, shape, NO_CALLBACK); // } // // public interface OnFinishListener { // void onFinish(); // } // // public ShapeAnimator setStartDelay(long startDelayInMilliseconds) { // this.startDelayInMilliseconds = startDelayInMilliseconds; // return this; // } // } // // Path: HintCase/src/main/java/com/joanfuentes/hintcase/Shape.java // public abstract class Shape { // private static final int DEFAULT_COLOR = 0xFFFFFF; // private static final int DEFAULT_ALPHA = 0; // private int left; // private int top; // private int right; // private int bottom; // private float centerX; // private float centerY; // private float width; // private float height; // private Paint shapePaint; // // public Shape() { // shapePaint = getInitializedTypePaint(); // } // // private Paint getInitializedTypePaint() { // Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // paint.setColor(DEFAULT_COLOR); // paint.setAlpha(DEFAULT_ALPHA); // paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); // return paint; // } // // public int getLeft() { // return left; // } // // public void setLeft(int left) { // this.left = left; // } // // public int getTop() { // return top; // } // // public void setTop(int top) { // this.top = top; // } // // public int getRight() { // return right; // } // // public void setRight(int right) { // this.right = right; // } // // public int getBottom() { // return bottom; // } // // public void setBottom(int bottom) { // this.bottom = bottom; // } // // public float getCenterX() { // return centerX; // } // // public void setCenterX(float centerX) { // this.centerX = centerX; // } // // public float getCenterY() { // return centerY; // } // // public void setCenterY(float centerY) { // this.centerY = centerY; // } // // public float getWidth() { // return width; // } // // public void setWidth(float width) { // this.width = width; // } // // public float getHeight() { // return height; // } // // public void setHeight(float height) { // this.height = height; // } // // public Paint getShapePaint() { // return shapePaint; // } // // abstract public void setMinimumValue(); // abstract public void setShapeInfo(View targetView, ViewGroup parent, int offset, Context context); // abstract public boolean isTouchEventInsideTheHint(MotionEvent event); // abstract public void draw(Canvas canvas); // } // Path: HintCaseAssets/src/main/java/com/joanfuentes/hintcaseassets/shapeanimators/FadeOutShapeAnimator.java import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.view.View; import com.joanfuentes.hintcase.ShapeAnimator; import com.joanfuentes.hintcase.Shape; package com.joanfuentes.hintcaseassets.shapeanimators; public class FadeOutShapeAnimator extends ShapeAnimator { public FadeOutShapeAnimator() { super(); } public FadeOutShapeAnimator(int durationInMilliseconds) { super(durationInMilliseconds); } @Override
public ValueAnimator getAnimator(View view, Shape shape,
Nescafemix/hintcase
HintCase/src/main/java/com/joanfuentes/hintcase/RectangularShape.java
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/utils/RoundRect.java // public class RoundRect { // private Path path; // // public RoundRect(float left, float top, float right, float bottom, float rx, float ry) { // init(left, top, right, bottom, rx, ry, true, true, true, true); // } // // public RoundRect(float left, float top, float right, float bottom, float rx, float ry, // boolean tl, boolean tr, boolean br, boolean bl) { // init(left, top, right, bottom, rx, ry, tl, tr, br, bl); // } // // private void init(float left, float top, float right, float bottom, float rx, float ry, // boolean applyRoundToTopLeft, boolean applyRoundToTopRight, // boolean applyRoundToBottomRight, boolean applyRoundToBottomLeft) { // float width = right - left; // float height = bottom - top; // rx = normalizeValue(rx, 0, width / 2); // ry = normalizeValue(ry, 0, height / 2); // float widthMinusCorners = (width - (2 * rx)); // float heightMinusCorners = (height - (2 * ry)); // path = new Path(); // path.moveTo(right, top + ry); // drawTopRightCorner(rx, ry, applyRoundToTopRight); // path.rLineTo(-widthMinusCorners, 0); // drawTopLeftCorner(rx, ry, applyRoundToTopLeft); // path.rLineTo(0, heightMinusCorners); // drawBottomLeftCorner(rx, ry, applyRoundToBottomLeft); // path.rLineTo(widthMinusCorners, 0); // drawBottomRightCorner(rx, ry, applyRoundToBottomRight); // path.rLineTo(0, -heightMinusCorners); // path.close(); // } // // private void drawBottomRightCorner(float rx, float ry, boolean applyRoundToBottomRight) { // if (applyRoundToBottomRight) { // path.rQuadTo(rx, 0, rx, -ry); // } else { // path.rLineTo(rx, 0); // path.rLineTo(0, -ry); // } // } // // private void drawBottomLeftCorner(float rx, float ry, boolean applyRoundToBottomLeft) { // if (applyRoundToBottomLeft) { // path.rQuadTo(0, ry, rx, ry); // } else { // path.rLineTo(0, ry); // path.rLineTo(rx, 0); // } // } // // private void drawTopLeftCorner(float rx, float ry, boolean applyRoundToTopLeft) { // if (applyRoundToTopLeft) { // path.rQuadTo(-rx, 0, -rx, ry); // } else { // path.rLineTo(-rx, 0); // path.rLineTo(0, ry); // } // } // // private void drawTopRightCorner(float rx, float ry, boolean applyRoundToTopRight) { // if (applyRoundToTopRight) { // path.rQuadTo(0, -ry, -rx, -ry); // } else { // path.rLineTo(0, -ry); // path.rLineTo(-rx, 0); // } // } // // private float normalizeValue(float value, float min, float max) { // if (value < min) { // value = 0; // } // if (value > max) { // value = max; // } // return value; // } // // public Path getPath() { // return path; // } // }
import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.joanfuentes.hintcase.utils.RoundRect;
@Override public boolean isTouchEventInsideTheHint(MotionEvent event) { return event.getRawX() <= getRight() && event.getRawX() >= getLeft() && event.getRawY() <= getBottom() && event.getRawY() >= getTop(); } @Override public void draw(Canvas canvas) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { drawRoundRectAfterLollipop(canvas); } else { drawRoundRectPreLollipop(canvas); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void drawRoundRectAfterLollipop(Canvas canvas) { canvas.drawRoundRect(getCenterX() - (currentWidth / 2), getCenterY() - (currentHeight / 2), getCenterX() + (currentWidth / 2), getCenterY() + (currentHeight / 2), 10f, 10f, getShapePaint()); } private void drawRoundRectPreLollipop(Canvas canvas) {
// Path: HintCase/src/main/java/com/joanfuentes/hintcase/utils/RoundRect.java // public class RoundRect { // private Path path; // // public RoundRect(float left, float top, float right, float bottom, float rx, float ry) { // init(left, top, right, bottom, rx, ry, true, true, true, true); // } // // public RoundRect(float left, float top, float right, float bottom, float rx, float ry, // boolean tl, boolean tr, boolean br, boolean bl) { // init(left, top, right, bottom, rx, ry, tl, tr, br, bl); // } // // private void init(float left, float top, float right, float bottom, float rx, float ry, // boolean applyRoundToTopLeft, boolean applyRoundToTopRight, // boolean applyRoundToBottomRight, boolean applyRoundToBottomLeft) { // float width = right - left; // float height = bottom - top; // rx = normalizeValue(rx, 0, width / 2); // ry = normalizeValue(ry, 0, height / 2); // float widthMinusCorners = (width - (2 * rx)); // float heightMinusCorners = (height - (2 * ry)); // path = new Path(); // path.moveTo(right, top + ry); // drawTopRightCorner(rx, ry, applyRoundToTopRight); // path.rLineTo(-widthMinusCorners, 0); // drawTopLeftCorner(rx, ry, applyRoundToTopLeft); // path.rLineTo(0, heightMinusCorners); // drawBottomLeftCorner(rx, ry, applyRoundToBottomLeft); // path.rLineTo(widthMinusCorners, 0); // drawBottomRightCorner(rx, ry, applyRoundToBottomRight); // path.rLineTo(0, -heightMinusCorners); // path.close(); // } // // private void drawBottomRightCorner(float rx, float ry, boolean applyRoundToBottomRight) { // if (applyRoundToBottomRight) { // path.rQuadTo(rx, 0, rx, -ry); // } else { // path.rLineTo(rx, 0); // path.rLineTo(0, -ry); // } // } // // private void drawBottomLeftCorner(float rx, float ry, boolean applyRoundToBottomLeft) { // if (applyRoundToBottomLeft) { // path.rQuadTo(0, ry, rx, ry); // } else { // path.rLineTo(0, ry); // path.rLineTo(rx, 0); // } // } // // private void drawTopLeftCorner(float rx, float ry, boolean applyRoundToTopLeft) { // if (applyRoundToTopLeft) { // path.rQuadTo(-rx, 0, -rx, ry); // } else { // path.rLineTo(-rx, 0); // path.rLineTo(0, ry); // } // } // // private void drawTopRightCorner(float rx, float ry, boolean applyRoundToTopRight) { // if (applyRoundToTopRight) { // path.rQuadTo(0, -ry, -rx, -ry); // } else { // path.rLineTo(0, -ry); // path.rLineTo(-rx, 0); // } // } // // private float normalizeValue(float value, float min, float max) { // if (value < min) { // value = 0; // } // if (value > max) { // value = max; // } // return value; // } // // public Path getPath() { // return path; // } // } // Path: HintCase/src/main/java/com/joanfuentes/hintcase/RectangularShape.java import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.joanfuentes.hintcase.utils.RoundRect; @Override public boolean isTouchEventInsideTheHint(MotionEvent event) { return event.getRawX() <= getRight() && event.getRawX() >= getLeft() && event.getRawY() <= getBottom() && event.getRawY() >= getTop(); } @Override public void draw(Canvas canvas) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { drawRoundRectAfterLollipop(canvas); } else { drawRoundRectPreLollipop(canvas); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void drawRoundRectAfterLollipop(Canvas canvas) { canvas.drawRoundRect(getCenterX() - (currentWidth / 2), getCenterY() - (currentHeight / 2), getCenterX() + (currentWidth / 2), getCenterY() + (currentHeight / 2), 10f, 10f, getShapePaint()); } private void drawRoundRectPreLollipop(Canvas canvas) {
RoundRect roundRect = new RoundRect(getCenterX() - (currentWidth / 2),
mvescovo/item-reaper
app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry";
import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ public class RepositoryTest { private Repository mRepository; @Mock private DataSource mRemoteDataSource; @Mock private DataSource.GetItemsCallback mGetItemsCallback; @Captor private ArgumentCaptor<DataSource.GetItemsCallback> mItemsCallbackCaptor; @Mock private DataSource.GetNewItemIdCallback mGetNewItemIdCallback; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; @Mock private DataSource.GetItemCallback mGetItemCallback; @Before public void setupRepository() { MockitoAnnotations.initMocks(this); mRepository = new Repository(mRemoteDataSource); } @Test public void getItems_CacheAfterFirstCall() { // First call.
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry"; // Path: app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ public class RepositoryTest { private Repository mRepository; @Mock private DataSource mRemoteDataSource; @Mock private DataSource.GetItemsCallback mGetItemsCallback; @Captor private ArgumentCaptor<DataSource.GetItemsCallback> mItemsCallbackCaptor; @Mock private DataSource.GetNewItemIdCallback mGetNewItemIdCallback; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; @Mock private DataSource.GetItemCallback mGetItemCallback; @Before public void setupRepository() { MockitoAnnotations.initMocks(this); mRepository = new Repository(mRemoteDataSource); } @Test public void getItems_CacheAfterFirstCall() { // First call.
mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback);
mvescovo/item-reaper
app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry";
import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ public class RepositoryTest { private Repository mRepository; @Mock private DataSource mRemoteDataSource; @Mock private DataSource.GetItemsCallback mGetItemsCallback; @Captor private ArgumentCaptor<DataSource.GetItemsCallback> mItemsCallbackCaptor; @Mock private DataSource.GetNewItemIdCallback mGetNewItemIdCallback; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; @Mock private DataSource.GetItemCallback mGetItemCallback; @Before public void setupRepository() { MockitoAnnotations.initMocks(this); mRepository = new Repository(mRemoteDataSource); } @Test public void getItems_CacheAfterFirstCall() { // First call.
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry"; // Path: app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ public class RepositoryTest { private Repository mRepository; @Mock private DataSource mRemoteDataSource; @Mock private DataSource.GetItemsCallback mGetItemsCallback; @Captor private ArgumentCaptor<DataSource.GetItemsCallback> mItemsCallbackCaptor; @Mock private DataSource.GetNewItemIdCallback mGetNewItemIdCallback; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; @Mock private DataSource.GetItemCallback mGetItemCallback; @Before public void setupRepository() { MockitoAnnotations.initMocks(this); mRepository = new Repository(mRemoteDataSource); } @Test public void getItems_CacheAfterFirstCall() { // First call.
mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback);
mvescovo/item-reaper
app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry";
import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ public class RepositoryTest { private Repository mRepository; @Mock private DataSource mRemoteDataSource; @Mock private DataSource.GetItemsCallback mGetItemsCallback; @Captor private ArgumentCaptor<DataSource.GetItemsCallback> mItemsCallbackCaptor; @Mock private DataSource.GetNewItemIdCallback mGetNewItemIdCallback; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; @Mock private DataSource.GetItemCallback mGetItemCallback; @Before public void setupRepository() { MockitoAnnotations.initMocks(this); mRepository = new Repository(mRemoteDataSource); } @Test public void getItems_CacheAfterFirstCall() { // First call.
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry"; // Path: app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ public class RepositoryTest { private Repository mRepository; @Mock private DataSource mRemoteDataSource; @Mock private DataSource.GetItemsCallback mGetItemsCallback; @Captor private ArgumentCaptor<DataSource.GetItemsCallback> mItemsCallbackCaptor; @Mock private DataSource.GetNewItemIdCallback mGetNewItemIdCallback; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; @Mock private DataSource.GetItemCallback mGetItemCallback; @Before public void setupRepository() { MockitoAnnotations.initMocks(this); mRepository = new Repository(mRemoteDataSource); } @Test public void getItems_CacheAfterFirstCall() { // First call.
mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback);
mvescovo/item-reaper
app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry";
import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ public class RepositoryTest { private Repository mRepository; @Mock private DataSource mRemoteDataSource; @Mock private DataSource.GetItemsCallback mGetItemsCallback; @Captor private ArgumentCaptor<DataSource.GetItemsCallback> mItemsCallbackCaptor; @Mock private DataSource.GetNewItemIdCallback mGetNewItemIdCallback; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; @Mock private DataSource.GetItemCallback mGetItemCallback; @Before public void setupRepository() { MockitoAnnotations.initMocks(this); mRepository = new Repository(mRemoteDataSource); } @Test public void getItems_CacheAfterFirstCall() { // First call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data.
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry"; // Path: app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ public class RepositoryTest { private Repository mRepository; @Mock private DataSource mRemoteDataSource; @Mock private DataSource.GetItemsCallback mGetItemsCallback; @Captor private ArgumentCaptor<DataSource.GetItemsCallback> mItemsCallbackCaptor; @Mock private DataSource.GetNewItemIdCallback mGetNewItemIdCallback; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; @Mock private DataSource.GetItemCallback mGetItemCallback; @Before public void setupRepository() { MockitoAnnotations.initMocks(this); mRepository = new Repository(mRemoteDataSource); } @Test public void getItems_CacheAfterFirstCall() { // First call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data.
mItemsCallbackCaptor.getValue().onItemsLoaded(ITEMS);
mvescovo/item-reaper
app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry";
import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
// First call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(ITEMS); // Second call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Confirm the total calls to the remote data source is only 1; the cache was used. verify(mRemoteDataSource, times(1)).getItems(anyString(), anyString(), anyString(), any(DataSource.GetItemsCallback.class)); } @Test public void noItems_getItemsReturnsEmptyList() { List<Item> emptyList = new ArrayList<>(); mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(emptyList); // Returns null verify(mGetItemsCallback).onItemsLoaded(emptyList); } @Test public void getItem_CacheAfterFirstCall() { // First call.
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry"; // Path: app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; // First call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(ITEMS); // Second call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Confirm the total calls to the remote data source is only 1; the cache was used. verify(mRemoteDataSource, times(1)).getItems(anyString(), anyString(), anyString(), any(DataSource.GetItemsCallback.class)); } @Test public void noItems_getItemsReturnsEmptyList() { List<Item> emptyList = new ArrayList<>(); mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(emptyList); // Returns null verify(mGetItemsCallback).onItemsLoaded(emptyList); } @Test public void getItem_CacheAfterFirstCall() { // First call.
mRepository.getItem(ITEM_1.getId(), USER_ID, ITEM_DETAILS_CALLER, mGetItemCallback);
mvescovo/item-reaper
app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry";
import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
// First call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(ITEMS); // Second call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Confirm the total calls to the remote data source is only 1; the cache was used. verify(mRemoteDataSource, times(1)).getItems(anyString(), anyString(), anyString(), any(DataSource.GetItemsCallback.class)); } @Test public void noItems_getItemsReturnsEmptyList() { List<Item> emptyList = new ArrayList<>(); mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(emptyList); // Returns null verify(mGetItemsCallback).onItemsLoaded(emptyList); } @Test public void getItem_CacheAfterFirstCall() { // First call.
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry"; // Path: app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; // First call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(ITEMS); // Second call. mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Confirm the total calls to the remote data source is only 1; the cache was used. verify(mRemoteDataSource, times(1)).getItems(anyString(), anyString(), anyString(), any(DataSource.GetItemsCallback.class)); } @Test public void noItems_getItemsReturnsEmptyList() { List<Item> emptyList = new ArrayList<>(); mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(emptyList); // Returns null verify(mGetItemsCallback).onItemsLoaded(emptyList); } @Test public void getItem_CacheAfterFirstCall() { // First call.
mRepository.getItem(ITEM_1.getId(), USER_ID, ITEM_DETAILS_CALLER, mGetItemCallback);
mvescovo/item-reaper
app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry";
import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
List<Item> emptyList = new ArrayList<>(); mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(emptyList); // Returns null verify(mGetItemsCallback).onItemsLoaded(emptyList); } @Test public void getItem_CacheAfterFirstCall() { // First call. mRepository.getItem(ITEM_1.getId(), USER_ID, ITEM_DETAILS_CALLER, mGetItemCallback); // Trigger callback. verify(mRemoteDataSource).getItem(anyString(), anyString(), anyString(), mItemCallbackCaptor.capture()); // Set the callback data. mItemCallbackCaptor.getValue().onItemLoaded(ITEM_1); // Second call. mRepository.getItem(ITEM_1.getId(), USER_ID, ITEM_DETAILS_CALLER, mGetItemCallback); // Confirm the total calls to the remote data source is only 1; the cache was used. verify(mRemoteDataSource, times(1)).getItem(anyString(), anyString(), anyString(), any(DataSource.GetItemCallback.class)); } @Test public void getItemNotInCache_queriesRemoteDataSource() { // Call to get item not in cache.
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // final static List<Item> ITEMS = Lists.newArrayList(); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_1 = new Item("1", // 1453554000000L, // purchase: 24/01/2016 // 2000, // 0, // 1485176400000L, // expiry: 24/01/2017 // "Clothing", "Casual", "T-shirt", // "Short sleeve", "V-neck", "Plain", "Black", "Dark", "Some secondary colour", // "Some Size", "Some Brand", "Some Shop", "Standard plain T-shirt", "Some note", // "file:///android_asset/black-t-shirt.jpg", false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static Item ITEM_2 = new Item("2", // -1, // purchase: unknown // 3000, // -1, // 1514206800000L, // expiry: 26/12/2017 // "Bathroom", null, // "Towel", null, null, null, "White", null, null, null, null, null, null, null, null, // false); // // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenter.java // public final static String ITEM_DETAILS_CALLER = "item_details"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsPresenter.java // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // public final static String ITEMS_CALLER = "items"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry"; // Path: app/src/testMock/java/com/michaelvescovo/android/itemreaper/data/RepositoryTest.java import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEMS; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static com.michaelvescovo.android.itemreaper.item_details.ItemDetailsPresenter.ITEM_DETAILS_CALLER; import static com.michaelvescovo.android.itemreaper.items.ItemsPresenter.ITEMS_CALLER; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; List<Item> emptyList = new ArrayList<>(); mRepository.getItems(USER_ID, SORT_BY_EXPIRY_STRING, ITEMS_CALLER, mGetItemsCallback); // Trigger callback. verify(mRemoteDataSource).getItems(anyString(), anyString(), anyString(), mItemsCallbackCaptor.capture()); // Set the callback data. mItemsCallbackCaptor.getValue().onItemsLoaded(emptyList); // Returns null verify(mGetItemsCallback).onItemsLoaded(emptyList); } @Test public void getItem_CacheAfterFirstCall() { // First call. mRepository.getItem(ITEM_1.getId(), USER_ID, ITEM_DETAILS_CALLER, mGetItemCallback); // Trigger callback. verify(mRemoteDataSource).getItem(anyString(), anyString(), anyString(), mItemCallbackCaptor.capture()); // Set the callback data. mItemCallbackCaptor.getValue().onItemLoaded(ITEM_1); // Second call. mRepository.getItem(ITEM_1.getId(), USER_ID, ITEM_DETAILS_CALLER, mGetItemCallback); // Confirm the total calls to the remote data source is only 1; the cache was used. verify(mRemoteDataSource, times(1)).getItem(anyString(), anyString(), anyString(), any(DataSource.GetItemCallback.class)); } @Test public void getItemNotInCache_queriesRemoteDataSource() { // Call to get item not in cache.
mRepository.getItem(ITEM_2.getId(), USER_ID, ITEM_DETAILS_CALLER, mGetItemCallback);
mvescovo/item-reaper
app/src/prod/java/com.michaelvescovo.android.itemreaper/edit_item/EditItemModule.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/ImageFile.java // public interface ImageFile { // void create(Context context, String name, String extension); // // boolean exists(); // // void delete(Context context); // // Uri getUri(Context context); // // String getPath(); // } // // Path: app/src/prod/java/com.michaelvescovo.android.itemreaper/util/ImageFileImpl.java // public class ImageFileImpl implements ImageFile, Serializable { // // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // File mImageFile; // // @Override // public void create(Context context, String name, String extension) { // mImageFile = new File(context.getFilesDir(), name + extension); // } // // @Override // public boolean exists() { // return null != mImageFile && mImageFile.exists(); // } // // @Override // public void delete(Context context) { // if (mImageFile != null) { // context.deleteFile(mImageFile.getName()); // } // mImageFile = null; // } // // @Override // public Uri getUri(Context context) { // return FileProvider.getUriForFile(context, // context.getPackageName() + ".fileprovider", mImageFile); // } // // @Override // public String getPath() { // return mImageFile.getAbsolutePath(); // } // }
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.michaelvescovo.android.itemreaper.util.ImageFile; import com.michaelvescovo.android.itemreaper.util.ImageFileImpl; import dagger.Module; import dagger.Provides;
package com.michaelvescovo.android.itemreaper.edit_item; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/ImageFile.java // public interface ImageFile { // void create(Context context, String name, String extension); // // boolean exists(); // // void delete(Context context); // // Uri getUri(Context context); // // String getPath(); // } // // Path: app/src/prod/java/com.michaelvescovo.android.itemreaper/util/ImageFileImpl.java // public class ImageFileImpl implements ImageFile, Serializable { // // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // File mImageFile; // // @Override // public void create(Context context, String name, String extension) { // mImageFile = new File(context.getFilesDir(), name + extension); // } // // @Override // public boolean exists() { // return null != mImageFile && mImageFile.exists(); // } // // @Override // public void delete(Context context) { // if (mImageFile != null) { // context.deleteFile(mImageFile.getName()); // } // mImageFile = null; // } // // @Override // public Uri getUri(Context context) { // return FileProvider.getUriForFile(context, // context.getPackageName() + ".fileprovider", mImageFile); // } // // @Override // public String getPath() { // return mImageFile.getAbsolutePath(); // } // } // Path: app/src/prod/java/com.michaelvescovo.android.itemreaper/edit_item/EditItemModule.java import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.michaelvescovo.android.itemreaper.util.ImageFile; import com.michaelvescovo.android.itemreaper.util.ImageFileImpl; import dagger.Module; import dagger.Provides; package com.michaelvescovo.android.itemreaper.edit_item; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides
ImageFile provideImageFile() {
mvescovo/item-reaper
app/src/prod/java/com.michaelvescovo.android.itemreaper/edit_item/EditItemModule.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/ImageFile.java // public interface ImageFile { // void create(Context context, String name, String extension); // // boolean exists(); // // void delete(Context context); // // Uri getUri(Context context); // // String getPath(); // } // // Path: app/src/prod/java/com.michaelvescovo.android.itemreaper/util/ImageFileImpl.java // public class ImageFileImpl implements ImageFile, Serializable { // // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // File mImageFile; // // @Override // public void create(Context context, String name, String extension) { // mImageFile = new File(context.getFilesDir(), name + extension); // } // // @Override // public boolean exists() { // return null != mImageFile && mImageFile.exists(); // } // // @Override // public void delete(Context context) { // if (mImageFile != null) { // context.deleteFile(mImageFile.getName()); // } // mImageFile = null; // } // // @Override // public Uri getUri(Context context) { // return FileProvider.getUriForFile(context, // context.getPackageName() + ".fileprovider", mImageFile); // } // // @Override // public String getPath() { // return mImageFile.getAbsolutePath(); // } // }
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.michaelvescovo.android.itemreaper.util.ImageFile; import com.michaelvescovo.android.itemreaper.util.ImageFileImpl; import dagger.Module; import dagger.Provides;
package com.michaelvescovo.android.itemreaper.edit_item; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides ImageFile provideImageFile() {
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/ImageFile.java // public interface ImageFile { // void create(Context context, String name, String extension); // // boolean exists(); // // void delete(Context context); // // Uri getUri(Context context); // // String getPath(); // } // // Path: app/src/prod/java/com.michaelvescovo.android.itemreaper/util/ImageFileImpl.java // public class ImageFileImpl implements ImageFile, Serializable { // // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // File mImageFile; // // @Override // public void create(Context context, String name, String extension) { // mImageFile = new File(context.getFilesDir(), name + extension); // } // // @Override // public boolean exists() { // return null != mImageFile && mImageFile.exists(); // } // // @Override // public void delete(Context context) { // if (mImageFile != null) { // context.deleteFile(mImageFile.getName()); // } // mImageFile = null; // } // // @Override // public Uri getUri(Context context) { // return FileProvider.getUriForFile(context, // context.getPackageName() + ".fileprovider", mImageFile); // } // // @Override // public String getPath() { // return mImageFile.getAbsolutePath(); // } // } // Path: app/src/prod/java/com.michaelvescovo.android.itemreaper/edit_item/EditItemModule.java import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.michaelvescovo.android.itemreaper.util.ImageFile; import com.michaelvescovo.android.itemreaper.util.ImageFileImpl; import dagger.Module; import dagger.Provides; package com.michaelvescovo.android.itemreaper.edit_item; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides ImageFile provideImageFile() {
return new ImageFileImpl();
mvescovo/item-reaper
app/src/mock/java/com/michaelvescovo/android/itemreaper/auth/AuthFragment.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/widget/ItemWidgetProvider.java // public class ItemWidgetProvider extends AppWidgetProvider { // // public static final String ACTION_DATA_UPDATED = "data_updated"; // public static final String ACTION_EDIT_NEW_ITEM = "action_edit_new_item"; // // @Override // public void onReceive(Context context, Intent intent) { // super.onReceive(context, intent); // if (intent.getAction().equals(ACTION_DATA_UPDATED)) { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds( // new ComponentName(context, getClass())); // appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list); // } // } // // @Override // public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // super.onUpdate(context, appWidgetManager, appWidgetIds); // boolean largeScreen = context.getResources().getBoolean(R.bool.large_layout); // for (int appWidgetId : appWidgetIds) { // RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget); // // // WidgetListService intent for populating collection views. // Intent collectionIntent = new Intent(context, WidgetListService.class); // rv.setRemoteAdapter(R.id.widget_list, collectionIntent); // rv.setEmptyView(R.id.widget_list, R.id.widget_empty); // // // Intent for opening the main app from the widget title. // Intent itemReaperIntent = new Intent(context, ItemsActivity.class); // PendingIntent itemReaperPendingIntent = PendingIntent.getActivity(context, 0, // itemReaperIntent, 0); // rv.setOnClickPendingIntent(R.id.widget_title, itemReaperPendingIntent); // // // Intent for adding an item when clicking the add item button. // Intent addItemIntent = largeScreen // ? new Intent(context, ItemsActivity.class) // : new Intent(context, EditItemActivity.class); // addItemIntent.putExtra(EXTRA_EDIT_NEW_ITEM, true); // addItemIntent.setAction(ACTION_EDIT_NEW_ITEM); // PendingIntent addItemPendingIntent = TaskStackBuilder.create(context) // .addNextIntentWithParentStack(addItemIntent) // .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // rv.setOnClickPendingIntent(R.id.widget_add_item, addItemPendingIntent); // // // Collection for ItemDetailsActivity intent when opening individual list item. // Intent clickIntentTemplate = largeScreen // ? new Intent(context, ItemsActivity.class) // : new Intent(context, ItemDetailsActivity.class); // PendingIntent clickPendingIntentTemplate = TaskStackBuilder.create(context) // .addNextIntentWithParentStack(clickIntentTemplate) // .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // rv.setPendingIntentTemplate(R.id.widget_list, clickPendingIntentTemplate); // appWidgetManager.updateAppWidget(appWidgetId, rv); // } // } // // @Override // public void onDeleted(Context context, int[] appWidgetIds) { // super.onDeleted(context, appWidgetIds); // for (int appWidgetId : appWidgetIds) { // RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget); // rv.removeAllViews(appWidgetId); // } // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.google.android.gms.common.SignInButton; import com.michaelvescovo.android.itemreaper.R; import com.michaelvescovo.android.itemreaper.widget.ItemWidgetProvider; import butterknife.BindView; import butterknife.ButterKnife;
} } @Override public void showSignInButton(boolean visible) { if (visible) { mSignInButton.setVisibility(View.VISIBLE); } else { mSignInButton.setVisibility(View.GONE); } } @Override public void showGoogleSignInUi() { mPresenter.handleGoogleSignInResult(true); } @Override public void showFailMessage() { Snackbar.make(getActivity().findViewById(android.R.id.content), getString(R.string.auth_failed), Snackbar.LENGTH_SHORT).show(); } @Override public void showFireBaseAuthUi() { mPresenter.handleFirebaseSignInResult(true); } @Override public void updateWidget() {
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/widget/ItemWidgetProvider.java // public class ItemWidgetProvider extends AppWidgetProvider { // // public static final String ACTION_DATA_UPDATED = "data_updated"; // public static final String ACTION_EDIT_NEW_ITEM = "action_edit_new_item"; // // @Override // public void onReceive(Context context, Intent intent) { // super.onReceive(context, intent); // if (intent.getAction().equals(ACTION_DATA_UPDATED)) { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds( // new ComponentName(context, getClass())); // appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list); // } // } // // @Override // public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // super.onUpdate(context, appWidgetManager, appWidgetIds); // boolean largeScreen = context.getResources().getBoolean(R.bool.large_layout); // for (int appWidgetId : appWidgetIds) { // RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget); // // // WidgetListService intent for populating collection views. // Intent collectionIntent = new Intent(context, WidgetListService.class); // rv.setRemoteAdapter(R.id.widget_list, collectionIntent); // rv.setEmptyView(R.id.widget_list, R.id.widget_empty); // // // Intent for opening the main app from the widget title. // Intent itemReaperIntent = new Intent(context, ItemsActivity.class); // PendingIntent itemReaperPendingIntent = PendingIntent.getActivity(context, 0, // itemReaperIntent, 0); // rv.setOnClickPendingIntent(R.id.widget_title, itemReaperPendingIntent); // // // Intent for adding an item when clicking the add item button. // Intent addItemIntent = largeScreen // ? new Intent(context, ItemsActivity.class) // : new Intent(context, EditItemActivity.class); // addItemIntent.putExtra(EXTRA_EDIT_NEW_ITEM, true); // addItemIntent.setAction(ACTION_EDIT_NEW_ITEM); // PendingIntent addItemPendingIntent = TaskStackBuilder.create(context) // .addNextIntentWithParentStack(addItemIntent) // .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // rv.setOnClickPendingIntent(R.id.widget_add_item, addItemPendingIntent); // // // Collection for ItemDetailsActivity intent when opening individual list item. // Intent clickIntentTemplate = largeScreen // ? new Intent(context, ItemsActivity.class) // : new Intent(context, ItemDetailsActivity.class); // PendingIntent clickPendingIntentTemplate = TaskStackBuilder.create(context) // .addNextIntentWithParentStack(clickIntentTemplate) // .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // rv.setPendingIntentTemplate(R.id.widget_list, clickPendingIntentTemplate); // appWidgetManager.updateAppWidget(appWidgetId, rv); // } // } // // @Override // public void onDeleted(Context context, int[] appWidgetIds) { // super.onDeleted(context, appWidgetIds); // for (int appWidgetId : appWidgetIds) { // RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget); // rv.removeAllViews(appWidgetId); // } // } // } // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/auth/AuthFragment.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.google.android.gms.common.SignInButton; import com.michaelvescovo.android.itemreaper.R; import com.michaelvescovo.android.itemreaper.widget.ItemWidgetProvider; import butterknife.BindView; import butterknife.ButterKnife; } } @Override public void showSignInButton(boolean visible) { if (visible) { mSignInButton.setVisibility(View.VISIBLE); } else { mSignInButton.setVisibility(View.GONE); } } @Override public void showGoogleSignInUi() { mPresenter.handleGoogleSignInResult(true); } @Override public void showFailMessage() { Snackbar.make(getActivity().findViewById(android.R.id.content), getString(R.string.auth_failed), Snackbar.LENGTH_SHORT).show(); } @Override public void showFireBaseAuthUi() { mPresenter.handleFirebaseSignInResult(true); } @Override public void updateWidget() {
Intent updateWidgetIntent = new Intent(getContext(), ItemWidgetProvider.class);
mvescovo/item-reaper
app/src/main/java/com/michaelvescovo/android/itemreaper/auth/AuthActivity.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/ItemReaperApplication.java // public class ItemReaperApplication extends Application { // // private ApplicationComponent mApplicationComponent; // private RepositoryComponent mRepositoryComponent; // // static { // AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO); // } // // @Override // public void onCreate() { // super.onCreate(); // mApplicationComponent = DaggerApplicationComponent.builder().applicationModule( // new ApplicationModule(PreferenceManager.getDefaultSharedPreferences(this))).build(); // mRepositoryComponent = DaggerRepositoryComponent.builder().build(); // } // // public ApplicationComponent getApplicationComponent() { // return mApplicationComponent; // } // // public RepositoryComponent getRepositoryComponent() { // return mRepositoryComponent; // } // } // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/EspressoIdlingResource.java // public class EspressoIdlingResource { // // private static final String RESOURCE = "GLOBAL"; // // private static SimpleCountingIdlingResource mCountingIdlingResource = // new SimpleCountingIdlingResource(RESOURCE); // // public static void increment() { // mCountingIdlingResource.increment(); // } // // public static void decrement() { // mCountingIdlingResource.decrement(); // } // // public static IdlingResource getIdlingResource() { // return mCountingIdlingResource; // } // }
import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.support.test.espresso.IdlingResource; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.michaelvescovo.android.itemreaper.ItemReaperApplication; import com.michaelvescovo.android.itemreaper.R; import com.michaelvescovo.android.itemreaper.util.EspressoIdlingResource; import butterknife.BindView; import butterknife.ButterKnife;
setResult(RESULT_CANCELED); super.onBackPressed(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auth); ButterKnife.bind(this); setSupportActionBar(mToolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(false); } Typeface appbarTitle = Typeface.createFromAsset(getAssets(), "Nosifer-Regular.ttf"); mAppbarTitle.setTypeface(appbarTitle); // Create the View AuthFragment authFragment = (AuthFragment) getSupportFragmentManager() .findFragmentById(R.id.contentFrame); if (authFragment == null) { authFragment = AuthFragment.newInstance(); initFragment(authFragment); } // Create the Presenter which does the following: // Sets authFragment as the View for authPresenter. // Sets authPresenter as the presenter for authFragment. AuthComponent authComponent = DaggerAuthComponent.builder() .authModule(new AuthModule(authFragment))
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/ItemReaperApplication.java // public class ItemReaperApplication extends Application { // // private ApplicationComponent mApplicationComponent; // private RepositoryComponent mRepositoryComponent; // // static { // AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO); // } // // @Override // public void onCreate() { // super.onCreate(); // mApplicationComponent = DaggerApplicationComponent.builder().applicationModule( // new ApplicationModule(PreferenceManager.getDefaultSharedPreferences(this))).build(); // mRepositoryComponent = DaggerRepositoryComponent.builder().build(); // } // // public ApplicationComponent getApplicationComponent() { // return mApplicationComponent; // } // // public RepositoryComponent getRepositoryComponent() { // return mRepositoryComponent; // } // } // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/EspressoIdlingResource.java // public class EspressoIdlingResource { // // private static final String RESOURCE = "GLOBAL"; // // private static SimpleCountingIdlingResource mCountingIdlingResource = // new SimpleCountingIdlingResource(RESOURCE); // // public static void increment() { // mCountingIdlingResource.increment(); // } // // public static void decrement() { // mCountingIdlingResource.decrement(); // } // // public static IdlingResource getIdlingResource() { // return mCountingIdlingResource; // } // } // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/auth/AuthActivity.java import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.support.test.espresso.IdlingResource; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.michaelvescovo.android.itemreaper.ItemReaperApplication; import com.michaelvescovo.android.itemreaper.R; import com.michaelvescovo.android.itemreaper.util.EspressoIdlingResource; import butterknife.BindView; import butterknife.ButterKnife; setResult(RESULT_CANCELED); super.onBackPressed(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auth); ButterKnife.bind(this); setSupportActionBar(mToolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(false); } Typeface appbarTitle = Typeface.createFromAsset(getAssets(), "Nosifer-Regular.ttf"); mAppbarTitle.setTypeface(appbarTitle); // Create the View AuthFragment authFragment = (AuthFragment) getSupportFragmentManager() .findFragmentById(R.id.contentFrame); if (authFragment == null) { authFragment = AuthFragment.newInstance(); initFragment(authFragment); } // Create the Presenter which does the following: // Sets authFragment as the View for authPresenter. // Sets authPresenter as the presenter for authFragment. AuthComponent authComponent = DaggerAuthComponent.builder() .authModule(new AuthModule(authFragment))
.applicationComponent(((ItemReaperApplication)getApplication()).getApplicationComponent())
mvescovo/item-reaper
app/src/main/java/com/michaelvescovo/android/itemreaper/auth/AuthActivity.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/ItemReaperApplication.java // public class ItemReaperApplication extends Application { // // private ApplicationComponent mApplicationComponent; // private RepositoryComponent mRepositoryComponent; // // static { // AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO); // } // // @Override // public void onCreate() { // super.onCreate(); // mApplicationComponent = DaggerApplicationComponent.builder().applicationModule( // new ApplicationModule(PreferenceManager.getDefaultSharedPreferences(this))).build(); // mRepositoryComponent = DaggerRepositoryComponent.builder().build(); // } // // public ApplicationComponent getApplicationComponent() { // return mApplicationComponent; // } // // public RepositoryComponent getRepositoryComponent() { // return mRepositoryComponent; // } // } // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/EspressoIdlingResource.java // public class EspressoIdlingResource { // // private static final String RESOURCE = "GLOBAL"; // // private static SimpleCountingIdlingResource mCountingIdlingResource = // new SimpleCountingIdlingResource(RESOURCE); // // public static void increment() { // mCountingIdlingResource.increment(); // } // // public static void decrement() { // mCountingIdlingResource.decrement(); // } // // public static IdlingResource getIdlingResource() { // return mCountingIdlingResource; // } // }
import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.support.test.espresso.IdlingResource; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.michaelvescovo.android.itemreaper.ItemReaperApplication; import com.michaelvescovo.android.itemreaper.R; import com.michaelvescovo.android.itemreaper.util.EspressoIdlingResource; import butterknife.BindView; import butterknife.ButterKnife;
Typeface appbarTitle = Typeface.createFromAsset(getAssets(), "Nosifer-Regular.ttf"); mAppbarTitle.setTypeface(appbarTitle); // Create the View AuthFragment authFragment = (AuthFragment) getSupportFragmentManager() .findFragmentById(R.id.contentFrame); if (authFragment == null) { authFragment = AuthFragment.newInstance(); initFragment(authFragment); } // Create the Presenter which does the following: // Sets authFragment as the View for authPresenter. // Sets authPresenter as the presenter for authFragment. AuthComponent authComponent = DaggerAuthComponent.builder() .authModule(new AuthModule(authFragment)) .applicationComponent(((ItemReaperApplication)getApplication()).getApplicationComponent()) .build(); authComponent.getAuthPresenter(); } private void initFragment(Fragment authFragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.contentFrame, authFragment); transaction.commit(); } @VisibleForTesting public IdlingResource getCountingIdlingResource() {
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/ItemReaperApplication.java // public class ItemReaperApplication extends Application { // // private ApplicationComponent mApplicationComponent; // private RepositoryComponent mRepositoryComponent; // // static { // AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO); // } // // @Override // public void onCreate() { // super.onCreate(); // mApplicationComponent = DaggerApplicationComponent.builder().applicationModule( // new ApplicationModule(PreferenceManager.getDefaultSharedPreferences(this))).build(); // mRepositoryComponent = DaggerRepositoryComponent.builder().build(); // } // // public ApplicationComponent getApplicationComponent() { // return mApplicationComponent; // } // // public RepositoryComponent getRepositoryComponent() { // return mRepositoryComponent; // } // } // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/EspressoIdlingResource.java // public class EspressoIdlingResource { // // private static final String RESOURCE = "GLOBAL"; // // private static SimpleCountingIdlingResource mCountingIdlingResource = // new SimpleCountingIdlingResource(RESOURCE); // // public static void increment() { // mCountingIdlingResource.increment(); // } // // public static void decrement() { // mCountingIdlingResource.decrement(); // } // // public static IdlingResource getIdlingResource() { // return mCountingIdlingResource; // } // } // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/auth/AuthActivity.java import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.support.test.espresso.IdlingResource; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.michaelvescovo.android.itemreaper.ItemReaperApplication; import com.michaelvescovo.android.itemreaper.R; import com.michaelvescovo.android.itemreaper.util.EspressoIdlingResource; import butterknife.BindView; import butterknife.ButterKnife; Typeface appbarTitle = Typeface.createFromAsset(getAssets(), "Nosifer-Regular.ttf"); mAppbarTitle.setTypeface(appbarTitle); // Create the View AuthFragment authFragment = (AuthFragment) getSupportFragmentManager() .findFragmentById(R.id.contentFrame); if (authFragment == null) { authFragment = AuthFragment.newInstance(); initFragment(authFragment); } // Create the Presenter which does the following: // Sets authFragment as the View for authPresenter. // Sets authPresenter as the presenter for authFragment. AuthComponent authComponent = DaggerAuthComponent.builder() .authModule(new AuthModule(authFragment)) .applicationComponent(((ItemReaperApplication)getApplication()).getApplicationComponent()) .build(); authComponent.getAuthPresenter(); } private void initFragment(Fragment authFragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.contentFrame, authFragment); transaction.commit(); } @VisibleForTesting public IdlingResource getCountingIdlingResource() {
return EspressoIdlingResource.getIdlingResource();
mvescovo/item-reaper
app/src/main/java/com/michaelvescovo/android/itemreaper/ItemReaperApplication.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/data/RepositoryComponent.java // @Singleton // @Component(modules = DataSourceModule.class) // public interface RepositoryComponent { // // Repository getRepository(); // }
import android.app.Application; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatDelegate; import com.michaelvescovo.android.itemreaper.data.DaggerRepositoryComponent; import com.michaelvescovo.android.itemreaper.data.RepositoryComponent;
package com.michaelvescovo.android.itemreaper; /** * @author Michael Vescovo */ public class ItemReaperApplication extends Application { private ApplicationComponent mApplicationComponent;
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/data/RepositoryComponent.java // @Singleton // @Component(modules = DataSourceModule.class) // public interface RepositoryComponent { // // Repository getRepository(); // } // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/ItemReaperApplication.java import android.app.Application; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatDelegate; import com.michaelvescovo.android.itemreaper.data.DaggerRepositoryComponent; import com.michaelvescovo.android.itemreaper.data.RepositoryComponent; package com.michaelvescovo.android.itemreaper; /** * @author Michael Vescovo */ public class ItemReaperApplication extends Application { private ApplicationComponent mApplicationComponent;
private RepositoryComponent mRepositoryComponent;
mvescovo/item-reaper
app/src/test/java/com/michaelvescovo/android/itemreaper/SharedPreferencesHelperTest.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsFragment.java // public static String STATE_CURRENT_SORT = "current_sort"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/SortItemsDialogFragment.java // public static final int SORT_BY_EXPIRY = 0;
import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; import android.content.SharedPreferences; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static com.michaelvescovo.android.itemreaper.items.ItemsFragment.STATE_CURRENT_SORT; import static com.michaelvescovo.android.itemreaper.items.SortItemsDialogFragment.SORT_BY_EXPIRY; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is;
/* * Copyright 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications have been made by Michael Vescovo. */ package com.michaelvescovo.android.itemreaper; @RunWith(MockitoJUnitRunner.class) public class SharedPreferencesHelperTest { private SharedPreferencesHelper mMockSharedPreferencesHelper; private SharedPreferencesHelper mMockBrokenSharedPreferencesHelper; @Mock SharedPreferences mMockSharedPreferences; @Mock SharedPreferences mMockBrokenSharedPreferences; @Mock SharedPreferences.Editor mMockEditor; @Mock SharedPreferences.Editor mMockBrokenEditor; @Before public void initMocks() { mMockSharedPreferencesHelper = createMockSharedPreference(); mMockBrokenSharedPreferencesHelper = createBrokenMockSharedPreference(); } @Test public void saveAndReadSortBy() {
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsFragment.java // public static String STATE_CURRENT_SORT = "current_sort"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/SortItemsDialogFragment.java // public static final int SORT_BY_EXPIRY = 0; // Path: app/src/test/java/com/michaelvescovo/android/itemreaper/SharedPreferencesHelperTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; import android.content.SharedPreferences; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static com.michaelvescovo.android.itemreaper.items.ItemsFragment.STATE_CURRENT_SORT; import static com.michaelvescovo.android.itemreaper.items.SortItemsDialogFragment.SORT_BY_EXPIRY; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; /* * Copyright 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications have been made by Michael Vescovo. */ package com.michaelvescovo.android.itemreaper; @RunWith(MockitoJUnitRunner.class) public class SharedPreferencesHelperTest { private SharedPreferencesHelper mMockSharedPreferencesHelper; private SharedPreferencesHelper mMockBrokenSharedPreferencesHelper; @Mock SharedPreferences mMockSharedPreferences; @Mock SharedPreferences mMockBrokenSharedPreferences; @Mock SharedPreferences.Editor mMockEditor; @Mock SharedPreferences.Editor mMockBrokenEditor; @Before public void initMocks() { mMockSharedPreferencesHelper = createMockSharedPreference(); mMockBrokenSharedPreferencesHelper = createBrokenMockSharedPreference(); } @Test public void saveAndReadSortBy() {
boolean success = mMockSharedPreferencesHelper.saveSortBy(SORT_BY_EXPIRY);
mvescovo/item-reaper
app/src/test/java/com/michaelvescovo/android/itemreaper/SharedPreferencesHelperTest.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsFragment.java // public static String STATE_CURRENT_SORT = "current_sort"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/SortItemsDialogFragment.java // public static final int SORT_BY_EXPIRY = 0;
import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; import android.content.SharedPreferences; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static com.michaelvescovo.android.itemreaper.items.ItemsFragment.STATE_CURRENT_SORT; import static com.michaelvescovo.android.itemreaper.items.SortItemsDialogFragment.SORT_BY_EXPIRY; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is;
@Mock SharedPreferences.Editor mMockEditor; @Mock SharedPreferences.Editor mMockBrokenEditor; @Before public void initMocks() { mMockSharedPreferencesHelper = createMockSharedPreference(); mMockBrokenSharedPreferencesHelper = createBrokenMockSharedPreference(); } @Test public void saveAndReadSortBy() { boolean success = mMockSharedPreferencesHelper.saveSortBy(SORT_BY_EXPIRY); assertThat("Checking that SharedPreferenceEntry.save... returns true", success, is(true)); int sortBy = mMockSharedPreferencesHelper.getSortBy(); assertThat("Checking that SharedPreferenceEntry.name has been persisted and read correctly", SORT_BY_EXPIRY, is(equalTo(sortBy))); } @Test public void saveSortByFailed_ReturnsFalse() { boolean success = mMockBrokenSharedPreferencesHelper.saveSortBy(SORT_BY_EXPIRY); assertThat("Makes sure writing to a broken SharedPreferencesHelper returns false", success, is(false)); } private SharedPreferencesHelper createMockSharedPreference() {
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsFragment.java // public static String STATE_CURRENT_SORT = "current_sort"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/SortItemsDialogFragment.java // public static final int SORT_BY_EXPIRY = 0; // Path: app/src/test/java/com/michaelvescovo/android/itemreaper/SharedPreferencesHelperTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; import android.content.SharedPreferences; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static com.michaelvescovo.android.itemreaper.items.ItemsFragment.STATE_CURRENT_SORT; import static com.michaelvescovo.android.itemreaper.items.SortItemsDialogFragment.SORT_BY_EXPIRY; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @Mock SharedPreferences.Editor mMockEditor; @Mock SharedPreferences.Editor mMockBrokenEditor; @Before public void initMocks() { mMockSharedPreferencesHelper = createMockSharedPreference(); mMockBrokenSharedPreferencesHelper = createBrokenMockSharedPreference(); } @Test public void saveAndReadSortBy() { boolean success = mMockSharedPreferencesHelper.saveSortBy(SORT_BY_EXPIRY); assertThat("Checking that SharedPreferenceEntry.save... returns true", success, is(true)); int sortBy = mMockSharedPreferencesHelper.getSortBy(); assertThat("Checking that SharedPreferenceEntry.name has been persisted and read correctly", SORT_BY_EXPIRY, is(equalTo(sortBy))); } @Test public void saveSortByFailed_ReturnsFalse() { boolean success = mMockBrokenSharedPreferencesHelper.saveSortBy(SORT_BY_EXPIRY); assertThat("Makes sure writing to a broken SharedPreferencesHelper returns false", success, is(false)); } private SharedPreferencesHelper createMockSharedPreference() {
when(mMockSharedPreferences.getInt(eq(STATE_CURRENT_SORT), anyInt()))
mvescovo/item-reaper
app/src/mock/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsModule.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID";
import dagger.Module; import dagger.Provides; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID;
package com.michaelvescovo.android.itemreaper.item_details; /** * @author Michael Vescovo */ @Module public class ItemDetailsModule { private ItemDetailsContract.View mView; public ItemDetailsModule(ItemDetailsContract.View view) { mView = view; } @Provides ItemDetailsContract.View provideItemDetailsView() { return mView; } @Provides String provideUserId() {
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/data/FakeDataSource.java // public final static String USER_ID = "testUID"; // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsModule.java import dagger.Module; import dagger.Provides; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; package com.michaelvescovo.android.itemreaper.item_details; /** * @author Michael Vescovo */ @Module public class ItemDetailsModule { private ItemDetailsContract.View mView; public ItemDetailsModule(ItemDetailsContract.View view) { mView = view; } @Provides ItemDetailsContract.View provideItemDetailsView() { return mView; } @Provides String provideUserId() {
return USER_ID;
mvescovo/item-reaper
app/src/main/java/com/michaelvescovo/android/itemreaper/SharedPreferencesHelper.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsFragment.java // public static String STATE_CURRENT_SORT = "current_sort"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/SortItemsDialogFragment.java // public static final int SORT_BY_EXPIRY = 0;
import android.content.SharedPreferences; import static com.michaelvescovo.android.itemreaper.items.ItemsFragment.STATE_CURRENT_SORT; import static com.michaelvescovo.android.itemreaper.items.SortItemsDialogFragment.SORT_BY_EXPIRY;
/* * Copyright 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications have been made by Michael Vescovo. */ package com.michaelvescovo.android.itemreaper; public class SharedPreferencesHelper { private static final String KEY_IMAGE_UPLOADING = "image_uploading_"; private final SharedPreferences mSharedPreferences; public SharedPreferencesHelper(SharedPreferences sharedPreferences) { mSharedPreferences = sharedPreferences; } public boolean saveSortBy(int sortBy) { SharedPreferences.Editor editor = mSharedPreferences.edit();
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsFragment.java // public static String STATE_CURRENT_SORT = "current_sort"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/SortItemsDialogFragment.java // public static final int SORT_BY_EXPIRY = 0; // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/SharedPreferencesHelper.java import android.content.SharedPreferences; import static com.michaelvescovo.android.itemreaper.items.ItemsFragment.STATE_CURRENT_SORT; import static com.michaelvescovo.android.itemreaper.items.SortItemsDialogFragment.SORT_BY_EXPIRY; /* * Copyright 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications have been made by Michael Vescovo. */ package com.michaelvescovo.android.itemreaper; public class SharedPreferencesHelper { private static final String KEY_IMAGE_UPLOADING = "image_uploading_"; private final SharedPreferences mSharedPreferences; public SharedPreferencesHelper(SharedPreferences sharedPreferences) { mSharedPreferences = sharedPreferences; } public boolean saveSortBy(int sortBy) { SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt(STATE_CURRENT_SORT, sortBy);
mvescovo/item-reaper
app/src/main/java/com/michaelvescovo/android/itemreaper/SharedPreferencesHelper.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsFragment.java // public static String STATE_CURRENT_SORT = "current_sort"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/SortItemsDialogFragment.java // public static final int SORT_BY_EXPIRY = 0;
import android.content.SharedPreferences; import static com.michaelvescovo.android.itemreaper.items.ItemsFragment.STATE_CURRENT_SORT; import static com.michaelvescovo.android.itemreaper.items.SortItemsDialogFragment.SORT_BY_EXPIRY;
/* * Copyright 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications have been made by Michael Vescovo. */ package com.michaelvescovo.android.itemreaper; public class SharedPreferencesHelper { private static final String KEY_IMAGE_UPLOADING = "image_uploading_"; private final SharedPreferences mSharedPreferences; public SharedPreferencesHelper(SharedPreferences sharedPreferences) { mSharedPreferences = sharedPreferences; } public boolean saveSortBy(int sortBy) { SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putInt(STATE_CURRENT_SORT, sortBy); return editor.commit(); } public int getSortBy() {
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/ItemsFragment.java // public static String STATE_CURRENT_SORT = "current_sort"; // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/items/SortItemsDialogFragment.java // public static final int SORT_BY_EXPIRY = 0; // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/SharedPreferencesHelper.java import android.content.SharedPreferences; import static com.michaelvescovo.android.itemreaper.items.ItemsFragment.STATE_CURRENT_SORT; import static com.michaelvescovo.android.itemreaper.items.SortItemsDialogFragment.SORT_BY_EXPIRY; /* * Copyright 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications have been made by Michael Vescovo. */ package com.michaelvescovo.android.itemreaper; public class SharedPreferencesHelper { private static final String KEY_IMAGE_UPLOADING = "image_uploading_"; private final SharedPreferences mSharedPreferences; public SharedPreferencesHelper(SharedPreferences sharedPreferences) { mSharedPreferences = sharedPreferences; } public boolean saveSortBy(int sortBy) { SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putInt(STATE_CURRENT_SORT, sortBy); return editor.commit(); } public int getSortBy() {
return mSharedPreferences.getInt(STATE_CURRENT_SORT, SORT_BY_EXPIRY);
mvescovo/item-reaper
app/src/prod/java/com.michaelvescovo.android.itemreaper/data/RemoteDataSource.java
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry";
import android.support.annotation.NonNull; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING;
package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ class RemoteDataSource implements DataSource { private DatabaseReference mDatabase; private Query mCurrentItemsQuery; private ValueEventListener mItemsListener; private String mCurrentSort; RemoteDataSource() { FirebaseDatabase.getInstance().setPersistenceEnabled(true); mDatabase = FirebaseDatabase.getInstance().getReference();
// Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/Constants.java // public static final String SORT_BY_EXPIRY_STRING = "expiry"; // Path: app/src/prod/java/com.michaelvescovo.android.itemreaper/data/RemoteDataSource.java import android.support.annotation.NonNull; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import static com.michaelvescovo.android.itemreaper.util.Constants.SORT_BY_EXPIRY_STRING; package com.michaelvescovo.android.itemreaper.data; /** * @author Michael Vescovo */ class RemoteDataSource implements DataSource { private DatabaseReference mDatabase; private Query mCurrentItemsQuery; private ValueEventListener mItemsListener; private String mCurrentSort; RemoteDataSource() { FirebaseDatabase.getInstance().setPersistenceEnabled(true); mDatabase = FirebaseDatabase.getInstance().getReference();
mCurrentSort = SORT_BY_EXPIRY_STRING;
mvescovo/item-reaper
app/src/mock/java/com/michaelvescovo/android/itemreaper/edit_item/EditItemModule.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/util/FakeImageFileImpl.java // public class FakeImageFileImpl implements ImageFile, Serializable { // // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // File mImageFile; // // @Override // public void create(Context context, String name, String extension) { // File storageDir = context.getFilesDir(); // try { // mImageFile = File.createTempFile( // name, /* prefix */ // extension, /* suffix */ // storageDir /* directory */ // ); // mImageFile.deleteOnExit(); // } catch (IOException e) { // e.printStackTrace(); // } // // // For the fake image file, copy the sample image in assets to the file. // InputStream inputStream = null; // OutputStream outputStream = null; // try { // inputStream = context.getAssets().open("black-t-shirt.jpg"); // outputStream = new FileOutputStream(mImageFile); // copyFile(inputStream, outputStream); // } catch (IOException e) { // e.printStackTrace(); // } // finally { // if (inputStream != null) { // try { // inputStream.close(); // } catch (IOException ignore) {} // } // if (outputStream != null) { // try { // outputStream.close(); // } catch (IOException ignore) {} // } // } // } // // private void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { // byte[] buffer = new byte[1024]; // int read; // while((read = inputStream.read(buffer)) != -1){ // outputStream.write(buffer, 0, read); // } // } // // @Override // public String getPath() { // return "file:///android_asset/black-t-shirt.jpg"; // } // // @Override // public boolean exists() { // return true; // } // // @Override // public void delete(Context context) { // // Do nothing // } // // @Override // public Uri getUri(Context context) { // return FileProvider.getUriForFile(context, // context.getPackageName() + ".fileprovider", mImageFile); // } // } // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/ImageFile.java // public interface ImageFile { // void create(Context context, String name, String extension); // // boolean exists(); // // void delete(Context context); // // Uri getUri(Context context); // // String getPath(); // }
import com.michaelvescovo.android.itemreaper.util.FakeImageFileImpl; import com.michaelvescovo.android.itemreaper.util.ImageFile; import dagger.Module; import dagger.Provides;
package com.michaelvescovo.android.itemreaper.edit_item; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/util/FakeImageFileImpl.java // public class FakeImageFileImpl implements ImageFile, Serializable { // // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // File mImageFile; // // @Override // public void create(Context context, String name, String extension) { // File storageDir = context.getFilesDir(); // try { // mImageFile = File.createTempFile( // name, /* prefix */ // extension, /* suffix */ // storageDir /* directory */ // ); // mImageFile.deleteOnExit(); // } catch (IOException e) { // e.printStackTrace(); // } // // // For the fake image file, copy the sample image in assets to the file. // InputStream inputStream = null; // OutputStream outputStream = null; // try { // inputStream = context.getAssets().open("black-t-shirt.jpg"); // outputStream = new FileOutputStream(mImageFile); // copyFile(inputStream, outputStream); // } catch (IOException e) { // e.printStackTrace(); // } // finally { // if (inputStream != null) { // try { // inputStream.close(); // } catch (IOException ignore) {} // } // if (outputStream != null) { // try { // outputStream.close(); // } catch (IOException ignore) {} // } // } // } // // private void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { // byte[] buffer = new byte[1024]; // int read; // while((read = inputStream.read(buffer)) != -1){ // outputStream.write(buffer, 0, read); // } // } // // @Override // public String getPath() { // return "file:///android_asset/black-t-shirt.jpg"; // } // // @Override // public boolean exists() { // return true; // } // // @Override // public void delete(Context context) { // // Do nothing // } // // @Override // public Uri getUri(Context context) { // return FileProvider.getUriForFile(context, // context.getPackageName() + ".fileprovider", mImageFile); // } // } // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/ImageFile.java // public interface ImageFile { // void create(Context context, String name, String extension); // // boolean exists(); // // void delete(Context context); // // Uri getUri(Context context); // // String getPath(); // } // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/edit_item/EditItemModule.java import com.michaelvescovo.android.itemreaper.util.FakeImageFileImpl; import com.michaelvescovo.android.itemreaper.util.ImageFile; import dagger.Module; import dagger.Provides; package com.michaelvescovo.android.itemreaper.edit_item; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides
ImageFile provideImageFile() {
mvescovo/item-reaper
app/src/mock/java/com/michaelvescovo/android/itemreaper/edit_item/EditItemModule.java
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/util/FakeImageFileImpl.java // public class FakeImageFileImpl implements ImageFile, Serializable { // // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // File mImageFile; // // @Override // public void create(Context context, String name, String extension) { // File storageDir = context.getFilesDir(); // try { // mImageFile = File.createTempFile( // name, /* prefix */ // extension, /* suffix */ // storageDir /* directory */ // ); // mImageFile.deleteOnExit(); // } catch (IOException e) { // e.printStackTrace(); // } // // // For the fake image file, copy the sample image in assets to the file. // InputStream inputStream = null; // OutputStream outputStream = null; // try { // inputStream = context.getAssets().open("black-t-shirt.jpg"); // outputStream = new FileOutputStream(mImageFile); // copyFile(inputStream, outputStream); // } catch (IOException e) { // e.printStackTrace(); // } // finally { // if (inputStream != null) { // try { // inputStream.close(); // } catch (IOException ignore) {} // } // if (outputStream != null) { // try { // outputStream.close(); // } catch (IOException ignore) {} // } // } // } // // private void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { // byte[] buffer = new byte[1024]; // int read; // while((read = inputStream.read(buffer)) != -1){ // outputStream.write(buffer, 0, read); // } // } // // @Override // public String getPath() { // return "file:///android_asset/black-t-shirt.jpg"; // } // // @Override // public boolean exists() { // return true; // } // // @Override // public void delete(Context context) { // // Do nothing // } // // @Override // public Uri getUri(Context context) { // return FileProvider.getUriForFile(context, // context.getPackageName() + ".fileprovider", mImageFile); // } // } // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/ImageFile.java // public interface ImageFile { // void create(Context context, String name, String extension); // // boolean exists(); // // void delete(Context context); // // Uri getUri(Context context); // // String getPath(); // }
import com.michaelvescovo.android.itemreaper.util.FakeImageFileImpl; import com.michaelvescovo.android.itemreaper.util.ImageFile; import dagger.Module; import dagger.Provides;
package com.michaelvescovo.android.itemreaper.edit_item; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides ImageFile provideImageFile() {
// Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/util/FakeImageFileImpl.java // public class FakeImageFileImpl implements ImageFile, Serializable { // // @SuppressWarnings("WeakerAccess") // @VisibleForTesting // File mImageFile; // // @Override // public void create(Context context, String name, String extension) { // File storageDir = context.getFilesDir(); // try { // mImageFile = File.createTempFile( // name, /* prefix */ // extension, /* suffix */ // storageDir /* directory */ // ); // mImageFile.deleteOnExit(); // } catch (IOException e) { // e.printStackTrace(); // } // // // For the fake image file, copy the sample image in assets to the file. // InputStream inputStream = null; // OutputStream outputStream = null; // try { // inputStream = context.getAssets().open("black-t-shirt.jpg"); // outputStream = new FileOutputStream(mImageFile); // copyFile(inputStream, outputStream); // } catch (IOException e) { // e.printStackTrace(); // } // finally { // if (inputStream != null) { // try { // inputStream.close(); // } catch (IOException ignore) {} // } // if (outputStream != null) { // try { // outputStream.close(); // } catch (IOException ignore) {} // } // } // } // // private void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { // byte[] buffer = new byte[1024]; // int read; // while((read = inputStream.read(buffer)) != -1){ // outputStream.write(buffer, 0, read); // } // } // // @Override // public String getPath() { // return "file:///android_asset/black-t-shirt.jpg"; // } // // @Override // public boolean exists() { // return true; // } // // @Override // public void delete(Context context) { // // Do nothing // } // // @Override // public Uri getUri(Context context) { // return FileProvider.getUriForFile(context, // context.getPackageName() + ".fileprovider", mImageFile); // } // } // // Path: app/src/main/java/com/michaelvescovo/android/itemreaper/util/ImageFile.java // public interface ImageFile { // void create(Context context, String name, String extension); // // boolean exists(); // // void delete(Context context); // // Uri getUri(Context context); // // String getPath(); // } // Path: app/src/mock/java/com/michaelvescovo/android/itemreaper/edit_item/EditItemModule.java import com.michaelvescovo.android.itemreaper.util.FakeImageFileImpl; import com.michaelvescovo.android.itemreaper.util.ImageFile; import dagger.Module; import dagger.Provides; package com.michaelvescovo.android.itemreaper.edit_item; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides ImageFile provideImageFile() {
return new FakeImageFileImpl();
antlr4ide/antlr4ide
antlr4ide.ui/src/main/java/com/github/jknack/antlr4ide/ui/preferences/BuilderPreferencePage.java
// Path: antlr4ide.core/src/main/java/com/github/jknack/antlr4ide/console/Console.java // public interface Console { // // /** // * Write an ERROR message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void error(String message, Object...args); // // /** // * Write a WARNING message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void warning(String message, Object...args); // // /** // * Write an INFO message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void info(String message, Object...args); // // /** // * Write a DEBUG message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void debug(String message, Object...args); // // /** // * Write a TRACE message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void trace(String message, Object...args); // // }
import java.util.Map; import com.github.jknack.antlr4ide.console.Console; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.preference.IPreferencePageContainer; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer; import org.eclipse.xtext.Constants; import org.eclipse.xtext.builder.DerivedResourceCleanerJob; import org.eclipse.xtext.builder.EclipseOutputConfigurationProvider; import org.eclipse.xtext.ui.IImageHelper; import org.eclipse.xtext.ui.editor.preferences.PreferenceStoreAccessImpl; import org.eclipse.xtext.ui.preferences.OptionsConfigurationBlock; import org.eclipse.xtext.ui.preferences.PropertyAndPreferencePage; import com.google.common.collect.MapDifference.ValueDifference; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.name.Named;
package com.github.jknack.antlr4ide.ui.preferences; /** * @author Michael Clay - Initial contribution and API * @since 2.1 */ @SuppressWarnings("restriction") public class BuilderPreferencePage extends PropertyAndPreferencePage { private static final boolean DEBUG = false; private OptionsConfigurationBlock builderConfigurationBlock; private EclipseOutputConfigurationProvider configurationProvider; private String languageName; private PreferenceStoreAccessImpl preferenceStoreAccessImpl; private Provider<DerivedResourceCleanerJob> cleanerProvider; private IImageHelper imageHelper; @Inject
// Path: antlr4ide.core/src/main/java/com/github/jknack/antlr4ide/console/Console.java // public interface Console { // // /** // * Write an ERROR message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void error(String message, Object...args); // // /** // * Write a WARNING message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void warning(String message, Object...args); // // /** // * Write an INFO message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void info(String message, Object...args); // // /** // * Write a DEBUG message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void debug(String message, Object...args); // // /** // * Write a TRACE message into the console. // * // * @param message The message. Might includes place holder. See String#format // * @param args Message arguments. // */ // public void trace(String message, Object...args); // // } // Path: antlr4ide.ui/src/main/java/com/github/jknack/antlr4ide/ui/preferences/BuilderPreferencePage.java import java.util.Map; import com.github.jknack.antlr4ide.console.Console; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.preference.IPreferencePageContainer; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer; import org.eclipse.xtext.Constants; import org.eclipse.xtext.builder.DerivedResourceCleanerJob; import org.eclipse.xtext.builder.EclipseOutputConfigurationProvider; import org.eclipse.xtext.ui.IImageHelper; import org.eclipse.xtext.ui.editor.preferences.PreferenceStoreAccessImpl; import org.eclipse.xtext.ui.preferences.OptionsConfigurationBlock; import org.eclipse.xtext.ui.preferences.PropertyAndPreferencePage; import com.google.common.collect.MapDifference.ValueDifference; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.name.Named; package com.github.jknack.antlr4ide.ui.preferences; /** * @author Michael Clay - Initial contribution and API * @since 2.1 */ @SuppressWarnings("restriction") public class BuilderPreferencePage extends PropertyAndPreferencePage { private static final boolean DEBUG = false; private OptionsConfigurationBlock builderConfigurationBlock; private EclipseOutputConfigurationProvider configurationProvider; private String languageName; private PreferenceStoreAccessImpl preferenceStoreAccessImpl; private Provider<DerivedResourceCleanerJob> cleanerProvider; private IImageHelper imageHelper; @Inject
private Console console;