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
|
---|---|---|---|---|---|---|
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/publisher/Publisher.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishContext.java
// public interface TransportPublishContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportPublishProperties getPublishProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishContext;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.TimeoutException; | package io.rtr.conduit.amqp.publisher;
/**
* The publisher operates in terms of a publish context; an encapsulation of a
* concrete transport and its properties.
* Example:
*
* AMQPPublishContext context = new AMQPPublishContext(
* username, password, virtualHost, exchange, routingKey, host, port
* );
*
* Publisher publisher = new Publisher(context);
*/
public class Publisher implements AutoCloseable {
private TransportPublishContext transportContext;
//! Public interface.
Publisher(TransportPublishContext transportContext) {
this.transportContext = transportContext;
}
//! Connects to the context-specified host with context-specified credentials.
public void connect() throws IOException {
transportContext.getTransport().connect(transportContext.getConnectionProperties());
}
public boolean isConnected() {
return transportContext.getTransport().isConnected();
}
@Override
public void close() throws IOException {
transportContext.getTransport().close();
}
/**
* Publish the message using the publish properties defined in the transport context
* @param messageBundle Message to send
*/
public boolean publish(TransportMessageBundle messageBundle)
throws IOException, TimeoutException, InterruptedException {
return publish(messageBundle, null);
}
/**
* Publish the message with the publish properties passed as parameter, instead of the ones defined in the transport
* context. Useful when those properties change from one message to another (i.e. send messages using different
* routing keys)
* @param messageBundle Message to send
* @param overridePublishProperties Publish properties to use when sending the message. If null, the ones defined
* in the transport context will be used.
* @return
* @throws IOException
* @throws TimeoutException
* @throws InterruptedException
*/ | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishContext.java
// public interface TransportPublishContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportPublishProperties getPublishProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/publisher/Publisher.java
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishContext;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.TimeoutException;
package io.rtr.conduit.amqp.publisher;
/**
* The publisher operates in terms of a publish context; an encapsulation of a
* concrete transport and its properties.
* Example:
*
* AMQPPublishContext context = new AMQPPublishContext(
* username, password, virtualHost, exchange, routingKey, host, port
* );
*
* Publisher publisher = new Publisher(context);
*/
public class Publisher implements AutoCloseable {
private TransportPublishContext transportContext;
//! Public interface.
Publisher(TransportPublishContext transportContext) {
this.transportContext = transportContext;
}
//! Connects to the context-specified host with context-specified credentials.
public void connect() throws IOException {
transportContext.getTransport().connect(transportContext.getConnectionProperties());
}
public boolean isConnected() {
return transportContext.getTransport().isConnected();
}
@Override
public void close() throws IOException {
transportContext.getTransport().close();
}
/**
* Publish the message using the publish properties defined in the transport context
* @param messageBundle Message to send
*/
public boolean publish(TransportMessageBundle messageBundle)
throws IOException, TimeoutException, InterruptedException {
return publish(messageBundle, null);
}
/**
* Publish the message with the publish properties passed as parameter, instead of the ones defined in the transport
* context. Useful when those properties change from one message to another (i.e. send messages using different
* routing keys)
* @param messageBundle Message to send
* @param overridePublishProperties Publish properties to use when sending the message. If null, the ones defined
* in the transport context will be used.
* @return
* @throws IOException
* @throws TimeoutException
* @throws InterruptedException
*/ | public boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties overridePublishProperties) |
RentTheRunway/conduit | conduit/src/test/java/io/rtr/conduit/amqp/impl/AMQPTransportTest.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
| import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.impl.AMQImpl;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.anyMap;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package io.rtr.conduit.amqp.impl;
public class AMQPTransportTest {
Channel channel;
AMQPTransport amqpTransport;
AMQPPublishProperties properties; | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
// Path: conduit/src/test/java/io/rtr/conduit/amqp/impl/AMQPTransportTest.java
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.impl.AMQImpl;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.anyMap;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package io.rtr.conduit.amqp.impl;
public class AMQPTransportTest {
Channel channel;
AMQPTransport amqpTransport;
AMQPPublishProperties properties; | AMQPMessageBundle messageBundle; |
RentTheRunway/conduit | conduit/src/test/java/io/rtr/conduit/amqp/impl/AMQPTransportTest.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
| import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.impl.AMQImpl;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.anyMap;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package io.rtr.conduit.amqp.impl;
public class AMQPTransportTest {
Channel channel;
AMQPTransport amqpTransport;
AMQPPublishProperties properties;
AMQPMessageBundle messageBundle; | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
// Path: conduit/src/test/java/io/rtr/conduit/amqp/impl/AMQPTransportTest.java
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.impl.AMQImpl;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.anyMap;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package io.rtr.conduit.amqp.impl;
public class AMQPTransportTest {
Channel channel;
AMQPTransport amqpTransport;
AMQPPublishProperties properties;
AMQPMessageBundle messageBundle; | AMQPConsumerCallback consumerCallback = mock(AMQPConsumerCallback.class); |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPPublishContext.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishContext.java
// public interface TransportPublishContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportPublishProperties getPublishProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportPublishContext;
import io.rtr.conduit.amqp.transport.TransportPublishProperties; | package io.rtr.conduit.amqp.impl;
public class AMQPPublishContext implements TransportPublishContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private AMQPPublishProperties publishProperties;
AMQPPublishContext(
AMQPTransport transport
, AMQPConnectionProperties connectionProperties
, AMQPPublishProperties publishProperties
) {
this.transport = transport;
this.connectionProperties = connectionProperties;
this.publishProperties = publishProperties;
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishContext.java
// public interface TransportPublishContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportPublishProperties getPublishProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPPublishContext.java
import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportPublishContext;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
package io.rtr.conduit.amqp.impl;
public class AMQPPublishContext implements TransportPublishContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private AMQPPublishProperties publishProperties;
AMQPPublishContext(
AMQPTransport transport
, AMQPConnectionProperties connectionProperties
, AMQPPublishProperties publishProperties
) {
this.transport = transport;
this.connectionProperties = connectionProperties;
this.publishProperties = publishProperties;
}
@Override | public Transport getTransport() { |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPPublishContext.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishContext.java
// public interface TransportPublishContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportPublishProperties getPublishProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportPublishContext;
import io.rtr.conduit.amqp.transport.TransportPublishProperties; | package io.rtr.conduit.amqp.impl;
public class AMQPPublishContext implements TransportPublishContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private AMQPPublishProperties publishProperties;
AMQPPublishContext(
AMQPTransport transport
, AMQPConnectionProperties connectionProperties
, AMQPPublishProperties publishProperties
) {
this.transport = transport;
this.connectionProperties = connectionProperties;
this.publishProperties = publishProperties;
}
@Override
public Transport getTransport() {
return transport;
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishContext.java
// public interface TransportPublishContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportPublishProperties getPublishProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPPublishContext.java
import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportPublishContext;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
package io.rtr.conduit.amqp.impl;
public class AMQPPublishContext implements TransportPublishContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private AMQPPublishProperties publishProperties;
AMQPPublishContext(
AMQPTransport transport
, AMQPConnectionProperties connectionProperties
, AMQPPublishProperties publishProperties
) {
this.transport = transport;
this.connectionProperties = connectionProperties;
this.publishProperties = publishProperties;
}
@Override
public Transport getTransport() {
return transport;
}
@Override | public TransportConnectionProperties getConnectionProperties() { |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPPublishContext.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishContext.java
// public interface TransportPublishContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportPublishProperties getPublishProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportPublishContext;
import io.rtr.conduit.amqp.transport.TransportPublishProperties; | package io.rtr.conduit.amqp.impl;
public class AMQPPublishContext implements TransportPublishContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private AMQPPublishProperties publishProperties;
AMQPPublishContext(
AMQPTransport transport
, AMQPConnectionProperties connectionProperties
, AMQPPublishProperties publishProperties
) {
this.transport = transport;
this.connectionProperties = connectionProperties;
this.publishProperties = publishProperties;
}
@Override
public Transport getTransport() {
return transport;
}
@Override
public TransportConnectionProperties getConnectionProperties() {
return connectionProperties;
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishContext.java
// public interface TransportPublishContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportPublishProperties getPublishProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPPublishContext.java
import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportPublishContext;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
package io.rtr.conduit.amqp.impl;
public class AMQPPublishContext implements TransportPublishContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private AMQPPublishProperties publishProperties;
AMQPPublishContext(
AMQPTransport transport
, AMQPConnectionProperties connectionProperties
, AMQPPublishProperties publishProperties
) {
this.transport = transport;
this.connectionProperties = connectionProperties;
this.publishProperties = publishProperties;
}
@Override
public Transport getTransport() {
return transport;
}
@Override
public TransportConnectionProperties getConnectionProperties() {
return connectionProperties;
}
@Override | public TransportPublishProperties getPublishProperties() { |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncTransport.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
| import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
import io.rtr.conduit.amqp.transport.TransportListenProperties; | package io.rtr.conduit.amqp.impl;
public class AMQPAsyncTransport extends AMQPTransport {
public AMQPAsyncTransport(boolean ssl, String host, int port, MetricsCollector metricsCollector) {
super(ssl, host, port, metricsCollector);
}
public AMQPAsyncTransport(AMQPConnection sharedConnection) {
super(sharedConnection);
}
@Override
protected AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix){
return new AMQPAsyncQueueConsumer(
getChannel(), | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncTransport.java
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
package io.rtr.conduit.amqp.impl;
public class AMQPAsyncTransport extends AMQPTransport {
public AMQPAsyncTransport(boolean ssl, String host, int port, MetricsCollector metricsCollector) {
super(ssl, host, port, metricsCollector);
}
public AMQPAsyncTransport(AMQPConnection sharedConnection) {
super(sharedConnection);
}
@Override
protected AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix){
return new AMQPAsyncQueueConsumer(
getChannel(), | (AMQPAsyncConsumerCallback) callback, |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncTransport.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
| import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
import io.rtr.conduit.amqp.transport.TransportListenProperties; | package io.rtr.conduit.amqp.impl;
public class AMQPAsyncTransport extends AMQPTransport {
public AMQPAsyncTransport(boolean ssl, String host, int port, MetricsCollector metricsCollector) {
super(ssl, host, port, metricsCollector);
}
public AMQPAsyncTransport(AMQPConnection sharedConnection) {
super(sharedConnection);
}
@Override
protected AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix){
return new AMQPAsyncQueueConsumer(
getChannel(),
(AMQPAsyncConsumerCallback) callback,
commonListenProperties.getThreshold(),
poisonPrefix,
commonListenProperties.isPoisonQueueEnabled()
);
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncTransport.java
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
package io.rtr.conduit.amqp.impl;
public class AMQPAsyncTransport extends AMQPTransport {
public AMQPAsyncTransport(boolean ssl, String host, int port, MetricsCollector metricsCollector) {
super(ssl, host, port, metricsCollector);
}
public AMQPAsyncTransport(AMQPConnection sharedConnection) {
super(sharedConnection);
}
@Override
protected AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix){
return new AMQPAsyncQueueConsumer(
getChannel(),
(AMQPAsyncConsumerCallback) callback,
commonListenProperties.getThreshold(),
poisonPrefix,
commonListenProperties.isPoisonQueueEnabled()
);
}
@Override | protected AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties) { |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException; | private final boolean hasPrivateConnection;
private Channel channel;
static final String POISON = ".poison";
private String dynamicQueue;
private boolean dynamicPoisonQueueInUse = false;
protected AMQPTransport(boolean ssl, String host, int port, MetricsCollector metricsCollector) {
this(new AMQPConnection(ssl, host, port, metricsCollector), true);
}
protected AMQPTransport(AMQPConnection sharedConnection) {
this(sharedConnection, false);
}
private AMQPTransport(AMQPConnection connection, boolean hasPrivateConnection) {
conn = connection;
this.hasPrivateConnection = hasPrivateConnection;
}
protected Channel getChannel() {
return channel;
}
@Override
protected boolean isConnectedImpl() {
return this.conn.isConnected();
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
private final boolean hasPrivateConnection;
private Channel channel;
static final String POISON = ".poison";
private String dynamicQueue;
private boolean dynamicPoisonQueueInUse = false;
protected AMQPTransport(boolean ssl, String host, int port, MetricsCollector metricsCollector) {
this(new AMQPConnection(ssl, host, port, metricsCollector), true);
}
protected AMQPTransport(AMQPConnection sharedConnection) {
this(sharedConnection, false);
}
private AMQPTransport(AMQPConnection connection, boolean hasPrivateConnection) {
conn = connection;
this.hasPrivateConnection = hasPrivateConnection;
}
protected Channel getChannel() {
return channel;
}
@Override
protected boolean isConnectedImpl() {
return this.conn.isConnected();
}
@Override | protected void connectImpl(TransportConnectionProperties properties) throws IOException { |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException; | protected void connectImpl(TransportConnectionProperties properties) throws IOException {
if (hasPrivateConnection && !isConnected()) {
try {
conn.connect((AMQPConnectionProperties) properties);
} catch (TimeoutException e) {
throw new IOException("Timed-out waiting for new connection", e);
}
}
if (channel == null || !channel.isOpen()) {
channel = conn.createChannel();
}
}
@Override
protected void closeImpl() throws IOException {
if (hasPrivateConnection) {
if (conn.isConnected()) {
conn.disconnect();
}
}
//If the connection is shared, just try and close the channel
else stop();
}
@Override
protected AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix) {
return new AMQPQueueConsumer(
getChannel(), | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
protected void connectImpl(TransportConnectionProperties properties) throws IOException {
if (hasPrivateConnection && !isConnected()) {
try {
conn.connect((AMQPConnectionProperties) properties);
} catch (TimeoutException e) {
throw new IOException("Timed-out waiting for new connection", e);
}
}
if (channel == null || !channel.isOpen()) {
channel = conn.createChannel();
}
}
@Override
protected void closeImpl() throws IOException {
if (hasPrivateConnection) {
if (conn.isConnected()) {
conn.disconnect();
}
}
//If the connection is shared, just try and close the channel
else stop();
}
@Override
protected AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix) {
return new AMQPQueueConsumer(
getChannel(), | (AMQPConsumerCallback) callback, |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException; |
if (channel == null || !channel.isOpen()) {
channel = conn.createChannel();
}
}
@Override
protected void closeImpl() throws IOException {
if (hasPrivateConnection) {
if (conn.isConnected()) {
conn.disconnect();
}
}
//If the connection is shared, just try and close the channel
else stop();
}
@Override
protected AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix) {
return new AMQPQueueConsumer(
getChannel(),
(AMQPConsumerCallback) callback,
commonListenProperties.getThreshold(),
poisonPrefix,
commonListenProperties.isPoisonQueueEnabled()
);
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
if (channel == null || !channel.isOpen()) {
channel = conn.createChannel();
}
}
@Override
protected void closeImpl() throws IOException {
if (hasPrivateConnection) {
if (conn.isConnected()) {
conn.disconnect();
}
}
//If the connection is shared, just try and close the channel
else stop();
}
@Override
protected AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix) {
return new AMQPQueueConsumer(
getChannel(),
(AMQPConsumerCallback) callback,
commonListenProperties.getThreshold(),
poisonPrefix,
commonListenProperties.isPoisonQueueEnabled()
);
}
@Override | protected AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties) { |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException; | }
@Override
protected void stopImpl() throws IOException {
// As with closing the connection, closing an already
// closed channel is considered success.
if (channel != null && channel.isOpen()) {
try {
channel.close();
} catch (TimeoutException e) {
throw new IOException("Timed-out closing connection", e);
} catch (AlreadyClosedException ignored) {
}
}
if (hasPrivateConnection) {
conn.stopListening();
}
}
@Override
protected boolean isStoppedImpl(int waitForMillis) throws InterruptedException {
if (hasPrivateConnection) {
return conn.waitToStopListening(Duration.ofMillis(waitForMillis));
} else {
return (channel == null || !channel.isOpen());
}
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
}
@Override
protected void stopImpl() throws IOException {
// As with closing the connection, closing an already
// closed channel is considered success.
if (channel != null && channel.isOpen()) {
try {
channel.close();
} catch (TimeoutException e) {
throw new IOException("Timed-out closing connection", e);
} catch (AlreadyClosedException ignored) {
}
}
if (hasPrivateConnection) {
conn.stopListening();
}
}
@Override
protected boolean isStoppedImpl(int waitForMillis) throws InterruptedException {
if (hasPrivateConnection) {
return conn.waitToStopListening(Duration.ofMillis(waitForMillis));
} else {
return (channel == null || !channel.isOpen());
}
}
@Override | protected boolean publishImpl(TransportMessageBundle bundle, TransportPublishProperties properties) |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException; | }
@Override
protected void stopImpl() throws IOException {
// As with closing the connection, closing an already
// closed channel is considered success.
if (channel != null && channel.isOpen()) {
try {
channel.close();
} catch (TimeoutException e) {
throw new IOException("Timed-out closing connection", e);
} catch (AlreadyClosedException ignored) {
}
}
if (hasPrivateConnection) {
conn.stopListening();
}
}
@Override
protected boolean isStoppedImpl(int waitForMillis) throws InterruptedException {
if (hasPrivateConnection) {
return conn.waitToStopListening(Duration.ofMillis(waitForMillis));
} else {
return (channel == null || !channel.isOpen());
}
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
}
@Override
protected void stopImpl() throws IOException {
// As with closing the connection, closing an already
// closed channel is considered success.
if (channel != null && channel.isOpen()) {
try {
channel.close();
} catch (TimeoutException e) {
throw new IOException("Timed-out closing connection", e);
} catch (AlreadyClosedException ignored) {
}
}
if (hasPrivateConnection) {
conn.stopListening();
}
}
@Override
protected boolean isStoppedImpl(int waitForMillis) throws InterruptedException {
if (hasPrivateConnection) {
return conn.waitToStopListening(Duration.ofMillis(waitForMillis));
} else {
return (channel == null || !channel.isOpen());
}
}
@Override | protected boolean publishImpl(TransportMessageBundle bundle, TransportPublishProperties properties) |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
| import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException; | protected void stopImpl() throws IOException {
// As with closing the connection, closing an already
// closed channel is considered success.
if (channel != null && channel.isOpen()) {
try {
channel.close();
} catch (TimeoutException e) {
throw new IOException("Timed-out closing connection", e);
} catch (AlreadyClosedException ignored) {
}
}
if (hasPrivateConnection) {
conn.stopListening();
}
}
@Override
protected boolean isStoppedImpl(int waitForMillis) throws InterruptedException {
if (hasPrivateConnection) {
return conn.waitToStopListening(Duration.ofMillis(waitForMillis));
} else {
return (channel == null || !channel.isOpen());
}
}
@Override
protected boolean publishImpl(TransportMessageBundle bundle, TransportPublishProperties properties)
throws IOException, TimeoutException, InterruptedException {
AMQPPublishProperties publishProperties = (AMQPPublishProperties) properties; | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AbstractAMQPTransport.java
// public abstract class AbstractAMQPTransport extends Transport{
// protected abstract AMQPQueueConsumer getConsumer(Object callback, AMQPCommonListenProperties commonListenProperties, String poisonPrefix);
// protected abstract AMQPCommonListenProperties getCommonListenProperties(TransportListenProperties properties);
// protected abstract Object getConsumerCallback(TransportListenProperties properties);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportMessageBundle.java
// public interface TransportMessageBundle {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportPublishProperties.java
// public interface TransportPublishProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPTransport.java
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MetricsCollector;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.AbstractAMQPTransport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
import io.rtr.conduit.amqp.transport.TransportMessageBundle;
import io.rtr.conduit.amqp.transport.TransportPublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
protected void stopImpl() throws IOException {
// As with closing the connection, closing an already
// closed channel is considered success.
if (channel != null && channel.isOpen()) {
try {
channel.close();
} catch (TimeoutException e) {
throw new IOException("Timed-out closing connection", e);
} catch (AlreadyClosedException ignored) {
}
}
if (hasPrivateConnection) {
conn.stopListening();
}
}
@Override
protected boolean isStoppedImpl(int waitForMillis) throws InterruptedException {
if (hasPrivateConnection) {
return conn.waitToStopListening(Duration.ofMillis(waitForMillis));
} else {
return (channel == null || !channel.isOpen());
}
}
@Override
protected boolean publishImpl(TransportMessageBundle bundle, TransportPublishProperties properties)
throws IOException, TimeoutException, InterruptedException {
AMQPPublishProperties publishProperties = (AMQPPublishProperties) properties; | AMQPMessageBundle messageBundle = (AMQPMessageBundle) bundle; |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPConsumerBuilder.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/consumer/ConsumerBuilder.java
// public abstract class ConsumerBuilder<T extends Transport
// , C extends TransportConnectionProperties
// , L extends TransportListenProperties
// , LC extends TransportListenContext>
// extends Validatable {
// protected abstract T buildTransport();
// protected abstract C buildConnectionProperties();
// protected abstract L buildListenProperties();
// protected abstract LC buildListenContext(T transport, C connectionProperties, L listenProperties);
//
// public final Consumer build() {
// validate();
// LC context = buildListenContext(buildTransport(), buildConnectionProperties(), buildListenProperties());
// return new Consumer(context);
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
| import io.rtr.conduit.amqp.consumer.ConsumerBuilder;
import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportListenProperties; | package io.rtr.conduit.amqp.impl;
public abstract class AMQPConsumerBuilder<T extends Transport
, L extends TransportListenProperties
, R extends AMQPConsumerBuilder<?,?,?>> | // Path: conduit/src/main/java/io/rtr/conduit/amqp/consumer/ConsumerBuilder.java
// public abstract class ConsumerBuilder<T extends Transport
// , C extends TransportConnectionProperties
// , L extends TransportListenProperties
// , LC extends TransportListenContext>
// extends Validatable {
// protected abstract T buildTransport();
// protected abstract C buildConnectionProperties();
// protected abstract L buildListenProperties();
// protected abstract LC buildListenContext(T transport, C connectionProperties, L listenProperties);
//
// public final Consumer build() {
// validate();
// LC context = buildListenContext(buildTransport(), buildConnectionProperties(), buildListenProperties());
// return new Consumer(context);
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPConsumerBuilder.java
import io.rtr.conduit.amqp.consumer.ConsumerBuilder;
import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
package io.rtr.conduit.amqp.impl;
public abstract class AMQPConsumerBuilder<T extends Transport
, L extends TransportListenProperties
, R extends AMQPConsumerBuilder<?,?,?>> | extends ConsumerBuilder<T |
RentTheRunway/conduit | conduit/src/test/java/io/rtr/conduit/amqp/impl/AMQPConnectionTest.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportExecutor.java
// public class TransportExecutor extends ThreadPoolExecutor {
//
// // From ConsumerWorkService
// private static final int DEFAULT_NUM_THREADS = Runtime.getRuntime().availableProcessors() * 2;
//
// private static ThreadFactory buildCountedDaemonThreadFactory() {
// AtomicInteger threadCount = new AtomicInteger(0);
// return run -> {
// Thread thread = new Thread(run);
// thread.setDaemon(true);
// thread.setName(String.format("AMQPConnection-%s", threadCount.getAndIncrement()));
// return thread;
// };
// }
//
// public TransportExecutor() {
// this(DEFAULT_NUM_THREADS, buildCountedDaemonThreadFactory());
// }
//
// /**
// * Based on Executors.newFixedThreadPool
// * @param nThreads
// * @param threadFactory
// */
// public TransportExecutor(int nThreads, ThreadFactory threadFactory) {
// super(nThreads, nThreads,
// 0L, TimeUnit.MILLISECONDS,
// new LinkedBlockingQueue<Runnable>(),
// threadFactory);
// }
// }
| import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.transport.TransportExecutor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package io.rtr.conduit.amqp.impl;
public class AMQPConnectionTest {
private final static int CONNECTION_TIMEOUT = 1337;
private final static int PORT = 42;
Connection mockConnection;
ConnectionFactory mockFactory; | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportExecutor.java
// public class TransportExecutor extends ThreadPoolExecutor {
//
// // From ConsumerWorkService
// private static final int DEFAULT_NUM_THREADS = Runtime.getRuntime().availableProcessors() * 2;
//
// private static ThreadFactory buildCountedDaemonThreadFactory() {
// AtomicInteger threadCount = new AtomicInteger(0);
// return run -> {
// Thread thread = new Thread(run);
// thread.setDaemon(true);
// thread.setName(String.format("AMQPConnection-%s", threadCount.getAndIncrement()));
// return thread;
// };
// }
//
// public TransportExecutor() {
// this(DEFAULT_NUM_THREADS, buildCountedDaemonThreadFactory());
// }
//
// /**
// * Based on Executors.newFixedThreadPool
// * @param nThreads
// * @param threadFactory
// */
// public TransportExecutor(int nThreads, ThreadFactory threadFactory) {
// super(nThreads, nThreads,
// 0L, TimeUnit.MILLISECONDS,
// new LinkedBlockingQueue<Runnable>(),
// threadFactory);
// }
// }
// Path: conduit/src/test/java/io/rtr/conduit/amqp/impl/AMQPConnectionTest.java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.transport.TransportExecutor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package io.rtr.conduit.amqp.impl;
public class AMQPConnectionTest {
private final static int CONNECTION_TIMEOUT = 1337;
private final static int PORT = 42;
Connection mockConnection;
ConnectionFactory mockFactory; | TransportExecutor mockExecutor; |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncConsumerBuilder.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
| import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback; | package io.rtr.conduit.amqp.impl;
public class AMQPAsyncConsumerBuilder extends AMQPConsumerBuilder<AMQPAsyncTransport
, AMQPAsyncListenProperties
, AMQPAsyncConsumerBuilder> { | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncConsumerBuilder.java
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
package io.rtr.conduit.amqp.impl;
public class AMQPAsyncConsumerBuilder extends AMQPConsumerBuilder<AMQPAsyncTransport
, AMQPAsyncListenProperties
, AMQPAsyncConsumerBuilder> { | private AMQPAsyncConsumerCallback callback; |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPSyncConsumerBuilder.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
| import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPConsumerCallback; | package io.rtr.conduit.amqp.impl;
public class AMQPSyncConsumerBuilder extends AMQPConsumerBuilder<AMQPTransport
, AMQPListenProperties
, AMQPSyncConsumerBuilder> { | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPConsumerCallback.java
// public interface AMQPConsumerCallback {
// ActionResponse handle(AMQPMessageBundle messageBundle);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPSyncConsumerBuilder.java
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPConsumerCallback;
package io.rtr.conduit.amqp.impl;
public class AMQPSyncConsumerBuilder extends AMQPConsumerBuilder<AMQPTransport
, AMQPListenProperties
, AMQPSyncConsumerBuilder> { | private AMQPConsumerCallback callback; |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPConnection.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportExecutor.java
// public class TransportExecutor extends ThreadPoolExecutor {
//
// // From ConsumerWorkService
// private static final int DEFAULT_NUM_THREADS = Runtime.getRuntime().availableProcessors() * 2;
//
// private static ThreadFactory buildCountedDaemonThreadFactory() {
// AtomicInteger threadCount = new AtomicInteger(0);
// return run -> {
// Thread thread = new Thread(run);
// thread.setDaemon(true);
// thread.setName(String.format("AMQPConnection-%s", threadCount.getAndIncrement()));
// return thread;
// };
// }
//
// public TransportExecutor() {
// this(DEFAULT_NUM_THREADS, buildCountedDaemonThreadFactory());
// }
//
// /**
// * Based on Executors.newFixedThreadPool
// * @param nThreads
// * @param threadFactory
// */
// public TransportExecutor(int nThreads, ThreadFactory threadFactory) {
// super(nThreads, nThreads,
// 0L, TimeUnit.MILLISECONDS,
// new LinkedBlockingQueue<Runnable>(),
// threadFactory);
// }
// }
| import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.transport.TransportExecutor;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier; | package io.rtr.conduit.amqp.impl;
public class AMQPConnection {
private final ConnectionFactory connectionFactory;
private Connection connection; | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportExecutor.java
// public class TransportExecutor extends ThreadPoolExecutor {
//
// // From ConsumerWorkService
// private static final int DEFAULT_NUM_THREADS = Runtime.getRuntime().availableProcessors() * 2;
//
// private static ThreadFactory buildCountedDaemonThreadFactory() {
// AtomicInteger threadCount = new AtomicInteger(0);
// return run -> {
// Thread thread = new Thread(run);
// thread.setDaemon(true);
// thread.setName(String.format("AMQPConnection-%s", threadCount.getAndIncrement()));
// return thread;
// };
// }
//
// public TransportExecutor() {
// this(DEFAULT_NUM_THREADS, buildCountedDaemonThreadFactory());
// }
//
// /**
// * Based on Executors.newFixedThreadPool
// * @param nThreads
// * @param threadFactory
// */
// public TransportExecutor(int nThreads, ThreadFactory threadFactory) {
// super(nThreads, nThreads,
// 0L, TimeUnit.MILLISECONDS,
// new LinkedBlockingQueue<Runnable>(),
// threadFactory);
// }
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPConnection.java
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.transport.TransportExecutor;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
package io.rtr.conduit.amqp.impl;
public class AMQPConnection {
private final ConnectionFactory connectionFactory;
private Connection connection; | private TransportExecutor executor; |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPListenContext.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenContext.java
// public interface TransportListenContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportListenProperties getListenProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
| import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenContext;
import io.rtr.conduit.amqp.transport.TransportListenProperties; | package io.rtr.conduit.amqp.impl;
public class AMQPListenContext implements TransportListenContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties; | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenContext.java
// public interface TransportListenContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportListenProperties getListenProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPListenContext.java
import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenContext;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
package io.rtr.conduit.amqp.impl;
public class AMQPListenContext implements TransportListenContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties; | private TransportListenProperties listenProperties; |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPListenContext.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenContext.java
// public interface TransportListenContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportListenProperties getListenProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
| import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenContext;
import io.rtr.conduit.amqp.transport.TransportListenProperties; | package io.rtr.conduit.amqp.impl;
public class AMQPListenContext implements TransportListenContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private TransportListenProperties listenProperties;
//! Consume context.
AMQPListenContext(
AMQPTransport amqpTransport
, AMQPConnectionProperties amqpConnectionProperties
, AMQPCommonListenProperties amqpListenProperties
) {
connectionProperties = amqpConnectionProperties;
listenProperties = amqpListenProperties;
transport = amqpTransport;
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenContext.java
// public interface TransportListenContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportListenProperties getListenProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPListenContext.java
import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenContext;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
package io.rtr.conduit.amqp.impl;
public class AMQPListenContext implements TransportListenContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private TransportListenProperties listenProperties;
//! Consume context.
AMQPListenContext(
AMQPTransport amqpTransport
, AMQPConnectionProperties amqpConnectionProperties
, AMQPCommonListenProperties amqpListenProperties
) {
connectionProperties = amqpConnectionProperties;
listenProperties = amqpListenProperties;
transport = amqpTransport;
}
@Override | public Transport getTransport() { |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPListenContext.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenContext.java
// public interface TransportListenContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportListenProperties getListenProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
| import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenContext;
import io.rtr.conduit.amqp.transport.TransportListenProperties; | package io.rtr.conduit.amqp.impl;
public class AMQPListenContext implements TransportListenContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private TransportListenProperties listenProperties;
//! Consume context.
AMQPListenContext(
AMQPTransport amqpTransport
, AMQPConnectionProperties amqpConnectionProperties
, AMQPCommonListenProperties amqpListenProperties
) {
connectionProperties = amqpConnectionProperties;
listenProperties = amqpListenProperties;
transport = amqpTransport;
}
@Override
public Transport getTransport() {
return transport;
}
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/Transport.java
// public abstract class Transport {
// //! Public interface.
//
// //! Establishes a connection to either an intermediary or the other
// // end point. In the case of AMQP, this method is used to connect
// // to the broker.
// public final void connect(TransportConnectionProperties properties) throws IOException {
// connectImpl(properties);
// }
//
// public boolean isConnected() {
// return isConnectedImpl();
// }
//
// //! Closes the connection.
// public final void close() throws IOException {
// closeImpl();
// }
//
// //! Starts the asynchronous delivery mechanism.
// public final void listen(TransportListenProperties properties) throws IOException {
// listenImpl(properties);
// }
//
// //! Stops listening for incoming messages.
// public final void stop() throws IOException {
// stopImpl();
// }
//
// // Is the listener thread pool still doing work? (stop is not synchronous)
// public final boolean isStopped(int maxWaitMilliseconds) throws InterruptedException {
// return isStoppedImpl(maxWaitMilliseconds);
// }
//
// //! Publish a message to the other endpoint.
// public final boolean publish(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return publishImpl(messageBundle, properties);
// }
//
// public final <E> boolean transactionalPublish(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException {
// return transactionalPublishImpl(messageBundles, properties);
// }
//
// //! Implementation
//
// protected abstract boolean isConnectedImpl();
// protected abstract void connectImpl(TransportConnectionProperties properties) throws IOException;
// protected abstract void closeImpl() throws IOException;
//
// protected void listenImpl(TransportListenProperties properties) throws IOException {}
// protected void stopImpl() throws IOException {}
// protected abstract boolean isStoppedImpl(int waitMillSeconds) throws InterruptedException;
//
// protected boolean publishImpl(TransportMessageBundle messageBundle, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// protected <E> boolean transactionalPublishImpl(Collection<E> messageBundles, TransportPublishProperties properties)
// throws IOException, TimeoutException, InterruptedException { return false; }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportConnectionProperties.java
// public interface TransportConnectionProperties {
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenContext.java
// public interface TransportListenContext {
// Transport getTransport();
// TransportConnectionProperties getConnectionProperties();
// TransportListenProperties getListenProperties();
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/transport/TransportListenProperties.java
// public interface TransportListenProperties {
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPListenContext.java
import io.rtr.conduit.amqp.transport.Transport;
import io.rtr.conduit.amqp.transport.TransportConnectionProperties;
import io.rtr.conduit.amqp.transport.TransportListenContext;
import io.rtr.conduit.amqp.transport.TransportListenProperties;
package io.rtr.conduit.amqp.impl;
public class AMQPListenContext implements TransportListenContext {
private AMQPTransport transport;
private AMQPConnectionProperties connectionProperties;
private TransportListenProperties listenProperties;
//! Consume context.
AMQPListenContext(
AMQPTransport amqpTransport
, AMQPConnectionProperties amqpConnectionProperties
, AMQPCommonListenProperties amqpListenProperties
) {
connectionProperties = amqpConnectionProperties;
listenProperties = amqpListenProperties;
transport = amqpTransport;
}
@Override
public Transport getTransport() {
return transport;
}
@Override | public TransportConnectionProperties getConnectionProperties() { |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncQueueConsumer.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/ActionResponse.java
// public class ActionResponse {
//
// private Action action;
// private String reason;
// public static final String REASON_KEY = "reason";
//
// private ActionResponse(Action action, String reason) {
// this.action = action;
// this.reason = reason;
// }
//
// public static ActionResponse acknowledge() {
// return new ActionResponse(Action.Acknowledge, null);
// }
//
// public static ActionResponse retry() {
// return new ActionResponse(Action.RejectAndRequeue, null);
// }
//
// public static ActionResponse retry(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndRequeue, String.format(reason, args));
// }
//
// public static ActionResponse discard() {
// return new ActionResponse(Action.RejectAndDiscard, null);
// }
//
// public static ActionResponse discard(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndDiscard, String.format(reason, args));
// }
//
// public String getReason() {
// return reason;
// }
//
// public Action getAction() {
// return action;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ActionResponse that = (ActionResponse) o;
//
// if (action != that.action) return false;
// if (reason != null ? !reason.equals(that.reason) : that.reason != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = action != null ? action.hashCode() : 0;
// result = 31 * result + (reason != null ? reason.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "ActionResponse{" +
// "action=" + action +
// ", reason='" + reason + '\'' +
// '}';
// }
//
// public enum Action {
// Acknowledge, //! The transport will ack the message explicitly.
// RejectAndRequeue, //! The message wasn't meant to be processed.
// // For example, if the message delivered is of
// // a higher version than what we are able to
// // deal with.
// RejectAndDiscard //! A malformed message, place it on a poison queue.
// }
//
//
//
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AsyncResponse.java
// public interface AsyncResponse {
// /**
// * Responds to all previously unacknowledged messages, up to and including the given message
// */
// public void respondMultiple(AMQPMessageBundle messageBundle, ActionResponse actionResponse);
//
// /**
// * Responds to a single unacknowledged message
// */
// public void respondSingle(AMQPMessageBundle messageBundle, ActionResponse actionResponse);
// }
| import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.ActionResponse;
import io.rtr.conduit.amqp.AsyncResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry; | package io.rtr.conduit.amqp.impl;
public class AMQPAsyncQueueConsumer extends AMQPQueueConsumer implements AsyncResponse {
private static final Logger log = LoggerFactory.getLogger(AMQPAsyncQueueConsumer.class); | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/ActionResponse.java
// public class ActionResponse {
//
// private Action action;
// private String reason;
// public static final String REASON_KEY = "reason";
//
// private ActionResponse(Action action, String reason) {
// this.action = action;
// this.reason = reason;
// }
//
// public static ActionResponse acknowledge() {
// return new ActionResponse(Action.Acknowledge, null);
// }
//
// public static ActionResponse retry() {
// return new ActionResponse(Action.RejectAndRequeue, null);
// }
//
// public static ActionResponse retry(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndRequeue, String.format(reason, args));
// }
//
// public static ActionResponse discard() {
// return new ActionResponse(Action.RejectAndDiscard, null);
// }
//
// public static ActionResponse discard(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndDiscard, String.format(reason, args));
// }
//
// public String getReason() {
// return reason;
// }
//
// public Action getAction() {
// return action;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ActionResponse that = (ActionResponse) o;
//
// if (action != that.action) return false;
// if (reason != null ? !reason.equals(that.reason) : that.reason != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = action != null ? action.hashCode() : 0;
// result = 31 * result + (reason != null ? reason.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "ActionResponse{" +
// "action=" + action +
// ", reason='" + reason + '\'' +
// '}';
// }
//
// public enum Action {
// Acknowledge, //! The transport will ack the message explicitly.
// RejectAndRequeue, //! The message wasn't meant to be processed.
// // For example, if the message delivered is of
// // a higher version than what we are able to
// // deal with.
// RejectAndDiscard //! A malformed message, place it on a poison queue.
// }
//
//
//
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AsyncResponse.java
// public interface AsyncResponse {
// /**
// * Responds to all previously unacknowledged messages, up to and including the given message
// */
// public void respondMultiple(AMQPMessageBundle messageBundle, ActionResponse actionResponse);
//
// /**
// * Responds to a single unacknowledged message
// */
// public void respondSingle(AMQPMessageBundle messageBundle, ActionResponse actionResponse);
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncQueueConsumer.java
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.ActionResponse;
import io.rtr.conduit.amqp.AsyncResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
package io.rtr.conduit.amqp.impl;
public class AMQPAsyncQueueConsumer extends AMQPQueueConsumer implements AsyncResponse {
private static final Logger log = LoggerFactory.getLogger(AMQPAsyncQueueConsumer.class); | private final AMQPAsyncConsumerCallback callback; |
RentTheRunway/conduit | conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncQueueConsumer.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/ActionResponse.java
// public class ActionResponse {
//
// private Action action;
// private String reason;
// public static final String REASON_KEY = "reason";
//
// private ActionResponse(Action action, String reason) {
// this.action = action;
// this.reason = reason;
// }
//
// public static ActionResponse acknowledge() {
// return new ActionResponse(Action.Acknowledge, null);
// }
//
// public static ActionResponse retry() {
// return new ActionResponse(Action.RejectAndRequeue, null);
// }
//
// public static ActionResponse retry(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndRequeue, String.format(reason, args));
// }
//
// public static ActionResponse discard() {
// return new ActionResponse(Action.RejectAndDiscard, null);
// }
//
// public static ActionResponse discard(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndDiscard, String.format(reason, args));
// }
//
// public String getReason() {
// return reason;
// }
//
// public Action getAction() {
// return action;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ActionResponse that = (ActionResponse) o;
//
// if (action != that.action) return false;
// if (reason != null ? !reason.equals(that.reason) : that.reason != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = action != null ? action.hashCode() : 0;
// result = 31 * result + (reason != null ? reason.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "ActionResponse{" +
// "action=" + action +
// ", reason='" + reason + '\'' +
// '}';
// }
//
// public enum Action {
// Acknowledge, //! The transport will ack the message explicitly.
// RejectAndRequeue, //! The message wasn't meant to be processed.
// // For example, if the message delivered is of
// // a higher version than what we are able to
// // deal with.
// RejectAndDiscard //! A malformed message, place it on a poison queue.
// }
//
//
//
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AsyncResponse.java
// public interface AsyncResponse {
// /**
// * Responds to all previously unacknowledged messages, up to and including the given message
// */
// public void respondMultiple(AMQPMessageBundle messageBundle, ActionResponse actionResponse);
//
// /**
// * Responds to a single unacknowledged message
// */
// public void respondSingle(AMQPMessageBundle messageBundle, ActionResponse actionResponse);
// }
| import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.ActionResponse;
import io.rtr.conduit.amqp.AsyncResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry; | package io.rtr.conduit.amqp.impl;
public class AMQPAsyncQueueConsumer extends AMQPQueueConsumer implements AsyncResponse {
private static final Logger log = LoggerFactory.getLogger(AMQPAsyncQueueConsumer.class);
private final AMQPAsyncConsumerCallback callback; | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPAsyncConsumerCallback.java
// public interface AMQPAsyncConsumerCallback {
// void handle(AMQPMessageBundle messageBundle, AsyncResponse response);
// void notifyOfActionFailure(Exception e);
// void notifyOfShutdown(String consumerTag, ShutdownSignalException sig);
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/ActionResponse.java
// public class ActionResponse {
//
// private Action action;
// private String reason;
// public static final String REASON_KEY = "reason";
//
// private ActionResponse(Action action, String reason) {
// this.action = action;
// this.reason = reason;
// }
//
// public static ActionResponse acknowledge() {
// return new ActionResponse(Action.Acknowledge, null);
// }
//
// public static ActionResponse retry() {
// return new ActionResponse(Action.RejectAndRequeue, null);
// }
//
// public static ActionResponse retry(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndRequeue, String.format(reason, args));
// }
//
// public static ActionResponse discard() {
// return new ActionResponse(Action.RejectAndDiscard, null);
// }
//
// public static ActionResponse discard(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndDiscard, String.format(reason, args));
// }
//
// public String getReason() {
// return reason;
// }
//
// public Action getAction() {
// return action;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ActionResponse that = (ActionResponse) o;
//
// if (action != that.action) return false;
// if (reason != null ? !reason.equals(that.reason) : that.reason != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = action != null ? action.hashCode() : 0;
// result = 31 * result + (reason != null ? reason.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "ActionResponse{" +
// "action=" + action +
// ", reason='" + reason + '\'' +
// '}';
// }
//
// public enum Action {
// Acknowledge, //! The transport will ack the message explicitly.
// RejectAndRequeue, //! The message wasn't meant to be processed.
// // For example, if the message delivered is of
// // a higher version than what we are able to
// // deal with.
// RejectAndDiscard //! A malformed message, place it on a poison queue.
// }
//
//
//
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/AsyncResponse.java
// public interface AsyncResponse {
// /**
// * Responds to all previously unacknowledged messages, up to and including the given message
// */
// public void respondMultiple(AMQPMessageBundle messageBundle, ActionResponse actionResponse);
//
// /**
// * Responds to a single unacknowledged message
// */
// public void respondSingle(AMQPMessageBundle messageBundle, ActionResponse actionResponse);
// }
// Path: conduit/src/main/java/io/rtr/conduit/amqp/impl/AMQPAsyncQueueConsumer.java
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;
import io.rtr.conduit.amqp.AMQPAsyncConsumerCallback;
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.ActionResponse;
import io.rtr.conduit.amqp.AsyncResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
package io.rtr.conduit.amqp.impl;
public class AMQPAsyncQueueConsumer extends AMQPQueueConsumer implements AsyncResponse {
private static final Logger log = LoggerFactory.getLogger(AMQPAsyncQueueConsumer.class);
private final AMQPAsyncConsumerCallback callback; | private final Map<Long, AMQPMessageBundle> unacknowledgedMessages = new LinkedHashMap<Long, AMQPMessageBundle>(); |
RentTheRunway/conduit | conduit/src/test/java/io/rtr/conduit/util/RecordingAmqpCallbackHandler.java | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/ActionResponse.java
// public class ActionResponse {
//
// private Action action;
// private String reason;
// public static final String REASON_KEY = "reason";
//
// private ActionResponse(Action action, String reason) {
// this.action = action;
// this.reason = reason;
// }
//
// public static ActionResponse acknowledge() {
// return new ActionResponse(Action.Acknowledge, null);
// }
//
// public static ActionResponse retry() {
// return new ActionResponse(Action.RejectAndRequeue, null);
// }
//
// public static ActionResponse retry(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndRequeue, String.format(reason, args));
// }
//
// public static ActionResponse discard() {
// return new ActionResponse(Action.RejectAndDiscard, null);
// }
//
// public static ActionResponse discard(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndDiscard, String.format(reason, args));
// }
//
// public String getReason() {
// return reason;
// }
//
// public Action getAction() {
// return action;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ActionResponse that = (ActionResponse) o;
//
// if (action != that.action) return false;
// if (reason != null ? !reason.equals(that.reason) : that.reason != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = action != null ? action.hashCode() : 0;
// result = 31 * result + (reason != null ? reason.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "ActionResponse{" +
// "action=" + action +
// ", reason='" + reason + '\'' +
// '}';
// }
//
// public enum Action {
// Acknowledge, //! The transport will ack the message explicitly.
// RejectAndRequeue, //! The message wasn't meant to be processed.
// // For example, if the message delivered is of
// // a higher version than what we are able to
// // deal with.
// RejectAndDiscard //! A malformed message, place it on a poison queue.
// }
//
//
//
// }
| import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.ActionResponse;
import java.util.ArrayList;
import java.util.List; | package io.rtr.conduit.util;
public class RecordingAmqpCallbackHandler extends LoggingAmqpCallbackHandler {
private final List<AMQPMessageBundle> capturedMessages = new ArrayList<>();
@Override | // Path: conduit/src/main/java/io/rtr/conduit/amqp/AMQPMessageBundle.java
// public class AMQPMessageBundle implements TransportMessageBundle {
// private String consumerTag;
// private Envelope envelope;
// private AMQP.BasicProperties basicProperties;
// private byte[] body;
//
// private static AMQP.BasicProperties initialProperties() {
// return initialProperties(null);
// }
//
// private static AMQP.BasicProperties initialProperties(Map<String, Object> additionalHeaders) {
// Map<String, Object> headers = new HashMap<String, Object>();
//
// if (additionalHeaders != null) {
// headers.putAll(additionalHeaders);
// }
//
// headers.put("conduit-retry-count", 0);
//
// return new AMQP.BasicProperties()
// .builder()
// .deliveryMode(2 /*persistent*/)
// .priority(0)
// .headers(headers)
// .contentType("text/plain")
// .build();
// }
//
// public AMQPMessageBundle(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] body) {
// this.consumerTag = consumerTag;
// this.envelope = envelope;
// this.basicProperties = basicProperties;
// this.body = body;
// }
//
// public AMQPMessageBundle(String message) {
// this(null, null, initialProperties(), message.getBytes());
// }
//
// public AMQPMessageBundle(String message, Map<String, Object> headers) {
// this(null, null, initialProperties(headers), message.getBytes());
// }
//
// public String getConsumerTag() {
// return consumerTag;
// }
//
// public Envelope getEnvelope() {
// return envelope;
// }
//
// public AMQP.BasicProperties getBasicProperties() {
// return basicProperties;
// }
//
// public byte[] getBody() {
// return body;
// }
// }
//
// Path: conduit/src/main/java/io/rtr/conduit/amqp/ActionResponse.java
// public class ActionResponse {
//
// private Action action;
// private String reason;
// public static final String REASON_KEY = "reason";
//
// private ActionResponse(Action action, String reason) {
// this.action = action;
// this.reason = reason;
// }
//
// public static ActionResponse acknowledge() {
// return new ActionResponse(Action.Acknowledge, null);
// }
//
// public static ActionResponse retry() {
// return new ActionResponse(Action.RejectAndRequeue, null);
// }
//
// public static ActionResponse retry(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndRequeue, String.format(reason, args));
// }
//
// public static ActionResponse discard() {
// return new ActionResponse(Action.RejectAndDiscard, null);
// }
//
// public static ActionResponse discard(String reason, Object... args) {
// return new ActionResponse(Action.RejectAndDiscard, String.format(reason, args));
// }
//
// public String getReason() {
// return reason;
// }
//
// public Action getAction() {
// return action;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ActionResponse that = (ActionResponse) o;
//
// if (action != that.action) return false;
// if (reason != null ? !reason.equals(that.reason) : that.reason != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = action != null ? action.hashCode() : 0;
// result = 31 * result + (reason != null ? reason.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "ActionResponse{" +
// "action=" + action +
// ", reason='" + reason + '\'' +
// '}';
// }
//
// public enum Action {
// Acknowledge, //! The transport will ack the message explicitly.
// RejectAndRequeue, //! The message wasn't meant to be processed.
// // For example, if the message delivered is of
// // a higher version than what we are able to
// // deal with.
// RejectAndDiscard //! A malformed message, place it on a poison queue.
// }
//
//
//
// }
// Path: conduit/src/test/java/io/rtr/conduit/util/RecordingAmqpCallbackHandler.java
import io.rtr.conduit.amqp.AMQPMessageBundle;
import io.rtr.conduit.amqp.ActionResponse;
import java.util.ArrayList;
import java.util.List;
package io.rtr.conduit.util;
public class RecordingAmqpCallbackHandler extends LoggingAmqpCallbackHandler {
private final List<AMQPMessageBundle> capturedMessages = new ArrayList<>();
@Override | public ActionResponse handle(AMQPMessageBundle messageBundle) { |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/MvcContextImpl.java | // Path: core/src/main/java/org/mvcspec/ozark/util/PathUtils.java
// public final class PathUtils {
//
// /**
// * Drops starting slash from path if present.
// *
// * @param path the path.
// * @return the resulting path without a starting slash.
// */
// public static String noStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return hasStartingSlash(path) ? path.substring(1) : path;
// }
//
// /**
// * Determines of path starts with a slash.
// *
// * @param path the path to test.
// * @return outcome of test.
// */
// public static boolean hasStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return !"".equals(path) && path.charAt(0) == '/';
// }
//
// /**
// * Drops a prefix from a path if it exists or returns original path if prefix does
// * not match.
// *
// * @param path the path.
// * @param prefix the prefix to drop.
// * @return new path without prefix or old path if prefix does not exist.
// */
// public static String noPrefix(String path, String prefix) {
// Objects.requireNonNull(path, "path must not be null");
// Objects.requireNonNull(prefix, "prefix must not be null");
// return path.startsWith(prefix) ? path.substring(prefix.length()) : path;
// }
//
// /**
// * Ensures that a path always starts with a slash.
// *
// * @param path the path.
// * @return path that starts with a slash.
// */
// public static String ensureStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return "".equals(path) || path.charAt(0) != '/' ? ("/" + path) : path;
// }
//
// /**
// * Ensures that a path always ends with a slash.
// *
// * @param path the path.
// * @return path that starts with a slash.
// */
// public static String ensureEndingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return "".equals(path) || path.charAt(path.length() - 1) != '/' ? (path + "/") : path;
// }
//
// /**
// * Ensures that a path does not end with a slash. May return an
// * empty string.
// *
// * @param path the path.
// * @return path not ending with slash or empty string.
// */
// public static String ensureNotEndingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// if ("".equals(path)) {
// return path;
// }
// final int length = path.length();
// return path.charAt(length - 1) == '/' ? path.substring(0, length - 1) : path;
// }
//
// /**
// * Returns a normalized path. If the path is empty or "/*", then an empty string
// * is returned. Otherwise, the path returned always starts with a "/" but does not
// * end with one.
// *
// * @param path the path to normalize.
// * @return normalized path.
// */
// public static String normalizePath(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return path.isEmpty() || path.equals("/*") ? "" : ensureNotEndingSlash(ensureStartingSlash(path));
// }
//
// }
| import org.mvcspec.ozark.jaxrs.JaxRsContext;
import org.mvcspec.ozark.uri.ApplicationUris;
import org.mvcspec.ozark.util.PathUtils;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.mvc.MvcContext;
import javax.mvc.security.Csrf;
import javax.mvc.security.Encoders;
import javax.servlet.ServletContext;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark;
/**
* Implementation of {@link javax.mvc.MvcContext}.
*
* @author Santiago Pericas-Geertsen
*/
@Named("mvc")
@RequestScoped
public class MvcContextImpl implements MvcContext {
private static final Logger log = Logger.getLogger(MvcContextImpl.class.getName());
@Inject
private Csrf csrf;
@Inject
private Encoders encoders;
@Inject
private ServletContext servletContext;
@Inject
private ApplicationUris applicationUris;
@Inject
@JaxRsContext
private Configuration configuration;
@Inject
@JaxRsContext
private UriInfo uriInfo;
private Locale locale;
private String applicationPath;
@PostConstruct
public void init() {
Objects.requireNonNull(configuration, "Cannot obtain JAX-RS Configuration instance");
Objects.requireNonNull(uriInfo, "Cannot obtain JAX-RS UriInfo instance");
Objects.requireNonNull(servletContext, "Cannot obtain ServletContext");
| // Path: core/src/main/java/org/mvcspec/ozark/util/PathUtils.java
// public final class PathUtils {
//
// /**
// * Drops starting slash from path if present.
// *
// * @param path the path.
// * @return the resulting path without a starting slash.
// */
// public static String noStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return hasStartingSlash(path) ? path.substring(1) : path;
// }
//
// /**
// * Determines of path starts with a slash.
// *
// * @param path the path to test.
// * @return outcome of test.
// */
// public static boolean hasStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return !"".equals(path) && path.charAt(0) == '/';
// }
//
// /**
// * Drops a prefix from a path if it exists or returns original path if prefix does
// * not match.
// *
// * @param path the path.
// * @param prefix the prefix to drop.
// * @return new path without prefix or old path if prefix does not exist.
// */
// public static String noPrefix(String path, String prefix) {
// Objects.requireNonNull(path, "path must not be null");
// Objects.requireNonNull(prefix, "prefix must not be null");
// return path.startsWith(prefix) ? path.substring(prefix.length()) : path;
// }
//
// /**
// * Ensures that a path always starts with a slash.
// *
// * @param path the path.
// * @return path that starts with a slash.
// */
// public static String ensureStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return "".equals(path) || path.charAt(0) != '/' ? ("/" + path) : path;
// }
//
// /**
// * Ensures that a path always ends with a slash.
// *
// * @param path the path.
// * @return path that starts with a slash.
// */
// public static String ensureEndingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return "".equals(path) || path.charAt(path.length() - 1) != '/' ? (path + "/") : path;
// }
//
// /**
// * Ensures that a path does not end with a slash. May return an
// * empty string.
// *
// * @param path the path.
// * @return path not ending with slash or empty string.
// */
// public static String ensureNotEndingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// if ("".equals(path)) {
// return path;
// }
// final int length = path.length();
// return path.charAt(length - 1) == '/' ? path.substring(0, length - 1) : path;
// }
//
// /**
// * Returns a normalized path. If the path is empty or "/*", then an empty string
// * is returned. Otherwise, the path returned always starts with a "/" but does not
// * end with one.
// *
// * @param path the path to normalize.
// * @return normalized path.
// */
// public static String normalizePath(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return path.isEmpty() || path.equals("/*") ? "" : ensureNotEndingSlash(ensureStartingSlash(path));
// }
//
// }
// Path: core/src/main/java/org/mvcspec/ozark/MvcContextImpl.java
import org.mvcspec.ozark.jaxrs.JaxRsContext;
import org.mvcspec.ozark.uri.ApplicationUris;
import org.mvcspec.ozark.util.PathUtils;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.mvc.MvcContext;
import javax.mvc.security.Csrf;
import javax.mvc.security.Encoders;
import javax.servlet.ServletContext;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark;
/**
* Implementation of {@link javax.mvc.MvcContext}.
*
* @author Santiago Pericas-Geertsen
*/
@Named("mvc")
@RequestScoped
public class MvcContextImpl implements MvcContext {
private static final Logger log = Logger.getLogger(MvcContextImpl.class.getName());
@Inject
private Csrf csrf;
@Inject
private Encoders encoders;
@Inject
private ServletContext servletContext;
@Inject
private ApplicationUris applicationUris;
@Inject
@JaxRsContext
private Configuration configuration;
@Inject
@JaxRsContext
private UriInfo uriInfo;
private Locale locale;
private String applicationPath;
@PostConstruct
public void init() {
Objects.requireNonNull(configuration, "Cannot obtain JAX-RS Configuration instance");
Objects.requireNonNull(uriInfo, "Cannot obtain JAX-RS UriInfo instance");
Objects.requireNonNull(servletContext, "Cannot obtain ServletContext");
| applicationPath = PathUtils.normalizePath( |
mvc-spec/ozark | ext/jade/src/main/java/org/mvcspec/ozark/ext/jade/JadeViewEngine.java | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
| import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import de.neuland.jade4j.JadeConfiguration;
import de.neuland.jade4j.exceptions.JadeException;
import de.neuland.jade4j.template.JadeTemplate;
import org.mvcspec.ozark.engine.ViewEngineBase;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStreamWriter; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.jade;
/**
* The Jade View Engine.
*
* @author Florian Hirsch
* @see <a href="http://jade-lang.com/">Jade</a>
* @see <a href="https://github.com/neuland/jade4j">Jade4J</a>
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
// Path: ext/jade/src/main/java/org/mvcspec/ozark/ext/jade/JadeViewEngine.java
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import de.neuland.jade4j.JadeConfiguration;
import de.neuland.jade4j.exceptions.JadeException;
import de.neuland.jade4j.template.JadeTemplate;
import org.mvcspec.ozark.engine.ViewEngineBase;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStreamWriter;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.jade;
/**
* The Jade View Engine.
*
* @author Florian Hirsch
* @see <a href="http://jade-lang.com/">Jade</a>
* @see <a href="https://github.com/neuland/jade4j">Jade4J</a>
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | public class JadeViewEngine extends ViewEngineBase { |
mvc-spec/ozark | jersey/src/main/java/org/mvcspec/ozark/jersey/bootstrap/JerseyConfigProvider.java | // Path: core/src/main/java/org/mvcspec/ozark/bootstrap/ConfigProvider.java
// public interface ConfigProvider {
//
// void configure(FeatureContext context);
//
// }
//
// Path: jersey/src/main/java/org/mvcspec/ozark/jersey/validation/OzarkValidationInterceptor.java
// public class OzarkValidationInterceptor implements ValidationInterceptor {
//
// /**
// * For some weird reason we cannot preserve the <code>throws ConstraintViolationException</code>
// * in the method signature. Bundling Ozark as a Glassfish plugin starts failing as soon as
// * this class uses any interface from the javax.validation package. My current guess is
// * that this is related to the OSGi bundling.
// */
// @Override
// public void onValidate(ValidationInterceptorContext context) {
//
// /*
// * TODO: Won't work correctly for mixed controller/resource methods.
// */
// Class<?> resourceClass = context.getResource().getClass();
// boolean mvcRequest = AnnotationUtils.hasAnnotationOnClassOrMethod(resourceClass, Controller.class);
//
// if (!mvcRequest) {
// context.proceed();
// }
//
// }
//
// }
| import org.mvcspec.ozark.bootstrap.ConfigProvider;
import org.mvcspec.ozark.jersey.model.OzarkModelProcessor;
import org.mvcspec.ozark.jersey.validation.OzarkValidationInterceptor;
import javax.ws.rs.core.FeatureContext; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.jersey.bootstrap;
/**
* Implementation of ConfigProvider for the Jersey module.
*
* @author Christian Kaltepoth
*/
public class JerseyConfigProvider implements ConfigProvider {
@Override
public void configure(FeatureContext context) {
context.register(OzarkModelProcessor.class); | // Path: core/src/main/java/org/mvcspec/ozark/bootstrap/ConfigProvider.java
// public interface ConfigProvider {
//
// void configure(FeatureContext context);
//
// }
//
// Path: jersey/src/main/java/org/mvcspec/ozark/jersey/validation/OzarkValidationInterceptor.java
// public class OzarkValidationInterceptor implements ValidationInterceptor {
//
// /**
// * For some weird reason we cannot preserve the <code>throws ConstraintViolationException</code>
// * in the method signature. Bundling Ozark as a Glassfish plugin starts failing as soon as
// * this class uses any interface from the javax.validation package. My current guess is
// * that this is related to the OSGi bundling.
// */
// @Override
// public void onValidate(ValidationInterceptorContext context) {
//
// /*
// * TODO: Won't work correctly for mixed controller/resource methods.
// */
// Class<?> resourceClass = context.getResource().getClass();
// boolean mvcRequest = AnnotationUtils.hasAnnotationOnClassOrMethod(resourceClass, Controller.class);
//
// if (!mvcRequest) {
// context.proceed();
// }
//
// }
//
// }
// Path: jersey/src/main/java/org/mvcspec/ozark/jersey/bootstrap/JerseyConfigProvider.java
import org.mvcspec.ozark.bootstrap.ConfigProvider;
import org.mvcspec.ozark.jersey.model.OzarkModelProcessor;
import org.mvcspec.ozark.jersey.validation.OzarkValidationInterceptor;
import javax.ws.rs.core.FeatureContext;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.jersey.bootstrap;
/**
* Implementation of ConfigProvider for the Jersey module.
*
* @author Christian Kaltepoth
*/
public class JerseyConfigProvider implements ConfigProvider {
@Override
public void configure(FeatureContext context) {
context.register(OzarkModelProcessor.class); | context.register(OzarkValidationInterceptor.class); |
mvc-spec/ozark | core/src/test/java/org/mvcspec/ozark/engine/ViewEngineContextImplTest.java | // Path: core/src/main/java/org/mvcspec/ozark/core/ModelsImpl.java
// @RequestScoped
// public class ModelsImpl implements Models {
//
// private final Map<String, Object> map = new LinkedHashMap<>();
//
// @Override
// public Models put(String name, Object model) {
// Objects.requireNonNull(name, "Name must not be null");
// map.put(name, model);
// return this;
// }
//
// @Override
// public Object get(String name) {
// return get(name, Object.class);
// }
//
// @Override
// public <T> T get(String name, Class<T> type) {
// Objects.requireNonNull(name, "Name must not be null");
// Objects.requireNonNull(type, "Type must not be null");
// return type.cast(map.get(name));
// }
//
// @Override
// public Map<String, Object> asMap() {
// return Collections.unmodifiableMap(new LinkedHashMap<>(map));
// }
//
// @Override
// public Iterator<String> iterator() {
// return map.keySet().iterator();
// }
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.UriInfo;
import org.easymock.EasyMock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import org.mvcspec.ozark.core.ModelsImpl;
import org.junit.Test;
import static org.junit.Assert.*; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.engine;
/**
* The JUnit test for the ViewEngineContext class.
*
* @author Manfred Riem (manfred.riem at oracle.com)
*/
public class ViewEngineContextImplTest {
/**
* Test getView method.
*/
@Test
public void testGetView() {
ViewEngineContextImpl context = new ViewEngineContextImpl("view", null, null, null, null, null, null, null, null, null, null);
assertEquals("view", context.getView());
}
/**
* Test getModels method.
*/
@Test
public void testGetModels() {
ViewEngineContextImpl context = new ViewEngineContextImpl(null, null, null, null, null, null, null, null, null, null, null);
assertNull(context.getModels()); | // Path: core/src/main/java/org/mvcspec/ozark/core/ModelsImpl.java
// @RequestScoped
// public class ModelsImpl implements Models {
//
// private final Map<String, Object> map = new LinkedHashMap<>();
//
// @Override
// public Models put(String name, Object model) {
// Objects.requireNonNull(name, "Name must not be null");
// map.put(name, model);
// return this;
// }
//
// @Override
// public Object get(String name) {
// return get(name, Object.class);
// }
//
// @Override
// public <T> T get(String name, Class<T> type) {
// Objects.requireNonNull(name, "Name must not be null");
// Objects.requireNonNull(type, "Type must not be null");
// return type.cast(map.get(name));
// }
//
// @Override
// public Map<String, Object> asMap() {
// return Collections.unmodifiableMap(new LinkedHashMap<>(map));
// }
//
// @Override
// public Iterator<String> iterator() {
// return map.keySet().iterator();
// }
// }
// Path: core/src/test/java/org/mvcspec/ozark/engine/ViewEngineContextImplTest.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.UriInfo;
import org.easymock.EasyMock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import org.mvcspec.ozark.core.ModelsImpl;
import org.junit.Test;
import static org.junit.Assert.*;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.engine;
/**
* The JUnit test for the ViewEngineContext class.
*
* @author Manfred Riem (manfred.riem at oracle.com)
*/
public class ViewEngineContextImplTest {
/**
* Test getView method.
*/
@Test
public void testGetView() {
ViewEngineContextImpl context = new ViewEngineContextImpl("view", null, null, null, null, null, null, null, null, null, null);
assertEquals("view", context.getView());
}
/**
* Test getModels method.
*/
@Test
public void testGetModels() {
ViewEngineContextImpl context = new ViewEngineContextImpl(null, null, null, null, null, null, null, null, null, null, null);
assertNull(context.getModels()); | context = new ViewEngineContextImpl(null, new ModelsImpl(), null, null, null, null, null, null, null, null, null); |
mvc-spec/ozark | resteasy/src/main/java/org/mvcspec/ozark/resteasy/bootstrap/RestEasyConfigProvider.java | // Path: core/src/main/java/org/mvcspec/ozark/bootstrap/ConfigProvider.java
// public interface ConfigProvider {
//
// void configure(FeatureContext context);
//
// }
//
// Path: resteasy/src/main/java/org/mvcspec/ozark/resteasy/validation/OzarkValidationResolver.java
// public class OzarkValidationResolver implements ContextResolver<GeneralValidator> {
//
// public GeneralValidator getContext(Class<?> aClass) {
//
// // get the real RESTEasy validator
// GeneralValidator wrapped = new ValidatorContextResolver().getContext(aClass);
//
// // only delegate to wrapped validator for regular JAX-RS requests
// return new OzarkGeneralValidator(wrapped);
//
// }
//
// }
| import org.mvcspec.ozark.bootstrap.ConfigProvider;
import org.mvcspec.ozark.resteasy.validation.OzarkValidationResolver;
import javax.ws.rs.core.FeatureContext; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.resteasy.bootstrap;
/**
* Implementation of ConfigProvider for the RESTEasy module.
*
* @author Christian Kaltepoth
*/
public class RestEasyConfigProvider implements ConfigProvider {
@Override
public void configure(FeatureContext context) { | // Path: core/src/main/java/org/mvcspec/ozark/bootstrap/ConfigProvider.java
// public interface ConfigProvider {
//
// void configure(FeatureContext context);
//
// }
//
// Path: resteasy/src/main/java/org/mvcspec/ozark/resteasy/validation/OzarkValidationResolver.java
// public class OzarkValidationResolver implements ContextResolver<GeneralValidator> {
//
// public GeneralValidator getContext(Class<?> aClass) {
//
// // get the real RESTEasy validator
// GeneralValidator wrapped = new ValidatorContextResolver().getContext(aClass);
//
// // only delegate to wrapped validator for regular JAX-RS requests
// return new OzarkGeneralValidator(wrapped);
//
// }
//
// }
// Path: resteasy/src/main/java/org/mvcspec/ozark/resteasy/bootstrap/RestEasyConfigProvider.java
import org.mvcspec.ozark.bootstrap.ConfigProvider;
import org.mvcspec.ozark.resteasy.validation.OzarkValidationResolver;
import javax.ws.rs.core.FeatureContext;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.resteasy.bootstrap;
/**
* Implementation of ConfigProvider for the RESTEasy module.
*
* @author Christian Kaltepoth
*/
public class RestEasyConfigProvider implements ConfigProvider {
@Override
public void configure(FeatureContext context) { | context.register(OzarkValidationResolver.class); |
mvc-spec/ozark | ext/pebble/src/main/java/org/mvcspec/ozark/ext/pebble/PebbleViewEngine.java | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
| import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import org.mvcspec.ozark.engine.ViewEngineBase;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.pebble;
/**
* @see <a href="http://www.mitchellbosecke.com/pebble/home">Pebble</a>
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
// Path: ext/pebble/src/main/java/org/mvcspec/ozark/ext/pebble/PebbleViewEngine.java
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import org.mvcspec.ozark.engine.ViewEngineBase;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.pebble;
/**
* @see <a href="http://www.mitchellbosecke.com/pebble/home">Pebble</a>
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | public class PebbleViewEngine extends ViewEngineBase { |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/cdi/RedirectScopeManager.java | // Path: core/src/main/java/org/mvcspec/ozark/util/CdiUtils.java
// @ApplicationScoped
// @SuppressWarnings("unchecked")
// public class CdiUtils {
//
// @Inject
// private BeanManager beanManager;
//
// /**
// * Create a new CDI bean given its class. The bean is created in the context
// * defined by the scope annotation on the class.
// *
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// @SuppressWarnings("unchecked")
// public <T> T newBean(Class<T> clazz) {
// return newBean(beanManager, clazz);
// }
//
// /**
// * Create a new CDI bean given its class and a bean manager. The bean is created
// * in the context defined by the scope annotation on the class.
// *
// * @param bm The BeanManager.
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// public static <T> T newBean(BeanManager bm, Class<T> clazz) {
// Set<Bean<?>> beans = bm.getBeans(clazz);
// final Bean<T> bean = (Bean<T>) bm.resolve(beans);
// final CreationalContext<T> ctx = bm.createCreationalContext(bean);
// return (T) bm.getReference(bean, clazz, ctx);
// }
//
// /**
// * @param beforeBean The BeforeBeanDiscovery.
// * @param bm The BeanManager.
// * @param types annotated types to register
// */
// public static void addAnnotatedTypes(BeforeBeanDiscovery beforeBean, BeanManager bm, Class<?>... types) {
// for (Class<?> type : types) {
// beforeBean.addAnnotatedType(bm.createAnnotatedType(type), type.getName());
// }
// }
//
// /**
// * Returns a list of CDI beans with the specified bean type and qualifiers.
// * Please note that this method supports looking up beans deployed with the application
// * even if Ozark is deployed as a container archive.
// */
// public static <T> List<T> getApplicationBeans(Class<T> type, Annotation... qualifiers) {
// BeanManager manager = getApplicationBeanManager();
// return manager.getBeans(type, qualifiers).stream()
// .map(bean -> (T) manager.getReference(bean, type, manager.createCreationalContext(bean)))
// .collect(Collectors.toList());
// }
//
// /**
// * Returns a single CDI bean with the given type and qualifiers. Will throw an exception if there
// * is more than one matching bean. Please note that this method supports looking up beans deployed
// * with the application even if Ozark is deployed as a container archive.
// */
// public static <T> Optional<T> getApplicationBean(Class<T> type, Annotation... qualifiers) {
// List<T> instances = getApplicationBeans(type);
// if (instances.size() == 0) {
// return Optional.empty();
// } else if (instances.size() == 1) {
// return Optional.of(instances.get(0));
// } else {
// throw new IllegalStateException("More than one CDI managed instance found of: " + type.getName());
// }
// }
//
// /**
// * This method returns a {@link BeanManager} which can resolve beans defined in the application.
// * In case of Glassfish the injected {@link BeanManager} doesn't work here as it only resolves
// * beans in the Ozark archive if Ozark is installed as part of the container.
// */
// public static BeanManager getApplicationBeanManager() {
// return CDI.current().getBeanManager();
// }
//
// }
| import org.mvcspec.ozark.Properties;
import org.mvcspec.ozark.event.ControllerRedirectEventImpl;
import org.mvcspec.ozark.jaxrs.JaxRsContext;
import org.mvcspec.ozark.util.CdiUtils;
import org.mvcspec.ozark.util.PropertyUtils;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.PassivationCapable;
import javax.inject.Inject;
import javax.mvc.MvcContext;
import javax.mvc.event.AfterProcessViewEvent;
import javax.mvc.event.BeforeControllerEvent;
import javax.mvc.event.ControllerRedirectEvent;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.UriBuilder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; | if (cookie.getName().equals(COOKIE_NAME)) {
request.setAttribute(SCOPE_ID, cookie.getValue());
return; // we're done
}
}
}
} else {
final String scopeId = event.getUriInfo().getQueryParameters().getFirst(SCOPE_ID);
if (scopeId != null) {
request.setAttribute(SCOPE_ID, scopeId);
}
}
}
/**
* Perform the work we need to do at AfterProcessViewEvent time.
*
* @param event the event.
*/
public void afterProcessViewEvent(@Observes AfterProcessViewEvent event) {
if (request.getAttribute(SCOPE_ID) != null) {
String scopeId = (String) request.getAttribute(SCOPE_ID);
HttpSession session = request.getSession();
final String sessionKey = SCOPE_ID + "-" + scopeId;
Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
if (null != scopeMap) {
scopeMap.entrySet().stream().forEach((entrySet) -> {
String key = entrySet.getKey();
Object value = entrySet.getValue();
if (key.startsWith(INSTANCE)) { | // Path: core/src/main/java/org/mvcspec/ozark/util/CdiUtils.java
// @ApplicationScoped
// @SuppressWarnings("unchecked")
// public class CdiUtils {
//
// @Inject
// private BeanManager beanManager;
//
// /**
// * Create a new CDI bean given its class. The bean is created in the context
// * defined by the scope annotation on the class.
// *
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// @SuppressWarnings("unchecked")
// public <T> T newBean(Class<T> clazz) {
// return newBean(beanManager, clazz);
// }
//
// /**
// * Create a new CDI bean given its class and a bean manager. The bean is created
// * in the context defined by the scope annotation on the class.
// *
// * @param bm The BeanManager.
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// public static <T> T newBean(BeanManager bm, Class<T> clazz) {
// Set<Bean<?>> beans = bm.getBeans(clazz);
// final Bean<T> bean = (Bean<T>) bm.resolve(beans);
// final CreationalContext<T> ctx = bm.createCreationalContext(bean);
// return (T) bm.getReference(bean, clazz, ctx);
// }
//
// /**
// * @param beforeBean The BeforeBeanDiscovery.
// * @param bm The BeanManager.
// * @param types annotated types to register
// */
// public static void addAnnotatedTypes(BeforeBeanDiscovery beforeBean, BeanManager bm, Class<?>... types) {
// for (Class<?> type : types) {
// beforeBean.addAnnotatedType(bm.createAnnotatedType(type), type.getName());
// }
// }
//
// /**
// * Returns a list of CDI beans with the specified bean type and qualifiers.
// * Please note that this method supports looking up beans deployed with the application
// * even if Ozark is deployed as a container archive.
// */
// public static <T> List<T> getApplicationBeans(Class<T> type, Annotation... qualifiers) {
// BeanManager manager = getApplicationBeanManager();
// return manager.getBeans(type, qualifiers).stream()
// .map(bean -> (T) manager.getReference(bean, type, manager.createCreationalContext(bean)))
// .collect(Collectors.toList());
// }
//
// /**
// * Returns a single CDI bean with the given type and qualifiers. Will throw an exception if there
// * is more than one matching bean. Please note that this method supports looking up beans deployed
// * with the application even if Ozark is deployed as a container archive.
// */
// public static <T> Optional<T> getApplicationBean(Class<T> type, Annotation... qualifiers) {
// List<T> instances = getApplicationBeans(type);
// if (instances.size() == 0) {
// return Optional.empty();
// } else if (instances.size() == 1) {
// return Optional.of(instances.get(0));
// } else {
// throw new IllegalStateException("More than one CDI managed instance found of: " + type.getName());
// }
// }
//
// /**
// * This method returns a {@link BeanManager} which can resolve beans defined in the application.
// * In case of Glassfish the injected {@link BeanManager} doesn't work here as it only resolves
// * beans in the Ozark archive if Ozark is installed as part of the container.
// */
// public static BeanManager getApplicationBeanManager() {
// return CDI.current().getBeanManager();
// }
//
// }
// Path: core/src/main/java/org/mvcspec/ozark/cdi/RedirectScopeManager.java
import org.mvcspec.ozark.Properties;
import org.mvcspec.ozark.event.ControllerRedirectEventImpl;
import org.mvcspec.ozark.jaxrs.JaxRsContext;
import org.mvcspec.ozark.util.CdiUtils;
import org.mvcspec.ozark.util.PropertyUtils;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.PassivationCapable;
import javax.inject.Inject;
import javax.mvc.MvcContext;
import javax.mvc.event.AfterProcessViewEvent;
import javax.mvc.event.BeforeControllerEvent;
import javax.mvc.event.ControllerRedirectEvent;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.UriBuilder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
if (cookie.getName().equals(COOKIE_NAME)) {
request.setAttribute(SCOPE_ID, cookie.getValue());
return; // we're done
}
}
}
} else {
final String scopeId = event.getUriInfo().getQueryParameters().getFirst(SCOPE_ID);
if (scopeId != null) {
request.setAttribute(SCOPE_ID, scopeId);
}
}
}
/**
* Perform the work we need to do at AfterProcessViewEvent time.
*
* @param event the event.
*/
public void afterProcessViewEvent(@Observes AfterProcessViewEvent event) {
if (request.getAttribute(SCOPE_ID) != null) {
String scopeId = (String) request.getAttribute(SCOPE_ID);
HttpSession session = request.getSession();
final String sessionKey = SCOPE_ID + "-" + scopeId;
Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
if (null != scopeMap) {
scopeMap.entrySet().stream().forEach((entrySet) -> {
String key = entrySet.getKey();
Object value = entrySet.getValue();
if (key.startsWith(INSTANCE)) { | BeanManager beanManager = CdiUtils.getApplicationBeanManager(); |
mvc-spec/ozark | ext/asciidoc/src/main/java/org/mvcspec/ozark/ext/asciidoc/AsciiDocViewEngine.java | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
| import org.asciidoctor.Asciidoctor;
import org.asciidoctor.Asciidoctor.Factory;
import org.asciidoctor.Options;
import org.mvcspec.ozark.engine.ViewEngineBase;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.asciidoc;
/**
* Class AsciiDocViewEngine.
*
* @author Ricardo Arguello
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
// Path: ext/asciidoc/src/main/java/org/mvcspec/ozark/ext/asciidoc/AsciiDocViewEngine.java
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.Asciidoctor.Factory;
import org.asciidoctor.Options;
import org.mvcspec.ozark.engine.ViewEngineBase;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.asciidoc;
/**
* Class AsciiDocViewEngine.
*
* @author Ricardo Arguello
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | public class AsciiDocViewEngine extends ViewEngineBase { |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/security/CsrfValidateInterceptor.java | // Path: core/src/main/java/org/mvcspec/ozark/util/AnnotationUtils.java
// public static <T extends Annotation> boolean hasAnnotation(Class<?> clazz, Class<T> annotationType) {
// return getAnnotation(clazz, annotationType) != null;
// }
| import org.mvcspec.ozark.OzarkConfig;
import org.mvcspec.ozark.core.Messages;
import javax.annotation.Priority;
import javax.inject.Inject;
import javax.mvc.Controller;
import javax.mvc.security.CsrfProtected;
import javax.mvc.security.CsrfValidationException;
import javax.ws.rs.POST;
import javax.ws.rs.Priorities;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import static org.mvcspec.ozark.util.AnnotationUtils.hasAnnotation; | return contentType != null &&
contentType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
}
private ByteArrayInputStream copyStream(InputStream is) throws IOException {
int n;
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
final byte[] buffer = new byte[BUFFER_SIZE];
while ((n = is.read(buffer)) >= 0) {
baos.write(buffer, 0, n);
}
return new ByteArrayInputStream(baos.toByteArray());
}
}
private String toString(ByteArrayInputStream bais, String encoding) throws UnsupportedEncodingException {
int n = 0;
final byte[] bb = new byte[bais.available()];
while ((n = bais.read(bb, n, bb.length - n)) >= 0); // NOPMD ignore empty while block
bais.reset();
return new String(bb, encoding);
}
/**
* Determines if a controller method needs CSRF validation based on the config options.
*
* @param controller controller to inspect.
* @return outcome of test.
*/
private boolean needsValidation(Method controller) { | // Path: core/src/main/java/org/mvcspec/ozark/util/AnnotationUtils.java
// public static <T extends Annotation> boolean hasAnnotation(Class<?> clazz, Class<T> annotationType) {
// return getAnnotation(clazz, annotationType) != null;
// }
// Path: core/src/main/java/org/mvcspec/ozark/security/CsrfValidateInterceptor.java
import org.mvcspec.ozark.OzarkConfig;
import org.mvcspec.ozark.core.Messages;
import javax.annotation.Priority;
import javax.inject.Inject;
import javax.mvc.Controller;
import javax.mvc.security.CsrfProtected;
import javax.mvc.security.CsrfValidationException;
import javax.ws.rs.POST;
import javax.ws.rs.Priorities;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import static org.mvcspec.ozark.util.AnnotationUtils.hasAnnotation;
return contentType != null &&
contentType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
}
private ByteArrayInputStream copyStream(InputStream is) throws IOException {
int n;
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
final byte[] buffer = new byte[BUFFER_SIZE];
while ((n = is.read(buffer)) >= 0) {
baos.write(buffer, 0, n);
}
return new ByteArrayInputStream(baos.toByteArray());
}
}
private String toString(ByteArrayInputStream bais, String encoding) throws UnsupportedEncodingException {
int n = 0;
final byte[] bb = new byte[bais.available()];
while ((n = bais.read(bb, n, bb.length - n)) >= 0); // NOPMD ignore empty while block
bais.reset();
return new String(bb, encoding);
}
/**
* Determines if a controller method needs CSRF validation based on the config options.
*
* @param controller controller to inspect.
* @return outcome of test.
*/
private boolean needsValidation(Method controller) { | if (controller == null || !hasAnnotation(controller, POST.class)) { |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/util/ServiceLoaders.java | // Path: core/src/main/java/org/mvcspec/ozark/bootstrap/ConfigProvider.java
// public interface ConfigProvider {
//
// void configure(FeatureContext context);
//
// }
| import org.mvcspec.ozark.bootstrap.ConfigProvider;
import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.util;
/**
* Utility code for the {@link ServiceLoader} class.
*
* @author Christian Kaltepoth
*/
public class ServiceLoaders {
private ServiceLoaders() {
// only static methods
}
public static <T> List<T> list(Class<T> type) {
// classloader to use for ServiceLoader lookups
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
/*
* Special workaround for TomEE . The context classloader is an instance of CxfContainerClassLoader
* and NOT the TomEEWebappClassLoader, which seems to break when redeploying apps into a running
* container for some reason.
*/
if (classLoader.getClass().getName().contains("CxfContainerClassLoader")) { | // Path: core/src/main/java/org/mvcspec/ozark/bootstrap/ConfigProvider.java
// public interface ConfigProvider {
//
// void configure(FeatureContext context);
//
// }
// Path: core/src/main/java/org/mvcspec/ozark/util/ServiceLoaders.java
import org.mvcspec.ozark.bootstrap.ConfigProvider;
import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.util;
/**
* Utility code for the {@link ServiceLoader} class.
*
* @author Christian Kaltepoth
*/
public class ServiceLoaders {
private ServiceLoaders() {
// only static methods
}
public static <T> List<T> list(Class<T> type) {
// classloader to use for ServiceLoader lookups
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
/*
* Special workaround for TomEE . The context classloader is an instance of CxfContainerClassLoader
* and NOT the TomEEWebappClassLoader, which seems to break when redeploying apps into a running
* container for some reason.
*/
if (classLoader.getClass().getName().contains("CxfContainerClassLoader")) { | classLoader = ConfigProvider.class.getClassLoader(); |
mvc-spec/ozark | ext/handlebars/src/main/java/org/mvcspec/ozark/ext/handlebars/HandlebarsViewEngine.java | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
| import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import org.mvcspec.ozark.engine.ViewEngineBase;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.handlebars;
/**
* Class HandlebarsViewEngine
*
* @author Rahman Usta
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
// Path: ext/handlebars/src/main/java/org/mvcspec/ozark/ext/handlebars/HandlebarsViewEngine.java
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import org.mvcspec.ozark.engine.ViewEngineBase;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.handlebars;
/**
* Class HandlebarsViewEngine
*
* @author Rahman Usta
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | public class HandlebarsViewEngine extends ViewEngineBase { |
mvc-spec/ozark | testsuite/src/test/java/org/mvcspec/ozark/test/MvcIT.java | // Path: testsuite/src/test/java/org/mvcspec/ozark/test/util/WebArchiveBuilder.java
// public class WebArchiveBuilder {
//
// private final WebArchive archive = ShrinkWrap.create(WebArchive.class);
// private List<MavenDependency> additionalDependencies = new ArrayList<>();
//
// public WebArchiveBuilder addPackage(String packageName) {
// archive.addPackage(packageName);
// return this;
// }
//
// public WebArchiveBuilder addView(Asset asset, String name) {
// archive.addAsWebInfResource(asset, "views/" + name);
// return this;
// }
//
// public WebArchiveBuilder addView(File file, String name) {
// return this.addView(new FileAsset(file), name);
// }
//
// public WebArchiveBuilder addBeansXml() {
// archive.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
// return this;
// }
//
// public WebArchiveBuilder addDependencies(MavenDependency... dependencies) {
// this.additionalDependencies.addAll(Arrays.asList(dependencies));
// return this;
// }
//
// public WebArchiveBuilder addDependency(String coordinates) {
// addDependencies(MavenDependencies.createDependency(coordinates, ScopeType.RUNTIME,false));
// return this;
// }
//
// public WebArchive build() {
// PomEquippedResolveStage stage = Maven.configureResolver().workOffline()
// .withClassPathResolution(true)
// .loadPomFromFile("pom.xml", System.getProperty("testsuite.profile"))
// .importCompileAndRuntimeDependencies();
//
// if (!this.additionalDependencies.isEmpty()) {
// stage = stage.addDependencies(this.additionalDependencies);
// }
//
// return archive.addAsLibraries(stage.resolve().withTransitivity().asFile());
// }
//
// }
| import static org.junit.Assert.assertEquals;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.resolver.api.maven.ScopeType;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencies;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mvcspec.ozark.test.util.WebArchiveBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.net.URL;
import java.nio.file.Paths; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.test;
/**
* Tests Mvc Implementation.
*
* @author Santiago Pericas-Geertsen
*/
@RunWith(Arquillian.class)
public class MvcIT {
private static final String CSRF_PARAM = "_csrf";
private static final String WEB_INF_SRC = "src/main/resources/mvc/";
@ArquillianResource
private URL baseURL;
@Drone
private WebDriver webDriver;
@Deployment(testable = false, name = "thymeleaf")
public static Archive createDeployment() { | // Path: testsuite/src/test/java/org/mvcspec/ozark/test/util/WebArchiveBuilder.java
// public class WebArchiveBuilder {
//
// private final WebArchive archive = ShrinkWrap.create(WebArchive.class);
// private List<MavenDependency> additionalDependencies = new ArrayList<>();
//
// public WebArchiveBuilder addPackage(String packageName) {
// archive.addPackage(packageName);
// return this;
// }
//
// public WebArchiveBuilder addView(Asset asset, String name) {
// archive.addAsWebInfResource(asset, "views/" + name);
// return this;
// }
//
// public WebArchiveBuilder addView(File file, String name) {
// return this.addView(new FileAsset(file), name);
// }
//
// public WebArchiveBuilder addBeansXml() {
// archive.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
// return this;
// }
//
// public WebArchiveBuilder addDependencies(MavenDependency... dependencies) {
// this.additionalDependencies.addAll(Arrays.asList(dependencies));
// return this;
// }
//
// public WebArchiveBuilder addDependency(String coordinates) {
// addDependencies(MavenDependencies.createDependency(coordinates, ScopeType.RUNTIME,false));
// return this;
// }
//
// public WebArchive build() {
// PomEquippedResolveStage stage = Maven.configureResolver().workOffline()
// .withClassPathResolution(true)
// .loadPomFromFile("pom.xml", System.getProperty("testsuite.profile"))
// .importCompileAndRuntimeDependencies();
//
// if (!this.additionalDependencies.isEmpty()) {
// stage = stage.addDependencies(this.additionalDependencies);
// }
//
// return archive.addAsLibraries(stage.resolve().withTransitivity().asFile());
// }
//
// }
// Path: testsuite/src/test/java/org/mvcspec/ozark/test/MvcIT.java
import static org.junit.Assert.assertEquals;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.resolver.api.maven.ScopeType;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencies;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mvcspec.ozark.test.util.WebArchiveBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.net.URL;
import java.nio.file.Paths;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.test;
/**
* Tests Mvc Implementation.
*
* @author Santiago Pericas-Geertsen
*/
@RunWith(Arquillian.class)
public class MvcIT {
private static final String CSRF_PARAM = "_csrf";
private static final String WEB_INF_SRC = "src/main/resources/mvc/";
@ArquillianResource
private URL baseURL;
@Drone
private WebDriver webDriver;
@Deployment(testable = false, name = "thymeleaf")
public static Archive createDeployment() { | return new WebArchiveBuilder() |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/binding/convert/MvcConverterProvider.java | // Path: core/src/main/java/org/mvcspec/ozark/binding/BindingErrorImpl.java
// public class BindingErrorImpl implements BindingError {
//
// private String message;
//
// private String paramName;
//
// private String submittedValue;
//
// public BindingErrorImpl(String message, String paramName, String submittedValue) {
// this.message = message;
// this.paramName = paramName;
// this.submittedValue = submittedValue;
// }
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String getParamName() {
// return paramName;
// }
//
// public void setParamName(String paramName) {
// this.paramName = paramName;
// }
//
// @Override
// public String getSubmittedValue() {
// return submittedValue;
// }
// }
//
// Path: core/src/main/java/org/mvcspec/ozark/binding/BindingResultImpl.java
// @Vetoed // produced by BindingResultManager
// public class BindingResultImpl implements BindingResult {
//
// private final Set<BindingError> bindingErrors = new LinkedHashSet<>();
//
// private final Set<ValidationError> validationErrors = new LinkedHashSet<>();
//
// private boolean consumed;
//
// @Override
// public boolean isFailed() {
// this.consumed = true;
// return validationErrors.size() > 0 || bindingErrors.size() > 0;
// }
//
// @Override
// public List<String> getAllMessages() {
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .map(ParamError::getMessage)
// .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
// }
//
// @Override
// public Set<ParamError> getAllErrors() {
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
// }
//
// @Override
// public Set<ParamError> getErrors(String param) {
// Objects.requireNonNull(param, "Parameter name is required");
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .filter(paramError -> Objects.equals(paramError.getParamName(), param))
// .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
// }
//
// public void addValidationErrors(Set<ValidationError> validationErrors) {
// this.validationErrors.addAll(validationErrors);
// }
//
// public void addBindingError(BindingError bindingError) {
// this.bindingErrors.add(bindingError);
// }
//
// public boolean hasUnconsumedErrors() {
// return !consumed && (!bindingErrors.isEmpty() || !validationErrors.isEmpty());
// }
//
// }
| import java.util.Locale;
import java.util.stream.Stream;
import org.mvcspec.ozark.binding.BindingErrorImpl;
import org.mvcspec.ozark.binding.BindingResultImpl;
import javax.inject.Inject;
import javax.mvc.MvcContext;
import javax.mvc.binding.MvcBinding;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.binding.convert;
/**
* Implementation if the JAX-RS {@link ParamConverterProvider} contract which delegates conversion
* to the custom implementations for MVC.
*
* @author Christian Kaltepoth
*/
public class MvcConverterProvider implements ParamConverterProvider {
@Inject
private ConverterRegistry converterRegistry;
@Inject
private MvcContext mvcContext;
@Inject | // Path: core/src/main/java/org/mvcspec/ozark/binding/BindingErrorImpl.java
// public class BindingErrorImpl implements BindingError {
//
// private String message;
//
// private String paramName;
//
// private String submittedValue;
//
// public BindingErrorImpl(String message, String paramName, String submittedValue) {
// this.message = message;
// this.paramName = paramName;
// this.submittedValue = submittedValue;
// }
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String getParamName() {
// return paramName;
// }
//
// public void setParamName(String paramName) {
// this.paramName = paramName;
// }
//
// @Override
// public String getSubmittedValue() {
// return submittedValue;
// }
// }
//
// Path: core/src/main/java/org/mvcspec/ozark/binding/BindingResultImpl.java
// @Vetoed // produced by BindingResultManager
// public class BindingResultImpl implements BindingResult {
//
// private final Set<BindingError> bindingErrors = new LinkedHashSet<>();
//
// private final Set<ValidationError> validationErrors = new LinkedHashSet<>();
//
// private boolean consumed;
//
// @Override
// public boolean isFailed() {
// this.consumed = true;
// return validationErrors.size() > 0 || bindingErrors.size() > 0;
// }
//
// @Override
// public List<String> getAllMessages() {
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .map(ParamError::getMessage)
// .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
// }
//
// @Override
// public Set<ParamError> getAllErrors() {
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
// }
//
// @Override
// public Set<ParamError> getErrors(String param) {
// Objects.requireNonNull(param, "Parameter name is required");
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .filter(paramError -> Objects.equals(paramError.getParamName(), param))
// .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
// }
//
// public void addValidationErrors(Set<ValidationError> validationErrors) {
// this.validationErrors.addAll(validationErrors);
// }
//
// public void addBindingError(BindingError bindingError) {
// this.bindingErrors.add(bindingError);
// }
//
// public boolean hasUnconsumedErrors() {
// return !consumed && (!bindingErrors.isEmpty() || !validationErrors.isEmpty());
// }
//
// }
// Path: core/src/main/java/org/mvcspec/ozark/binding/convert/MvcConverterProvider.java
import java.util.Locale;
import java.util.stream.Stream;
import org.mvcspec.ozark.binding.BindingErrorImpl;
import org.mvcspec.ozark.binding.BindingResultImpl;
import javax.inject.Inject;
import javax.mvc.MvcContext;
import javax.mvc.binding.MvcBinding;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.binding.convert;
/**
* Implementation if the JAX-RS {@link ParamConverterProvider} contract which delegates conversion
* to the custom implementations for MVC.
*
* @author Christian Kaltepoth
*/
public class MvcConverterProvider implements ParamConverterProvider {
@Inject
private ConverterRegistry converterRegistry;
@Inject
private MvcContext mvcContext;
@Inject | private BindingResultImpl bindingResult; |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/binding/convert/MvcConverterProvider.java | // Path: core/src/main/java/org/mvcspec/ozark/binding/BindingErrorImpl.java
// public class BindingErrorImpl implements BindingError {
//
// private String message;
//
// private String paramName;
//
// private String submittedValue;
//
// public BindingErrorImpl(String message, String paramName, String submittedValue) {
// this.message = message;
// this.paramName = paramName;
// this.submittedValue = submittedValue;
// }
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String getParamName() {
// return paramName;
// }
//
// public void setParamName(String paramName) {
// this.paramName = paramName;
// }
//
// @Override
// public String getSubmittedValue() {
// return submittedValue;
// }
// }
//
// Path: core/src/main/java/org/mvcspec/ozark/binding/BindingResultImpl.java
// @Vetoed // produced by BindingResultManager
// public class BindingResultImpl implements BindingResult {
//
// private final Set<BindingError> bindingErrors = new LinkedHashSet<>();
//
// private final Set<ValidationError> validationErrors = new LinkedHashSet<>();
//
// private boolean consumed;
//
// @Override
// public boolean isFailed() {
// this.consumed = true;
// return validationErrors.size() > 0 || bindingErrors.size() > 0;
// }
//
// @Override
// public List<String> getAllMessages() {
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .map(ParamError::getMessage)
// .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
// }
//
// @Override
// public Set<ParamError> getAllErrors() {
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
// }
//
// @Override
// public Set<ParamError> getErrors(String param) {
// Objects.requireNonNull(param, "Parameter name is required");
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .filter(paramError -> Objects.equals(paramError.getParamName(), param))
// .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
// }
//
// public void addValidationErrors(Set<ValidationError> validationErrors) {
// this.validationErrors.addAll(validationErrors);
// }
//
// public void addBindingError(BindingError bindingError) {
// this.bindingErrors.add(bindingError);
// }
//
// public boolean hasUnconsumedErrors() {
// return !consumed && (!bindingErrors.isEmpty() || !validationErrors.isEmpty());
// }
//
// }
| import java.util.Locale;
import java.util.stream.Stream;
import org.mvcspec.ozark.binding.BindingErrorImpl;
import org.mvcspec.ozark.binding.BindingResultImpl;
import javax.inject.Inject;
import javax.mvc.MvcContext;
import javax.mvc.binding.MvcBinding;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.binding.convert;
/**
* Implementation if the JAX-RS {@link ParamConverterProvider} contract which delegates conversion
* to the custom implementations for MVC.
*
* @author Christian Kaltepoth
*/
public class MvcConverterProvider implements ParamConverterProvider {
@Inject
private ConverterRegistry converterRegistry;
@Inject
private MvcContext mvcContext;
@Inject
private BindingResultImpl bindingResult;
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
MvcBinding mvcBinding = (MvcBinding) Stream.of(annotations != null ? annotations : new Annotation[0])
.filter(a -> a.annotationType().equals(MvcBinding.class))
.findFirst()
.orElse(null);
if (mvcBinding != null) {
MvcConverter<T> mvcConverter = converterRegistry.lookup(rawType, annotations);
if (mvcConverter != null) {
return new ParamConverter<T>() {
@Override
public T fromString(String value) {
// execute the converter
ConverterResult<T> result = mvcConverter.convert(value, rawType, mvcContext.getLocale());
// register possible errors in BindingResult
result.getError() | // Path: core/src/main/java/org/mvcspec/ozark/binding/BindingErrorImpl.java
// public class BindingErrorImpl implements BindingError {
//
// private String message;
//
// private String paramName;
//
// private String submittedValue;
//
// public BindingErrorImpl(String message, String paramName, String submittedValue) {
// this.message = message;
// this.paramName = paramName;
// this.submittedValue = submittedValue;
// }
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String getParamName() {
// return paramName;
// }
//
// public void setParamName(String paramName) {
// this.paramName = paramName;
// }
//
// @Override
// public String getSubmittedValue() {
// return submittedValue;
// }
// }
//
// Path: core/src/main/java/org/mvcspec/ozark/binding/BindingResultImpl.java
// @Vetoed // produced by BindingResultManager
// public class BindingResultImpl implements BindingResult {
//
// private final Set<BindingError> bindingErrors = new LinkedHashSet<>();
//
// private final Set<ValidationError> validationErrors = new LinkedHashSet<>();
//
// private boolean consumed;
//
// @Override
// public boolean isFailed() {
// this.consumed = true;
// return validationErrors.size() > 0 || bindingErrors.size() > 0;
// }
//
// @Override
// public List<String> getAllMessages() {
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .map(ParamError::getMessage)
// .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
// }
//
// @Override
// public Set<ParamError> getAllErrors() {
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
// }
//
// @Override
// public Set<ParamError> getErrors(String param) {
// Objects.requireNonNull(param, "Parameter name is required");
// this.consumed = true;
// return Stream.concat(bindingErrors.stream(), validationErrors.stream())
// .filter(paramError -> Objects.equals(paramError.getParamName(), param))
// .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
// }
//
// public void addValidationErrors(Set<ValidationError> validationErrors) {
// this.validationErrors.addAll(validationErrors);
// }
//
// public void addBindingError(BindingError bindingError) {
// this.bindingErrors.add(bindingError);
// }
//
// public boolean hasUnconsumedErrors() {
// return !consumed && (!bindingErrors.isEmpty() || !validationErrors.isEmpty());
// }
//
// }
// Path: core/src/main/java/org/mvcspec/ozark/binding/convert/MvcConverterProvider.java
import java.util.Locale;
import java.util.stream.Stream;
import org.mvcspec.ozark.binding.BindingErrorImpl;
import org.mvcspec.ozark.binding.BindingResultImpl;
import javax.inject.Inject;
import javax.mvc.MvcContext;
import javax.mvc.binding.MvcBinding;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.binding.convert;
/**
* Implementation if the JAX-RS {@link ParamConverterProvider} contract which delegates conversion
* to the custom implementations for MVC.
*
* @author Christian Kaltepoth
*/
public class MvcConverterProvider implements ParamConverterProvider {
@Inject
private ConverterRegistry converterRegistry;
@Inject
private MvcContext mvcContext;
@Inject
private BindingResultImpl bindingResult;
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
MvcBinding mvcBinding = (MvcBinding) Stream.of(annotations != null ? annotations : new Annotation[0])
.filter(a -> a.annotationType().equals(MvcBinding.class))
.findFirst()
.orElse(null);
if (mvcBinding != null) {
MvcConverter<T> mvcConverter = converterRegistry.lookup(rawType, annotations);
if (mvcConverter != null) {
return new ParamConverter<T>() {
@Override
public T fromString(String value) {
// execute the converter
ConverterResult<T> result = mvcConverter.convert(value, rawType, mvcContext.getLocale());
// register possible errors in BindingResult
result.getError() | .map(error -> new BindingErrorImpl(error, getParamName(annotations), value)) |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/jaxrs/JaxRsContextFilter.java | // Path: core/src/main/java/org/mvcspec/ozark/util/CdiUtils.java
// @ApplicationScoped
// @SuppressWarnings("unchecked")
// public class CdiUtils {
//
// @Inject
// private BeanManager beanManager;
//
// /**
// * Create a new CDI bean given its class. The bean is created in the context
// * defined by the scope annotation on the class.
// *
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// @SuppressWarnings("unchecked")
// public <T> T newBean(Class<T> clazz) {
// return newBean(beanManager, clazz);
// }
//
// /**
// * Create a new CDI bean given its class and a bean manager. The bean is created
// * in the context defined by the scope annotation on the class.
// *
// * @param bm The BeanManager.
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// public static <T> T newBean(BeanManager bm, Class<T> clazz) {
// Set<Bean<?>> beans = bm.getBeans(clazz);
// final Bean<T> bean = (Bean<T>) bm.resolve(beans);
// final CreationalContext<T> ctx = bm.createCreationalContext(bean);
// return (T) bm.getReference(bean, clazz, ctx);
// }
//
// /**
// * @param beforeBean The BeforeBeanDiscovery.
// * @param bm The BeanManager.
// * @param types annotated types to register
// */
// public static void addAnnotatedTypes(BeforeBeanDiscovery beforeBean, BeanManager bm, Class<?>... types) {
// for (Class<?> type : types) {
// beforeBean.addAnnotatedType(bm.createAnnotatedType(type), type.getName());
// }
// }
//
// /**
// * Returns a list of CDI beans with the specified bean type and qualifiers.
// * Please note that this method supports looking up beans deployed with the application
// * even if Ozark is deployed as a container archive.
// */
// public static <T> List<T> getApplicationBeans(Class<T> type, Annotation... qualifiers) {
// BeanManager manager = getApplicationBeanManager();
// return manager.getBeans(type, qualifiers).stream()
// .map(bean -> (T) manager.getReference(bean, type, manager.createCreationalContext(bean)))
// .collect(Collectors.toList());
// }
//
// /**
// * Returns a single CDI bean with the given type and qualifiers. Will throw an exception if there
// * is more than one matching bean. Please note that this method supports looking up beans deployed
// * with the application even if Ozark is deployed as a container archive.
// */
// public static <T> Optional<T> getApplicationBean(Class<T> type, Annotation... qualifiers) {
// List<T> instances = getApplicationBeans(type);
// if (instances.size() == 0) {
// return Optional.empty();
// } else if (instances.size() == 1) {
// return Optional.of(instances.get(0));
// } else {
// throw new IllegalStateException("More than one CDI managed instance found of: " + type.getName());
// }
// }
//
// /**
// * This method returns a {@link BeanManager} which can resolve beans defined in the application.
// * In case of Glassfish the injected {@link BeanManager} doesn't work here as it only resolves
// * beans in the Ozark archive if Ozark is installed as part of the container.
// */
// public static BeanManager getApplicationBeanManager() {
// return CDI.current().getBeanManager();
// }
//
// }
| import org.mvcspec.ozark.util.CdiUtils;
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.io.IOException; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.jaxrs;
/**
* This filter is used to get the JAX-RS context objects and feed them to the corresponding
* CDI producer.
* <p>
* This class must not be a CDI bean, because CXF/OWB fails to process <code>@Context</code> in this case.
*
* @author Christian Kaltepoth
*/
@PreMatching
@Priority(0) // very early
public class JaxRsContextFilter implements ContainerRequestFilter {
@Context
private Configuration configuration;
@Context
private HttpServletRequest request;
@Context
private HttpServletResponse response;
@Context
private Application application;
@Context
private UriInfo uriInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
/*
* Please note that we CANNOT inject JaxRsContextProducer here, because this will
* fail on TomEE/CXF/OWB because processing @Context fails for some reason.
*/ | // Path: core/src/main/java/org/mvcspec/ozark/util/CdiUtils.java
// @ApplicationScoped
// @SuppressWarnings("unchecked")
// public class CdiUtils {
//
// @Inject
// private BeanManager beanManager;
//
// /**
// * Create a new CDI bean given its class. The bean is created in the context
// * defined by the scope annotation on the class.
// *
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// @SuppressWarnings("unchecked")
// public <T> T newBean(Class<T> clazz) {
// return newBean(beanManager, clazz);
// }
//
// /**
// * Create a new CDI bean given its class and a bean manager. The bean is created
// * in the context defined by the scope annotation on the class.
// *
// * @param bm The BeanManager.
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// public static <T> T newBean(BeanManager bm, Class<T> clazz) {
// Set<Bean<?>> beans = bm.getBeans(clazz);
// final Bean<T> bean = (Bean<T>) bm.resolve(beans);
// final CreationalContext<T> ctx = bm.createCreationalContext(bean);
// return (T) bm.getReference(bean, clazz, ctx);
// }
//
// /**
// * @param beforeBean The BeforeBeanDiscovery.
// * @param bm The BeanManager.
// * @param types annotated types to register
// */
// public static void addAnnotatedTypes(BeforeBeanDiscovery beforeBean, BeanManager bm, Class<?>... types) {
// for (Class<?> type : types) {
// beforeBean.addAnnotatedType(bm.createAnnotatedType(type), type.getName());
// }
// }
//
// /**
// * Returns a list of CDI beans with the specified bean type and qualifiers.
// * Please note that this method supports looking up beans deployed with the application
// * even if Ozark is deployed as a container archive.
// */
// public static <T> List<T> getApplicationBeans(Class<T> type, Annotation... qualifiers) {
// BeanManager manager = getApplicationBeanManager();
// return manager.getBeans(type, qualifiers).stream()
// .map(bean -> (T) manager.getReference(bean, type, manager.createCreationalContext(bean)))
// .collect(Collectors.toList());
// }
//
// /**
// * Returns a single CDI bean with the given type and qualifiers. Will throw an exception if there
// * is more than one matching bean. Please note that this method supports looking up beans deployed
// * with the application even if Ozark is deployed as a container archive.
// */
// public static <T> Optional<T> getApplicationBean(Class<T> type, Annotation... qualifiers) {
// List<T> instances = getApplicationBeans(type);
// if (instances.size() == 0) {
// return Optional.empty();
// } else if (instances.size() == 1) {
// return Optional.of(instances.get(0));
// } else {
// throw new IllegalStateException("More than one CDI managed instance found of: " + type.getName());
// }
// }
//
// /**
// * This method returns a {@link BeanManager} which can resolve beans defined in the application.
// * In case of Glassfish the injected {@link BeanManager} doesn't work here as it only resolves
// * beans in the Ozark archive if Ozark is installed as part of the container.
// */
// public static BeanManager getApplicationBeanManager() {
// return CDI.current().getBeanManager();
// }
//
// }
// Path: core/src/main/java/org/mvcspec/ozark/jaxrs/JaxRsContextFilter.java
import org.mvcspec.ozark.util.CdiUtils;
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.jaxrs;
/**
* This filter is used to get the JAX-RS context objects and feed them to the corresponding
* CDI producer.
* <p>
* This class must not be a CDI bean, because CXF/OWB fails to process <code>@Context</code> in this case.
*
* @author Christian Kaltepoth
*/
@PreMatching
@Priority(0) // very early
public class JaxRsContextFilter implements ContainerRequestFilter {
@Context
private Configuration configuration;
@Context
private HttpServletRequest request;
@Context
private HttpServletResponse response;
@Context
private Application application;
@Context
private UriInfo uriInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
/*
* Please note that we CANNOT inject JaxRsContextProducer here, because this will
* fail on TomEE/CXF/OWB because processing @Context fails for some reason.
*/ | CdiUtils.getApplicationBean(JaxRsContextProducer.class) |
mvc-spec/ozark | ext/jtwig/src/main/java/org/mvcspec/ozark/ext/jtwig/JtwigViewEngine.java | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
| import org.mvcspec.ozark.engine.ViewEngineBase;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jtwig.web.servlet.JtwigRenderer; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.jtwig;
/**
* @author Daniel Dias
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
// Path: ext/jtwig/src/main/java/org/mvcspec/ozark/ext/jtwig/JtwigViewEngine.java
import org.mvcspec.ozark.engine.ViewEngineBase;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jtwig.web.servlet.JtwigRenderer;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.jtwig;
/**
* @author Daniel Dias
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | public class JtwigViewEngine extends ViewEngineBase { |
mvc-spec/ozark | ext/jetbrick/src/main/java/org/mvcspec/ozark/ext/jetbrick/JetbrickViewEngine.java | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
| import jetbrick.template.JetEngine;
import jetbrick.template.JetTemplate;
import jetbrick.template.TemplateException;
import jetbrick.template.web.JetWebEngine;
import org.mvcspec.ozark.engine.ViewEngineBase;
import javax.annotation.PostConstruct;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.jetbrick;
/**
* @author Daniel Dias
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
// Path: ext/jetbrick/src/main/java/org/mvcspec/ozark/ext/jetbrick/JetbrickViewEngine.java
import jetbrick.template.JetEngine;
import jetbrick.template.JetTemplate;
import jetbrick.template.TemplateException;
import jetbrick.template.web.JetWebEngine;
import org.mvcspec.ozark.engine.ViewEngineBase;
import javax.annotation.PostConstruct;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.jetbrick;
/**
* @author Daniel Dias
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | public class JetbrickViewEngine extends ViewEngineBase { |
mvc-spec/ozark | ext/freemarker/src/main/java/org/mvcspec/ozark/ext/freemarker/FreemarkerViewEngine.java | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
| import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.mvcspec.ozark.engine.ViewEngineBase;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStreamWriter; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.freemarker;
/**
* Class FreemarkerViewEngine.
*
* @author Santiago Pericas-Geertsen
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
// Path: ext/freemarker/src/main/java/org/mvcspec/ozark/ext/freemarker/FreemarkerViewEngine.java
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.mvcspec.ozark.engine.ViewEngineBase;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStreamWriter;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.freemarker;
/**
* Class FreemarkerViewEngine.
*
* @author Santiago Pericas-Geertsen
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | public class FreemarkerViewEngine extends ViewEngineBase { |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/engine/ViewEngineFinder.java | // Path: core/src/main/java/org/mvcspec/ozark/util/CdiUtils.java
// @ApplicationScoped
// @SuppressWarnings("unchecked")
// public class CdiUtils {
//
// @Inject
// private BeanManager beanManager;
//
// /**
// * Create a new CDI bean given its class. The bean is created in the context
// * defined by the scope annotation on the class.
// *
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// @SuppressWarnings("unchecked")
// public <T> T newBean(Class<T> clazz) {
// return newBean(beanManager, clazz);
// }
//
// /**
// * Create a new CDI bean given its class and a bean manager. The bean is created
// * in the context defined by the scope annotation on the class.
// *
// * @param bm The BeanManager.
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// public static <T> T newBean(BeanManager bm, Class<T> clazz) {
// Set<Bean<?>> beans = bm.getBeans(clazz);
// final Bean<T> bean = (Bean<T>) bm.resolve(beans);
// final CreationalContext<T> ctx = bm.createCreationalContext(bean);
// return (T) bm.getReference(bean, clazz, ctx);
// }
//
// /**
// * @param beforeBean The BeforeBeanDiscovery.
// * @param bm The BeanManager.
// * @param types annotated types to register
// */
// public static void addAnnotatedTypes(BeforeBeanDiscovery beforeBean, BeanManager bm, Class<?>... types) {
// for (Class<?> type : types) {
// beforeBean.addAnnotatedType(bm.createAnnotatedType(type), type.getName());
// }
// }
//
// /**
// * Returns a list of CDI beans with the specified bean type and qualifiers.
// * Please note that this method supports looking up beans deployed with the application
// * even if Ozark is deployed as a container archive.
// */
// public static <T> List<T> getApplicationBeans(Class<T> type, Annotation... qualifiers) {
// BeanManager manager = getApplicationBeanManager();
// return manager.getBeans(type, qualifiers).stream()
// .map(bean -> (T) manager.getReference(bean, type, manager.createCreationalContext(bean)))
// .collect(Collectors.toList());
// }
//
// /**
// * Returns a single CDI bean with the given type and qualifiers. Will throw an exception if there
// * is more than one matching bean. Please note that this method supports looking up beans deployed
// * with the application even if Ozark is deployed as a container archive.
// */
// public static <T> Optional<T> getApplicationBean(Class<T> type, Annotation... qualifiers) {
// List<T> instances = getApplicationBeans(type);
// if (instances.size() == 0) {
// return Optional.empty();
// } else if (instances.size() == 1) {
// return Optional.of(instances.get(0));
// } else {
// throw new IllegalStateException("More than one CDI managed instance found of: " + type.getName());
// }
// }
//
// /**
// * This method returns a {@link BeanManager} which can resolve beans defined in the application.
// * In case of Glassfish the injected {@link BeanManager} doesn't work here as it only resolves
// * beans in the Ozark archive if Ozark is installed as part of the container.
// */
// public static BeanManager getApplicationBeanManager() {
// return CDI.current().getBeanManager();
// }
//
// }
//
// Path: core/src/main/java/org/mvcspec/ozark/util/AnnotationUtils.java
// public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationType) {
// T an = clazz.getDeclaredAnnotation(annotationType);
// if (an == null && isProxy(clazz)) {
// an = clazz.getSuperclass().getDeclaredAnnotation(annotationType);
// }
// return an;
// }
| import org.mvcspec.ozark.util.CdiUtils;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static java.util.stream.Collectors.toSet;
import static org.mvcspec.ozark.util.AnnotationUtils.getAnnotation; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.engine;
/**
* <p>Selects the view engine for a {@link Viewable}. If the viewable
* includes a reference to an engine, the selection process stops and returns
* it. Otherwise, the method {@link javax.mvc.engine.ViewEngine#supports(String)}
* is called for each of the view engines injectable via CDI (i.e., all classes
* that implement {@link javax.mvc.engine.ViewEngine}).</p>
*
* <p>The resulting set of candidates is sorted based on its priority as
* defined by the annotation {@link javax.annotation.Priority} on the view engine
* implementation.</p>
*
* <p>This class implements a simple cache to avoid repeated look-ups for the same
* view.</p>
*
* @author Santiago Pericas-Geertsen
* @author Eddú Meléndez
*/
@ApplicationScoped
public class ViewEngineFinder {
@Inject | // Path: core/src/main/java/org/mvcspec/ozark/util/CdiUtils.java
// @ApplicationScoped
// @SuppressWarnings("unchecked")
// public class CdiUtils {
//
// @Inject
// private BeanManager beanManager;
//
// /**
// * Create a new CDI bean given its class. The bean is created in the context
// * defined by the scope annotation on the class.
// *
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// @SuppressWarnings("unchecked")
// public <T> T newBean(Class<T> clazz) {
// return newBean(beanManager, clazz);
// }
//
// /**
// * Create a new CDI bean given its class and a bean manager. The bean is created
// * in the context defined by the scope annotation on the class.
// *
// * @param bm The BeanManager.
// * @param clazz CDI class.
// * @param <T> class parameter.
// * @return newly allocated CDI bean.
// */
// public static <T> T newBean(BeanManager bm, Class<T> clazz) {
// Set<Bean<?>> beans = bm.getBeans(clazz);
// final Bean<T> bean = (Bean<T>) bm.resolve(beans);
// final CreationalContext<T> ctx = bm.createCreationalContext(bean);
// return (T) bm.getReference(bean, clazz, ctx);
// }
//
// /**
// * @param beforeBean The BeforeBeanDiscovery.
// * @param bm The BeanManager.
// * @param types annotated types to register
// */
// public static void addAnnotatedTypes(BeforeBeanDiscovery beforeBean, BeanManager bm, Class<?>... types) {
// for (Class<?> type : types) {
// beforeBean.addAnnotatedType(bm.createAnnotatedType(type), type.getName());
// }
// }
//
// /**
// * Returns a list of CDI beans with the specified bean type and qualifiers.
// * Please note that this method supports looking up beans deployed with the application
// * even if Ozark is deployed as a container archive.
// */
// public static <T> List<T> getApplicationBeans(Class<T> type, Annotation... qualifiers) {
// BeanManager manager = getApplicationBeanManager();
// return manager.getBeans(type, qualifiers).stream()
// .map(bean -> (T) manager.getReference(bean, type, manager.createCreationalContext(bean)))
// .collect(Collectors.toList());
// }
//
// /**
// * Returns a single CDI bean with the given type and qualifiers. Will throw an exception if there
// * is more than one matching bean. Please note that this method supports looking up beans deployed
// * with the application even if Ozark is deployed as a container archive.
// */
// public static <T> Optional<T> getApplicationBean(Class<T> type, Annotation... qualifiers) {
// List<T> instances = getApplicationBeans(type);
// if (instances.size() == 0) {
// return Optional.empty();
// } else if (instances.size() == 1) {
// return Optional.of(instances.get(0));
// } else {
// throw new IllegalStateException("More than one CDI managed instance found of: " + type.getName());
// }
// }
//
// /**
// * This method returns a {@link BeanManager} which can resolve beans defined in the application.
// * In case of Glassfish the injected {@link BeanManager} doesn't work here as it only resolves
// * beans in the Ozark archive if Ozark is installed as part of the container.
// */
// public static BeanManager getApplicationBeanManager() {
// return CDI.current().getBeanManager();
// }
//
// }
//
// Path: core/src/main/java/org/mvcspec/ozark/util/AnnotationUtils.java
// public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationType) {
// T an = clazz.getDeclaredAnnotation(annotationType);
// if (an == null && isProxy(clazz)) {
// an = clazz.getSuperclass().getDeclaredAnnotation(annotationType);
// }
// return an;
// }
// Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineFinder.java
import org.mvcspec.ozark.util.CdiUtils;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static java.util.stream.Collectors.toSet;
import static org.mvcspec.ozark.util.AnnotationUtils.getAnnotation;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.engine;
/**
* <p>Selects the view engine for a {@link Viewable}. If the viewable
* includes a reference to an engine, the selection process stops and returns
* it. Otherwise, the method {@link javax.mvc.engine.ViewEngine#supports(String)}
* is called for each of the view engines injectable via CDI (i.e., all classes
* that implement {@link javax.mvc.engine.ViewEngine}).</p>
*
* <p>The resulting set of candidates is sorted based on its priority as
* defined by the annotation {@link javax.annotation.Priority} on the view engine
* implementation.</p>
*
* <p>This class implements a simple cache to avoid repeated look-ups for the same
* view.</p>
*
* @author Santiago Pericas-Geertsen
* @author Eddú Meléndez
*/
@ApplicationScoped
public class ViewEngineFinder {
@Inject | private CdiUtils cdiUtils; |
mvc-spec/ozark | testsuite/src/test/java/org/mvcspec/ozark/test/ThymeleafIT.java | // Path: testsuite/src/test/java/org/mvcspec/ozark/test/util/WebArchiveBuilder.java
// public class WebArchiveBuilder {
//
// private final WebArchive archive = ShrinkWrap.create(WebArchive.class);
// private List<MavenDependency> additionalDependencies = new ArrayList<>();
//
// public WebArchiveBuilder addPackage(String packageName) {
// archive.addPackage(packageName);
// return this;
// }
//
// public WebArchiveBuilder addView(Asset asset, String name) {
// archive.addAsWebInfResource(asset, "views/" + name);
// return this;
// }
//
// public WebArchiveBuilder addView(File file, String name) {
// return this.addView(new FileAsset(file), name);
// }
//
// public WebArchiveBuilder addBeansXml() {
// archive.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
// return this;
// }
//
// public WebArchiveBuilder addDependencies(MavenDependency... dependencies) {
// this.additionalDependencies.addAll(Arrays.asList(dependencies));
// return this;
// }
//
// public WebArchiveBuilder addDependency(String coordinates) {
// addDependencies(MavenDependencies.createDependency(coordinates, ScopeType.RUNTIME,false));
// return this;
// }
//
// public WebArchive build() {
// PomEquippedResolveStage stage = Maven.configureResolver().workOffline()
// .withClassPathResolution(true)
// .loadPomFromFile("pom.xml", System.getProperty("testsuite.profile"))
// .importCompileAndRuntimeDependencies();
//
// if (!this.additionalDependencies.isEmpty()) {
// stage = stage.addDependencies(this.additionalDependencies);
// }
//
// return archive.addAsLibraries(stage.resolve().withTransitivity().asFile());
// }
//
// }
| import java.net.URL;
import java.nio.file.Paths;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.resolver.api.maven.ScopeType;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencies;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mvcspec.ozark.test.util.WebArchiveBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.test;
/**
* @author Gregor Tudan
*/
@RunWith(Arquillian.class)
public class ThymeleafIT {
private static final String WEB_INF_SRC = "src/main/resources/thymeleaf/";
@ArquillianResource
private URL baseURL;
@Drone
private WebDriver webDriver;
@Deployment(testable = false, name = "thymeleaf")
public static Archive createDeployment() { | // Path: testsuite/src/test/java/org/mvcspec/ozark/test/util/WebArchiveBuilder.java
// public class WebArchiveBuilder {
//
// private final WebArchive archive = ShrinkWrap.create(WebArchive.class);
// private List<MavenDependency> additionalDependencies = new ArrayList<>();
//
// public WebArchiveBuilder addPackage(String packageName) {
// archive.addPackage(packageName);
// return this;
// }
//
// public WebArchiveBuilder addView(Asset asset, String name) {
// archive.addAsWebInfResource(asset, "views/" + name);
// return this;
// }
//
// public WebArchiveBuilder addView(File file, String name) {
// return this.addView(new FileAsset(file), name);
// }
//
// public WebArchiveBuilder addBeansXml() {
// archive.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
// return this;
// }
//
// public WebArchiveBuilder addDependencies(MavenDependency... dependencies) {
// this.additionalDependencies.addAll(Arrays.asList(dependencies));
// return this;
// }
//
// public WebArchiveBuilder addDependency(String coordinates) {
// addDependencies(MavenDependencies.createDependency(coordinates, ScopeType.RUNTIME,false));
// return this;
// }
//
// public WebArchive build() {
// PomEquippedResolveStage stage = Maven.configureResolver().workOffline()
// .withClassPathResolution(true)
// .loadPomFromFile("pom.xml", System.getProperty("testsuite.profile"))
// .importCompileAndRuntimeDependencies();
//
// if (!this.additionalDependencies.isEmpty()) {
// stage = stage.addDependencies(this.additionalDependencies);
// }
//
// return archive.addAsLibraries(stage.resolve().withTransitivity().asFile());
// }
//
// }
// Path: testsuite/src/test/java/org/mvcspec/ozark/test/ThymeleafIT.java
import java.net.URL;
import java.nio.file.Paths;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.resolver.api.maven.ScopeType;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencies;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mvcspec.ozark.test.util.WebArchiveBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.test;
/**
* @author Gregor Tudan
*/
@RunWith(Arquillian.class)
public class ThymeleafIT {
private static final String WEB_INF_SRC = "src/main/resources/thymeleaf/";
@ArquillianResource
private URL baseURL;
@Drone
private WebDriver webDriver;
@Deployment(testable = false, name = "thymeleaf")
public static Archive createDeployment() { | return new WebArchiveBuilder() |
mvc-spec/ozark | core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java | // Path: core/src/main/java/org/mvcspec/ozark/util/PathUtils.java
// public final class PathUtils {
//
// /**
// * Drops starting slash from path if present.
// *
// * @param path the path.
// * @return the resulting path without a starting slash.
// */
// public static String noStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return hasStartingSlash(path) ? path.substring(1) : path;
// }
//
// /**
// * Determines of path starts with a slash.
// *
// * @param path the path to test.
// * @return outcome of test.
// */
// public static boolean hasStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return !"".equals(path) && path.charAt(0) == '/';
// }
//
// /**
// * Drops a prefix from a path if it exists or returns original path if prefix does
// * not match.
// *
// * @param path the path.
// * @param prefix the prefix to drop.
// * @return new path without prefix or old path if prefix does not exist.
// */
// public static String noPrefix(String path, String prefix) {
// Objects.requireNonNull(path, "path must not be null");
// Objects.requireNonNull(prefix, "prefix must not be null");
// return path.startsWith(prefix) ? path.substring(prefix.length()) : path;
// }
//
// /**
// * Ensures that a path always starts with a slash.
// *
// * @param path the path.
// * @return path that starts with a slash.
// */
// public static String ensureStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return "".equals(path) || path.charAt(0) != '/' ? ("/" + path) : path;
// }
//
// /**
// * Ensures that a path always ends with a slash.
// *
// * @param path the path.
// * @return path that starts with a slash.
// */
// public static String ensureEndingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return "".equals(path) || path.charAt(path.length() - 1) != '/' ? (path + "/") : path;
// }
//
// /**
// * Ensures that a path does not end with a slash. May return an
// * empty string.
// *
// * @param path the path.
// * @return path not ending with slash or empty string.
// */
// public static String ensureNotEndingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// if ("".equals(path)) {
// return path;
// }
// final int length = path.length();
// return path.charAt(length - 1) == '/' ? path.substring(0, length - 1) : path;
// }
//
// /**
// * Returns a normalized path. If the path is empty or "/*", then an empty string
// * is returned. Otherwise, the path returned always starts with a "/" but does not
// * end with one.
// *
// * @param path the path to normalize.
// * @return normalized path.
// */
// public static String normalizePath(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return path.isEmpty() || path.equals("/*") ? "" : ensureNotEndingSlash(ensureStartingSlash(path));
// }
//
// }
| import org.mvcspec.ozark.util.PathUtils;
import org.mvcspec.ozark.util.PropertyUtils;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.nio.charset.Charset; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.engine;
/**
* Base class for view engines that factors out all common logic.
*
* @author Santiago Pericas-Geertsen
*/
public abstract class ViewEngineBase implements ViewEngine {
/**
* Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
* in the active configuration. If the view is absolute, starts with '/', then
* it is returned unchanged.
*
* @param context view engine context.
* @return resolved view.
*/
protected String resolveView(ViewEngineContext context) {
final String view = context.getView(); | // Path: core/src/main/java/org/mvcspec/ozark/util/PathUtils.java
// public final class PathUtils {
//
// /**
// * Drops starting slash from path if present.
// *
// * @param path the path.
// * @return the resulting path without a starting slash.
// */
// public static String noStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return hasStartingSlash(path) ? path.substring(1) : path;
// }
//
// /**
// * Determines of path starts with a slash.
// *
// * @param path the path to test.
// * @return outcome of test.
// */
// public static boolean hasStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return !"".equals(path) && path.charAt(0) == '/';
// }
//
// /**
// * Drops a prefix from a path if it exists or returns original path if prefix does
// * not match.
// *
// * @param path the path.
// * @param prefix the prefix to drop.
// * @return new path without prefix or old path if prefix does not exist.
// */
// public static String noPrefix(String path, String prefix) {
// Objects.requireNonNull(path, "path must not be null");
// Objects.requireNonNull(prefix, "prefix must not be null");
// return path.startsWith(prefix) ? path.substring(prefix.length()) : path;
// }
//
// /**
// * Ensures that a path always starts with a slash.
// *
// * @param path the path.
// * @return path that starts with a slash.
// */
// public static String ensureStartingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return "".equals(path) || path.charAt(0) != '/' ? ("/" + path) : path;
// }
//
// /**
// * Ensures that a path always ends with a slash.
// *
// * @param path the path.
// * @return path that starts with a slash.
// */
// public static String ensureEndingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return "".equals(path) || path.charAt(path.length() - 1) != '/' ? (path + "/") : path;
// }
//
// /**
// * Ensures that a path does not end with a slash. May return an
// * empty string.
// *
// * @param path the path.
// * @return path not ending with slash or empty string.
// */
// public static String ensureNotEndingSlash(String path) {
// Objects.requireNonNull(path, "path must not be null");
// if ("".equals(path)) {
// return path;
// }
// final int length = path.length();
// return path.charAt(length - 1) == '/' ? path.substring(0, length - 1) : path;
// }
//
// /**
// * Returns a normalized path. If the path is empty or "/*", then an empty string
// * is returned. Otherwise, the path returned always starts with a "/" but does not
// * end with one.
// *
// * @param path the path to normalize.
// * @return normalized path.
// */
// public static String normalizePath(String path) {
// Objects.requireNonNull(path, "path must not be null");
// return path.isEmpty() || path.equals("/*") ? "" : ensureNotEndingSlash(ensureStartingSlash(path));
// }
//
// }
// Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
import org.mvcspec.ozark.util.PathUtils;
import org.mvcspec.ozark.util.PropertyUtils;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.nio.charset.Charset;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.engine;
/**
* Base class for view engines that factors out all common logic.
*
* @author Santiago Pericas-Geertsen
*/
public abstract class ViewEngineBase implements ViewEngine {
/**
* Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
* in the active configuration. If the view is absolute, starts with '/', then
* it is returned unchanged.
*
* @param context view engine context.
* @return resolved view.
*/
protected String resolveView(ViewEngineContext context) {
final String view = context.getView(); | if (!PathUtils.hasStartingSlash(view)) { // Relative? |
mvc-spec/ozark | ext/groovy/src/main/java/org/mvcspec/ozark/ext/groovy/GroovyViewEngine.java | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.codehaus.groovy.control.CompilationFailedException;
import org.mvcspec.ozark.engine.ViewEngineBase;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import groovy.lang.Writable;
import groovy.text.Template;
import groovy.text.markup.MarkupTemplateEngine; | /*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.groovy;
/**
* @author Daniel Dias
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | // Path: core/src/main/java/org/mvcspec/ozark/engine/ViewEngineBase.java
// public abstract class ViewEngineBase implements ViewEngine {
//
// /**
// * Resolves a view path based on {@link javax.mvc.engine.ViewEngine#VIEW_FOLDER}
// * in the active configuration. If the view is absolute, starts with '/', then
// * it is returned unchanged.
// *
// * @param context view engine context.
// * @return resolved view.
// */
// protected String resolveView(ViewEngineContext context) {
// final String view = context.getView();
// if (!PathUtils.hasStartingSlash(view)) { // Relative?
// final String viewFolder = PropertyUtils.getProperty(context.getConfiguration(), VIEW_FOLDER, DEFAULT_VIEW_FOLDER);
// return PathUtils.ensureEndingSlash(viewFolder) + view;
// }
// return view;
// }
//
// /**
// * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8'
// * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct
// * encoding to the response headers. Finally it returns the effective character set so that
// * the view engine implementation can use it write the data correctly to the output stream.
// *
// * @param context The context
// * @return the effective charset
// */
// protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) {
//
// String charset = context.getMediaType().getParameters().get("charset");
// if (charset == null) {
// charset = "UTF-8";
// }
//
// MediaType mediaType = context.getMediaType().withCharset(charset);
//
// context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString());
//
// return Charset.forName(charset);
//
// }
//
//
// }
// Path: ext/groovy/src/main/java/org/mvcspec/ozark/ext/groovy/GroovyViewEngine.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.mvc.engine.ViewEngine;
import javax.mvc.engine.ViewEngineContext;
import javax.mvc.engine.ViewEngineException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.codehaus.groovy.control.CompilationFailedException;
import org.mvcspec.ozark.engine.ViewEngineBase;
import org.mvcspec.ozark.engine.ViewEngineConfig;
import groovy.lang.Writable;
import groovy.text.Template;
import groovy.text.markup.MarkupTemplateEngine;
/*
* Copyright © 2017 Ivar Grimstad ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.ext.groovy;
/**
* @author Daniel Dias
*/
@ApplicationScoped
@Priority(ViewEngine.PRIORITY_FRAMEWORK) | public class GroovyViewEngine extends ViewEngineBase { |
Uphie/ONE-Unofficial | app/src/main/java/studio/uphie/one/ui/personal/PersonalFragment.java | // Path: app/src/main/java/studio/uphie/one/utils/TextToast.java
// public class TextToast {
//
// private static Context context;
//
// public static void init(Context ctx){
// context=ctx;
// }
//
// public static void shortShow(String content){
// if (context==null){
// throw new IllegalStateException("TextToast was not initialized");
// }
// Toast toast= Toast.makeText(context, content, Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
// }
// public static void shortShow(int resId){
// String content=context.getResources().getString(resId);
// if (context==null){
// throw new IllegalStateException("TextToast was not initialized");
// }
// Toast toast= Toast.makeText(context, content, Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
// }
// public static void longShow(String content){
// if (context==null){
// throw new IllegalStateException("TextToast was not initialized");
// }
// Toast toast= Toast.makeText(context, content, Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
// }
// public static void longShow(int resId){
// String content=context.getResources().getString(resId);
// if (context==null){
// throw new IllegalStateException("TextToast was not initialized");
// }
// Toast toast= Toast.makeText(context, content, Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
// }
// }
| import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.umeng.analytics.MobclickAgent;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import studio.uphie.one.R;
import studio.uphie.one.utils.TextToast; | }
@OnClick({R.id.item_about, R.id.item_share_app, R.id.item_feedback, R.id.item_comment})
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.item_about:
intent = new Intent(getActivity(), AboutActivity.class);
startActivity(intent);
break;
case R.id.item_share_app:
intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "我发现一个不错的应用,ONE(非官方版),每天给你一个新心情:)\n Github: https://github.com/Uphie/ONE-Unofficial");
intent.setType("text/plain");
startActivity(intent);
break;
case R.id.item_feedback:
intent = new Intent(getActivity(), FeedbackActivity.class);
startActivity(intent);
break;
case R.id.item_comment:
//跳转到应用商店,官方ONE的详情页
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=one.hh.oneclient"));
//必须先检查是否有应用商店安装,否则可能会崩溃
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
//有应用商店
startActivity(intent);
}else {
//无应用商店 | // Path: app/src/main/java/studio/uphie/one/utils/TextToast.java
// public class TextToast {
//
// private static Context context;
//
// public static void init(Context ctx){
// context=ctx;
// }
//
// public static void shortShow(String content){
// if (context==null){
// throw new IllegalStateException("TextToast was not initialized");
// }
// Toast toast= Toast.makeText(context, content, Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
// }
// public static void shortShow(int resId){
// String content=context.getResources().getString(resId);
// if (context==null){
// throw new IllegalStateException("TextToast was not initialized");
// }
// Toast toast= Toast.makeText(context, content, Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
// }
// public static void longShow(String content){
// if (context==null){
// throw new IllegalStateException("TextToast was not initialized");
// }
// Toast toast= Toast.makeText(context, content, Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
// }
// public static void longShow(int resId){
// String content=context.getResources().getString(resId);
// if (context==null){
// throw new IllegalStateException("TextToast was not initialized");
// }
// Toast toast= Toast.makeText(context, content, Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
// }
// }
// Path: app/src/main/java/studio/uphie/one/ui/personal/PersonalFragment.java
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.umeng.analytics.MobclickAgent;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import studio.uphie.one.R;
import studio.uphie.one.utils.TextToast;
}
@OnClick({R.id.item_about, R.id.item_share_app, R.id.item_feedback, R.id.item_comment})
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.item_about:
intent = new Intent(getActivity(), AboutActivity.class);
startActivity(intent);
break;
case R.id.item_share_app:
intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "我发现一个不错的应用,ONE(非官方版),每天给你一个新心情:)\n Github: https://github.com/Uphie/ONE-Unofficial");
intent.setType("text/plain");
startActivity(intent);
break;
case R.id.item_feedback:
intent = new Intent(getActivity(), FeedbackActivity.class);
startActivity(intent);
break;
case R.id.item_comment:
//跳转到应用商店,官方ONE的详情页
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=one.hh.oneclient"));
//必须先检查是否有应用商店安装,否则可能会崩溃
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
//有应用商店
startActivity(intent);
}else {
//无应用商店 | TextToast.longShow(R.string.non_market_app); |
Uphie/ONE-Unofficial | app/src/main/java/studio/uphie/one/interfaces/IHttp.java | // Path: app/src/main/java/studio/uphie/one/common/HttpData.java
// public class HttpData {
// public String result;
// public String data;
//
// public HttpData(String result, String data) {
// this.result = result == null ? "" : result;
// this.data = data == null ? "" : data;
// }
// }
//
// Path: app/src/main/java/studio/uphie/one/common/HttpError.java
// public class HttpError {
// /**
// * 错误码
// */
// public int statusCode;
// /**
// * 原因
// */
// public String cause;
// /**
// * 返回结果
// */
// public String response;
//
// public HttpError() {
//
// }
//
// public HttpError(int status, String cause, String response) {
// this.statusCode = status;
// this.cause = cause;
// this.response = response;
// }
// }
| import com.loopj.android.http.RequestParams;
import studio.uphie.one.common.HttpData;
import studio.uphie.one.common.HttpError; | package studio.uphie.one.interfaces;
/**
* Created by Uphie on 2015/9/5.
* Email: [email protected]
*/
public interface IHttp {
void getHttpData(String url, RequestParams param,HttpData httpData);
void onDataOk(String url, String data);
| // Path: app/src/main/java/studio/uphie/one/common/HttpData.java
// public class HttpData {
// public String result;
// public String data;
//
// public HttpData(String result, String data) {
// this.result = result == null ? "" : result;
// this.data = data == null ? "" : data;
// }
// }
//
// Path: app/src/main/java/studio/uphie/one/common/HttpError.java
// public class HttpError {
// /**
// * 错误码
// */
// public int statusCode;
// /**
// * 原因
// */
// public String cause;
// /**
// * 返回结果
// */
// public String response;
//
// public HttpError() {
//
// }
//
// public HttpError(int status, String cause, String response) {
// this.statusCode = status;
// this.cause = cause;
// this.response = response;
// }
// }
// Path: app/src/main/java/studio/uphie/one/interfaces/IHttp.java
import com.loopj.android.http.RequestParams;
import studio.uphie.one.common.HttpData;
import studio.uphie.one.common.HttpError;
package studio.uphie.one.interfaces;
/**
* Created by Uphie on 2015/9/5.
* Email: [email protected]
*/
public interface IHttp {
void getHttpData(String url, RequestParams param,HttpData httpData);
void onDataOk(String url, String data);
| void onDataError(String url, HttpError error); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CodingAgreementMeasure.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AgreementMeasure.java
// public abstract class AgreementMeasure
// implements IAgreementMeasure
// {
//
// @Override
// public double calculateAgreement()
// {
// double A_O = calculateObservedAgreement();
// double A_E = calculateExpectedAgreement();
// if (A_E == 0.0) {
// return A_O;
// }
// else if (A_O == 1.0 && A_E == 1.0) {
// throw new InsufficientDataException(
// "Insufficient variation. Most likely, the raters only used a single category which yields an expected agreement of 1.0. In this case, it is not possible to make any statement about the other categories and thus the agreement of the study itself.");
// }
// else {
// return (A_O - A_E) / (1.0 - A_E);
// }
// }
//
// protected abstract double calculateObservedAgreement();
//
// protected double calculateExpectedAgreement()
// {
// return 0.0;
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
| import java.util.Map;
import org.dkpro.statistics.agreement.AgreementMeasure;
import org.dkpro.statistics.agreement.InsufficientDataException; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Abstract base class of agreement measures for {@link ICodingAnnotationStudy}s.
*
* @author Christian M. Meyer
*/
public abstract class CodingAgreementMeasure
extends AgreementMeasure
implements ICodingAgreementMeasure
{
protected ICodingAnnotationStudy study;
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public CodingAgreementMeasure(final ICodingAnnotationStudy study)
{
this.study = study;
}
@Override
public double calculateObservedAgreement()
{
if (study.getCategoryCount() <= 1) { | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AgreementMeasure.java
// public abstract class AgreementMeasure
// implements IAgreementMeasure
// {
//
// @Override
// public double calculateAgreement()
// {
// double A_O = calculateObservedAgreement();
// double A_E = calculateExpectedAgreement();
// if (A_E == 0.0) {
// return A_O;
// }
// else if (A_O == 1.0 && A_E == 1.0) {
// throw new InsufficientDataException(
// "Insufficient variation. Most likely, the raters only used a single category which yields an expected agreement of 1.0. In this case, it is not possible to make any statement about the other categories and thus the agreement of the study itself.");
// }
// else {
// return (A_O - A_E) / (1.0 - A_E);
// }
// }
//
// protected abstract double calculateObservedAgreement();
//
// protected double calculateExpectedAgreement()
// {
// return 0.0;
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CodingAgreementMeasure.java
import java.util.Map;
import org.dkpro.statistics.agreement.AgreementMeasure;
import org.dkpro.statistics.agreement.InsufficientDataException;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Abstract base class of agreement measures for {@link ICodingAnnotationStudy}s.
*
* @author Christian M. Meyer
*/
public abstract class CodingAgreementMeasure
extends AgreementMeasure
implements ICodingAgreementMeasure
{
protected ICodingAnnotationStudy study;
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public CodingAgreementMeasure(final ICodingAnnotationStudy study)
{
this.study = study;
}
@Override
public double calculateObservedAgreement()
{
if (study.getCategoryCount() <= 1) { | throw new InsufficientDataException( |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/ArtsteinPoesio2008Test.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
| import static junit.framework.Assert.assertEquals;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.junit.Test; |
BennettSAgreement s = new BennettSAgreement(study);
assertEquals(0.88, s.calculateObservedAgreement(), 0.001);
assertEquals(0.333, s.calculateExpectedAgreement(), 0.001);
assertEquals(0.82, s.calculateAgreement(), 0.001);
ScottPiAgreement pi = new ScottPiAgreement(study);
assertEquals(0.88, pi.calculateObservedAgreement(), 0.001);
assertEquals(0.401, pi.calculateExpectedAgreement(), 0.001);
assertEquals(0.799, pi.calculateAgreement(), 0.001);
CohenKappaAgreement kappa = new CohenKappaAgreement(study);
assertEquals(0.88, kappa.calculateObservedAgreement(), 0.001);
assertEquals(0.396, kappa.calculateExpectedAgreement(), 0.001);
assertEquals(0.801, kappa.calculateAgreement(), 0.001);
}
/*
* public void testCategoryAgreement() { //TODO positive and negative agreement!
* ICodingAnnotationStudy study = createExample1();
*
* PercentageAgreement cat = new PercentageAgreement(study); assertEquals(0.571,
* cat.calculateCategoryAgreement("STAT"), 0.001); assertEquals(0.769,
* cat.calculateCategoryAgreement("IReq"), 0.001); }
*/
@Test
public void testWeightedAgreement()
{
ICodingAnnotationStudy study = createExample2(); | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/ArtsteinPoesio2008Test.java
import static junit.framework.Assert.assertEquals;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.junit.Test;
BennettSAgreement s = new BennettSAgreement(study);
assertEquals(0.88, s.calculateObservedAgreement(), 0.001);
assertEquals(0.333, s.calculateExpectedAgreement(), 0.001);
assertEquals(0.82, s.calculateAgreement(), 0.001);
ScottPiAgreement pi = new ScottPiAgreement(study);
assertEquals(0.88, pi.calculateObservedAgreement(), 0.001);
assertEquals(0.401, pi.calculateExpectedAgreement(), 0.001);
assertEquals(0.799, pi.calculateAgreement(), 0.001);
CohenKappaAgreement kappa = new CohenKappaAgreement(study);
assertEquals(0.88, kappa.calculateObservedAgreement(), 0.001);
assertEquals(0.396, kappa.calculateExpectedAgreement(), 0.001);
assertEquals(0.801, kappa.calculateAgreement(), 0.001);
}
/*
* public void testCategoryAgreement() { //TODO positive and negative agreement!
* ICodingAnnotationStudy study = createExample1();
*
* PercentageAgreement cat = new PercentageAgreement(study); assertEquals(0.571,
* cat.calculateCategoryAgreement("STAT"), 0.001); assertEquals(0.769,
* cat.calculateCategoryAgreement("IReq"), 0.001); }
*/
@Test
public void testWeightedAgreement()
{
ICodingAnnotationStudy study = createExample2(); | IDistanceFunction weightedDistanceFunction = new IDistanceFunction() |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/ArtsteinPoesio2008Test.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
| import static junit.framework.Assert.assertEquals;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.junit.Test; | assertEquals(0.333, s.calculateExpectedAgreement(), 0.001);
assertEquals(0.82, s.calculateAgreement(), 0.001);
ScottPiAgreement pi = new ScottPiAgreement(study);
assertEquals(0.88, pi.calculateObservedAgreement(), 0.001);
assertEquals(0.401, pi.calculateExpectedAgreement(), 0.001);
assertEquals(0.799, pi.calculateAgreement(), 0.001);
CohenKappaAgreement kappa = new CohenKappaAgreement(study);
assertEquals(0.88, kappa.calculateObservedAgreement(), 0.001);
assertEquals(0.396, kappa.calculateExpectedAgreement(), 0.001);
assertEquals(0.801, kappa.calculateAgreement(), 0.001);
}
/*
* public void testCategoryAgreement() { //TODO positive and negative agreement!
* ICodingAnnotationStudy study = createExample1();
*
* PercentageAgreement cat = new PercentageAgreement(study); assertEquals(0.571,
* cat.calculateCategoryAgreement("STAT"), 0.001); assertEquals(0.769,
* cat.calculateCategoryAgreement("IReq"), 0.001); }
*/
@Test
public void testWeightedAgreement()
{
ICodingAnnotationStudy study = createExample2();
IDistanceFunction weightedDistanceFunction = new IDistanceFunction()
{
@Override | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/ArtsteinPoesio2008Test.java
import static junit.framework.Assert.assertEquals;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.junit.Test;
assertEquals(0.333, s.calculateExpectedAgreement(), 0.001);
assertEquals(0.82, s.calculateAgreement(), 0.001);
ScottPiAgreement pi = new ScottPiAgreement(study);
assertEquals(0.88, pi.calculateObservedAgreement(), 0.001);
assertEquals(0.401, pi.calculateExpectedAgreement(), 0.001);
assertEquals(0.799, pi.calculateAgreement(), 0.001);
CohenKappaAgreement kappa = new CohenKappaAgreement(study);
assertEquals(0.88, kappa.calculateObservedAgreement(), 0.001);
assertEquals(0.396, kappa.calculateExpectedAgreement(), 0.001);
assertEquals(0.801, kappa.calculateAgreement(), 0.001);
}
/*
* public void testCategoryAgreement() { //TODO positive and negative agreement!
* ICodingAnnotationStudy study = createExample1();
*
* PercentageAgreement cat = new PercentageAgreement(study); assertEquals(0.571,
* cat.calculateCategoryAgreement("STAT"), 0.001); assertEquals(0.769,
* cat.calculateCategoryAgreement("IReq"), 0.001); }
*/
@Test
public void testWeightedAgreement()
{
ICodingAnnotationStudy study = createExample2();
IDistanceFunction weightedDistanceFunction = new IDistanceFunction()
{
@Override | public double measureDistance(final IAnnotationStudy study, final Object category1, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/ArtsteinPoesio2008Test.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
| import static junit.framework.Assert.assertEquals;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.junit.Test; | final Object category2)
{
if (category1.equals(category2)) {
return 0.0;
}
if ("Chck".equals(category1) || "Chck".equals(category2)) {
return 0.5;
}
return 1.0;
}
};
// Unweighted coefficients.
PercentageAgreement poa = new PercentageAgreement(study);
assertEquals(0.880, poa.calculateAgreement(), 0.001);
BennettSAgreement s = new BennettSAgreement(study);
assertEquals(0.880, s.calculateObservedAgreement(), 0.001);
assertEquals(0.333, s.calculateExpectedAgreement(), 0.001);
assertEquals(0.820, s.calculateAgreement(), 0.001);
ScottPiAgreement pi = new ScottPiAgreement(study);
assertEquals(0.880, pi.calculateObservedAgreement(), 0.001);
assertEquals(0.4014, pi.calculateExpectedAgreement(), 0.001);
assertEquals(0.7995, pi.calculateAgreement(), 0.001);
CohenKappaAgreement kappa = new CohenKappaAgreement(study);
assertEquals(0.880, kappa.calculateObservedAgreement(), 0.001);
assertEquals(0.396, kappa.calculateExpectedAgreement(), 0.001);
assertEquals(0.8013, kappa.calculateAgreement(), 0.001);
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/ArtsteinPoesio2008Test.java
import static junit.framework.Assert.assertEquals;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.junit.Test;
final Object category2)
{
if (category1.equals(category2)) {
return 0.0;
}
if ("Chck".equals(category1) || "Chck".equals(category2)) {
return 0.5;
}
return 1.0;
}
};
// Unweighted coefficients.
PercentageAgreement poa = new PercentageAgreement(study);
assertEquals(0.880, poa.calculateAgreement(), 0.001);
BennettSAgreement s = new BennettSAgreement(study);
assertEquals(0.880, s.calculateObservedAgreement(), 0.001);
assertEquals(0.333, s.calculateExpectedAgreement(), 0.001);
assertEquals(0.820, s.calculateAgreement(), 0.001);
ScottPiAgreement pi = new ScottPiAgreement(study);
assertEquals(0.880, pi.calculateObservedAgreement(), 0.001);
assertEquals(0.4014, pi.calculateExpectedAgreement(), 0.001);
assertEquals(0.7995, pi.calculateAgreement(), 0.001);
CohenKappaAgreement kappa = new CohenKappaAgreement(study);
assertEquals(0.880, kappa.calculateObservedAgreement(), 0.001);
assertEquals(0.396, kappa.calculateExpectedAgreement(), 0.001);
assertEquals(0.8013, kappa.calculateAgreement(), 0.001);
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, | new NominalDistanceFunction()); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/SetAnnotationsTest.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/MASISetAnnotationDistanceFunction.java
// public class MASISetAnnotationDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, Object category1, Object category2)
// {
// SetAnnotation c1 = (SetAnnotation) category1;
// SetAnnotation c2 = (SetAnnotation) category2;
//
// SetAnnotation delta = new SetAnnotation(c1);
// delta.removeAll(c2);
// boolean c1_subset_c2 = (delta.size() == 0);
// int overlap = c1.size() - delta.size();
// int union = c2.size() + delta.size();
// delta = new SetAnnotation(c2);
// delta.removeAll(c1);
// boolean c2_subset_c1 = (delta.size() == 0);
//
// double jaccard = (union == 0 ? 1.0 : (1.0 - overlap / (double) union));
// if (c1_subset_c2 && c2_subset_c1) {
// return jaccard * 0.0; // identical.
// }
// if (c1_subset_c2 || c2_subset_c1) {
// return jaccard * (1.0 / 3.0); // subsets.
// }
// if (overlap > 0) {
// return jaccard * (2.0 / 3.0); // some intersection.
// }
// else {
// return jaccard * 1.0; // disjoint.
// }
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotationDistanceFunction.java
// public class SetAnnotationDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// SetAnnotation c1 = (SetAnnotation) category1;
// SetAnnotation c2 = (SetAnnotation) category2;
//
// SetAnnotation delta = new SetAnnotation(c1);
// delta.removeAll(c2);
// boolean c1_subset_c2 = (delta.size() == 0);
// int overlap = c1.size() - delta.size();
// delta = new SetAnnotation(c2);
// delta.removeAll(c1);
// boolean c2_subset_c1 = (delta.size() == 0);
//
// if (c1_subset_c2 && c2_subset_c1) {
// return 0.0; // identical.
// }
// if (c1_subset_c2 || c2_subset_c1) {
// return 1.0 / 3.0; // subsets.
// }
// if (overlap > 0) {
// return 2.0 / 3.0; // some intersection.
// }
// else {
// return 1.0; // disjoint.
// }
// }
//
// }
| import org.dkpro.statistics.agreement.distance.MASISetAnnotationDistanceFunction;
import org.dkpro.statistics.agreement.distance.SetAnnotation;
import org.dkpro.statistics.agreement.distance.SetAnnotationDistanceFunction;
import junit.framework.TestCase; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests for {@link KrippendorffAlphaAgreement} with {@link SetAnnotationDistanceFunction} and
* {@link MASISetAnnotationDistanceFunction}.
*
* @author Christian M. Meyer
* @author Tristan Miller
*/
public class SetAnnotationsTest
extends TestCase
{
public void testSetDistanceFunction()
{
ICodingAnnotationStudy study = createExample();
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, null); | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/MASISetAnnotationDistanceFunction.java
// public class MASISetAnnotationDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, Object category1, Object category2)
// {
// SetAnnotation c1 = (SetAnnotation) category1;
// SetAnnotation c2 = (SetAnnotation) category2;
//
// SetAnnotation delta = new SetAnnotation(c1);
// delta.removeAll(c2);
// boolean c1_subset_c2 = (delta.size() == 0);
// int overlap = c1.size() - delta.size();
// int union = c2.size() + delta.size();
// delta = new SetAnnotation(c2);
// delta.removeAll(c1);
// boolean c2_subset_c1 = (delta.size() == 0);
//
// double jaccard = (union == 0 ? 1.0 : (1.0 - overlap / (double) union));
// if (c1_subset_c2 && c2_subset_c1) {
// return jaccard * 0.0; // identical.
// }
// if (c1_subset_c2 || c2_subset_c1) {
// return jaccard * (1.0 / 3.0); // subsets.
// }
// if (overlap > 0) {
// return jaccard * (2.0 / 3.0); // some intersection.
// }
// else {
// return jaccard * 1.0; // disjoint.
// }
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotationDistanceFunction.java
// public class SetAnnotationDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// SetAnnotation c1 = (SetAnnotation) category1;
// SetAnnotation c2 = (SetAnnotation) category2;
//
// SetAnnotation delta = new SetAnnotation(c1);
// delta.removeAll(c2);
// boolean c1_subset_c2 = (delta.size() == 0);
// int overlap = c1.size() - delta.size();
// delta = new SetAnnotation(c2);
// delta.removeAll(c1);
// boolean c2_subset_c1 = (delta.size() == 0);
//
// if (c1_subset_c2 && c2_subset_c1) {
// return 0.0; // identical.
// }
// if (c1_subset_c2 || c2_subset_c1) {
// return 1.0 / 3.0; // subsets.
// }
// if (overlap > 0) {
// return 2.0 / 3.0; // some intersection.
// }
// else {
// return 1.0; // disjoint.
// }
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/SetAnnotationsTest.java
import org.dkpro.statistics.agreement.distance.MASISetAnnotationDistanceFunction;
import org.dkpro.statistics.agreement.distance.SetAnnotation;
import org.dkpro.statistics.agreement.distance.SetAnnotationDistanceFunction;
import junit.framework.TestCase;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests for {@link KrippendorffAlphaAgreement} with {@link SetAnnotationDistanceFunction} and
* {@link MASISetAnnotationDistanceFunction}.
*
* @author Christian M. Meyer
* @author Tristan Miller
*/
public class SetAnnotationsTest
extends TestCase
{
public void testSetDistanceFunction()
{
ICodingAnnotationStudy study = createExample();
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, null); | alpha.setDistanceFunction(new SetAnnotationDistanceFunction()); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/SetAnnotationsTest.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/MASISetAnnotationDistanceFunction.java
// public class MASISetAnnotationDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, Object category1, Object category2)
// {
// SetAnnotation c1 = (SetAnnotation) category1;
// SetAnnotation c2 = (SetAnnotation) category2;
//
// SetAnnotation delta = new SetAnnotation(c1);
// delta.removeAll(c2);
// boolean c1_subset_c2 = (delta.size() == 0);
// int overlap = c1.size() - delta.size();
// int union = c2.size() + delta.size();
// delta = new SetAnnotation(c2);
// delta.removeAll(c1);
// boolean c2_subset_c1 = (delta.size() == 0);
//
// double jaccard = (union == 0 ? 1.0 : (1.0 - overlap / (double) union));
// if (c1_subset_c2 && c2_subset_c1) {
// return jaccard * 0.0; // identical.
// }
// if (c1_subset_c2 || c2_subset_c1) {
// return jaccard * (1.0 / 3.0); // subsets.
// }
// if (overlap > 0) {
// return jaccard * (2.0 / 3.0); // some intersection.
// }
// else {
// return jaccard * 1.0; // disjoint.
// }
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotationDistanceFunction.java
// public class SetAnnotationDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// SetAnnotation c1 = (SetAnnotation) category1;
// SetAnnotation c2 = (SetAnnotation) category2;
//
// SetAnnotation delta = new SetAnnotation(c1);
// delta.removeAll(c2);
// boolean c1_subset_c2 = (delta.size() == 0);
// int overlap = c1.size() - delta.size();
// delta = new SetAnnotation(c2);
// delta.removeAll(c1);
// boolean c2_subset_c1 = (delta.size() == 0);
//
// if (c1_subset_c2 && c2_subset_c1) {
// return 0.0; // identical.
// }
// if (c1_subset_c2 || c2_subset_c1) {
// return 1.0 / 3.0; // subsets.
// }
// if (overlap > 0) {
// return 2.0 / 3.0; // some intersection.
// }
// else {
// return 1.0; // disjoint.
// }
// }
//
// }
| import org.dkpro.statistics.agreement.distance.MASISetAnnotationDistanceFunction;
import org.dkpro.statistics.agreement.distance.SetAnnotation;
import org.dkpro.statistics.agreement.distance.SetAnnotationDistanceFunction;
import junit.framework.TestCase; | public void testPercentageAgreement()
{
ICodingAnnotationStudy study = createExample();
PercentageAgreement percentageAgreement = new PercentageAgreement(study);
assertEquals(0.333, percentageAgreement.calculateAgreement(), 0.001);
}
public void testMaxPercentageAgreement()
{
ICodingAnnotationStudy study = createExample();
MaxPercentageAgreement maxPercentageAgreement = new MaxPercentageAgreement(study);
assertEquals(0.667, maxPercentageAgreement.calculateAgreement(), 0.001);
}
public void testDiceAgreement()
{
ICodingAnnotationStudy study = createExample();
DiceAgreement DiceAgreement = new DiceAgreement(study);
assertEquals(0.5, DiceAgreement.calculateAgreement(), 0.001);
}
/** Creates an example annotation study. */
public ICodingAnnotationStudy createExample()
{
CodingAnnotationStudy study = new CodingAnnotationStudy(2); | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/MASISetAnnotationDistanceFunction.java
// public class MASISetAnnotationDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, Object category1, Object category2)
// {
// SetAnnotation c1 = (SetAnnotation) category1;
// SetAnnotation c2 = (SetAnnotation) category2;
//
// SetAnnotation delta = new SetAnnotation(c1);
// delta.removeAll(c2);
// boolean c1_subset_c2 = (delta.size() == 0);
// int overlap = c1.size() - delta.size();
// int union = c2.size() + delta.size();
// delta = new SetAnnotation(c2);
// delta.removeAll(c1);
// boolean c2_subset_c1 = (delta.size() == 0);
//
// double jaccard = (union == 0 ? 1.0 : (1.0 - overlap / (double) union));
// if (c1_subset_c2 && c2_subset_c1) {
// return jaccard * 0.0; // identical.
// }
// if (c1_subset_c2 || c2_subset_c1) {
// return jaccard * (1.0 / 3.0); // subsets.
// }
// if (overlap > 0) {
// return jaccard * (2.0 / 3.0); // some intersection.
// }
// else {
// return jaccard * 1.0; // disjoint.
// }
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotationDistanceFunction.java
// public class SetAnnotationDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// SetAnnotation c1 = (SetAnnotation) category1;
// SetAnnotation c2 = (SetAnnotation) category2;
//
// SetAnnotation delta = new SetAnnotation(c1);
// delta.removeAll(c2);
// boolean c1_subset_c2 = (delta.size() == 0);
// int overlap = c1.size() - delta.size();
// delta = new SetAnnotation(c2);
// delta.removeAll(c1);
// boolean c2_subset_c1 = (delta.size() == 0);
//
// if (c1_subset_c2 && c2_subset_c1) {
// return 0.0; // identical.
// }
// if (c1_subset_c2 || c2_subset_c1) {
// return 1.0 / 3.0; // subsets.
// }
// if (overlap > 0) {
// return 2.0 / 3.0; // some intersection.
// }
// else {
// return 1.0; // disjoint.
// }
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/SetAnnotationsTest.java
import org.dkpro.statistics.agreement.distance.MASISetAnnotationDistanceFunction;
import org.dkpro.statistics.agreement.distance.SetAnnotation;
import org.dkpro.statistics.agreement.distance.SetAnnotationDistanceFunction;
import junit.framework.TestCase;
public void testPercentageAgreement()
{
ICodingAnnotationStudy study = createExample();
PercentageAgreement percentageAgreement = new PercentageAgreement(study);
assertEquals(0.333, percentageAgreement.calculateAgreement(), 0.001);
}
public void testMaxPercentageAgreement()
{
ICodingAnnotationStudy study = createExample();
MaxPercentageAgreement maxPercentageAgreement = new MaxPercentageAgreement(study);
assertEquals(0.667, maxPercentageAgreement.calculateAgreement(), 0.001);
}
public void testDiceAgreement()
{
ICodingAnnotationStudy study = createExample();
DiceAgreement DiceAgreement = new DiceAgreement(study);
assertEquals(0.5, DiceAgreement.calculateAgreement(), 0.001);
}
/** Creates an example annotation study. */
public ICodingAnnotationStudy createExample()
{
CodingAnnotationStudy study = new CodingAnnotationStudy(2); | study.addItem(new SetAnnotation(), new SetAnnotation()); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/MaxPercentageAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
| import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.distance.SetAnnotation; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a simple "max" percentage agreement measure for calculating the inter-rater
* agreement for two or more raters applying set-valued annotations. The measure is neither
* chance-corrected nor weighted.<br>
* <br>
* References:
* <ul>
* <li>Jean Véronis. A study of polysemy judgements and inter-annotator agreement. In
* <em>Proceedings of SENSEVAL-1</em>, 1998.</li>
* </ul>
*
* @author Tristan Miller
*/
public class MaxPercentageAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement /* , IRaterAgreement */
{
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public MaxPercentageAgreement(final ICodingAnnotationStudy study)
{
super(study);
ensureTwoRaters();
warnIfMissingValues();
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double doCalculateItemAgreement(final ICodingAnnotationItem item)
{ | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/MaxPercentageAgreement.java
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.distance.SetAnnotation;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a simple "max" percentage agreement measure for calculating the inter-rater
* agreement for two or more raters applying set-valued annotations. The measure is neither
* chance-corrected nor weighted.<br>
* <br>
* References:
* <ul>
* <li>Jean Véronis. A study of polysemy judgements and inter-annotator agreement. In
* <em>Proceedings of SENSEVAL-1</em>, 1998.</li>
* </ul>
*
* @author Tristan Miller
*/
public class MaxPercentageAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement /* , IRaterAgreement */
{
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public MaxPercentageAgreement(final ICodingAnnotationStudy study)
{
super(study);
ensureTwoRaters();
warnIfMissingValues();
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double doCalculateItemAgreement(final ICodingAnnotationItem item)
{ | SetAnnotation setAnnotation = null; |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/MaxPercentageAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
| import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.distance.SetAnnotation; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a simple "max" percentage agreement measure for calculating the inter-rater
* agreement for two or more raters applying set-valued annotations. The measure is neither
* chance-corrected nor weighted.<br>
* <br>
* References:
* <ul>
* <li>Jean Véronis. A study of polysemy judgements and inter-annotator agreement. In
* <em>Proceedings of SENSEVAL-1</em>, 1998.</li>
* </ul>
*
* @author Tristan Miller
*/
public class MaxPercentageAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement /* , IRaterAgreement */
{
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public MaxPercentageAgreement(final ICodingAnnotationStudy study)
{
super(study);
ensureTwoRaters();
warnIfMissingValues();
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double doCalculateItemAgreement(final ICodingAnnotationItem item)
{
SetAnnotation setAnnotation = null; | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/MaxPercentageAgreement.java
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.distance.SetAnnotation;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a simple "max" percentage agreement measure for calculating the inter-rater
* agreement for two or more raters applying set-valued annotations. The measure is neither
* chance-corrected nor weighted.<br>
* <br>
* References:
* <ul>
* <li>Jean Véronis. A study of polysemy judgements and inter-annotator agreement. In
* <em>Proceedings of SENSEVAL-1</em>, 1998.</li>
* </ul>
*
* @author Tristan Miller
*/
public class MaxPercentageAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement /* , IRaterAgreement */
{
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public MaxPercentageAgreement(final ICodingAnnotationStudy study)
{
super(study);
ensureTwoRaters();
warnIfMissingValues();
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double doCalculateItemAgreement(final ICodingAnnotationItem item)
{
SetAnnotation setAnnotation = null; | for (IAnnotationUnit annotationUnit : item.getUnits()) { |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/RandolphKappaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
| import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Generalization of Bennett et al.'s (1954) S-measure for calculating a chance-corrected
* inter-rater agreement for multiple raters, which is known as Randolph's (2005) kappa. The measure
* assumes a uniform probability distribution for all raters and categories. It yields thus
* identical results as Bennett's S.<br>
* <br>
* References:
* <ul>
* <li>Bennett, E.M.; Alpert, R. & Goldstein, A.C.: Communications through limited response
* questioning. Public Opinion Quarterly 18(3):303-308, 1954.</li>
* <li>Randolph, J.J.: Free-marginal multirater kappa (multirater kappa_free): An alternative to
* Fleiss' fixed-marginal multirater kappa. In: Proceedings of the 5th Joensuu University Learning
* and Instruction Symposium, 2005.</li>
* <li>Warrens, M.J.: Inequalities between multi-rater kappas. Advances in Data Analysis and
* Classification 4(4):271-286, 2010.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class RandolphKappaAgreement
extends CodingAgreementMeasure | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/RandolphKappaAgreement.java
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Generalization of Bennett et al.'s (1954) S-measure for calculating a chance-corrected
* inter-rater agreement for multiple raters, which is known as Randolph's (2005) kappa. The measure
* assumes a uniform probability distribution for all raters and categories. It yields thus
* identical results as Bennett's S.<br>
* <br>
* References:
* <ul>
* <li>Bennett, E.M.; Alpert, R. & Goldstein, A.C.: Communications through limited response
* questioning. Public Opinion Quarterly 18(3):303-308, 1954.</li>
* <li>Randolph, J.J.: Free-marginal multirater kappa (multirater kappa_free): An alternative to
* Fleiss' fixed-marginal multirater kappa. In: Proceedings of the 5th Joensuu University Learning
* and Instruction Symposium, 2005.</li>
* <li>Warrens, M.J.: Inequalities between multi-rater kappas. Advances in Data Analysis and
* Classification 4(4):271-286, 2010.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class RandolphKappaAgreement
extends CodingAgreementMeasure | implements IChanceCorrectedAgreement |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
| import org.dkpro.statistics.agreement.IAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Implementation of the {@link IDistanceFunction} interface for scoring the distance between
* interval-scaled categories. That is to say, categories represent a numerical value whose
* difference can be measured. A typical example is date as measures, for instance, using the
* Gregorian calendar. We are able to measure the difference between the years 2010 and 2000 and to
* say that the difference equals the difference between he years 1980 and 1970. However, we cannot
* say that 2000 is twice the year 1000, since there is no absolute zero (note that the year 0 is
* arbitrarily defined and that we need to cater for years such as 200 BCE). For natural language
* processing tasks, judging the similarity between two entities on a linear scale of, say, 1 to 6
* is another example for interval-scaled data. Mathematically, the interval scale only allows for
* the equality, comparison, and addition operations, but prohibits multiplication. The distance
* function returns the squared difference between the numerical representation of two categories.
* It thus assumes the categories to be integers or doubles and falls back to a
* {@link NominalDistanceFunction} for other data types.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. Beverly Hills, CA:
* Sage Publications, 1980.</li>
* </ul>
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class IntervalDistanceFunction
implements IDistanceFunction
{
@Override | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
import org.dkpro.statistics.agreement.IAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Implementation of the {@link IDistanceFunction} interface for scoring the distance between
* interval-scaled categories. That is to say, categories represent a numerical value whose
* difference can be measured. A typical example is date as measures, for instance, using the
* Gregorian calendar. We are able to measure the difference between the years 2010 and 2000 and to
* say that the difference equals the difference between he years 1980 and 1970. However, we cannot
* say that 2000 is twice the year 1000, since there is no absolute zero (note that the year 0 is
* arbitrarily defined and that we need to cater for years such as 200 BCE). For natural language
* processing tasks, judging the similarity between two entities on a linear scale of, say, 1 to 6
* is another example for interval-scaled data. Mathematically, the interval scale only allows for
* the equality, comparison, and addition operations, but prohibits multiplication. The distance
* function returns the squared difference between the numerical representation of two categories.
* It thus assumes the categories to be integers or doubles and falls back to a
* {@link NominalDistanceFunction} for other data types.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. Beverly Hills, CA:
* Sage Publications, 1980.</li>
* </ul>
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class IntervalDistanceFunction
implements IDistanceFunction
{
@Override | public double measureDistance(final IAnnotationStudy study, final Object category1, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/WeightedAgreementTest.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// return (((Integer) category1) - ((Integer) category2))
// * (((Integer) category1) - ((Integer) category2));
// }
//
// if (category1 instanceof Double && category2 instanceof Double) {
// return (((Double) category1) - ((Double) category2))
// * (((Double) category1) - ((Double) category2));
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
| import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import junit.framework.TestCase; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests for {@link WeightedKappaAgreement} and {@link KrippendorffAlphaAgreement}.
*
* @author Christian M. Meyer
*/
public class WeightedAgreementTest
extends TestCase
{
public void testDistanceFunction1()
{
ICodingAnnotationStudy study = createExample();
| // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// return (((Integer) category1) - ((Integer) category2))
// * (((Integer) category1) - ((Integer) category2));
// }
//
// if (category1 instanceof Double && category2 instanceof Double) {
// return (((Double) category1) - ((Double) category2))
// * (((Double) category1) - ((Double) category2));
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/WeightedAgreementTest.java
import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import junit.framework.TestCase;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests for {@link WeightedKappaAgreement} and {@link KrippendorffAlphaAgreement}.
*
* @author Christian M. Meyer
*/
public class WeightedAgreementTest
extends TestCase
{
public void testDistanceFunction1()
{
ICodingAnnotationStudy study = createExample();
| IDistanceFunction weightedDistanceFunction = new IDistanceFunction() |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/WeightedAgreementTest.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// return (((Integer) category1) - ((Integer) category2))
// * (((Integer) category1) - ((Integer) category2));
// }
//
// if (category1 instanceof Double && category2 instanceof Double) {
// return (((Double) category1) - ((Double) category2))
// * (((Double) category1) - ((Double) category2));
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
| import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import junit.framework.TestCase; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests for {@link WeightedKappaAgreement} and {@link KrippendorffAlphaAgreement}.
*
* @author Christian M. Meyer
*/
public class WeightedAgreementTest
extends TestCase
{
public void testDistanceFunction1()
{
ICodingAnnotationStudy study = createExample();
IDistanceFunction weightedDistanceFunction = new IDistanceFunction()
{
@Override | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// return (((Integer) category1) - ((Integer) category2))
// * (((Integer) category1) - ((Integer) category2));
// }
//
// if (category1 instanceof Double && category2 instanceof Double) {
// return (((Double) category1) - ((Double) category2))
// * (((Double) category1) - ((Double) category2));
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/WeightedAgreementTest.java
import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import junit.framework.TestCase;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests for {@link WeightedKappaAgreement} and {@link KrippendorffAlphaAgreement}.
*
* @author Christian M. Meyer
*/
public class WeightedAgreementTest
extends TestCase
{
public void testDistanceFunction1()
{
ICodingAnnotationStudy study = createExample();
IDistanceFunction weightedDistanceFunction = new IDistanceFunction()
{
@Override | public double measureDistance(final IAnnotationStudy study, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/WeightedAgreementTest.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// return (((Integer) category1) - ((Integer) category2))
// * (((Integer) category1) - ((Integer) category2));
// }
//
// if (category1 instanceof Double && category2 instanceof Double) {
// return (((Double) category1) - ((Double) category2))
// * (((Double) category1) - ((Double) category2));
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
| import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import junit.framework.TestCase; | {1 / 3.0, 2 / 9.0, 2 / 9.0, 1 / 9.0, 1 / 9.0, 0 / 3.0, 2 / 9.0},
{1 / 3.0, 3 / 3.0, 3 / 3.0, 3 / 3.0, 1 / 6.0, 2 / 9.0, 0 / 3.0}
};
final Hashtable<Object, Integer> idx = new Hashtable<Object, Integer>();
idx.put("", 0);
idx.put("A", 1);
idx.put("B", 2);
idx.put("AB", 3);
idx.put("AC", 4);
idx.put("ABC", 5);
idx.put("C", 6);
return WEIGHTS[idx.get(category1)][idx.get(category2)];
}
};
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, null);
alpha.setDistanceFunction(weightedDistanceFunction);
assertEquals(0.253, alpha.calculateObservedDisagreement(), 0.001);
assertEquals(0.338, alpha.calculateExpectedDisagreement(), 0.001);
assertEquals(0.252, alpha.calculateAgreement(), 0.001);
}
public void testMissingVariance()
{
CodingAnnotationStudy study = new CodingAnnotationStudy(2);
study.addMultipleItems(11, 1, 1);
study.addItem(1, 2);
study.addItem(1, 3);
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// return (((Integer) category1) - ((Integer) category2))
// * (((Integer) category1) - ((Integer) category2));
// }
//
// if (category1 instanceof Double && category2 instanceof Double) {
// return (((Double) category1) - ((Double) category2))
// * (((Double) category1) - ((Double) category2));
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/WeightedAgreementTest.java
import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import junit.framework.TestCase;
{1 / 3.0, 2 / 9.0, 2 / 9.0, 1 / 9.0, 1 / 9.0, 0 / 3.0, 2 / 9.0},
{1 / 3.0, 3 / 3.0, 3 / 3.0, 3 / 3.0, 1 / 6.0, 2 / 9.0, 0 / 3.0}
};
final Hashtable<Object, Integer> idx = new Hashtable<Object, Integer>();
idx.put("", 0);
idx.put("A", 1);
idx.put("B", 2);
idx.put("AB", 3);
idx.put("AC", 4);
idx.put("ABC", 5);
idx.put("C", 6);
return WEIGHTS[idx.get(category1)][idx.get(category2)];
}
};
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, null);
alpha.setDistanceFunction(weightedDistanceFunction);
assertEquals(0.253, alpha.calculateObservedDisagreement(), 0.001);
assertEquals(0.338, alpha.calculateExpectedDisagreement(), 0.001);
assertEquals(0.252, alpha.calculateAgreement(), 0.001);
}
public void testMissingVariance()
{
CodingAnnotationStudy study = new CodingAnnotationStudy(2);
study.addMultipleItems(11, 1, 1);
study.addItem(1, 2);
study.addItem(1, 3);
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, | new NominalDistanceFunction()); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/WeightedAgreementTest.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// return (((Integer) category1) - ((Integer) category2))
// * (((Integer) category1) - ((Integer) category2));
// }
//
// if (category1 instanceof Double && category2 instanceof Double) {
// return (((Double) category1) - ((Double) category2))
// * (((Double) category1) - ((Double) category2));
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
| import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import junit.framework.TestCase; | return WEIGHTS[idx.get(category1)][idx.get(category2)];
}
};
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, null);
alpha.setDistanceFunction(weightedDistanceFunction);
assertEquals(0.253, alpha.calculateObservedDisagreement(), 0.001);
assertEquals(0.338, alpha.calculateExpectedDisagreement(), 0.001);
assertEquals(0.252, alpha.calculateAgreement(), 0.001);
}
public void testMissingVariance()
{
CodingAnnotationStudy study = new CodingAnnotationStudy(2);
study.addMultipleItems(11, 1, 1);
study.addItem(1, 2);
study.addItem(1, 3);
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
new NominalDistanceFunction());
assertEquals(0.153, alpha.calculateObservedDisagreement(), 0.001);
assertEquals(0.150, alpha.calculateExpectedDisagreement(), 0.001);
assertEquals(-0.020, alpha.calculateAgreement(), 0.001);
WeightedKappaAgreement kappaW = new WeightedKappaAgreement(study,
new NominalDistanceFunction());
assertEquals(0.153, kappaW.calculateObservedDisagreement(), 0.001);
assertEquals(0.153, kappaW.calculateExpectedDisagreement(), 0.001);
assertEquals(0.000, kappaW.calculateAgreement(), 0.001);
| // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// return (((Integer) category1) - ((Integer) category2))
// * (((Integer) category1) - ((Integer) category2));
// }
//
// if (category1 instanceof Double && category2 instanceof Double) {
// return (((Double) category1) - ((Double) category2))
// * (((Double) category1) - ((Double) category2));
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
//
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/WeightedAgreementTest.java
import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import junit.framework.TestCase;
return WEIGHTS[idx.get(category1)][idx.get(category2)];
}
};
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, null);
alpha.setDistanceFunction(weightedDistanceFunction);
assertEquals(0.253, alpha.calculateObservedDisagreement(), 0.001);
assertEquals(0.338, alpha.calculateExpectedDisagreement(), 0.001);
assertEquals(0.252, alpha.calculateAgreement(), 0.001);
}
public void testMissingVariance()
{
CodingAnnotationStudy study = new CodingAnnotationStudy(2);
study.addMultipleItems(11, 1, 1);
study.addItem(1, 2);
study.addItem(1, 3);
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
new NominalDistanceFunction());
assertEquals(0.153, alpha.calculateObservedDisagreement(), 0.001);
assertEquals(0.150, alpha.calculateExpectedDisagreement(), 0.001);
assertEquals(-0.020, alpha.calculateAgreement(), 0.001);
WeightedKappaAgreement kappaW = new WeightedKappaAgreement(study,
new NominalDistanceFunction());
assertEquals(0.153, kappaW.calculateObservedDisagreement(), 0.001);
assertEquals(0.153, kappaW.calculateExpectedDisagreement(), 0.001);
assertEquals(0.000, kappaW.calculateAgreement(), 0.001);
| kappaW = new WeightedKappaAgreement(study, new IntervalDistanceFunction()); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IWeightedAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import org.dkpro.statistics.agreement.distance.IDistanceFunction; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement;
/**
* Interface for all weighted inter-rater agreement measures. A weighted measure makes use of a
* user-defined {@link IDistanceFunction}, which is used to score the degree of disagreement between
* two categories. See Javadoc of {@link IDistanceFunction} for more information on weighted
* agreement measures.
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public interface IWeightedAgreement
{
/**
* Returns the distance function that is used to measure the distance between two annotation
* categories.
*/ | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IWeightedAgreement.java
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement;
/**
* Interface for all weighted inter-rater agreement measures. A weighted measure makes use of a
* user-defined {@link IDistanceFunction}, which is used to score the degree of disagreement between
* two categories. See Javadoc of {@link IDistanceFunction} for more information on weighted
* agreement measures.
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public interface IWeightedAgreement
{
/**
* Returns the distance function that is used to measure the distance between two annotation
* categories.
*/ | public IDistanceFunction getDistanceFunction(); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/WeightedAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/DisagreementMeasure.java
// public abstract class DisagreementMeasure
// implements IAgreementMeasure
// {
// /**
// * Calculates the inter-rater agreement for the annotation study that was passed to the class
// * constructor and the currently assigned distance function.
// *
// * @throws NullPointerException if the study is null.
// *
// * @throws ArithmeticException if the study does not contain any item or the number of raters is
// * smaller than 2.
// */
// @Override
// public double calculateAgreement()
// {
// double D_O = calculateObservedDisagreement();
// double D_E = calculateExpectedDisagreement();
// if (D_O == D_E) {
// return 0.0;
// }
// else {
// return 1.0 - (D_O / D_E);
// }
// }
//
// protected abstract double calculateObservedDisagreement();
//
// protected double calculateExpectedDisagreement()
// {
// return 0.0;
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IWeightedAgreement.java
// public interface IWeightedAgreement
// {
// /**
// * Returns the distance function that is used to measure the distance between two annotation
// * categories.
// */
// public IDistanceFunction getDistanceFunction();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import org.dkpro.statistics.agreement.DisagreementMeasure;
import org.dkpro.statistics.agreement.IWeightedAgreement;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Abstract base class for weighted measures. In most cases, weighted measures are defined as
* disagreement functions. They are characterized by a distance function that is used to score the
* similarity between two categories.
*
* @see IDistanceFunction
* @see DisagreementMeasure
* @author Christian M. Meyer
*/
public abstract class WeightedAgreement
extends DisagreementMeasure | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/DisagreementMeasure.java
// public abstract class DisagreementMeasure
// implements IAgreementMeasure
// {
// /**
// * Calculates the inter-rater agreement for the annotation study that was passed to the class
// * constructor and the currently assigned distance function.
// *
// * @throws NullPointerException if the study is null.
// *
// * @throws ArithmeticException if the study does not contain any item or the number of raters is
// * smaller than 2.
// */
// @Override
// public double calculateAgreement()
// {
// double D_O = calculateObservedDisagreement();
// double D_E = calculateExpectedDisagreement();
// if (D_O == D_E) {
// return 0.0;
// }
// else {
// return 1.0 - (D_O / D_E);
// }
// }
//
// protected abstract double calculateObservedDisagreement();
//
// protected double calculateExpectedDisagreement()
// {
// return 0.0;
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IWeightedAgreement.java
// public interface IWeightedAgreement
// {
// /**
// * Returns the distance function that is used to measure the distance between two annotation
// * categories.
// */
// public IDistanceFunction getDistanceFunction();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/WeightedAgreement.java
import org.dkpro.statistics.agreement.DisagreementMeasure;
import org.dkpro.statistics.agreement.IWeightedAgreement;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Abstract base class for weighted measures. In most cases, weighted measures are defined as
* disagreement functions. They are characterized by a distance function that is used to score the
* similarity between two categories.
*
* @see IDistanceFunction
* @see DisagreementMeasure
* @author Christian M. Meyer
*/
public abstract class WeightedAgreement
extends DisagreementMeasure | implements IWeightedAgreement |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/WeightedAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/DisagreementMeasure.java
// public abstract class DisagreementMeasure
// implements IAgreementMeasure
// {
// /**
// * Calculates the inter-rater agreement for the annotation study that was passed to the class
// * constructor and the currently assigned distance function.
// *
// * @throws NullPointerException if the study is null.
// *
// * @throws ArithmeticException if the study does not contain any item or the number of raters is
// * smaller than 2.
// */
// @Override
// public double calculateAgreement()
// {
// double D_O = calculateObservedDisagreement();
// double D_E = calculateExpectedDisagreement();
// if (D_O == D_E) {
// return 0.0;
// }
// else {
// return 1.0 - (D_O / D_E);
// }
// }
//
// protected abstract double calculateObservedDisagreement();
//
// protected double calculateExpectedDisagreement()
// {
// return 0.0;
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IWeightedAgreement.java
// public interface IWeightedAgreement
// {
// /**
// * Returns the distance function that is used to measure the distance between two annotation
// * categories.
// */
// public IDistanceFunction getDistanceFunction();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import org.dkpro.statistics.agreement.DisagreementMeasure;
import org.dkpro.statistics.agreement.IWeightedAgreement;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Abstract base class for weighted measures. In most cases, weighted measures are defined as
* disagreement functions. They are characterized by a distance function that is used to score the
* similarity between two categories.
*
* @see IDistanceFunction
* @see DisagreementMeasure
* @author Christian M. Meyer
*/
public abstract class WeightedAgreement
extends DisagreementMeasure
implements IWeightedAgreement
{
| // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/DisagreementMeasure.java
// public abstract class DisagreementMeasure
// implements IAgreementMeasure
// {
// /**
// * Calculates the inter-rater agreement for the annotation study that was passed to the class
// * constructor and the currently assigned distance function.
// *
// * @throws NullPointerException if the study is null.
// *
// * @throws ArithmeticException if the study does not contain any item or the number of raters is
// * smaller than 2.
// */
// @Override
// public double calculateAgreement()
// {
// double D_O = calculateObservedDisagreement();
// double D_E = calculateExpectedDisagreement();
// if (D_O == D_E) {
// return 0.0;
// }
// else {
// return 1.0 - (D_O / D_E);
// }
// }
//
// protected abstract double calculateObservedDisagreement();
//
// protected double calculateExpectedDisagreement()
// {
// return 0.0;
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IWeightedAgreement.java
// public interface IWeightedAgreement
// {
// /**
// * Returns the distance function that is used to measure the distance between two annotation
// * categories.
// */
// public IDistanceFunction getDistanceFunction();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/WeightedAgreement.java
import org.dkpro.statistics.agreement.DisagreementMeasure;
import org.dkpro.statistics.agreement.IWeightedAgreement;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Abstract base class for weighted measures. In most cases, weighted measures are defined as
* disagreement functions. They are characterized by a distance function that is used to score the
* similarity between two categories.
*
* @see IDistanceFunction
* @see DisagreementMeasure
* @author Christian M. Meyer
*/
public abstract class WeightedAgreement
extends DisagreementMeasure
implements IWeightedAgreement
{
| protected IDistanceFunction distanceFunction; |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/DiceAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
| import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.distance.SetAnnotation; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a mean Dice agreement measure for calculating the inter-rater agreement for two
* or more raters applying set-valued annotations. The measure is neither chance-corrected nor
* weighted.<br>
* <br>
* References:
* <ul>
* <li>Lee R. Dice. Measures of the amount of ecologic association between species. <em>Ecology</em>
* 36(3):297–302, 1945.</li>
* <li>Jean Véronis. A study of polysemy judgements and inter-annotator agreement. In
* <em>Proceedings of SENSEVAL-1</em>, 1998.</li>
* </ul>
*
* @author Tristan Miller
*/
public class DiceAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement /* , IRaterAgreement */
{
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public DiceAgreement(final ICodingAnnotationStudy study)
{
super(study);
ensureTwoRaters();
warnIfMissingValues();
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double doCalculateItemAgreement(final ICodingAnnotationItem item)
{ | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/DiceAgreement.java
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.distance.SetAnnotation;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a mean Dice agreement measure for calculating the inter-rater agreement for two
* or more raters applying set-valued annotations. The measure is neither chance-corrected nor
* weighted.<br>
* <br>
* References:
* <ul>
* <li>Lee R. Dice. Measures of the amount of ecologic association between species. <em>Ecology</em>
* 36(3):297–302, 1945.</li>
* <li>Jean Véronis. A study of polysemy judgements and inter-annotator agreement. In
* <em>Proceedings of SENSEVAL-1</em>, 1998.</li>
* </ul>
*
* @author Tristan Miller
*/
public class DiceAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement /* , IRaterAgreement */
{
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public DiceAgreement(final ICodingAnnotationStudy study)
{
super(study);
ensureTwoRaters();
warnIfMissingValues();
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double doCalculateItemAgreement(final ICodingAnnotationItem item)
{ | SetAnnotation setAnnotation = null; |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/DiceAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
| import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.distance.SetAnnotation; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a mean Dice agreement measure for calculating the inter-rater agreement for two
* or more raters applying set-valued annotations. The measure is neither chance-corrected nor
* weighted.<br>
* <br>
* References:
* <ul>
* <li>Lee R. Dice. Measures of the amount of ecologic association between species. <em>Ecology</em>
* 36(3):297–302, 1945.</li>
* <li>Jean Véronis. A study of polysemy judgements and inter-annotator agreement. In
* <em>Proceedings of SENSEVAL-1</em>, 1998.</li>
* </ul>
*
* @author Tristan Miller
*/
public class DiceAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement /* , IRaterAgreement */
{
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public DiceAgreement(final ICodingAnnotationStudy study)
{
super(study);
ensureTwoRaters();
warnIfMissingValues();
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double doCalculateItemAgreement(final ICodingAnnotationItem item)
{
SetAnnotation setAnnotation = null;
int numberOfCategories = 0; | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotation.java
// public class SetAnnotation
// extends HashSet<Object>
// implements Comparable<SetAnnotation>
// {
// private static final long serialVersionUID = 8656250211589017624L;
//
// /** Instantiates an empty set annotation. */
// public SetAnnotation()
// {
// super();
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Object... values)
// {
// super();
// for (Object value : values) {
// add(value);
// }
// }
//
// /** Instantiates a set annotation with the given values as set elements. */
// public SetAnnotation(Collection<? extends Object> c)
// {
// super(c);
// }
//
// @Override
// public int compareTo(final SetAnnotation that)
// {
// return toString().compareTo(that.toString());
// }
//
// @Override
// public boolean equals(final Object that)
// {
// if (!(that instanceof SetAnnotation)) {
// return false;
// }
// return toString().equals(((SetAnnotation) that).toString());
// }
//
// @Override
// public int hashCode()
// {
// return toString().hashCode();
// }
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder();
// for (Object value : this) {
// result.append(result.length() == 0 ? "" : ", ").append(value);
// }
// return result.toString();
// }
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/DiceAgreement.java
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.distance.SetAnnotation;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a mean Dice agreement measure for calculating the inter-rater agreement for two
* or more raters applying set-valued annotations. The measure is neither chance-corrected nor
* weighted.<br>
* <br>
* References:
* <ul>
* <li>Lee R. Dice. Measures of the amount of ecologic association between species. <em>Ecology</em>
* 36(3):297–302, 1945.</li>
* <li>Jean Véronis. A study of polysemy judgements and inter-annotator agreement. In
* <em>Proceedings of SENSEVAL-1</em>, 1998.</li>
* </ul>
*
* @author Tristan Miller
*/
public class DiceAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement /* , IRaterAgreement */
{
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public DiceAgreement(final ICodingAnnotationStudy study)
{
super(study);
ensureTwoRaters();
warnIfMissingValues();
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double doCalculateItemAgreement(final ICodingAnnotationItem item)
{
SetAnnotation setAnnotation = null;
int numberOfCategories = 0; | for (IAnnotationUnit annotationUnit : item.getUnits()) { |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
| import org.dkpro.statistics.agreement.IAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Implementation of the {@link IDistanceFunction} interface for scoring the distance between
* nominal-scaled categories. That is to say, categories are either equal (distance 0) or unequal
* (distance 1). A typical example for nominal-scaled categories are the part of speech tags NOUN,
* VERB, and ADJECTIVE. Mathematically, the nominal scale only allows for the equality operation,
* but prohibits comparison, addition, and multiplication. The distance function makes no assumption
* regarding the data type and thus allows for strings, enums, integers, etc.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. Beverly Hills, CA:
* Sage Publications, 1980.</li>
* </ul>
*
* @see IDistanceFunction
* @author Kostadin Cholakov
* @author Christian M. Meyer
*/
public class NominalDistanceFunction
implements IDistanceFunction
{
@Override | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
import org.dkpro.statistics.agreement.IAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Implementation of the {@link IDistanceFunction} interface for scoring the distance between
* nominal-scaled categories. That is to say, categories are either equal (distance 0) or unequal
* (distance 1). A typical example for nominal-scaled categories are the part of speech tags NOUN,
* VERB, and ADJECTIVE. Mathematically, the nominal scale only allows for the equality operation,
* but prohibits comparison, addition, and multiplication. The distance function makes no assumption
* regarding the data type and thus allows for strings, enums, integers, etc.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. Beverly Hills, CA:
* Sage Publications, 1980.</li>
* </ul>
*
* @see IDistanceFunction
* @author Kostadin Cholakov
* @author Christian M. Meyer
*/
public class NominalDistanceFunction
implements IDistanceFunction
{
@Override | public double measureDistance(final IAnnotationStudy study, final Object category1, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/DistanceMatrixPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import java.io.PrintStream;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for distance functions showing the distance scores between each pair of
* categories.
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class DistanceMatrixPrinter
{
/**
* Print a matrix of the distances between each pair of categories.
*/
public void print(final PrintStream out, final Iterable<Object> categories, | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/DistanceMatrixPrinter.java
import java.io.PrintStream;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for distance functions showing the distance scores between each pair of
* categories.
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class DistanceMatrixPrinter
{
/**
* Print a matrix of the distances between each pair of categories.
*/
public void print(final PrintStream out, final Iterable<Object> categories, | final IDistanceFunction distanceFunction) |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/DistanceMatrixPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import java.io.PrintStream;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for distance functions showing the distance scores between each pair of
* categories.
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class DistanceMatrixPrinter
{
/**
* Print a matrix of the distances between each pair of categories.
*/
public void print(final PrintStream out, final Iterable<Object> categories,
final IDistanceFunction distanceFunction)
{
doPrint(out, categories, null, distanceFunction);
}
/**
* Print a matrix representation of the distances between each pair of categories of the given
* study.
*/ | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/DistanceMatrixPrinter.java
import java.io.PrintStream;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for distance functions showing the distance scores between each pair of
* categories.
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class DistanceMatrixPrinter
{
/**
* Print a matrix of the distances between each pair of categories.
*/
public void print(final PrintStream out, final Iterable<Object> categories,
final IDistanceFunction distanceFunction)
{
doPrint(out, categories, null, distanceFunction);
}
/**
* Print a matrix representation of the distances between each pair of categories of the given
* study.
*/ | public void print(final PrintStream out, final ICodingAnnotationStudy study, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
| import org.dkpro.statistics.agreement.IAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Implementation of the {@link IDistanceFunction} interface for scoring the distance between
* ratio-scaled categories. That is to say, categories represent a numerical value whose difference
* and distance to a zero element can be measured. A typical example is measuring the time needed
* for a certain task: it makes a large difference if one accomplishes the task in 1 minute or in 5
* minutes, but there is not much difference between requiring 3 full hours and 3 hours plus 5
* minutes. Mathematically, the ratio scale allows for the equality, comparison, addition, and
* multiplication operations, which is why probabilities and measuring entropy is an often-used
* example for ratio scaled values (cf. Resnik & Lin, 2010). The distance function assumes the
* categories to be integers or doubles and falls back to a {@link NominalDistanceFunction} for
* other data types.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. Beverly Hills, CA:
* Sage Publications, 1980.</li>
* <li>Resnik, P. & Lin, J.: Evaluation of NLP Systems. In: The Handbook of Computational
* Licensesnguistics and Natural Language Processing, p. 271–295, Chichester/Malden:
* Wiley-Blackwell, 2010.</li>
* </ul>
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class RatioDistanceFunction
implements IDistanceFunction
{
@Override | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
import org.dkpro.statistics.agreement.IAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Implementation of the {@link IDistanceFunction} interface for scoring the distance between
* ratio-scaled categories. That is to say, categories represent a numerical value whose difference
* and distance to a zero element can be measured. A typical example is measuring the time needed
* for a certain task: it makes a large difference if one accomplishes the task in 1 minute or in 5
* minutes, but there is not much difference between requiring 3 full hours and 3 hours plus 5
* minutes. Mathematically, the ratio scale allows for the equality, comparison, addition, and
* multiplication operations, which is why probabilities and measuring entropy is an often-used
* example for ratio scaled values (cf. Resnik & Lin, 2010). The distance function assumes the
* categories to be integers or doubles and falls back to a {@link NominalDistanceFunction} for
* other data types.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. Beverly Hills, CA:
* Sage Publications, 1980.</li>
* <li>Resnik, P. & Lin, J.: Evaluation of NLP Systems. In: The Handbook of Computational
* Licensesnguistics and Natural Language Processing, p. 271–295, Chichester/Malden:
* Wiley-Blackwell, 2010.</li>
* </ul>
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class RatioDistanceFunction
implements IDistanceFunction
{
@Override | public double measureDistance(final IAnnotationStudy study, final Object category1, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Fleiss1971Test.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
| import java.util.Iterator;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import junit.framework.TestCase; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests based on Fleiss (1971) for measuring {@link FleissKappaAgreement}.<br>
* <br>
* References:
* <ul>
* <li>Fleiss, J.L.: Measuring nominal scale agreement among many raters. Psychological Bulletin
* 76(5):378-381, 1971.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class Fleiss1971Test
extends TestCase
{
public void testAgreement()
{
ICodingAnnotationStudy study = createExample();
assertEquals(30, study.getItemCount());
FleissKappaAgreement kappa = new FleissKappaAgreement(study);
assertEquals(0.5556, kappa.calculateObservedAgreement(), 0.001);
assertEquals(0.2201, kappa.calculateExpectedAgreement(), 0.001);
double agreement = kappa.calculateAgreement();
assertEquals(0.430, agreement, 0.001);
// Var = 0.000759 = 2/n*m(m-1) * (AE - (2m-3)AE^2 + 2(m-2)AE / (1-AE)^2)
// SE = 0.028
// TODO
/*
* double se = raw.standardError(agreement); double[] ci = raw.confidenceInterval(agreement,
* se, RawAgreement.CONFIDENCE_95); assertEquals(0.028, se, 0.001); assertEquals(0.610,
* ci[0], 0.001); assertEquals(0.789, ci[1], 0.001);
*/
}
public void testCategoryAgreement()
{
ICodingAnnotationStudy study = createExample();
| // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Fleiss1971Test.java
import java.util.Iterator;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import junit.framework.TestCase;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests based on Fleiss (1971) for measuring {@link FleissKappaAgreement}.<br>
* <br>
* References:
* <ul>
* <li>Fleiss, J.L.: Measuring nominal scale agreement among many raters. Psychological Bulletin
* 76(5):378-381, 1971.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class Fleiss1971Test
extends TestCase
{
public void testAgreement()
{
ICodingAnnotationStudy study = createExample();
assertEquals(30, study.getItemCount());
FleissKappaAgreement kappa = new FleissKappaAgreement(study);
assertEquals(0.5556, kappa.calculateObservedAgreement(), 0.001);
assertEquals(0.2201, kappa.calculateExpectedAgreement(), 0.001);
double agreement = kappa.calculateAgreement();
assertEquals(0.430, agreement, 0.001);
// Var = 0.000759 = 2/n*m(m-1) * (AE - (2m-3)AE^2 + 2(m-2)AE / (1-AE)^2)
// SE = 0.028
// TODO
/*
* double se = raw.standardError(agreement); double[] ci = raw.confidenceInterval(agreement,
* se, RawAgreement.CONFIDENCE_95); assertEquals(0.028, se, 0.001); assertEquals(0.610,
* ci[0], 0.001); assertEquals(0.789, ci[1], 0.001);
*/
}
public void testCategoryAgreement()
{
ICodingAnnotationStudy study = createExample();
| ICategorySpecificAgreement catAgreement = new FleissKappaAgreement(study); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/MASISetAnnotationDistanceFunction.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
| import org.dkpro.statistics.agreement.IAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Distance function for set-valued annotation studies based on the definition of Passonneau's
* (2006) MASI (Measuring Agreement on Set-valued Items). The measure is an improved version of
* {@link SetAnnotationDistanceFunction}<br>
* <br>
* References:
* <ul>
* <li>Passonneau, R.J.: Computing reliability for coreference annotation. In: Proceedings of the
* Fourth International Conference on Language Resources and Evaluation, p. 1503–1506, 2004.</li>
* <li>Passonneau, R.: Measuring agreement on set-valued items (MASI) for semantic and pragmatic
* annotation, in: Proceedings of the Fifth International Conference on Language Resources and
* Evaluation, p. 831–836, 2006.</li>
* </ul>
*
* @see IDistanceFunction
* @see SetAnnotation
* @see SetAnnotationDistanceFunction
* @author Christian M. Meyer
*/
public class MASISetAnnotationDistanceFunction
implements IDistanceFunction
{
@Override | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/MASISetAnnotationDistanceFunction.java
import org.dkpro.statistics.agreement.IAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Distance function for set-valued annotation studies based on the definition of Passonneau's
* (2006) MASI (Measuring Agreement on Set-valued Items). The measure is an improved version of
* {@link SetAnnotationDistanceFunction}<br>
* <br>
* References:
* <ul>
* <li>Passonneau, R.J.: Computing reliability for coreference annotation. In: Proceedings of the
* Fourth International Conference on Language Resources and Evaluation, p. 1503–1506, 2004.</li>
* <li>Passonneau, R.: Measuring agreement on set-valued items (MASI) for semantic and pragmatic
* annotation, in: Proceedings of the Fifth International Conference on Language Resources and
* Evaluation, p. 831–836, 2006.</li>
* </ul>
*
* @see IDistanceFunction
* @see SetAnnotation
* @see SetAnnotationDistanceFunction
* @author Christian M. Meyer
*/
public class MASISetAnnotationDistanceFunction
implements IDistanceFunction
{
@Override | public double measureDistance(final IAnnotationStudy study, Object category1, Object category2) |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/UnitizingStudyPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationStudy.java
// public interface IUnitizingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Units --
//
// /** Allows iterating all annotation units of this study. */
// Collection<IUnitizingAnnotationUnit> getUnits();
//
// // -- Continuum --
//
// // @Deprecated
// // public int getSectionCount();
// //
// // @Deprecated
// // public Iterable<Integer> getSectionBoundaries();
//
// /**
// * Returns the begin of the continuum (i.e., the first offset that is considered valid for
// * annotation units).
// */
// long getContinuumBegin();
//
// /**
// * Returns the length of the continuum (i.e., the last possible right delimiter of an annotation
// * unit).
// */
// long getContinuumLength();
//
// /**
// * Returns the number of units rated by the given rater.
// */
// long getUnitCount(int aRaterIdx);
//
// // TODO: public void addSectionBoundary(long position);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationUnit.java
// public interface IUnitizingAnnotationUnit
// extends IAnnotationUnit, Comparable<IUnitizingAnnotationUnit>
// {
//
// /**
// * Returns the offset of the annotation unit (i.e., the start position of the identified
// * segment).
// */
// public long getOffset();
//
// /**
// * Returns the length of the annotation unit (i.e., the difference between the end and start
// * position of the identified segment).
// */
// public long getLength();
//
// /**
// * Returns the right delimiter of the annotation unit (i.e., the end position of the identified
// * segment). The method is a shorthand for {@link #getOffset()} + {@link #getLength()}.
// */
// public long getEndOffset();
//
// }
| import java.io.PrintStream;
import java.util.Objects;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationStudy;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationUnit; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for unitizing studies. The visualization prints
* the continuum and marks the units of each individual rater and for each
* category using asterisks. For category A of Krippendorff's (1995) example,
* the implementation prints, for instance: <pre> 1 2 2
* r 0123456789012345678901234
* 0 ******** ******
* 1 **** **</pre>
* That is, a continuum starting at 0, ending at 24, in which two raters
* identified two units. By defining a {@link PrintStream}, it is possible to
* display a study on the console or to write the results to a text file.<br><br>
* References:<ul>
* <li>Krippendorff, K.: On the reliability of unitizing contiguous data.
* Sociological Methodology 25:47–76, 1995.</li></ul>
* @see IUnitizingAnnotationStudy
* @author Christian M. Meyer
*/
public class UnitizingStudyPrinter
{
/**
* Prints an integer scale of the continuum used for the given unitzing study. Optionally, the
* given prefix is printed left of the continuum scale and the output is correctly indented.
*/ | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationStudy.java
// public interface IUnitizingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Units --
//
// /** Allows iterating all annotation units of this study. */
// Collection<IUnitizingAnnotationUnit> getUnits();
//
// // -- Continuum --
//
// // @Deprecated
// // public int getSectionCount();
// //
// // @Deprecated
// // public Iterable<Integer> getSectionBoundaries();
//
// /**
// * Returns the begin of the continuum (i.e., the first offset that is considered valid for
// * annotation units).
// */
// long getContinuumBegin();
//
// /**
// * Returns the length of the continuum (i.e., the last possible right delimiter of an annotation
// * unit).
// */
// long getContinuumLength();
//
// /**
// * Returns the number of units rated by the given rater.
// */
// long getUnitCount(int aRaterIdx);
//
// // TODO: public void addSectionBoundary(long position);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationUnit.java
// public interface IUnitizingAnnotationUnit
// extends IAnnotationUnit, Comparable<IUnitizingAnnotationUnit>
// {
//
// /**
// * Returns the offset of the annotation unit (i.e., the start position of the identified
// * segment).
// */
// public long getOffset();
//
// /**
// * Returns the length of the annotation unit (i.e., the difference between the end and start
// * position of the identified segment).
// */
// public long getLength();
//
// /**
// * Returns the right delimiter of the annotation unit (i.e., the end position of the identified
// * segment). The method is a shorthand for {@link #getOffset()} + {@link #getLength()}.
// */
// public long getEndOffset();
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/UnitizingStudyPrinter.java
import java.io.PrintStream;
import java.util.Objects;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationStudy;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationUnit;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for unitizing studies. The visualization prints
* the continuum and marks the units of each individual rater and for each
* category using asterisks. For category A of Krippendorff's (1995) example,
* the implementation prints, for instance: <pre> 1 2 2
* r 0123456789012345678901234
* 0 ******** ******
* 1 **** **</pre>
* That is, a continuum starting at 0, ending at 24, in which two raters
* identified two units. By defining a {@link PrintStream}, it is possible to
* display a study on the console or to write the results to a text file.<br><br>
* References:<ul>
* <li>Krippendorff, K.: On the reliability of unitizing contiguous data.
* Sociological Methodology 25:47–76, 1995.</li></ul>
* @see IUnitizingAnnotationStudy
* @author Christian M. Meyer
*/
public class UnitizingStudyPrinter
{
/**
* Prints an integer scale of the continuum used for the given unitzing study. Optionally, the
* given prefix is printed left of the continuum scale and the output is correctly indented.
*/ | public void printContinuum(final PrintStream out, final IUnitizingAnnotationStudy study, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/UnitizingStudyPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationStudy.java
// public interface IUnitizingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Units --
//
// /** Allows iterating all annotation units of this study. */
// Collection<IUnitizingAnnotationUnit> getUnits();
//
// // -- Continuum --
//
// // @Deprecated
// // public int getSectionCount();
// //
// // @Deprecated
// // public Iterable<Integer> getSectionBoundaries();
//
// /**
// * Returns the begin of the continuum (i.e., the first offset that is considered valid for
// * annotation units).
// */
// long getContinuumBegin();
//
// /**
// * Returns the length of the continuum (i.e., the last possible right delimiter of an annotation
// * unit).
// */
// long getContinuumLength();
//
// /**
// * Returns the number of units rated by the given rater.
// */
// long getUnitCount(int aRaterIdx);
//
// // TODO: public void addSectionBoundary(long position);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationUnit.java
// public interface IUnitizingAnnotationUnit
// extends IAnnotationUnit, Comparable<IUnitizingAnnotationUnit>
// {
//
// /**
// * Returns the offset of the annotation unit (i.e., the start position of the identified
// * segment).
// */
// public long getOffset();
//
// /**
// * Returns the length of the annotation unit (i.e., the difference between the end and start
// * position of the identified segment).
// */
// public long getLength();
//
// /**
// * Returns the right delimiter of the annotation unit (i.e., the end position of the identified
// * segment). The method is a shorthand for {@link #getOffset()} + {@link #getLength()}.
// */
// public long getEndOffset();
//
// }
| import java.io.PrintStream;
import java.util.Objects;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationStudy;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationUnit; | if (lastDigit == 0 || i == 0 || i == L) {
pos = pos / 10;
}
else {
break;
}
}
while (pos > 0);
}
for (int j = digits - 1; j >= 0; j--) {
out.print(j == 0 ? p[0] : p[1]);
out.println(scale[j]);
}
}
/**
* Identifies all annotation units of the given rater which have been coded with the given
* category and marks their boundaries using asterisks. The scale is compatible to
* {@link #printContinuum( PrintStream, IUnitizingAnnotationStudy, String)}. Optionally, the
* given prefix is printed left of the continuum scale and the output is correctly indented.
*/
public void printUnitsForRater(final PrintStream out, final IUnitizingAnnotationStudy study,
int raterIdx, final Object category, final String prefix)
{
long B = study.getContinuumBegin();
long L = study.getContinuumLength();
char[] annotations = new char[(int) L];
for (int i = 0; i < L; i++) {
annotations[i] = ' ';
} | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationStudy.java
// public interface IUnitizingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Units --
//
// /** Allows iterating all annotation units of this study. */
// Collection<IUnitizingAnnotationUnit> getUnits();
//
// // -- Continuum --
//
// // @Deprecated
// // public int getSectionCount();
// //
// // @Deprecated
// // public Iterable<Integer> getSectionBoundaries();
//
// /**
// * Returns the begin of the continuum (i.e., the first offset that is considered valid for
// * annotation units).
// */
// long getContinuumBegin();
//
// /**
// * Returns the length of the continuum (i.e., the last possible right delimiter of an annotation
// * unit).
// */
// long getContinuumLength();
//
// /**
// * Returns the number of units rated by the given rater.
// */
// long getUnitCount(int aRaterIdx);
//
// // TODO: public void addSectionBoundary(long position);
//
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationUnit.java
// public interface IUnitizingAnnotationUnit
// extends IAnnotationUnit, Comparable<IUnitizingAnnotationUnit>
// {
//
// /**
// * Returns the offset of the annotation unit (i.e., the start position of the identified
// * segment).
// */
// public long getOffset();
//
// /**
// * Returns the length of the annotation unit (i.e., the difference between the end and start
// * position of the identified segment).
// */
// public long getLength();
//
// /**
// * Returns the right delimiter of the annotation unit (i.e., the end position of the identified
// * segment). The method is a shorthand for {@link #getOffset()} + {@link #getLength()}.
// */
// public long getEndOffset();
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/UnitizingStudyPrinter.java
import java.io.PrintStream;
import java.util.Objects;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationStudy;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationUnit;
if (lastDigit == 0 || i == 0 || i == L) {
pos = pos / 10;
}
else {
break;
}
}
while (pos > 0);
}
for (int j = digits - 1; j >= 0; j--) {
out.print(j == 0 ? p[0] : p[1]);
out.println(scale[j]);
}
}
/**
* Identifies all annotation units of the given rater which have been coded with the given
* category and marks their boundaries using asterisks. The scale is compatible to
* {@link #printContinuum( PrintStream, IUnitizingAnnotationStudy, String)}. Optionally, the
* given prefix is printed left of the continuum scale and the output is correctly indented.
*/
public void printUnitsForRater(final PrintStream out, final IUnitizingAnnotationStudy study,
int raterIdx, final Object category, final String prefix)
{
long B = study.getContinuumBegin();
long L = study.getContinuumLength();
char[] annotations = new char[(int) L];
for (int i = 0; i < L; i++) {
annotations[i] = ' ';
} | for (IUnitizingAnnotationUnit unit : study.getUnits()) { |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/HayesKrippendorff2007Test.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// if (category1.equals(category2)) {
// return 0.0;
// }
//
// // TODO: Provide generic method for the annotation study w/ potential use for unitizing
// // tasks!
// Map<Object, Integer> nk = CodingAnnotationStudy
// .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
// Integer v;
//
// double result = 0.0;
// v = nk.get(category1);
// if (v != null) {
// result += ((double) v) / 2.0;
// }
// v = nk.get(category2);
// if (v != null) {
// result += ((double) v) / 2.0;
// }
//
// int cat1 = (Integer) category1;
// int cat2 = (Integer) category2;
// int minCat = (cat1 < cat2 ? cat1 : cat2);
// int maxCat = (cat1 < cat2 ? cat2 : cat1);
// for (int i = minCat + 1; i < maxCat; i++) {
// v = nk.get(i);
// if (v != null) {
// result += v;
// }
// }
// return result * result;
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
// }
| import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import junit.framework.TestCase; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests based on Hayes & Krippendorff (2007) for measuring {@link KrippendorffAlphaAgreement}
* with an {@link OrdinalDistanceFunction}.<br>
* <br>
* References:
* <ul>
* <li>Hayes, A.F. & Krippendorff, K.: Answering the call for a standard reliability measure for
* coding data. Communication Methods and Measures 1(1):77–89, 2007.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class HayesKrippendorff2007Test
extends TestCase
{
public void testAgreement()
{
ICodingAnnotationStudy study = createExample();
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
// implements IDistanceFunction
// {
//
// @Override
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2)
// {
// if (category1 instanceof Integer && category2 instanceof Integer) {
// if (category1.equals(category2)) {
// return 0.0;
// }
//
// // TODO: Provide generic method for the annotation study w/ potential use for unitizing
// // tasks!
// Map<Object, Integer> nk = CodingAnnotationStudy
// .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
// Integer v;
//
// double result = 0.0;
// v = nk.get(category1);
// if (v != null) {
// result += ((double) v) / 2.0;
// }
// v = nk.get(category2);
// if (v != null) {
// result += ((double) v) / 2.0;
// }
//
// int cat1 = (Integer) category1;
// int cat2 = (Integer) category2;
// int minCat = (cat1 < cat2 ? cat1 : cat2);
// int maxCat = (cat1 < cat2 ? cat2 : cat1);
// for (int i = minCat + 1; i < maxCat; i++) {
// v = nk.get(i);
// if (v != null) {
// result += v;
// }
// }
// return result * result;
// }
//
// return (category1.equals(category2) ? 0.0 : 1.0);
// }
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/HayesKrippendorff2007Test.java
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import junit.framework.TestCase;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Tests based on Hayes & Krippendorff (2007) for measuring {@link KrippendorffAlphaAgreement}
* with an {@link OrdinalDistanceFunction}.<br>
* <br>
* References:
* <ul>
* <li>Hayes, A.F. & Krippendorff, K.: Answering the call for a standard reliability measure for
* coding data. Communication Methods and Measures 1(1):77–89, 2007.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class HayesKrippendorff2007Test
extends TestCase
{
public void testAgreement()
{
ICodingAnnotationStudy study = createExample();
KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, | new OrdinalDistanceFunction()); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/FleissKappaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Generalization of Scott's (1955) pi-measure for calculating a chance-corrected inter-rater
* agreement for multiple raters, which is known as Fleiss' (1971) kappa and Carletta's (1996) K.
* The basic idea is to average over all pairwise agreements. The measure assumes the same
* probability distribution for all raters.<br>
* <br>
* References:
* <ul>
* <li>Fleiss, J.L.: Measuring nominal scale agreement among many raters. Psychological Bulletin
* 76(5):378-381, 1971.</li>
* <li>Carletta, J.: Assessing agreement on classification tasks: The kappa statistic. Computational
* Linguistics 22(2):249-254, 1996.</li>
* <li>Scott, W.A.: Reliability of content analysis: The case of nominal scale coding. Public
* Opinion Quaterly 19(3):321-325, 1955.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class FleissKappaAgreement
extends CodingAgreementMeasure | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/FleissKappaAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Generalization of Scott's (1955) pi-measure for calculating a chance-corrected inter-rater
* agreement for multiple raters, which is known as Fleiss' (1971) kappa and Carletta's (1996) K.
* The basic idea is to average over all pairwise agreements. The measure assumes the same
* probability distribution for all raters.<br>
* <br>
* References:
* <ul>
* <li>Fleiss, J.L.: Measuring nominal scale agreement among many raters. Psychological Bulletin
* 76(5):378-381, 1971.</li>
* <li>Carletta, J.: Assessing agreement on classification tasks: The kappa statistic. Computational
* Linguistics 22(2):249-254, 1996.</li>
* <li>Scott, W.A.: Reliability of content analysis: The case of nominal scale coding. Public
* Opinion Quaterly 19(3):321-325, 1955.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class FleissKappaAgreement
extends CodingAgreementMeasure | implements IChanceCorrectedAgreement, ICategorySpecificAgreement |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/FleissKappaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Generalization of Scott's (1955) pi-measure for calculating a chance-corrected inter-rater
* agreement for multiple raters, which is known as Fleiss' (1971) kappa and Carletta's (1996) K.
* The basic idea is to average over all pairwise agreements. The measure assumes the same
* probability distribution for all raters.<br>
* <br>
* References:
* <ul>
* <li>Fleiss, J.L.: Measuring nominal scale agreement among many raters. Psychological Bulletin
* 76(5):378-381, 1971.</li>
* <li>Carletta, J.: Assessing agreement on classification tasks: The kappa statistic. Computational
* Linguistics 22(2):249-254, 1996.</li>
* <li>Scott, W.A.: Reliability of content analysis: The case of nominal scale coding. Public
* Opinion Quaterly 19(3):321-325, 1955.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class FleissKappaAgreement
extends CodingAgreementMeasure | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/FleissKappaAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Generalization of Scott's (1955) pi-measure for calculating a chance-corrected inter-rater
* agreement for multiple raters, which is known as Fleiss' (1971) kappa and Carletta's (1996) K.
* The basic idea is to average over all pairwise agreements. The measure assumes the same
* probability distribution for all raters.<br>
* <br>
* References:
* <ul>
* <li>Fleiss, J.L.: Measuring nominal scale agreement among many raters. Psychological Bulletin
* 76(5):378-381, 1971.</li>
* <li>Carletta, J.: Assessing agreement on classification tasks: The kappa statistic. Computational
* Linguistics 22(2):249-254, 1996.</li>
* <li>Scott, W.A.: Reliability of content analysis: The case of nominal scale coding. Public
* Opinion Quaterly 19(3):321-325, 1955.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class FleissKappaAgreement
extends CodingAgreementMeasure | implements IChanceCorrectedAgreement, ICategorySpecificAgreement |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/FleissKappaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | * @date 04.03.2011
*/
/*
* Calculates the inter-rater agreement for the given annotation category based on the object's
* annotation study that has been passed to the class constructor.
*
* @throws NullPointerException if the study is null or the given category is null.
*
* @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
*
* @throws ArithmeticException if the study does not contain annotations for the given category.
*/
@Override
public double calculateCategoryAgreement(final Object category)
{
// N = # subjects = #items -> index i
// n = # ratings/subject = #raters
// k = # categories -> index j
// n_ij = # raters that annotated item i as category j
//
// k_j = (P_j - p_j) / (1 - p_j)
// P_j = (sum( n_ij^2 ) - N n p_j) / (N n (n-1) p_j )
// p_j = 1/Nn sum n_ij
int N = study.getItemCount();
int n = study.getRaterCount();
int sum_nij = 0;
int sum_nij_2 = 0;
for (ICodingAnnotationItem item : study.getItems()) {
int nij = 0; | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/FleissKappaAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
* @date 04.03.2011
*/
/*
* Calculates the inter-rater agreement for the given annotation category based on the object's
* annotation study that has been passed to the class constructor.
*
* @throws NullPointerException if the study is null or the given category is null.
*
* @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
*
* @throws ArithmeticException if the study does not contain annotations for the given category.
*/
@Override
public double calculateCategoryAgreement(final Object category)
{
// N = # subjects = #items -> index i
// n = # ratings/subject = #raters
// k = # categories -> index j
// n_ij = # raters that annotated item i as category j
//
// k_j = (P_j - p_j) / (1 - p_j)
// P_j = (sum( n_ij^2 ) - N n p_j) / (N n (n-1) p_j )
// p_j = 1/Nn sum n_ij
int N = study.getItemCount();
int n = study.getRaterCount();
int sum_nij = 0;
int sum_nij_2 = 0;
for (ICodingAnnotationItem item : study.getItems()) {
int nij = 0; | for (IAnnotationUnit annotation : item.getUnits()) { |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Krippendorff's (1980) alpha-measure for calculating a chance-corrected
* inter-rater agreement for multiple raters with arbitrary distance/weighting functions. The basic
* idea is to divide the estimated variance of within the items by the estimated total variance.
* Before an inter-rater agreement can be calculated, an {@link IDistanceFunction} instance needs to
* be assigned.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Estimating the reliability, systematic error and random error of interval
* data. Educational and Psychological Measurement 30(1):61-70, 1970.</li>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. 2nd edition, Thousand
* Oaks, CA: Sage Publications, 2004.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class KrippendorffAlphaAgreement
extends WeightedAgreement | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Krippendorff's (1980) alpha-measure for calculating a chance-corrected
* inter-rater agreement for multiple raters with arbitrary distance/weighting functions. The basic
* idea is to divide the estimated variance of within the items by the estimated total variance.
* Before an inter-rater agreement can be calculated, an {@link IDistanceFunction} instance needs to
* be assigned.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Estimating the reliability, systematic error and random error of interval
* data. Educational and Psychological Measurement 30(1):61-70, 1970.</li>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. 2nd edition, Thousand
* Oaks, CA: Sage Publications, 2004.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class KrippendorffAlphaAgreement
extends WeightedAgreement | implements IChanceCorrectedDisagreement, ICategorySpecificAgreement, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Krippendorff's (1980) alpha-measure for calculating a chance-corrected
* inter-rater agreement for multiple raters with arbitrary distance/weighting functions. The basic
* idea is to divide the estimated variance of within the items by the estimated total variance.
* Before an inter-rater agreement can be calculated, an {@link IDistanceFunction} instance needs to
* be assigned.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Estimating the reliability, systematic error and random error of interval
* data. Educational and Psychological Measurement 30(1):61-70, 1970.</li>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. 2nd edition, Thousand
* Oaks, CA: Sage Publications, 2004.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class KrippendorffAlphaAgreement
extends WeightedAgreement | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Krippendorff's (1980) alpha-measure for calculating a chance-corrected
* inter-rater agreement for multiple raters with arbitrary distance/weighting functions. The basic
* idea is to divide the estimated variance of within the items by the estimated total variance.
* Before an inter-rater agreement can be calculated, an {@link IDistanceFunction} instance needs to
* be assigned.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Estimating the reliability, systematic error and random error of interval
* data. Educational and Psychological Measurement 30(1):61-70, 1970.</li>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. 2nd edition, Thousand
* Oaks, CA: Sage Publications, 2004.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class KrippendorffAlphaAgreement
extends WeightedAgreement | implements IChanceCorrectedDisagreement, ICategorySpecificAgreement, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Krippendorff's (1980) alpha-measure for calculating a chance-corrected
* inter-rater agreement for multiple raters with arbitrary distance/weighting functions. The basic
* idea is to divide the estimated variance of within the items by the estimated total variance.
* Before an inter-rater agreement can be calculated, an {@link IDistanceFunction} instance needs to
* be assigned.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Estimating the reliability, systematic error and random error of interval
* data. Educational and Psychological Measurement 30(1):61-70, 1970.</li>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. 2nd edition, Thousand
* Oaks, CA: Sage Publications, 2004.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class KrippendorffAlphaAgreement
extends WeightedAgreement
implements IChanceCorrectedDisagreement, ICategorySpecificAgreement,
ICodingItemSpecificAgreement
{
protected Map<Object, Map<Object, Double>> coincidenceMatrix;
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public KrippendorffAlphaAgreement(final ICodingAnnotationStudy study, | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Krippendorff's (1980) alpha-measure for calculating a chance-corrected
* inter-rater agreement for multiple raters with arbitrary distance/weighting functions. The basic
* idea is to divide the estimated variance of within the items by the estimated total variance.
* Before an inter-rater agreement can be calculated, an {@link IDistanceFunction} instance needs to
* be assigned.<br>
* <br>
* References:
* <ul>
* <li>Krippendorff, K.: Estimating the reliability, systematic error and random error of interval
* data. Educational and Psychological Measurement 30(1):61-70, 1970.</li>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. 2nd edition, Thousand
* Oaks, CA: Sage Publications, 2004.</li>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class KrippendorffAlphaAgreement
extends WeightedAgreement
implements IChanceCorrectedDisagreement, ICategorySpecificAgreement,
ICodingItemSpecificAgreement
{
protected Map<Object, Map<Object, Double>> coincidenceMatrix;
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public KrippendorffAlphaAgreement(final ICodingAnnotationStudy study, | final IDistanceFunction distanceFunction) |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | double result = 0.0;
for (Entry<Object, Map<Object, Double>> cat1 : coincidenceMatrix.entrySet()) {
for (Entry<Object, Double> cat2 : cat1.getValue().entrySet()) {
result += cat2.getValue()
* distanceFunction.measureDistance(study, cat1.getKey(), cat2.getKey());
n += cat2.getValue();
}
}
result /= n;
return result;
}
/**
* Calculates the expected inter-rater agreement using the defined distance function to infer
* the assumed probability distribution.
*
* @throws NullPointerException
* if the annotation study is null.
* @throws ArithmeticException
* if there are no items or raters in the annotation study.
*/
@Override
public double calculateExpectedDisagreement()
{
ensureDistanceFunction();
if (coincidenceMatrix == null) {
coincidenceMatrix = CodingAnnotationStudy.countCategoryCoincidence(study);
}
if (study.getCategoryCount() <= 1) { | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
double result = 0.0;
for (Entry<Object, Map<Object, Double>> cat1 : coincidenceMatrix.entrySet()) {
for (Entry<Object, Double> cat2 : cat1.getValue().entrySet()) {
result += cat2.getValue()
* distanceFunction.measureDistance(study, cat1.getKey(), cat2.getKey());
n += cat2.getValue();
}
}
result /= n;
return result;
}
/**
* Calculates the expected inter-rater agreement using the defined distance function to infer
* the assumed probability distribution.
*
* @throws NullPointerException
* if the annotation study is null.
* @throws ArithmeticException
* if there are no items or raters in the annotation study.
*/
@Override
public double calculateExpectedDisagreement()
{
ensureDistanceFunction();
if (coincidenceMatrix == null) {
coincidenceMatrix = CodingAnnotationStudy.countCategoryCoincidence(study);
}
if (study.getCategoryCount() <= 1) { | throw new InsufficientDataException( |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | n += n_c;
}
/*
* double D_E = 0.0; for (Entry<Object, Double> cat1 : marginals.entrySet()) for
* (Entry<Object, Double> cat2 : marginals.entrySet()) D_E += cat1.getValue() *
* cat2.getValue() distanceFunction.measureDistance(study, cat1.getKey(), cat2.getKey());
* D_E /= n * (n - 1.0);
*/
double D_E = calculateExpectedDisagreement();
if (D_E == 0.0) {
return 1.0;
}
else {
return 1.0 - (D_O / D_E);
}
}
@Override
public double calculateCategoryAgreement(final Object category)
{
ensureDistanceFunction();
final Object NULL_CATEGORY = new Object();
double observedDisagreement = 0.0;
int nKeepCategorySum = 0;
int nNullCategorySum = 0;
for (ICodingAnnotationItem item : study.getItems()) {
int nKeepCategory = 0;
int nNullCategory = 0; | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed disagreement of an annotation study. The observed disagreement is
// * basically the proportion of annotation units that the raters disagree on divided by the
// * number of units in the given study.
// */
// public double calculateObservedDisagreement();
//
// /**
// * Returns the expected disagreement of an annotation study. The expected disagreement is the
// * proportion of disagreement that would be expected by chance alone. The expected disagreement
// * should be equal to the observed disagreement if each rater makes a random decision for each
// * unit.
// */
// public double calculateExpectedDisagreement();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
//
// /**
// * Returns a distance value for the given pair of categories used within the given annotation
// * study. Normally, the measure should return a distance of 0 if, and only if, the two
// * categories are equal and a positive number otherwise.
// */
// public double measureDistance(final IAnnotationStudy study, final Object category1,
// final Object category2);
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/KrippendorffAlphaAgreement.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.InsufficientDataException;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
n += n_c;
}
/*
* double D_E = 0.0; for (Entry<Object, Double> cat1 : marginals.entrySet()) for
* (Entry<Object, Double> cat2 : marginals.entrySet()) D_E += cat1.getValue() *
* cat2.getValue() distanceFunction.measureDistance(study, cat1.getKey(), cat2.getKey());
* D_E /= n * (n - 1.0);
*/
double D_E = calculateExpectedDisagreement();
if (D_E == 0.0) {
return 1.0;
}
else {
return 1.0 - (D_O / D_E);
}
}
@Override
public double calculateCategoryAgreement(final Object category)
{
ensureDistanceFunction();
final Object NULL_CATEGORY = new Object();
double observedDisagreement = 0.0;
int nKeepCategorySum = 0;
int nNullCategorySum = 0;
for (ICodingAnnotationItem item : study.getItems()) {
int nKeepCategory = 0;
int nNullCategory = 0; | for (IAnnotationUnit annotation : item.getUnits()) { |
dkpro/dkpro-statistics | dkpro-statistics-significance/src/test/java/org/dkpro/statistics/significance/SignificanceTest.java | // Path: dkpro-statistics-significance/src/main/java/org/dkpro/statistics/significance/Significance.java
// public static boolean testCorrelations(double correlation1, double correlation2, int n1, int n2,
// double alpha)
// throws MathException
// {
//
// double p = getSignificance(correlation1, correlation2, n1, n2);
//
// if (p <= alpha) {
// return true;
// }
// else {
// return false;
// }
// }
| import static org.dkpro.statistics.significance.Significance.testCorrelations;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.commons.math.MathException;
import org.junit.Test; | /*
* Copyright 2013
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.significance;
public class SignificanceTest
{
@Test
public void testTestCorrelations() throws MathException
{ | // Path: dkpro-statistics-significance/src/main/java/org/dkpro/statistics/significance/Significance.java
// public static boolean testCorrelations(double correlation1, double correlation2, int n1, int n2,
// double alpha)
// throws MathException
// {
//
// double p = getSignificance(correlation1, correlation2, n1, n2);
//
// if (p <= alpha) {
// return true;
// }
// else {
// return false;
// }
// }
// Path: dkpro-statistics-significance/src/test/java/org/dkpro/statistics/significance/SignificanceTest.java
import static org.dkpro.statistics.significance.Significance.testCorrelations;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.commons.math.MathException;
import org.junit.Test;
/*
* Copyright 2013
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.significance;
public class SignificanceTest
{
@Test
public void testTestCorrelations() throws MathException
{ | assertTrue(testCorrelations(0.5, 0.74, 68, 68, 0.2)); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotationDistanceFunction.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
| import org.dkpro.statistics.agreement.IAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Distance function for set-valued annotation studies based on the definition of partial matching
* (Passonneau, 2004). The distance function assumes categories of type {@link SetAnnotation}.<br>
* <br>
* References:
* <ul>
* <li>Passonneau, R.J.: Computing reliability for coreference annotation. In: Proceedings of the
* Fourth International Conference on Language Resources and Evaluation, p. 1503–1506, 2004.</li>
* </ul>
*
* @see IDistanceFunction
* @see SetAnnotation
* @see MASISetAnnotationDistanceFunction
* @author Christian M. Meyer
*/
public class SetAnnotationDistanceFunction
implements IDistanceFunction
{
@Override | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/SetAnnotationDistanceFunction.java
import org.dkpro.statistics.agreement.IAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Distance function for set-valued annotation studies based on the definition of partial matching
* (Passonneau, 2004). The distance function assumes categories of type {@link SetAnnotation}.<br>
* <br>
* References:
* <ul>
* <li>Passonneau, R.J.: Computing reliability for coreference annotation. In: Proceedings of the
* Fourth International Conference on Language Resources and Evaluation, p. 1503–1506, 2004.</li>
* </ul>
*
* @see IDistanceFunction
* @see SetAnnotation
* @see MASISetAnnotationDistanceFunction
* @author Christian M. Meyer
*/
public class SetAnnotationDistanceFunction
implements IDistanceFunction
{
@Override | public double measureDistance(final IAnnotationStudy study, final Object category1, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ScottPiAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Scott's pi (1955) for calculating a chance-corrected inter-rater agreement for
* two raters. The measure assumes the same probability distribution for all raters.<br>
* <br>
* References:
* <ul>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* <li>Scott, W.A.: Reliability of content analysis: The case of nominal scale coding. Public
* Opinion Quaterly 19(3):321-325, 1955.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class ScottPiAgreement
extends CodingAgreementMeasure | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ScottPiAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Scott's pi (1955) for calculating a chance-corrected inter-rater agreement for
* two raters. The measure assumes the same probability distribution for all raters.<br>
* <br>
* References:
* <ul>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* <li>Scott, W.A.: Reliability of content analysis: The case of nominal scale coding. Public
* Opinion Quaterly 19(3):321-325, 1955.</li>
* </ul>
*
* @author Christian M. Meyer
*/
public class ScottPiAgreement
extends CodingAgreementMeasure | implements IChanceCorrectedAgreement |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ContingencyMatrixPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
| import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a contingency matrix as defined by
* Krippendorff (1980: p. 133). That is, a table showing the frequencies
* of each combination of categories used by two raters. A contigency table
* is only defined for coding studies with exactly two raters. For the example
* by Krippendorff (1980: p. 133), the implementation displays:
* <pre>
* 0 1 Σ
* 0 5 3 8
* 1 1 1 2
* Σ 6 4 10
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ContingencyMatrixPrinter
{
/**
* Print the contingency matrix for the given coding study.
*
* @throws IllegalArgumentException
* if the given study has more than two raters.
*/ | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ContingencyMatrixPrinter.java
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a contingency matrix as defined by
* Krippendorff (1980: p. 133). That is, a table showing the frequencies
* of each combination of categories used by two raters. A contigency table
* is only defined for coding studies with exactly two raters. For the example
* by Krippendorff (1980: p. 133), the implementation displays:
* <pre>
* 0 1 Σ
* 0 5 3 8
* 1 1 1 2
* Σ 6 4 10
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ContingencyMatrixPrinter
{
/**
* Print the contingency matrix for the given coding study.
*
* @throws IllegalArgumentException
* if the given study has more than two raters.
*/ | public void print(final PrintStream out, final ICodingAnnotationStudy study) |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ContingencyMatrixPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
| import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a contingency matrix as defined by
* Krippendorff (1980: p. 133). That is, a table showing the frequencies
* of each combination of categories used by two raters. A contigency table
* is only defined for coding studies with exactly two raters. For the example
* by Krippendorff (1980: p. 133), the implementation displays:
* <pre>
* 0 1 Σ
* 0 5 3 8
* 1 1 1 2
* Σ 6 4 10
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ContingencyMatrixPrinter
{
/**
* Print the contingency matrix for the given coding study.
*
* @throws IllegalArgumentException
* if the given study has more than two raters.
*/
public void print(final PrintStream out, final ICodingAnnotationStudy study)
{
if (study.getRaterCount() > 2) {
throw new IllegalArgumentException(
"Contingency tables are only applicable for two rater studies.");
}
// TODO: measure length of cats. maybe cut them.
Map<Object, Integer> categories = new LinkedHashMap<Object, Integer>();
for (Object cat : study.getCategories()) {
categories.put(cat, categories.size());
}
int[][] frequencies = new int[study.getCategoryCount()][study.getCategoryCount()]; | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ContingencyMatrixPrinter.java
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a contingency matrix as defined by
* Krippendorff (1980: p. 133). That is, a table showing the frequencies
* of each combination of categories used by two raters. A contigency table
* is only defined for coding studies with exactly two raters. For the example
* by Krippendorff (1980: p. 133), the implementation displays:
* <pre>
* 0 1 Σ
* 0 5 3 8
* 1 1 1 2
* Σ 6 4 10
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ContingencyMatrixPrinter
{
/**
* Print the contingency matrix for the given coding study.
*
* @throws IllegalArgumentException
* if the given study has more than two raters.
*/
public void print(final PrintStream out, final ICodingAnnotationStudy study)
{
if (study.getRaterCount() > 2) {
throw new IllegalArgumentException(
"Contingency tables are only applicable for two rater studies.");
}
// TODO: measure length of cats. maybe cut them.
Map<Object, Integer> categories = new LinkedHashMap<Object, Integer>();
for (Object cat : study.getCategories()) {
categories.put(cat, categories.size());
}
int[][] frequencies = new int[study.getCategoryCount()][study.getCategoryCount()]; | for (ICodingAnnotationItem item : study.getItems()) { |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CodingAnnotationStudy.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AnnotationStudy.java
// public abstract class AnnotationStudy
// implements IAnnotationStudy
// {
// private static final long serialVersionUID = -3596722258510421730L;
//
// protected List<String> raters;
// protected Set<Object> categories;
//
// protected AnnotationStudy()
// {
// raters = new ArrayList<String>();
// categories = new LinkedHashSet<Object>();
// }
//
// /**
// * Add a rater with the given name. Returns the index of the newly added rater which is required
// * to identify the rater in {@link IAnnotationUnit}. The first rater receives index 0. Note that
// * adding names for the raters is optional.
// */
// public int addRater(final String name)
// {
// raters.add(name);
// return (raters.size() - 1);
// }
//
// /** Find the index of the rater with the given name. */
// public int findRater(final String name)
// {
// return raters.indexOf(name);
// }
//
// @Override
// public int getRaterCount()
// {
// return raters.size();
// }
//
// /**
// * Adds the given category to the set of possible annotation labels. This method is only
// * required of a category has not been used by any rater of within the annotation study.
// *
// * @throws NullPointerException
// * if the specified category is null.
// */
// public void addCategory(final Object category)
// {
// categories.add(category);
// }
//
// @Override
// public Iterable<Object> getCategories()
// {
// return categories;
// }
//
// /*
// * public Object[] getCategoryArray() { Object[] result = null; int idx = 0; for (Object
// * category : getCategories()) { if (result == null) result = new Object[categories.size()];
// * result[idx++] = category; } return result; }
// */
//
// @Override
// public int getCategoryCount()
// {
// return categories.size();
// }
//
// @Override
// public boolean isDichotomous()
// {
// return (categories.size() == 2);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AnnotationUnit.java
// public class AnnotationUnit
// implements IAnnotationUnit
// {
// private static final long serialVersionUID = 4277733312128063453L;
//
// protected int raterIdx;
// protected Object category;
//
// /**
// * Initializes the annotation unit with the given category as the annotation by the rater with
// * the specified index.
// */
// public AnnotationUnit(int raterIdx, final Object category)
// {
// this.raterIdx = raterIdx;
// this.category = category;
// }
//
// @Override
// public int getRaterIdx()
// {
// return raterIdx;
// }
//
// @Override
// public Object getCategory()
// {
// return category;
// }
//
// @Override
// public String toString()
// {
// return raterIdx + "<" + category + ">";
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.AnnotationStudy;
import org.dkpro.statistics.agreement.AnnotationUnit;
import org.dkpro.statistics.agreement.IAnnotationUnit; | * if the number of annotations does not match the number of raters.
*/
public ICodingAnnotationItem addItemAsArray(final Object[] annotations)
{
if (annotations.length != raters.size()) {
throw new IllegalArgumentException("Incorrect number of annotation units "
+ "(expected " + raters.size() + ", given " + annotations.length + "). "
+ "For array params, use #addItemsAsArray instead of #addItem.");
}
int itemIdx = items.size();
CodingAnnotationItem item = new CodingAnnotationItem(raters.size());
for (int raterIdx = 0; raterIdx < annotations.length; raterIdx++) {
item.addUnit(createUnit(itemIdx, raterIdx, annotations[raterIdx]));
}
items.add(item);
return item;
}
/**
* Shorthand for invoking {@link #addItem(Object...)} with the same parameters multiple times.
* This method is useful for modeling annotation data based on a contingency table.
*/
public void addMultipleItems(int times, final Object... values)
{
for (int i = 0; i < times; i++) {
addItemAsArray(values);
}
}
| // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AnnotationStudy.java
// public abstract class AnnotationStudy
// implements IAnnotationStudy
// {
// private static final long serialVersionUID = -3596722258510421730L;
//
// protected List<String> raters;
// protected Set<Object> categories;
//
// protected AnnotationStudy()
// {
// raters = new ArrayList<String>();
// categories = new LinkedHashSet<Object>();
// }
//
// /**
// * Add a rater with the given name. Returns the index of the newly added rater which is required
// * to identify the rater in {@link IAnnotationUnit}. The first rater receives index 0. Note that
// * adding names for the raters is optional.
// */
// public int addRater(final String name)
// {
// raters.add(name);
// return (raters.size() - 1);
// }
//
// /** Find the index of the rater with the given name. */
// public int findRater(final String name)
// {
// return raters.indexOf(name);
// }
//
// @Override
// public int getRaterCount()
// {
// return raters.size();
// }
//
// /**
// * Adds the given category to the set of possible annotation labels. This method is only
// * required of a category has not been used by any rater of within the annotation study.
// *
// * @throws NullPointerException
// * if the specified category is null.
// */
// public void addCategory(final Object category)
// {
// categories.add(category);
// }
//
// @Override
// public Iterable<Object> getCategories()
// {
// return categories;
// }
//
// /*
// * public Object[] getCategoryArray() { Object[] result = null; int idx = 0; for (Object
// * category : getCategories()) { if (result == null) result = new Object[categories.size()];
// * result[idx++] = category; } return result; }
// */
//
// @Override
// public int getCategoryCount()
// {
// return categories.size();
// }
//
// @Override
// public boolean isDichotomous()
// {
// return (categories.size() == 2);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AnnotationUnit.java
// public class AnnotationUnit
// implements IAnnotationUnit
// {
// private static final long serialVersionUID = 4277733312128063453L;
//
// protected int raterIdx;
// protected Object category;
//
// /**
// * Initializes the annotation unit with the given category as the annotation by the rater with
// * the specified index.
// */
// public AnnotationUnit(int raterIdx, final Object category)
// {
// this.raterIdx = raterIdx;
// this.category = category;
// }
//
// @Override
// public int getRaterIdx()
// {
// return raterIdx;
// }
//
// @Override
// public Object getCategory()
// {
// return category;
// }
//
// @Override
// public String toString()
// {
// return raterIdx + "<" + category + ">";
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CodingAnnotationStudy.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.AnnotationStudy;
import org.dkpro.statistics.agreement.AnnotationUnit;
import org.dkpro.statistics.agreement.IAnnotationUnit;
* if the number of annotations does not match the number of raters.
*/
public ICodingAnnotationItem addItemAsArray(final Object[] annotations)
{
if (annotations.length != raters.size()) {
throw new IllegalArgumentException("Incorrect number of annotation units "
+ "(expected " + raters.size() + ", given " + annotations.length + "). "
+ "For array params, use #addItemsAsArray instead of #addItem.");
}
int itemIdx = items.size();
CodingAnnotationItem item = new CodingAnnotationItem(raters.size());
for (int raterIdx = 0; raterIdx < annotations.length; raterIdx++) {
item.addUnit(createUnit(itemIdx, raterIdx, annotations[raterIdx]));
}
items.add(item);
return item;
}
/**
* Shorthand for invoking {@link #addItem(Object...)} with the same parameters multiple times.
* This method is useful for modeling annotation data based on a contingency table.
*/
public void addMultipleItems(int times, final Object... values)
{
for (int i = 0; i < times; i++) {
addItemAsArray(values);
}
}
| protected IAnnotationUnit createUnit(int index, int raterIdx, final Object category) |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CodingAnnotationStudy.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AnnotationStudy.java
// public abstract class AnnotationStudy
// implements IAnnotationStudy
// {
// private static final long serialVersionUID = -3596722258510421730L;
//
// protected List<String> raters;
// protected Set<Object> categories;
//
// protected AnnotationStudy()
// {
// raters = new ArrayList<String>();
// categories = new LinkedHashSet<Object>();
// }
//
// /**
// * Add a rater with the given name. Returns the index of the newly added rater which is required
// * to identify the rater in {@link IAnnotationUnit}. The first rater receives index 0. Note that
// * adding names for the raters is optional.
// */
// public int addRater(final String name)
// {
// raters.add(name);
// return (raters.size() - 1);
// }
//
// /** Find the index of the rater with the given name. */
// public int findRater(final String name)
// {
// return raters.indexOf(name);
// }
//
// @Override
// public int getRaterCount()
// {
// return raters.size();
// }
//
// /**
// * Adds the given category to the set of possible annotation labels. This method is only
// * required of a category has not been used by any rater of within the annotation study.
// *
// * @throws NullPointerException
// * if the specified category is null.
// */
// public void addCategory(final Object category)
// {
// categories.add(category);
// }
//
// @Override
// public Iterable<Object> getCategories()
// {
// return categories;
// }
//
// /*
// * public Object[] getCategoryArray() { Object[] result = null; int idx = 0; for (Object
// * category : getCategories()) { if (result == null) result = new Object[categories.size()];
// * result[idx++] = category; } return result; }
// */
//
// @Override
// public int getCategoryCount()
// {
// return categories.size();
// }
//
// @Override
// public boolean isDichotomous()
// {
// return (categories.size() == 2);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AnnotationUnit.java
// public class AnnotationUnit
// implements IAnnotationUnit
// {
// private static final long serialVersionUID = 4277733312128063453L;
//
// protected int raterIdx;
// protected Object category;
//
// /**
// * Initializes the annotation unit with the given category as the annotation by the rater with
// * the specified index.
// */
// public AnnotationUnit(int raterIdx, final Object category)
// {
// this.raterIdx = raterIdx;
// this.category = category;
// }
//
// @Override
// public int getRaterIdx()
// {
// return raterIdx;
// }
//
// @Override
// public Object getCategory()
// {
// return category;
// }
//
// @Override
// public String toString()
// {
// return raterIdx + "<" + category + ">";
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.AnnotationStudy;
import org.dkpro.statistics.agreement.AnnotationUnit;
import org.dkpro.statistics.agreement.IAnnotationUnit; | public ICodingAnnotationItem addItemAsArray(final Object[] annotations)
{
if (annotations.length != raters.size()) {
throw new IllegalArgumentException("Incorrect number of annotation units "
+ "(expected " + raters.size() + ", given " + annotations.length + "). "
+ "For array params, use #addItemsAsArray instead of #addItem.");
}
int itemIdx = items.size();
CodingAnnotationItem item = new CodingAnnotationItem(raters.size());
for (int raterIdx = 0; raterIdx < annotations.length; raterIdx++) {
item.addUnit(createUnit(itemIdx, raterIdx, annotations[raterIdx]));
}
items.add(item);
return item;
}
/**
* Shorthand for invoking {@link #addItem(Object...)} with the same parameters multiple times.
* This method is useful for modeling annotation data based on a contingency table.
*/
public void addMultipleItems(int times, final Object... values)
{
for (int i = 0; i < times; i++) {
addItemAsArray(values);
}
}
protected IAnnotationUnit createUnit(int index, int raterIdx, final Object category)
{ | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AnnotationStudy.java
// public abstract class AnnotationStudy
// implements IAnnotationStudy
// {
// private static final long serialVersionUID = -3596722258510421730L;
//
// protected List<String> raters;
// protected Set<Object> categories;
//
// protected AnnotationStudy()
// {
// raters = new ArrayList<String>();
// categories = new LinkedHashSet<Object>();
// }
//
// /**
// * Add a rater with the given name. Returns the index of the newly added rater which is required
// * to identify the rater in {@link IAnnotationUnit}. The first rater receives index 0. Note that
// * adding names for the raters is optional.
// */
// public int addRater(final String name)
// {
// raters.add(name);
// return (raters.size() - 1);
// }
//
// /** Find the index of the rater with the given name. */
// public int findRater(final String name)
// {
// return raters.indexOf(name);
// }
//
// @Override
// public int getRaterCount()
// {
// return raters.size();
// }
//
// /**
// * Adds the given category to the set of possible annotation labels. This method is only
// * required of a category has not been used by any rater of within the annotation study.
// *
// * @throws NullPointerException
// * if the specified category is null.
// */
// public void addCategory(final Object category)
// {
// categories.add(category);
// }
//
// @Override
// public Iterable<Object> getCategories()
// {
// return categories;
// }
//
// /*
// * public Object[] getCategoryArray() { Object[] result = null; int idx = 0; for (Object
// * category : getCategories()) { if (result == null) result = new Object[categories.size()];
// * result[idx++] = category; } return result; }
// */
//
// @Override
// public int getCategoryCount()
// {
// return categories.size();
// }
//
// @Override
// public boolean isDichotomous()
// {
// return (categories.size() == 2);
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/AnnotationUnit.java
// public class AnnotationUnit
// implements IAnnotationUnit
// {
// private static final long serialVersionUID = 4277733312128063453L;
//
// protected int raterIdx;
// protected Object category;
//
// /**
// * Initializes the annotation unit with the given category as the annotation by the rater with
// * the specified index.
// */
// public AnnotationUnit(int raterIdx, final Object category)
// {
// this.raterIdx = raterIdx;
// this.category = category;
// }
//
// @Override
// public int getRaterIdx()
// {
// return raterIdx;
// }
//
// @Override
// public Object getCategory()
// {
// return category;
// }
//
// @Override
// public String toString()
// {
// return raterIdx + "<" + category + ">";
// }
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CodingAnnotationStudy.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.AnnotationStudy;
import org.dkpro.statistics.agreement.AnnotationUnit;
import org.dkpro.statistics.agreement.IAnnotationUnit;
public ICodingAnnotationItem addItemAsArray(final Object[] annotations)
{
if (annotations.length != raters.size()) {
throw new IllegalArgumentException("Incorrect number of annotation units "
+ "(expected " + raters.size() + ", given " + annotations.length + "). "
+ "For array params, use #addItemsAsArray instead of #addItem.");
}
int itemIdx = items.size();
CodingAnnotationItem item = new CodingAnnotationItem(raters.size());
for (int raterIdx = 0; raterIdx < annotations.length; raterIdx++) {
item.addUnit(createUnit(itemIdx, raterIdx, annotations[raterIdx]));
}
items.add(item);
return item;
}
/**
* Shorthand for invoking {@link #addItem(Object...)} with the same parameters multiple times.
* This method is useful for modeling annotation data based on a contingency table.
*/
public void addMultipleItems(int times, final Object... values)
{
for (int i = 0; i < times; i++) {
addItemAsArray(values);
}
}
protected IAnnotationUnit createUnit(int index, int raterIdx, final Object category)
{ | IAnnotationUnit result = new AnnotationUnit(/* index, */raterIdx, category); |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/CachedDistanceFunction.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
| import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Wrapper class for arbitrary distance functions that caches the distance scores between two
* categories in a hash table. This is useful, if the calculation of a distance value is
* computationally complex, for instance, for set-valued categories as assumed by the
* {@link SetAnnotationDistanceFunction}.
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class CachedDistanceFunction
implements IDistanceFunction
{
protected Hashtable<String, Double> cache;
protected IDistanceFunction wrappee;
/** Instantiates the wrapper for the given distance function. */
public CachedDistanceFunction(final IDistanceFunction wrappee)
{
this.wrappee = wrappee;
cache = new Hashtable<String, Double>();
}
@Override | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationStudy.java
// public interface IAnnotationStudy
// extends Serializable
// {
//
// // -- Raters --
//
// /** Returns the number of raters participating in this study. */
// int getRaterCount();
//
// int findRater(final String name);
//
// // -- Categories --
//
// /**
// * Returns an iterator over all annotation categories within the study. Note that the categories
// * are not per se clear; they might need to be gathered by iterating through all associated
// * items, which yields performance problems in large-scale annotation studies.
// */
// Iterable<Object> getCategories();
//
// /**
// * Returns the number of annotation categories in the study. Note that the categories are not
// * per se clear; they might need to be gathered by iterating through all associated items, which
// * yields performance problems in large-scale annotation studies.
// */
// int getCategoryCount();
//
// /**
// * Returns true if, and only if, the categories defined by the study yield a dichotomy (i.e.,
// * there are exactly two categories).
// */
// boolean isDichotomous();
//
// // -- Units --
//
// // public Iterable<? extends IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters.
// */
// int getUnitCount();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/CachedDistanceFunction.java
import java.util.Hashtable;
import org.dkpro.statistics.agreement.IAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.distance;
/**
* Wrapper class for arbitrary distance functions that caches the distance scores between two
* categories in a hash table. This is useful, if the calculation of a distance value is
* computationally complex, for instance, for set-valued categories as assumed by the
* {@link SetAnnotationDistanceFunction}.
*
* @see IDistanceFunction
* @author Christian M. Meyer
*/
public class CachedDistanceFunction
implements IDistanceFunction
{
protected Hashtable<String, Double> cache;
protected IDistanceFunction wrappee;
/** Instantiates the wrapper for the given distance function. */
public CachedDistanceFunction(final IDistanceFunction wrappee)
{
this.wrappee = wrappee;
cache = new Hashtable<String, Double>();
}
@Override | public double measureDistance(final IAnnotationStudy study, final Object category1, |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/TwoRaterAgreementTest.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
| import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Iterator;
import org.dkpro.statistics.agreement.InsufficientDataException; | public void testCategorySpecificAgreement() {
ICodingAnnotationStudy study = createExample();
new ContingencyMatrixPrinter().print(System.out, study);
new CoincidenceMatrixPrinter().print(System.out, study);
PercentageAgreement pa = new PercentageAgreement(study);
assertEquals(4 / 7, pa.calculateCategoryAgreement("low"));
assertEquals(10 / 13, pa.calculateCategoryAgreement("high"));
}*/
public void testMissingCategories()
{
// Annotation categories not used by any rater must be added to
// the study explicitly in order to avoid an InsufficientDataException.
CodingAnnotationStudy study = new CodingAnnotationStudy(2);
study.addCategory("A");
study.addCategory("B");
study.addItem("A", "A");
study.addItem("A", "A");
study.addItem("A", "A");
PercentageAgreement pa = new PercentageAgreement(study);
assertEquals(1.0, pa.calculateAgreement());
BennettSAgreement s = new BennettSAgreement(study);
assertEquals(1.0, s.calculateObservedAgreement(), 0.001);
assertEquals(0.5, s.calculateExpectedAgreement(), 0.001);
assertEquals(1.0, s.calculateAgreement(), 0.001);
| // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/InsufficientDataException.java
// public class InsufficientDataException
// extends RuntimeException
// {
// private static final long serialVersionUID = -3081535421752493402L;
//
// public InsufficientDataException()
// {
// super();
// }
//
// public InsufficientDataException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
//
// public InsufficientDataException(final String message)
// {
// super(message);
// }
//
// public InsufficientDataException(final Throwable cause)
// {
// super(cause);
// }
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/TwoRaterAgreementTest.java
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Iterator;
import org.dkpro.statistics.agreement.InsufficientDataException;
public void testCategorySpecificAgreement() {
ICodingAnnotationStudy study = createExample();
new ContingencyMatrixPrinter().print(System.out, study);
new CoincidenceMatrixPrinter().print(System.out, study);
PercentageAgreement pa = new PercentageAgreement(study);
assertEquals(4 / 7, pa.calculateCategoryAgreement("low"));
assertEquals(10 / 13, pa.calculateCategoryAgreement("high"));
}*/
public void testMissingCategories()
{
// Annotation categories not used by any rater must be added to
// the study explicitly in order to avoid an InsufficientDataException.
CodingAnnotationStudy study = new CodingAnnotationStudy(2);
study.addCategory("A");
study.addCategory("B");
study.addItem("A", "A");
study.addItem("A", "A");
study.addItem("A", "A");
PercentageAgreement pa = new PercentageAgreement(study);
assertEquals(1.0, pa.calculateAgreement());
BennettSAgreement s = new BennettSAgreement(study);
assertEquals(1.0, s.calculateObservedAgreement(), 0.001);
assertEquals(0.5, s.calculateExpectedAgreement(), 0.001);
assertEquals(1.0, s.calculateAgreement(), 0.001);
| assertThatExceptionOfType(InsufficientDataException.class) |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/BennettSAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
| import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Bennett et al.'s S (1954) for calculating a chance-corrected inter-rater
* agreement for two raters. The measure assumes a uniform probability distribution for all raters
* and categories. The measure is equivalent to Janson and Vegelius's (1979) C and Brennan and
* Prediger's (1981) kappa_n.<br>
* <br>
* References:
* <ul>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* <li>Bennett, E.M.; Alpert, R. & Goldstein, A.C.: Communications through limited response
* questioning. Public Opinion Quarterly 18(3):303-308, 1954.</li>
* <li>Brennan, R.L. & Prediger, D.: Coefficient kappa: Some uses, misuses, and alternatives.
* Educational and Psychological Measurement 41(3):687-699, 1981.</li>
* <li>Janson, S. & Vegelius, J.: On generalizations of the G index and the phi coefficient to
* nominal scales. Multivariate Behavioral Research 14(2):255-269, 1979.</li>
* </ul>
*
* @author Christian M. Meyer
*/
// TODO: Check correspondence to Guilford's (1961; Holley & Guilford, 1964)
// G index; and Maxwell's (1977) random error (RE) coefficient - Zwick88
public class BennettSAgreement
extends CodingAgreementMeasure | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
// extends IAgreementMeasure
// {
// /**
// * Returns the observed agreement of an annotation study. The observed agreement is basically
// * the proportion of annotation units that the raters agree on divided by the number of units in
// * the given study.
// */
// public double calculateObservedAgreement();
//
// /**
// * Returns the expected agreement of an annotation study. The expected agreement is the
// * proportion of agreement that would be expected by chance alone. The expected agreement should
// * be equal to the observed agreement if each rater makes a random decision for each unit.
// */
// public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/BennettSAgreement.java
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of Bennett et al.'s S (1954) for calculating a chance-corrected inter-rater
* agreement for two raters. The measure assumes a uniform probability distribution for all raters
* and categories. The measure is equivalent to Janson and Vegelius's (1979) C and Brennan and
* Prediger's (1981) kappa_n.<br>
* <br>
* References:
* <ul>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* <li>Bennett, E.M.; Alpert, R. & Goldstein, A.C.: Communications through limited response
* questioning. Public Opinion Quarterly 18(3):303-308, 1954.</li>
* <li>Brennan, R.L. & Prediger, D.: Coefficient kappa: Some uses, misuses, and alternatives.
* Educational and Psychological Measurement 41(3):687-699, 1981.</li>
* <li>Janson, S. & Vegelius, J.: On generalizations of the G index and the phi coefficient to
* nominal scales. Multivariate Behavioral Research 14(2):255-269, 1979.</li>
* </ul>
*
* @author Christian M. Meyer
*/
// TODO: Check correspondence to Guilford's (1961; Holley & Guilford, 1964)
// G index; and Maxwell's (1977) random error (RE) coefficient - Zwick88
public class BennettSAgreement
extends CodingAgreementMeasure | implements IChanceCorrectedAgreement |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ReliabilityMatrixPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
| import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a reliability matrix as defined by
* Krippendorff (1980: p. 136). That is, a table showing one annotation
* item per column and the categories assigned to them by a certain
* rater. In addition to that, the reliability matrix sums the number
* of units with identical categories. For the example by Krippendorff
* (1980: p. 139), the implementation displays:
* <pre>
* 1 2 3 4 5 6 7 8 9 Σ
* 1 1 1 2 4 1 2 1 3 2
* 2 1 2 2 4 4 2 2 3 2
* 3 1 2 2 4 4 2 3 3 2
*
* 1 3 1 1 1 6
* 2 2 3 3 1 3 12
* 3 1 3 4
* 4 3 2 5
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ReliabilityMatrixPrinter
{
/** Print the reliability matrix for the given coding study. */ | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ReliabilityMatrixPrinter.java
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a reliability matrix as defined by
* Krippendorff (1980: p. 136). That is, a table showing one annotation
* item per column and the categories assigned to them by a certain
* rater. In addition to that, the reliability matrix sums the number
* of units with identical categories. For the example by Krippendorff
* (1980: p. 139), the implementation displays:
* <pre>
* 1 2 3 4 5 6 7 8 9 Σ
* 1 1 1 2 4 1 2 1 3 2
* 2 1 2 2 4 4 2 2 3 2
* 3 1 2 2 4 4 2 3 3 2
*
* 1 3 1 1 1 6
* 2 2 3 3 1 3 12
* 3 1 3 4
* 4 3 2 5
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ReliabilityMatrixPrinter
{
/** Print the reliability matrix for the given coding study. */ | public void print(final PrintStream out, final ICodingAnnotationStudy study) |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ReliabilityMatrixPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
| import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a reliability matrix as defined by
* Krippendorff (1980: p. 136). That is, a table showing one annotation
* item per column and the categories assigned to them by a certain
* rater. In addition to that, the reliability matrix sums the number
* of units with identical categories. For the example by Krippendorff
* (1980: p. 139), the implementation displays:
* <pre>
* 1 2 3 4 5 6 7 8 9 Σ
* 1 1 1 2 4 1 2 1 3 2
* 2 1 2 2 4 4 2 2 3 2
* 3 1 2 2 4 4 2 3 3 2
*
* 1 3 1 1 1 6
* 2 2 3 3 1 3 12
* 3 1 3 4
* 4 3 2 5
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ReliabilityMatrixPrinter
{
/** Print the reliability matrix for the given coding study. */
public void print(final PrintStream out, final ICodingAnnotationStudy study)
{
// TODO: measure length of cats. maybe cut them.
Map<Object, Integer> categories = new LinkedHashMap<Object, Integer>();
for (Object cat : study.getCategories()) {
categories.put(cat, categories.size());
}
final String DIVIDER = "\t";
for (int i = 0; i < study.getItemCount(); i++) {
out.print(DIVIDER + (i + 1));
}
out.print(DIVIDER + "Σ");
out.println();
for (int r = 0; r < study.getRaterCount(); r++) {
out.print(r + 1); | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ReliabilityMatrixPrinter.java
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a reliability matrix as defined by
* Krippendorff (1980: p. 136). That is, a table showing one annotation
* item per column and the categories assigned to them by a certain
* rater. In addition to that, the reliability matrix sums the number
* of units with identical categories. For the example by Krippendorff
* (1980: p. 139), the implementation displays:
* <pre>
* 1 2 3 4 5 6 7 8 9 Σ
* 1 1 1 2 4 1 2 1 3 2
* 2 1 2 2 4 4 2 2 3 2
* 3 1 2 2 4 4 2 3 3 2
*
* 1 3 1 1 1 6
* 2 2 3 3 1 3 12
* 3 1 3 4
* 4 3 2 5
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ReliabilityMatrixPrinter
{
/** Print the reliability matrix for the given coding study. */
public void print(final PrintStream out, final ICodingAnnotationStudy study)
{
// TODO: measure length of cats. maybe cut them.
Map<Object, Integer> categories = new LinkedHashMap<Object, Integer>();
for (Object cat : study.getCategories()) {
categories.put(cat, categories.size());
}
final String DIVIDER = "\t";
for (int i = 0; i < study.getItemCount(); i++) {
out.print(DIVIDER + (i + 1));
}
out.print(DIVIDER + "Σ");
out.println();
for (int r = 0; r < study.getRaterCount(); r++) {
out.print(r + 1); | for (ICodingAnnotationItem item : study.getItems()) { |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ReliabilityMatrixPrinter.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
| import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a reliability matrix as defined by
* Krippendorff (1980: p. 136). That is, a table showing one annotation
* item per column and the categories assigned to them by a certain
* rater. In addition to that, the reliability matrix sums the number
* of units with identical categories. For the example by Krippendorff
* (1980: p. 139), the implementation displays:
* <pre>
* 1 2 3 4 5 6 7 8 9 Σ
* 1 1 1 2 4 1 2 1 3 2
* 2 1 2 2 4 4 2 2 3 2
* 3 1 2 2 4 4 2 3 3 2
*
* 1 3 1 1 1 6
* 2 2 3 3 1 3 12
* 3 1 3 4
* 4 3 2 5
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ReliabilityMatrixPrinter
{
/** Print the reliability matrix for the given coding study. */
public void print(final PrintStream out, final ICodingAnnotationStudy study)
{
// TODO: measure length of cats. maybe cut them.
Map<Object, Integer> categories = new LinkedHashMap<Object, Integer>();
for (Object cat : study.getCategories()) {
categories.put(cat, categories.size());
}
final String DIVIDER = "\t";
for (int i = 0; i < study.getItemCount(); i++) {
out.print(DIVIDER + (i + 1));
}
out.print(DIVIDER + "Σ");
out.println();
for (int r = 0; r < study.getRaterCount(); r++) {
out.print(r + 1);
for (ICodingAnnotationItem item : study.getItems()) {
out.print(DIVIDER + item.getUnit(r).getCategory());
}
out.println();
}
out.println();
for (Object category : study.getCategories()) {
out.print(category);
int catSum = 0;
for (ICodingAnnotationItem item : study.getItems()) {
int catCount = 0; | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
// public interface ICodingAnnotationItem
// extends IAnnotationItem
// {
// /**
// * Returns the annotation unit of the rater with the specified index. That is, the object
// * holding the category assigned to the item by the specified rater.
// */
// public IAnnotationUnit getUnit(int raterIdx);
//
// /**
// * Returns all coding units for this annotation item (i.e., the categories assigned by the
// * individual raters).
// */
// public Iterable<IAnnotationUnit> getUnits();
//
// /**
// * Returns the number of raters who annotated this item with a non-null category.
// */
// public int getRaterCount();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationStudy.java
// public interface ICodingAnnotationStudy
// extends IAnnotationStudy
// {
//
// // -- Categories --
//
// /**
// * Returns true if, and only if, the annotation study contains at least one item with a missing
// * value (i.e., an annotation item containing an annotation unit with category null).
// */
// public boolean hasMissingValues();
//
// // -- Items --
//
// /**
// * Returns the annotation item with the given index. The first item has index 0.
// */
// public ICodingAnnotationItem getItem(int index);
//
// /** Allows iterating all annotation items of this study. */
// public Iterable<ICodingAnnotationItem> getItems();
//
// /** Returns the number of annotation items defined by the study. */
// public int getItemCount();
//
// // -- Units --
//
// /**
// * Returns the number of annotation units defined by the study. That is, the number of
// * annotations coded by the raters. If there are no missing values, the unit count equals the
// * item count multiplied with the number of raters.
// */
// @Override
// public int getUnitCount();
//
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/ReliabilityMatrixPrinter.java
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationItem;
import org.dkpro.statistics.agreement.coding.ICodingAnnotationStudy;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.visualization;
/**
* Plain-text visualization for a reliability matrix as defined by
* Krippendorff (1980: p. 136). That is, a table showing one annotation
* item per column and the categories assigned to them by a certain
* rater. In addition to that, the reliability matrix sums the number
* of units with identical categories. For the example by Krippendorff
* (1980: p. 139), the implementation displays:
* <pre>
* 1 2 3 4 5 6 7 8 9 Σ
* 1 1 1 2 4 1 2 1 3 2
* 2 1 2 2 4 4 2 2 3 2
* 3 1 2 2 4 4 2 3 3 2
*
* 1 3 1 1 1 6
* 2 2 3 3 1 3 12
* 3 1 3 4
* 4 3 2 5
* </pre><br>
* References:<ul>
* <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology.
* Beverly Hills, CA: Sage Publications, 1980.</li></ul>
* @see ICodingAnnotationStudy
* @author Christian M. Meyer
*/
public class ReliabilityMatrixPrinter
{
/** Print the reliability matrix for the given coding study. */
public void print(final PrintStream out, final ICodingAnnotationStudy study)
{
// TODO: measure length of cats. maybe cut them.
Map<Object, Integer> categories = new LinkedHashMap<Object, Integer>();
for (Object cat : study.getCategories()) {
categories.put(cat, categories.size());
}
final String DIVIDER = "\t";
for (int i = 0; i < study.getItemCount(); i++) {
out.print(DIVIDER + (i + 1));
}
out.print(DIVIDER + "Σ");
out.println();
for (int r = 0; r < study.getRaterCount(); r++) {
out.print(r + 1);
for (ICodingAnnotationItem item : study.getItems()) {
out.print(DIVIDER + item.getUnit(r).getCategory());
}
out.println();
}
out.println();
for (Object category : study.getCategories()) {
out.print(category);
int catSum = 0;
for (ICodingAnnotationItem item : study.getItems()) {
int catCount = 0; | for (IAnnotationUnit unit : item.getUnits()) { |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/PercentageAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
| import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a simple percentage of agreement measure for calculating the inter-rater
* agreement for two or more raters. The measure is neither chance-corrected nor weighted.<br>
* <br>
* References:
* <ul>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
// TODO: Holsti.
public class PercentageAgreement
extends CodingAgreementMeasure | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/PercentageAgreement.java
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a simple percentage of agreement measure for calculating the inter-rater
* agreement for two or more raters. The measure is neither chance-corrected nor weighted.<br>
* <br>
* References:
* <ul>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
// TODO: Holsti.
public class PercentageAgreement
extends CodingAgreementMeasure | implements ICodingItemSpecificAgreement, ICategorySpecificAgreement |
dkpro/dkpro-statistics | dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/PercentageAgreement.java | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
| import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement; | /*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a simple percentage of agreement measure for calculating the inter-rater
* agreement for two or more raters. The measure is neither chance-corrected nor weighted.<br>
* <br>
* References:
* <ul>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
// TODO: Holsti.
public class PercentageAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement, ICategorySpecificAgreement
/* , IRaterAgreement */ {
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public PercentageAgreement(final ICodingAnnotationStudy study)
{
super(study);
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double calculateItemAgreement(final ICodingAnnotationItem item)
{
return doCalculateItemAgreement(item) / item.getRaterCount();
}
/**
* Calculates the inter-rater agreement for the given annotation category based on the object's
* annotation study that has been passed to the class constructor.
*
* @throws NullPointerException
* if the study is null or the given category is null.
* @throws ArrayIndexOutOfBoundsException
* if the study does not contain the given category.
* @throws ArithmeticException
* if the study does not contain annotations for the given category.
*/
/*
* public double calculateAgreement(final Object category) { // This is positive and negative
* agreement (Feinstein90) int agreements = 0; int annotations = 0; for (IAnnotationItem item :
* study.getItems()) { if (category.equals(item.getAnnotation(0)) &&
* category.equals(item.getAnnotation(1))) agreements++; if
* (category.equals(item.getAnnotation(0))) annotations++; if
* (category.equals(item.getAnnotation(1))) annotations++; } return (2 * agreements) / (double)
* annotations; }
*/
@Override
public double calculateCategoryAgreement(final Object category)
{
double result = 0;
for (ICodingAnnotationItem item : study.getItems()) {
int catCount = 0;
int otherCatCount = 0; | // Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
// extends Serializable
// {
// /**
// * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
// * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
// */
// public int getRaterIdx();
//
// /**
// * Returns the category assigned to this unit by one of the raters. The category might be null
// * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
// * case of a unitizing study).
// */
// public Object getCategory();
// }
//
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
// /**
// * Calculates the inter-rater agreement for the given category.
// *
// * @see ICategorySpecificAgreement
// */
// /*
// * TODO @throws NullPointerException if the study is null or the given category is null.
// *
// * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
// *
// * @throws ArithmeticException if the study does not contain annotations for the given category.
// */
// public double calculateCategoryAgreement(final Object category);
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/PercentageAgreement.java
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
/*
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.statistics.agreement.coding;
/**
* Implementation of a simple percentage of agreement measure for calculating the inter-rater
* agreement for two or more raters. The measure is neither chance-corrected nor weighted.<br>
* <br>
* References:
* <ul>
* <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
* Computational Linguistics 34(4):555-596, 2008.</li>
* </ul>
*
* @author Christian M. Meyer
*/
// TODO: Holsti.
public class PercentageAgreement
extends CodingAgreementMeasure
implements ICodingItemSpecificAgreement, ICategorySpecificAgreement
/* , IRaterAgreement */ {
/**
* Initializes the instance for the given annotation study. The study should never be null.
*/
public PercentageAgreement(final ICodingAnnotationStudy study)
{
super(study);
}
/**
* Calculates the inter-rater agreement for the given annotation item. This is the basic step
* that is performed for each item of an annotation study, when calling
* {@link #calculateAgreement()}.
*
* @throws NullPointerException
* if the given item is null.
*/
@Override
public double calculateItemAgreement(final ICodingAnnotationItem item)
{
return doCalculateItemAgreement(item) / item.getRaterCount();
}
/**
* Calculates the inter-rater agreement for the given annotation category based on the object's
* annotation study that has been passed to the class constructor.
*
* @throws NullPointerException
* if the study is null or the given category is null.
* @throws ArrayIndexOutOfBoundsException
* if the study does not contain the given category.
* @throws ArithmeticException
* if the study does not contain annotations for the given category.
*/
/*
* public double calculateAgreement(final Object category) { // This is positive and negative
* agreement (Feinstein90) int agreements = 0; int annotations = 0; for (IAnnotationItem item :
* study.getItems()) { if (category.equals(item.getAnnotation(0)) &&
* category.equals(item.getAnnotation(1))) agreements++; if
* (category.equals(item.getAnnotation(0))) annotations++; if
* (category.equals(item.getAnnotation(1))) annotations++; } return (2 * agreements) / (double)
* annotations; }
*/
@Override
public double calculateCategoryAgreement(final Object category)
{
double result = 0;
for (ICodingAnnotationItem item : study.getItems()) {
int catCount = 0;
int otherCatCount = 0; | for (IAnnotationUnit annotation : item.getUnits()) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.