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 |
|---|---|---|---|---|---|---|
tfredrich/Domain-Eventing | core/test/java/com/strategicgains/eventing/local/LocalEventBusTest.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler; | public void kerBlooey()
{
// do nothing.
}
}
private class ErroredEvent
extends HandledEvent
{
private int occurrences = 0;
@Override
public void kerBlooey()
{
if (occurrences++ < 5)
{
throw new RuntimeException("KER-BLOOEY!");
}
}
}
private class IgnoredEvent
{
}
private class LongEvent
{
}
private static class DomainEventsTestHandler | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: core/test/java/com/strategicgains/eventing/local/LocalEventBusTest.java
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler;
public void kerBlooey()
{
// do nothing.
}
}
private class ErroredEvent
extends HandledEvent
{
private int occurrences = 0;
@Override
public void kerBlooey()
{
if (occurrences++ < 5)
{
throw new RuntimeException("KER-BLOOEY!");
}
}
}
private class IgnoredEvent
{
}
private class LongEvent
{
}
private static class DomainEventsTestHandler | implements EventHandler |
tfredrich/Domain-Eventing | kafka/src/main/java/com/strategicgains/eventing/kafka/KafkaEventBusBuilder.java | // Path: core/src/java/com/strategicgains/eventing/EventBusBuilder.java
// public interface EventBusBuilder<T extends EventBus, B>
// {
// public B subscribe(EventHandler handler);
// public B unsubscribe(EventHandler handler);
// public T build();
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import com.strategicgains.eventing.EventBusBuilder;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2016, Ping Identity Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.kafka;
/**
* @author tfredrich
* @since 20 May 2016
*/
public class KafkaEventBusBuilder
implements EventBusBuilder<KafkaEventBus, KafkaEventBusBuilder>
{
@Override | // Path: core/src/java/com/strategicgains/eventing/EventBusBuilder.java
// public interface EventBusBuilder<T extends EventBus, B>
// {
// public B subscribe(EventHandler handler);
// public B unsubscribe(EventHandler handler);
// public T build();
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: kafka/src/main/java/com/strategicgains/eventing/kafka/KafkaEventBusBuilder.java
import com.strategicgains.eventing.EventBusBuilder;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2016, Ping Identity Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.kafka;
/**
* @author tfredrich
* @since 20 May 2016
*/
public class KafkaEventBusBuilder
implements EventBusBuilder<KafkaEventBus, KafkaEventBusBuilder>
{
@Override | public KafkaEventBusBuilder subscribe(EventHandler handler) |
tfredrich/Domain-Eventing | akka/src/test/java/com/strategicgains/eventing/akka/AkkaEventBusBuilderTest.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler; | {
assertEquals(0, handler.getCallCount());
queue.publish(new ErroredEvent());
Thread.sleep(50);
assertEquals(1, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
@Test
public void shouldProcessInParallel()
throws Exception
{
assertEquals(0, longHandler.getCallCount());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
Thread.sleep(50);
assertEquals(0, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
// System.out.println("longHandler instance=" + longHandler.toString());
assertEquals(5, longHandler.getCallCount());
}
// SECTION: INNER CLASSES
private static class DomainEventsTestHandler | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: akka/src/test/java/com/strategicgains/eventing/akka/AkkaEventBusBuilderTest.java
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler;
{
assertEquals(0, handler.getCallCount());
queue.publish(new ErroredEvent());
Thread.sleep(50);
assertEquals(1, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
@Test
public void shouldProcessInParallel()
throws Exception
{
assertEquals(0, longHandler.getCallCount());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
Thread.sleep(50);
assertEquals(0, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
// System.out.println("longHandler instance=" + longHandler.toString());
assertEquals(5, longHandler.getCallCount());
}
// SECTION: INNER CLASSES
private static class DomainEventsTestHandler | implements EventHandler |
tfredrich/Domain-Eventing | core/test/java/com/strategicgains/eventing/local/LocalEventBusBuilderTest.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler; | public void kerBlooey()
{
// do nothing.
}
}
private class ErroredEvent
extends HandledEvent
{
private int occurrences = 0;
@Override
public void kerBlooey()
{
if (occurrences++ < 5)
{
throw new RuntimeException("KER-BLOOEY!");
}
}
}
private class IgnoredEvent
{
}
private class LongEvent
{
}
private static class DomainEventsTestHandler | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: core/test/java/com/strategicgains/eventing/local/LocalEventBusBuilderTest.java
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler;
public void kerBlooey()
{
// do nothing.
}
}
private class ErroredEvent
extends HandledEvent
{
private int occurrences = 0;
@Override
public void kerBlooey()
{
if (occurrences++ < 5)
{
throw new RuntimeException("KER-BLOOEY!");
}
}
}
private class IgnoredEvent
{
}
private class LongEvent
{
}
private static class DomainEventsTestHandler | implements EventHandler |
tfredrich/Domain-Eventing | akka/src/main/java/com/strategicgains/eventing/akka/AkkaEventBusBuilder.java | // Path: core/src/java/com/strategicgains/eventing/EventBusBuilder.java
// public interface EventBusBuilder<T extends EventBus, B>
// {
// public B subscribe(EventHandler handler);
// public B unsubscribe(EventHandler handler);
// public T build();
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import akka.actor.ActorSystem;
import com.strategicgains.eventing.EventBusBuilder;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2015, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.akka;
/**
* @author tfredrich
* @since Jul 13, 2015
*/
public class AkkaEventBusBuilder
implements EventBusBuilder<AkkaEventBus, AkkaEventBusBuilder>
{
private ActorSystem actorSystem; | // Path: core/src/java/com/strategicgains/eventing/EventBusBuilder.java
// public interface EventBusBuilder<T extends EventBus, B>
// {
// public B subscribe(EventHandler handler);
// public B unsubscribe(EventHandler handler);
// public T build();
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: akka/src/main/java/com/strategicgains/eventing/akka/AkkaEventBusBuilder.java
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import akka.actor.ActorSystem;
import com.strategicgains.eventing.EventBusBuilder;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2015, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.akka;
/**
* @author tfredrich
* @since Jul 13, 2015
*/
public class AkkaEventBusBuilder
implements EventBusBuilder<AkkaEventBus, AkkaEventBusBuilder>
{
private ActorSystem actorSystem; | private Set<EventHandler> subscribers = new LinkedHashSet<EventHandler>(); |
tfredrich/Domain-Eventing | akka/src/test/java/com/strategicgains/eventing/akka/AkkaEventBusTest.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler; | }
@Test
public void shouldOnlyPublishSelected()
throws Exception
{
queue.addPublishableEventType(HandledEvent.class);
assertEquals(0, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
Thread.sleep(PAUSE_MILLIS);
assertEquals(5, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
// SECTION: INNER CLASSES
private static class DomainEventsTestHandler | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: akka/src/test/java/com/strategicgains/eventing/akka/AkkaEventBusTest.java
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler;
}
@Test
public void shouldOnlyPublishSelected()
throws Exception
{
queue.addPublishableEventType(HandledEvent.class);
assertEquals(0, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
Thread.sleep(PAUSE_MILLIS);
assertEquals(5, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
// SECTION: INNER CLASSES
private static class DomainEventsTestHandler | implements EventHandler |
tfredrich/Domain-Eventing | core/src/java/com/strategicgains/eventing/local/LocalEventTransport.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventTransport.java
// public interface EventTransport
// {
// public void publish(Object event);
// public boolean subscribe(EventHandler handler);
// public boolean unsubscribe(EventHandler handler);
// public void shutdown();
// }
| import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.strategicgains.eventing.EventHandler;
import com.strategicgains.eventing.EventTransport; | /*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.local;
/**
* @author toddf
* @since Oct 18, 2012
*/
public class LocalEventTransport
implements EventTransport
{
private Queue<Object> queue = new ConcurrentLinkedQueue<Object>();
private EventMonitor monitor;
| // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventTransport.java
// public interface EventTransport
// {
// public void publish(Object event);
// public boolean subscribe(EventHandler handler);
// public boolean unsubscribe(EventHandler handler);
// public void shutdown();
// }
// Path: core/src/java/com/strategicgains/eventing/local/LocalEventTransport.java
import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.strategicgains.eventing.EventHandler;
import com.strategicgains.eventing.EventTransport;
/*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.local;
/**
* @author toddf
* @since Oct 18, 2012
*/
public class LocalEventTransport
implements EventTransport
{
private Queue<Object> queue = new ConcurrentLinkedQueue<Object>();
private EventMonitor monitor;
| public LocalEventTransport(Collection<EventHandler> handlers, boolean shouldReraiseOnError, long pollDelayMillis) |
tfredrich/Domain-Eventing | akka/src/main/java/com/strategicgains/eventing/akka/AkkaEventTransport.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventTransport.java
// public interface EventTransport
// {
// public void publish(Object event);
// public boolean subscribe(EventHandler handler);
// public boolean unsubscribe(EventHandler handler);
// public void shutdown();
// }
| import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.event.japi.ScanningEventBus;
import com.strategicgains.eventing.EventHandler;
import com.strategicgains.eventing.EventTransport; | /*
Copyright 2015, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.akka;
/**
* @author toddf
* @since Jul 13, 2015
*/
public class AkkaEventTransport
implements EventTransport
{
private ActorSystem system; | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventTransport.java
// public interface EventTransport
// {
// public void publish(Object event);
// public boolean subscribe(EventHandler handler);
// public boolean unsubscribe(EventHandler handler);
// public void shutdown();
// }
// Path: akka/src/main/java/com/strategicgains/eventing/akka/AkkaEventTransport.java
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.event.japi.ScanningEventBus;
import com.strategicgains.eventing.EventHandler;
import com.strategicgains.eventing.EventTransport;
/*
Copyright 2015, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.akka;
/**
* @author toddf
* @since Jul 13, 2015
*/
public class AkkaEventTransport
implements EventTransport
{
private ActorSystem system; | private Map<EventHandler, ActorRef> subscribers = new ConcurrentHashMap<EventHandler, ActorRef>(); |
tfredrich/Domain-Eventing | core/src/java/com/strategicgains/eventing/local/LocalEventBusBuilder.java | // Path: core/src/java/com/strategicgains/eventing/EventBusBuilder.java
// public interface EventBusBuilder<T extends EventBus, B>
// {
// public B subscribe(EventHandler handler);
// public B unsubscribe(EventHandler handler);
// public T build();
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import com.strategicgains.eventing.EventBusBuilder;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.local;
/**
* Configure and build a local EventQueue that receives events only within the current JVM.
*
* @author toddf
* @since Oct 4, 2012
*/
public class LocalEventBusBuilder
implements EventBusBuilder<LocalEventBus, LocalEventBusBuilder>
{
private static final long DEFAULT_POLL_DELAY = 0L;
| // Path: core/src/java/com/strategicgains/eventing/EventBusBuilder.java
// public interface EventBusBuilder<T extends EventBus, B>
// {
// public B subscribe(EventHandler handler);
// public B unsubscribe(EventHandler handler);
// public T build();
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: core/src/java/com/strategicgains/eventing/local/LocalEventBusBuilder.java
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import com.strategicgains.eventing.EventBusBuilder;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.local;
/**
* Configure and build a local EventQueue that receives events only within the current JVM.
*
* @author toddf
* @since Oct 4, 2012
*/
public class LocalEventBusBuilder
implements EventBusBuilder<LocalEventBus, LocalEventBusBuilder>
{
private static final long DEFAULT_POLL_DELAY = 0L;
| private Set<EventHandler> subscribers = new LinkedHashSet<EventHandler>(); |
tfredrich/Domain-Eventing | hazelcast/src/java/com/strategicgains/eventing/hazelcast/HazelcastEventTransport.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventTransport.java
// public interface EventTransport
// {
// public void publish(Object event);
// public boolean subscribe(EventHandler handler);
// public boolean unsubscribe(EventHandler handler);
// public void shutdown();
// }
| import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.hazelcast.core.ITopic;
import com.strategicgains.eventing.EventHandler;
import com.strategicgains.eventing.EventTransport; | /*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.hazelcast;
/**
* @author toddf
* @since Oct 18, 2012
*/
public class HazelcastEventTransport
implements EventTransport
{
private ITopic<Object> topic; | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventTransport.java
// public interface EventTransport
// {
// public void publish(Object event);
// public boolean subscribe(EventHandler handler);
// public boolean unsubscribe(EventHandler handler);
// public void shutdown();
// }
// Path: hazelcast/src/java/com/strategicgains/eventing/hazelcast/HazelcastEventTransport.java
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.hazelcast.core.ITopic;
import com.strategicgains.eventing.EventHandler;
import com.strategicgains.eventing.EventTransport;
/*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.hazelcast;
/**
* @author toddf
* @since Oct 18, 2012
*/
public class HazelcastEventTransport
implements EventTransport
{
private ITopic<Object> topic; | private Map<EventHandler, String> subscriptions = new ConcurrentHashMap<EventHandler, String>(); |
pantsbuild/jarjar | src/main/java/org/pantsbuild/jarjar/MainProcessor.java | // Path: src/main/java/org/pantsbuild/jarjar/misplaced/MisplacedClassProcessorFactory.java
// public class MisplacedClassProcessorFactory {
//
// public enum Strategy {
// /** Strategy which fails-fast with an exception upon hitting misplaced class. */
// FATAL,
//
// /** Strategy which skips past misplaced classes, excluding them from shading. */
// SKIP,
//
// /** Strategy which omits misplaced classes from the output. */
// OMIT,
//
// /**
// * Strategy which renames misplaced classes to their "proper" location based on their
// * fully-qualified class name.
// */
// MOVE,
// };
//
// private static MisplacedClassProcessorFactory me;
//
// public static synchronized MisplacedClassProcessorFactory getInstance() {
// if (me == null) {
// me = new MisplacedClassProcessorFactory();
// }
// return me;
// }
//
// private MisplacedClassProcessorFactory() {}
//
// /**
// * Returns the default misplaced class processor, which is "omit".
// */
// public MisplacedClassProcessor getDefaultProcessor() {
// return new OmitMisplacedClassProcessor();
// }
//
// /**
// * Creates a MisplacedClassProcessor according for the given strategy name.
// *
// * @param name The case-insensitive user-level strategy name (see the STRATEGY_* constants).
// * @return The MisplacedClassProcessor corresponding to the strategy name, or the result of
// * getDefaultProcessor() if name is null.
// * @throws IllegalArgumentException if an unrecognized non-null strategy name is specified.
// */
// public MisplacedClassProcessor getProcessorForName(String name) {
// if (name == null) {
// return getDefaultProcessor();
// }
//
// switch (Strategy.valueOf(name.toUpperCase())) {
// case FATAL: return new FatalMisplacedClassProcessor();
// case MOVE: return new MoveMisplacedClassProcessor();
// case OMIT: return new OmitMisplacedClassProcessor();
// case SKIP: return new SkipMisplacedClassProcessor();
// }
//
// throw new IllegalArgumentException("Unrecognized strategy name \"" + name + "\".");
// }
//
// }
| import org.pantsbuild.jarjar.misplaced.MisplacedClassProcessorFactory;
import org.pantsbuild.jarjar.util.*;
import java.io.File;
import java.io.IOException;
import java.util.*; | * @param verbose Whether to verbosely log information.
* @param skipManifest If true, omits the manifest file from the processed jar.
* @param misplacedClassStrategy The strategy to use when processing class files that are in the
* wrong package (see MisplacedClassProcessorFactory.STRATEGY_* constants).
*/
public MainProcessor(List<PatternElement> patterns, boolean verbose, boolean skipManifest,
String misplacedClassStrategy) {
this.verbose = verbose;
List<Zap> zapList = new ArrayList<Zap>();
List<Rule> ruleList = new ArrayList<Rule>();
List<Keep> keepList = new ArrayList<Keep>();
for (PatternElement pattern : patterns) {
if (pattern instanceof Zap) {
zapList.add((Zap) pattern);
} else if (pattern instanceof Rule) {
ruleList.add((Rule) pattern);
} else if (pattern instanceof Keep) {
keepList.add((Keep) pattern);
}
}
PackageRemapper pr = new PackageRemapper(ruleList, verbose);
kp = keepList.isEmpty() ? null : new KeepProcessor(keepList);
List<JarProcessor> processors = new ArrayList<JarProcessor>();
if (skipManifest)
processors.add(ManifestProcessor.getInstance());
if (kp != null)
processors.add(kp);
| // Path: src/main/java/org/pantsbuild/jarjar/misplaced/MisplacedClassProcessorFactory.java
// public class MisplacedClassProcessorFactory {
//
// public enum Strategy {
// /** Strategy which fails-fast with an exception upon hitting misplaced class. */
// FATAL,
//
// /** Strategy which skips past misplaced classes, excluding them from shading. */
// SKIP,
//
// /** Strategy which omits misplaced classes from the output. */
// OMIT,
//
// /**
// * Strategy which renames misplaced classes to their "proper" location based on their
// * fully-qualified class name.
// */
// MOVE,
// };
//
// private static MisplacedClassProcessorFactory me;
//
// public static synchronized MisplacedClassProcessorFactory getInstance() {
// if (me == null) {
// me = new MisplacedClassProcessorFactory();
// }
// return me;
// }
//
// private MisplacedClassProcessorFactory() {}
//
// /**
// * Returns the default misplaced class processor, which is "omit".
// */
// public MisplacedClassProcessor getDefaultProcessor() {
// return new OmitMisplacedClassProcessor();
// }
//
// /**
// * Creates a MisplacedClassProcessor according for the given strategy name.
// *
// * @param name The case-insensitive user-level strategy name (see the STRATEGY_* constants).
// * @return The MisplacedClassProcessor corresponding to the strategy name, or the result of
// * getDefaultProcessor() if name is null.
// * @throws IllegalArgumentException if an unrecognized non-null strategy name is specified.
// */
// public MisplacedClassProcessor getProcessorForName(String name) {
// if (name == null) {
// return getDefaultProcessor();
// }
//
// switch (Strategy.valueOf(name.toUpperCase())) {
// case FATAL: return new FatalMisplacedClassProcessor();
// case MOVE: return new MoveMisplacedClassProcessor();
// case OMIT: return new OmitMisplacedClassProcessor();
// case SKIP: return new SkipMisplacedClassProcessor();
// }
//
// throw new IllegalArgumentException("Unrecognized strategy name \"" + name + "\".");
// }
//
// }
// Path: src/main/java/org/pantsbuild/jarjar/MainProcessor.java
import org.pantsbuild.jarjar.misplaced.MisplacedClassProcessorFactory;
import org.pantsbuild.jarjar.util.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
* @param verbose Whether to verbosely log information.
* @param skipManifest If true, omits the manifest file from the processed jar.
* @param misplacedClassStrategy The strategy to use when processing class files that are in the
* wrong package (see MisplacedClassProcessorFactory.STRATEGY_* constants).
*/
public MainProcessor(List<PatternElement> patterns, boolean verbose, boolean skipManifest,
String misplacedClassStrategy) {
this.verbose = verbose;
List<Zap> zapList = new ArrayList<Zap>();
List<Rule> ruleList = new ArrayList<Rule>();
List<Keep> keepList = new ArrayList<Keep>();
for (PatternElement pattern : patterns) {
if (pattern instanceof Zap) {
zapList.add((Zap) pattern);
} else if (pattern instanceof Rule) {
ruleList.add((Rule) pattern);
} else if (pattern instanceof Keep) {
keepList.add((Keep) pattern);
}
}
PackageRemapper pr = new PackageRemapper(ruleList, verbose);
kp = keepList.isEmpty() ? null : new KeepProcessor(keepList);
List<JarProcessor> processors = new ArrayList<JarProcessor>();
if (skipManifest)
processors.add(ManifestProcessor.getInstance());
if (kp != null)
processors.add(kp);
| JarProcessor misplacedClassProcessor = MisplacedClassProcessorFactory.getInstance() |
pantsbuild/jarjar | src/test/java/org/pantsbuild/jarjar/GenericsTest.java | // Path: src/main/java/org/pantsbuild/jarjar/util/RemappingClassTransformer.java
// public class RemappingClassTransformer extends ClassRemapper
// {
// public RemappingClassTransformer(Remapper pr) {
// super(new EmptyClassVisitor(), pr);
// }
//
// public void setTarget(ClassVisitor target) {
// cv = target;
// }
// }
| import java.util.Arrays;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.pantsbuild.jarjar.util.RemappingClassTransformer;
import junit.framework.TestCase; | /**
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.pantsbuild.jarjar;
public class GenericsTest
extends TestCase
{
@Test
public void testTransform() throws Exception {
Rule rule = new Rule();
rule.setPattern("java.lang.String");
rule.setResult("com.tonicsystems.String"); | // Path: src/main/java/org/pantsbuild/jarjar/util/RemappingClassTransformer.java
// public class RemappingClassTransformer extends ClassRemapper
// {
// public RemappingClassTransformer(Remapper pr) {
// super(new EmptyClassVisitor(), pr);
// }
//
// public void setTarget(ClassVisitor target) {
// cv = target;
// }
// }
// Path: src/test/java/org/pantsbuild/jarjar/GenericsTest.java
import java.util.Arrays;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.pantsbuild.jarjar.util.RemappingClassTransformer;
import junit.framework.TestCase;
/**
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.pantsbuild.jarjar;
public class GenericsTest
extends TestCase
{
@Test
public void testTransform() throws Exception {
Rule rule = new Rule();
rule.setPattern("java.lang.String");
rule.setResult("com.tonicsystems.String"); | RemappingClassTransformer t = new RemappingClassTransformer(new PackageRemapper(Arrays.asList(rule), false)); |
pantsbuild/jarjar | src/test/java/org/pantsbuild/jarjar/MethodRewriterTest.java | // Path: src/main/java/org/pantsbuild/jarjar/util/EntryStruct.java
// public class EntryStruct {
// public byte[] data;
// public String name;
// public long time;
// public boolean skipTransform;
// }
//
// Path: src/main/java/org/pantsbuild/jarjar/util/IoUtil.java
// public class IoUtil {
// private IoUtil() {}
//
// public static void pipe(InputStream is, OutputStream out, byte[] buf) throws IOException {
// for (;;) {
// int amt = is.read(buf);
// if (amt < 0)
// break;
// out.write(buf, 0, amt);
// }
// }
//
// public static void copy(File from, File to, byte[] buf) throws IOException {
// InputStream in = new FileInputStream(from);
// try {
// OutputStream out = new FileOutputStream(to);
// try {
// pipe(in, out, buf);
// } finally {
// out.close();
// }
// } finally {
// in.close();
// }
// }
//
// /**
// * Create a copy of an zip file without its empty directories.
// * @param inputFile
// * @param outputFile
// * @throws IOException
// */
// public static void copyZipWithoutEmptyDirectories(final File inputFile, final File outputFile) throws IOException
// {
// final byte[] buf = new byte[0x2000];
//
// final ZipFile inputZip = new ZipFile(inputFile);
// BufferedOutputStream buffered = new BufferedOutputStream(new FileOutputStream(outputFile));
//
// final ZipOutputStream outputStream = new ZipOutputStream(buffered);
// try
// {
// // read a the entries of the input zip file and sort them
// final Enumeration<? extends ZipEntry> e = inputZip.entries();
// final ArrayList<ZipEntry> sortedList = new ArrayList<ZipEntry>();
// while (e.hasMoreElements()) {
// final ZipEntry entry = e.nextElement();
// sortedList.add(entry);
// }
//
// Collections.sort(sortedList, new Comparator<ZipEntry>()
// {
// public int compare(ZipEntry o1, ZipEntry o2)
// {
// return o1.getName().compareTo(o2.getName());
// }
// });
//
// // treat them again and write them in output, wenn they not are empty directories
// for (int i = sortedList.size()-1; i>=0; i--)
// {
// final ZipEntry inputEntry = sortedList.get(i);
// final String name = inputEntry.getName();
// final boolean isEmptyDirectory;
// if (inputEntry.isDirectory())
// {
// if (i == sortedList.size()-1)
// {
// // no item afterwards; it was an empty directory
// isEmptyDirectory = true;
// }
// else
// {
// final String nextName = sortedList.get(i+1).getName();
// isEmptyDirectory = !nextName.startsWith(name);
// }
// }
// else
// {
// isEmptyDirectory = false;
// }
//
//
// // write the entry
// if (isEmptyDirectory)
// {
// sortedList.remove(inputEntry);
// }
// else
// {
// final ZipEntry outputEntry = new ZipEntry(inputEntry);
// outputStream.putNextEntry(outputEntry);
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// final InputStream is = inputZip.getInputStream(inputEntry);
// IoUtil.pipe(is, baos, buf);
// is.close();
// outputStream.write(baos.toByteArray());
// }
// }
// } finally {
// outputStream.close();
// }
//
// }
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import junit.framework.TestCase;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.pantsbuild.jarjar.util.EntryStruct;
import org.pantsbuild.jarjar.util.IoUtil; | super(Opcodes.ASM7);
}
@Override
public void visitLdcInsn(Object value) {
if (value instanceof String) {
assertFalse(((String) value).contains("com.google."));
assertFalse("Value was: " + value, ((String) value).contains("com/google/"));
}
}
}
private VerifyingClassVisitor() {
super(Opcodes.ASM7);
}
@Override
public MethodVisitor visitMethod(
int access,
java.lang.String name,
java.lang.String descriptor,
java.lang.String signature,
java.lang.String[] exceptions) {
return new VerifyingMethodVisitor();
}
}
private static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buf = new byte[0x2000];
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | // Path: src/main/java/org/pantsbuild/jarjar/util/EntryStruct.java
// public class EntryStruct {
// public byte[] data;
// public String name;
// public long time;
// public boolean skipTransform;
// }
//
// Path: src/main/java/org/pantsbuild/jarjar/util/IoUtil.java
// public class IoUtil {
// private IoUtil() {}
//
// public static void pipe(InputStream is, OutputStream out, byte[] buf) throws IOException {
// for (;;) {
// int amt = is.read(buf);
// if (amt < 0)
// break;
// out.write(buf, 0, amt);
// }
// }
//
// public static void copy(File from, File to, byte[] buf) throws IOException {
// InputStream in = new FileInputStream(from);
// try {
// OutputStream out = new FileOutputStream(to);
// try {
// pipe(in, out, buf);
// } finally {
// out.close();
// }
// } finally {
// in.close();
// }
// }
//
// /**
// * Create a copy of an zip file without its empty directories.
// * @param inputFile
// * @param outputFile
// * @throws IOException
// */
// public static void copyZipWithoutEmptyDirectories(final File inputFile, final File outputFile) throws IOException
// {
// final byte[] buf = new byte[0x2000];
//
// final ZipFile inputZip = new ZipFile(inputFile);
// BufferedOutputStream buffered = new BufferedOutputStream(new FileOutputStream(outputFile));
//
// final ZipOutputStream outputStream = new ZipOutputStream(buffered);
// try
// {
// // read a the entries of the input zip file and sort them
// final Enumeration<? extends ZipEntry> e = inputZip.entries();
// final ArrayList<ZipEntry> sortedList = new ArrayList<ZipEntry>();
// while (e.hasMoreElements()) {
// final ZipEntry entry = e.nextElement();
// sortedList.add(entry);
// }
//
// Collections.sort(sortedList, new Comparator<ZipEntry>()
// {
// public int compare(ZipEntry o1, ZipEntry o2)
// {
// return o1.getName().compareTo(o2.getName());
// }
// });
//
// // treat them again and write them in output, wenn they not are empty directories
// for (int i = sortedList.size()-1; i>=0; i--)
// {
// final ZipEntry inputEntry = sortedList.get(i);
// final String name = inputEntry.getName();
// final boolean isEmptyDirectory;
// if (inputEntry.isDirectory())
// {
// if (i == sortedList.size()-1)
// {
// // no item afterwards; it was an empty directory
// isEmptyDirectory = true;
// }
// else
// {
// final String nextName = sortedList.get(i+1).getName();
// isEmptyDirectory = !nextName.startsWith(name);
// }
// }
// else
// {
// isEmptyDirectory = false;
// }
//
//
// // write the entry
// if (isEmptyDirectory)
// {
// sortedList.remove(inputEntry);
// }
// else
// {
// final ZipEntry outputEntry = new ZipEntry(inputEntry);
// outputStream.putNextEntry(outputEntry);
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// final InputStream is = inputZip.getInputStream(inputEntry);
// IoUtil.pipe(is, baos, buf);
// is.close();
// outputStream.write(baos.toByteArray());
// }
// }
// } finally {
// outputStream.close();
// }
//
// }
//
// }
// Path: src/test/java/org/pantsbuild/jarjar/MethodRewriterTest.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import junit.framework.TestCase;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.pantsbuild.jarjar.util.EntryStruct;
import org.pantsbuild.jarjar.util.IoUtil;
super(Opcodes.ASM7);
}
@Override
public void visitLdcInsn(Object value) {
if (value instanceof String) {
assertFalse(((String) value).contains("com.google."));
assertFalse("Value was: " + value, ((String) value).contains("com/google/"));
}
}
}
private VerifyingClassVisitor() {
super(Opcodes.ASM7);
}
@Override
public MethodVisitor visitMethod(
int access,
java.lang.String name,
java.lang.String descriptor,
java.lang.String signature,
java.lang.String[] exceptions) {
return new VerifyingMethodVisitor();
}
}
private static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buf = new byte[0x2000];
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | IoUtil.pipe(inputStream, baos, buf); |
pantsbuild/jarjar | src/test/java/org/pantsbuild/jarjar/MethodRewriterTest.java | // Path: src/main/java/org/pantsbuild/jarjar/util/EntryStruct.java
// public class EntryStruct {
// public byte[] data;
// public String name;
// public long time;
// public boolean skipTransform;
// }
//
// Path: src/main/java/org/pantsbuild/jarjar/util/IoUtil.java
// public class IoUtil {
// private IoUtil() {}
//
// public static void pipe(InputStream is, OutputStream out, byte[] buf) throws IOException {
// for (;;) {
// int amt = is.read(buf);
// if (amt < 0)
// break;
// out.write(buf, 0, amt);
// }
// }
//
// public static void copy(File from, File to, byte[] buf) throws IOException {
// InputStream in = new FileInputStream(from);
// try {
// OutputStream out = new FileOutputStream(to);
// try {
// pipe(in, out, buf);
// } finally {
// out.close();
// }
// } finally {
// in.close();
// }
// }
//
// /**
// * Create a copy of an zip file without its empty directories.
// * @param inputFile
// * @param outputFile
// * @throws IOException
// */
// public static void copyZipWithoutEmptyDirectories(final File inputFile, final File outputFile) throws IOException
// {
// final byte[] buf = new byte[0x2000];
//
// final ZipFile inputZip = new ZipFile(inputFile);
// BufferedOutputStream buffered = new BufferedOutputStream(new FileOutputStream(outputFile));
//
// final ZipOutputStream outputStream = new ZipOutputStream(buffered);
// try
// {
// // read a the entries of the input zip file and sort them
// final Enumeration<? extends ZipEntry> e = inputZip.entries();
// final ArrayList<ZipEntry> sortedList = new ArrayList<ZipEntry>();
// while (e.hasMoreElements()) {
// final ZipEntry entry = e.nextElement();
// sortedList.add(entry);
// }
//
// Collections.sort(sortedList, new Comparator<ZipEntry>()
// {
// public int compare(ZipEntry o1, ZipEntry o2)
// {
// return o1.getName().compareTo(o2.getName());
// }
// });
//
// // treat them again and write them in output, wenn they not are empty directories
// for (int i = sortedList.size()-1; i>=0; i--)
// {
// final ZipEntry inputEntry = sortedList.get(i);
// final String name = inputEntry.getName();
// final boolean isEmptyDirectory;
// if (inputEntry.isDirectory())
// {
// if (i == sortedList.size()-1)
// {
// // no item afterwards; it was an empty directory
// isEmptyDirectory = true;
// }
// else
// {
// final String nextName = sortedList.get(i+1).getName();
// isEmptyDirectory = !nextName.startsWith(name);
// }
// }
// else
// {
// isEmptyDirectory = false;
// }
//
//
// // write the entry
// if (isEmptyDirectory)
// {
// sortedList.remove(inputEntry);
// }
// else
// {
// final ZipEntry outputEntry = new ZipEntry(inputEntry);
// outputStream.putNextEntry(outputEntry);
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// final InputStream is = inputZip.getInputStream(inputEntry);
// IoUtil.pipe(is, baos, buf);
// is.close();
// outputStream.write(baos.toByteArray());
// }
// }
// } finally {
// outputStream.close();
// }
//
// }
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import junit.framework.TestCase;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.pantsbuild.jarjar.util.EntryStruct;
import org.pantsbuild.jarjar.util.IoUtil; | assertFalse(((String) value).contains("com.google."));
assertFalse("Value was: " + value, ((String) value).contains("com/google/"));
}
}
}
private VerifyingClassVisitor() {
super(Opcodes.ASM7);
}
@Override
public MethodVisitor visitMethod(
int access,
java.lang.String name,
java.lang.String descriptor,
java.lang.String signature,
java.lang.String[] exceptions) {
return new VerifyingMethodVisitor();
}
}
private static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buf = new byte[0x2000];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IoUtil.pipe(inputStream, baos, buf);
return baos.toByteArray();
}
@Test
public void testRewriteMethod() throws IOException { | // Path: src/main/java/org/pantsbuild/jarjar/util/EntryStruct.java
// public class EntryStruct {
// public byte[] data;
// public String name;
// public long time;
// public boolean skipTransform;
// }
//
// Path: src/main/java/org/pantsbuild/jarjar/util/IoUtil.java
// public class IoUtil {
// private IoUtil() {}
//
// public static void pipe(InputStream is, OutputStream out, byte[] buf) throws IOException {
// for (;;) {
// int amt = is.read(buf);
// if (amt < 0)
// break;
// out.write(buf, 0, amt);
// }
// }
//
// public static void copy(File from, File to, byte[] buf) throws IOException {
// InputStream in = new FileInputStream(from);
// try {
// OutputStream out = new FileOutputStream(to);
// try {
// pipe(in, out, buf);
// } finally {
// out.close();
// }
// } finally {
// in.close();
// }
// }
//
// /**
// * Create a copy of an zip file without its empty directories.
// * @param inputFile
// * @param outputFile
// * @throws IOException
// */
// public static void copyZipWithoutEmptyDirectories(final File inputFile, final File outputFile) throws IOException
// {
// final byte[] buf = new byte[0x2000];
//
// final ZipFile inputZip = new ZipFile(inputFile);
// BufferedOutputStream buffered = new BufferedOutputStream(new FileOutputStream(outputFile));
//
// final ZipOutputStream outputStream = new ZipOutputStream(buffered);
// try
// {
// // read a the entries of the input zip file and sort them
// final Enumeration<? extends ZipEntry> e = inputZip.entries();
// final ArrayList<ZipEntry> sortedList = new ArrayList<ZipEntry>();
// while (e.hasMoreElements()) {
// final ZipEntry entry = e.nextElement();
// sortedList.add(entry);
// }
//
// Collections.sort(sortedList, new Comparator<ZipEntry>()
// {
// public int compare(ZipEntry o1, ZipEntry o2)
// {
// return o1.getName().compareTo(o2.getName());
// }
// });
//
// // treat them again and write them in output, wenn they not are empty directories
// for (int i = sortedList.size()-1; i>=0; i--)
// {
// final ZipEntry inputEntry = sortedList.get(i);
// final String name = inputEntry.getName();
// final boolean isEmptyDirectory;
// if (inputEntry.isDirectory())
// {
// if (i == sortedList.size()-1)
// {
// // no item afterwards; it was an empty directory
// isEmptyDirectory = true;
// }
// else
// {
// final String nextName = sortedList.get(i+1).getName();
// isEmptyDirectory = !nextName.startsWith(name);
// }
// }
// else
// {
// isEmptyDirectory = false;
// }
//
//
// // write the entry
// if (isEmptyDirectory)
// {
// sortedList.remove(inputEntry);
// }
// else
// {
// final ZipEntry outputEntry = new ZipEntry(inputEntry);
// outputStream.putNextEntry(outputEntry);
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// final InputStream is = inputZip.getInputStream(inputEntry);
// IoUtil.pipe(is, baos, buf);
// is.close();
// outputStream.write(baos.toByteArray());
// }
// }
// } finally {
// outputStream.close();
// }
//
// }
//
// }
// Path: src/test/java/org/pantsbuild/jarjar/MethodRewriterTest.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import junit.framework.TestCase;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.pantsbuild.jarjar.util.EntryStruct;
import org.pantsbuild.jarjar.util.IoUtil;
assertFalse(((String) value).contains("com.google."));
assertFalse("Value was: " + value, ((String) value).contains("com/google/"));
}
}
}
private VerifyingClassVisitor() {
super(Opcodes.ASM7);
}
@Override
public MethodVisitor visitMethod(
int access,
java.lang.String name,
java.lang.String descriptor,
java.lang.String signature,
java.lang.String[] exceptions) {
return new VerifyingMethodVisitor();
}
}
private static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buf = new byte[0x2000];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IoUtil.pipe(inputStream, baos, buf);
return baos.toByteArray();
}
@Test
public void testRewriteMethod() throws IOException { | EntryStruct entryStruct = new EntryStruct(); |
pantsbuild/jarjar | src/test/java/org/pantsbuild/jarjar/ZapProcessorTest.java | // Path: src/main/java/org/pantsbuild/jarjar/util/EntryStruct.java
// public class EntryStruct {
// public byte[] data;
// public String name;
// public long time;
// public boolean skipTransform;
// }
| import java.io.IOException;
import java.util.Collections;
import org.junit.Test;
import org.pantsbuild.jarjar.util.EntryStruct;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package org.pantsbuild.jarjar;
public class ZapProcessorTest
{
@Test
public void testZap() throws IOException {
Zap zap = new Zap();
zap.setPattern("org.**");
ZapProcessor zapProcessor = new ZapProcessor(Collections.singletonList(zap));
| // Path: src/main/java/org/pantsbuild/jarjar/util/EntryStruct.java
// public class EntryStruct {
// public byte[] data;
// public String name;
// public long time;
// public boolean skipTransform;
// }
// Path: src/test/java/org/pantsbuild/jarjar/ZapProcessorTest.java
import java.io.IOException;
import java.util.Collections;
import org.junit.Test;
import org.pantsbuild.jarjar.util.EntryStruct;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package org.pantsbuild.jarjar;
public class ZapProcessorTest
{
@Test
public void testZap() throws IOException {
Zap zap = new Zap();
zap.setPattern("org.**");
ZapProcessor zapProcessor = new ZapProcessor(Collections.singletonList(zap));
| EntryStruct entryStruct = new EntryStruct(); |
pantsbuild/jarjar | src/main/java/org/pantsbuild/jarjar/util/RemappingClassTransformer.java | // Path: src/main/java/org/pantsbuild/jarjar/EmptyClassVisitor.java
// public class EmptyClassVisitor extends ClassVisitor {
//
// public EmptyClassVisitor() {
// super(Opcodes.ASM7);
// }
//
// @Override
// public MethodVisitor visitMethod(int access, String name, String desc,
// String signature, String[] exceptions) {
// return new MethodVisitor(Opcodes.ASM7) {};
// }
//
// @Override
// public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
// return new AnnotationVisitor(Opcodes.ASM7) {};
// }
//
// @Override
// public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
// return new FieldVisitor(Opcodes.ASM7) {};
// }
//
// }
| import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.ClassRemapper;
import org.pantsbuild.jarjar.EmptyClassVisitor; | /**
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.pantsbuild.jarjar.util;
public class RemappingClassTransformer extends ClassRemapper
{
public RemappingClassTransformer(Remapper pr) { | // Path: src/main/java/org/pantsbuild/jarjar/EmptyClassVisitor.java
// public class EmptyClassVisitor extends ClassVisitor {
//
// public EmptyClassVisitor() {
// super(Opcodes.ASM7);
// }
//
// @Override
// public MethodVisitor visitMethod(int access, String name, String desc,
// String signature, String[] exceptions) {
// return new MethodVisitor(Opcodes.ASM7) {};
// }
//
// @Override
// public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
// return new AnnotationVisitor(Opcodes.ASM7) {};
// }
//
// @Override
// public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
// return new FieldVisitor(Opcodes.ASM7) {};
// }
//
// }
// Path: src/main/java/org/pantsbuild/jarjar/util/RemappingClassTransformer.java
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.ClassRemapper;
import org.pantsbuild.jarjar.EmptyClassVisitor;
/**
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.pantsbuild.jarjar.util;
public class RemappingClassTransformer extends ClassRemapper
{
public RemappingClassTransformer(Remapper pr) { | super(new EmptyClassVisitor(), pr); |
pantsbuild/jarjar | src/main/java/org/pantsbuild/jarjar/MethodSignatureProcessor.java | // Path: src/main/java/org/pantsbuild/jarjar/util/EntryStruct.java
// public class EntryStruct {
// public byte[] data;
// public String name;
// public long time;
// public boolean skipTransform;
// }
//
// Path: src/main/java/org/pantsbuild/jarjar/util/JarProcessor.java
// public interface JarProcessor
// {
// /**
// * Process the entry (p.ex. rename the file)
// * <p>
// * Returns <code>true</code> if the processor "successfully" processed the entry. In practice,
// * "true" is used to indicate that the entry should be kept, and false is used to indicate the
// * entry should be thrown away, and doesn't indicate anything in particular about what this
// * JarProcessor actually did to the entry (if anything).
// *
// * @param struct The jar entry.
// * @return <code>true</code> if the process chain can continue after this process
// * @throws IOException
// */
// boolean process(EntryStruct struct) throws IOException;
// }
| import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.Remapper;
import org.pantsbuild.jarjar.util.EntryStruct;
import org.pantsbuild.jarjar.util.JarProcessor; | package org.pantsbuild.jarjar;
/**
* Remaps string values representing method signatures to use the new package.
*
* <p>{@link PackageRemapper} is only able to remap string values which exactly match the package
* being renamed. Method signatures are more difficult to detect so this class keeps track of which
* methods definitely take method signatures and remaps those explicitly.
*/
public class MethodSignatureProcessor implements JarProcessor {
/**
* List of method names which take a method signature as their parameter.
*
* <p>Right now we assume all these methods take exactly one parameter and that it's a stirng.
*/
private static final Set<String> METHOD_NAMES_WITH_PARAMS_TO_REWRITE =
new HashSet<String>(Arrays.asList("getImplMethodSignature"));
private final Remapper remapper;
public MethodSignatureProcessor(Remapper remapper) {
this.remapper = remapper;
}
@Override | // Path: src/main/java/org/pantsbuild/jarjar/util/EntryStruct.java
// public class EntryStruct {
// public byte[] data;
// public String name;
// public long time;
// public boolean skipTransform;
// }
//
// Path: src/main/java/org/pantsbuild/jarjar/util/JarProcessor.java
// public interface JarProcessor
// {
// /**
// * Process the entry (p.ex. rename the file)
// * <p>
// * Returns <code>true</code> if the processor "successfully" processed the entry. In practice,
// * "true" is used to indicate that the entry should be kept, and false is used to indicate the
// * entry should be thrown away, and doesn't indicate anything in particular about what this
// * JarProcessor actually did to the entry (if anything).
// *
// * @param struct The jar entry.
// * @return <code>true</code> if the process chain can continue after this process
// * @throws IOException
// */
// boolean process(EntryStruct struct) throws IOException;
// }
// Path: src/main/java/org/pantsbuild/jarjar/MethodSignatureProcessor.java
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.Remapper;
import org.pantsbuild.jarjar.util.EntryStruct;
import org.pantsbuild.jarjar.util.JarProcessor;
package org.pantsbuild.jarjar;
/**
* Remaps string values representing method signatures to use the new package.
*
* <p>{@link PackageRemapper} is only able to remap string values which exactly match the package
* being renamed. Method signatures are more difficult to detect so this class keeps track of which
* methods definitely take method signatures and remaps those explicitly.
*/
public class MethodSignatureProcessor implements JarProcessor {
/**
* List of method names which take a method signature as their parameter.
*
* <p>Right now we assume all these methods take exactly one parameter and that it's a stirng.
*/
private static final Set<String> METHOD_NAMES_WITH_PARAMS_TO_REWRITE =
new HashSet<String>(Arrays.asList("getImplMethodSignature"));
private final Remapper remapper;
public MethodSignatureProcessor(Remapper remapper) {
this.remapper = remapper;
}
@Override | public boolean process(final EntryStruct struct) throws IOException { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/formatters/TypeFormatter.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Type.java
// public abstract class Type {
//
// protected final String primitiveType;
//
// public Type(String primitiveType) {
// this.primitiveType = primitiveType;
// }
//
// public String getPrimitiveType() {
// return primitiveType;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(" + primitiveType + ")";
// }
// }
//
// Path: src/main/java/com/at/avro/AvroType.java
// public class AvroType {
//
// private final Type type;
// private final boolean nullable;
//
// public AvroType(Type type, boolean nullable) {
// this.type = type;
// this.nullable = nullable;
// }
//
// public Type getType() {
// return type;
// }
//
// public boolean isNullable() {
// return nullable;
// }
//
// @Override
// public String toString() {
// return new StringJoiner(", ", AvroType.class.getSimpleName() + "[", "]")
// .add("type=" + type)
// .add("nullable=" + nullable)
// .toString();
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Type;
import com.at.avro.AvroType; | package com.at.avro.formatters;
/**
* Writes avro field type info.
*
* @author artur@callfire.com
*/
public class TypeFormatter implements Formatter<AvroType> {
@Override | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Type.java
// public abstract class Type {
//
// protected final String primitiveType;
//
// public Type(String primitiveType) {
// this.primitiveType = primitiveType;
// }
//
// public String getPrimitiveType() {
// return primitiveType;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(" + primitiveType + ")";
// }
// }
//
// Path: src/main/java/com/at/avro/AvroType.java
// public class AvroType {
//
// private final Type type;
// private final boolean nullable;
//
// public AvroType(Type type, boolean nullable) {
// this.type = type;
// this.nullable = nullable;
// }
//
// public Type getType() {
// return type;
// }
//
// public boolean isNullable() {
// return nullable;
// }
//
// @Override
// public String toString() {
// return new StringJoiner(", ", AvroType.class.getSimpleName() + "[", "]")
// .add("type=" + type)
// .add("nullable=" + nullable)
// .toString();
// }
// }
// Path: src/main/java/com/at/avro/formatters/TypeFormatter.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Type;
import com.at.avro.AvroType;
package com.at.avro.formatters;
/**
* Writes avro field type info.
*
* @author artur@callfire.com
*/
public class TypeFormatter implements Formatter<AvroType> {
@Override | public String toJson(AvroType avroType, FormatterConfig formatterConfig) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/formatters/TypeFormatter.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Type.java
// public abstract class Type {
//
// protected final String primitiveType;
//
// public Type(String primitiveType) {
// this.primitiveType = primitiveType;
// }
//
// public String getPrimitiveType() {
// return primitiveType;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(" + primitiveType + ")";
// }
// }
//
// Path: src/main/java/com/at/avro/AvroType.java
// public class AvroType {
//
// private final Type type;
// private final boolean nullable;
//
// public AvroType(Type type, boolean nullable) {
// this.type = type;
// this.nullable = nullable;
// }
//
// public Type getType() {
// return type;
// }
//
// public boolean isNullable() {
// return nullable;
// }
//
// @Override
// public String toString() {
// return new StringJoiner(", ", AvroType.class.getSimpleName() + "[", "]")
// .add("type=" + type)
// .add("nullable=" + nullable)
// .toString();
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Type;
import com.at.avro.AvroType; | package com.at.avro.formatters;
/**
* Writes avro field type info.
*
* @author artur@callfire.com
*/
public class TypeFormatter implements Formatter<AvroType> {
@Override
public String toJson(AvroType avroType, FormatterConfig formatterConfig) { | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Type.java
// public abstract class Type {
//
// protected final String primitiveType;
//
// public Type(String primitiveType) {
// this.primitiveType = primitiveType;
// }
//
// public String getPrimitiveType() {
// return primitiveType;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(" + primitiveType + ")";
// }
// }
//
// Path: src/main/java/com/at/avro/AvroType.java
// public class AvroType {
//
// private final Type type;
// private final boolean nullable;
//
// public AvroType(Type type, boolean nullable) {
// this.type = type;
// this.nullable = nullable;
// }
//
// public Type getType() {
// return type;
// }
//
// public boolean isNullable() {
// return nullable;
// }
//
// @Override
// public String toString() {
// return new StringJoiner(", ", AvroType.class.getSimpleName() + "[", "]")
// .add("type=" + type)
// .add("nullable=" + nullable)
// .toString();
// }
// }
// Path: src/main/java/com/at/avro/formatters/TypeFormatter.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Type;
import com.at.avro.AvroType;
package com.at.avro.formatters;
/**
* Writes avro field type info.
*
* @author artur@callfire.com
*/
public class TypeFormatter implements Formatter<AvroType> {
@Override
public String toJson(AvroType avroType, FormatterConfig formatterConfig) { | Formatter<Type> formatter = formatterConfig.getFormatter(avroType.getType()); |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/formatters/ArrayFormatter.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Array.java
// public class Array extends Type {
// public Array(Type itemsType) {
// super(itemsType.getPrimitiveType());
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Array;
import static java.lang.String.format; | package com.at.avro.formatters;
public class ArrayFormatter implements com.at.avro.formatters.Formatter<Array> {
@Override | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Array.java
// public class Array extends Type {
// public Array(Type itemsType) {
// super(itemsType.getPrimitiveType());
// }
// }
// Path: src/main/java/com/at/avro/formatters/ArrayFormatter.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Array;
import static java.lang.String.format;
package com.at.avro.formatters;
public class ArrayFormatter implements com.at.avro.formatters.Formatter<Array> {
@Override | public String toJson(Array array, FormatterConfig formatterConfig) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/AvroField.java | // Path: src/main/java/com/at/avro/config/AvroConfig.java
// public class AvroConfig {
//
// private boolean representEnumsAsStrings = false;
// private boolean nullableTrueByDefault = false;
// private boolean allFieldsDefaultNull = false;
// private boolean useSqlCommentsAsDoc = false;
//
// private Class<?> decimalTypeClass = BigDecimal.class;
// private Class<?> dateTypeClass = Date.class;
//
// private final String namespace;
//
// private Function<String, String> schemaNameMapper = tableName -> tableName;
// private Function<String, String> fieldNameMapper = columnName -> columnName;
// private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); };
// private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};
//
// public AvroConfig(String namespace) {
// this.namespace = namespace;
// }
//
// /**
// * Provide custom schema name resolver function which takes DB table name as an input.
// * Table name is used by default.
// */
// public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {
// this.schemaNameMapper = schemaNameMapper;
// return this;
// }
//
// public Function<String, String> getSchemaNameMapper() {
// return schemaNameMapper;
// }
//
// /**
// * Provide custom field names resolver function which takes DB column name as an input.
// * Column name is used by default.
// */
// public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {
// this.fieldNameMapper = fieldNameMapper;
// return this;
// }
//
// public Function<String, String> getFieldNameMapper() {
// return fieldNameMapper;
// }
//
// /**
// * Resolve 'enum' type to 'string' instead of 'enum'.
// */
// public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {
// this.representEnumsAsStrings = representEnumsAsStrings;
// return this;
// }
//
// public boolean representEnumsAsStrings() {
// return representEnumsAsStrings;
// }
//
// /**
// * Set to true to make all fields default to null. DB column definition is used by default.
// */
// public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {
// this.allFieldsDefaultNull = allFieldsDefaultNull;
// return this;
// }
//
// public boolean isAllFieldsDefaultNull() {
// return allFieldsDefaultNull;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// /**
// * Set to true to make all fields nullable in avro schema. DB column definition is used by default.
// */
// public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {
// this.nullableTrueByDefault = nullableTrueByDefault;
// return this;
// }
//
// public boolean isNullableTrueByDefault() {
// return nullableTrueByDefault;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for dates.
// */
// public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {
// this.dateTypeClass = dateTypeClass;
// return this;
// }
//
// public Class<?> getDateTypeClass() {
// return dateTypeClass;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for decimals.
// */
// public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {
// this.decimalTypeClass = decimalTypeClass;
// return this;
// }
//
// public Class<?> getDecimalTypeClass() {
// return decimalTypeClass;
// }
//
// /**
// * Provide mapper for unknown db types. Throws IllegalArgumentException by default.
// * For example, if you want to default all unknown types to string:
// * <code>
// * avroConfig.setUnknownTypeResolver(type -> "string")
// * </code>
// * IllegalArgumentException is thrown by default.
// **/
// public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {
// this.unknownTypeResolver = unknownTypeResolver;
// return this;
// }
//
// public Function<String, String> getUnknownTypeResolver() {
// return unknownTypeResolver;
// }
//
// /**
// * Set a callback that will be called after avro model was built.
// * Schema model is ready by this point, but you can still modify it by adding custom properties.
// */
// public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {
// this.avroSchemaPostProcessor = avroSchemaPostProcessor;
// return this;
// }
//
// public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {
// return avroSchemaPostProcessor;
// }
//
// /**
// * Set to true to use SQL comments at table and field level as optional avro doc fields.
// */
// public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {
// this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;
// return this;
// }
//
// public boolean isUseSqlCommentsAsDoc() {
// return useSqlCommentsAsDoc;
// }
//
// }
| import com.at.avro.config.AvroConfig;
import org.apache.commons.lang3.StringUtils;
import schemacrawler.schema.Column;
import java.util.StringJoiner; | package com.at.avro;
/**
* @author artur@callfire.com
*/
public class AvroField {
private static final Object NOT_SET = new Object();
private String name;
private AvroType type;
private Object defaultValue = NOT_SET;
private String doc;
| // Path: src/main/java/com/at/avro/config/AvroConfig.java
// public class AvroConfig {
//
// private boolean representEnumsAsStrings = false;
// private boolean nullableTrueByDefault = false;
// private boolean allFieldsDefaultNull = false;
// private boolean useSqlCommentsAsDoc = false;
//
// private Class<?> decimalTypeClass = BigDecimal.class;
// private Class<?> dateTypeClass = Date.class;
//
// private final String namespace;
//
// private Function<String, String> schemaNameMapper = tableName -> tableName;
// private Function<String, String> fieldNameMapper = columnName -> columnName;
// private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); };
// private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};
//
// public AvroConfig(String namespace) {
// this.namespace = namespace;
// }
//
// /**
// * Provide custom schema name resolver function which takes DB table name as an input.
// * Table name is used by default.
// */
// public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {
// this.schemaNameMapper = schemaNameMapper;
// return this;
// }
//
// public Function<String, String> getSchemaNameMapper() {
// return schemaNameMapper;
// }
//
// /**
// * Provide custom field names resolver function which takes DB column name as an input.
// * Column name is used by default.
// */
// public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {
// this.fieldNameMapper = fieldNameMapper;
// return this;
// }
//
// public Function<String, String> getFieldNameMapper() {
// return fieldNameMapper;
// }
//
// /**
// * Resolve 'enum' type to 'string' instead of 'enum'.
// */
// public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {
// this.representEnumsAsStrings = representEnumsAsStrings;
// return this;
// }
//
// public boolean representEnumsAsStrings() {
// return representEnumsAsStrings;
// }
//
// /**
// * Set to true to make all fields default to null. DB column definition is used by default.
// */
// public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {
// this.allFieldsDefaultNull = allFieldsDefaultNull;
// return this;
// }
//
// public boolean isAllFieldsDefaultNull() {
// return allFieldsDefaultNull;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// /**
// * Set to true to make all fields nullable in avro schema. DB column definition is used by default.
// */
// public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {
// this.nullableTrueByDefault = nullableTrueByDefault;
// return this;
// }
//
// public boolean isNullableTrueByDefault() {
// return nullableTrueByDefault;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for dates.
// */
// public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {
// this.dateTypeClass = dateTypeClass;
// return this;
// }
//
// public Class<?> getDateTypeClass() {
// return dateTypeClass;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for decimals.
// */
// public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {
// this.decimalTypeClass = decimalTypeClass;
// return this;
// }
//
// public Class<?> getDecimalTypeClass() {
// return decimalTypeClass;
// }
//
// /**
// * Provide mapper for unknown db types. Throws IllegalArgumentException by default.
// * For example, if you want to default all unknown types to string:
// * <code>
// * avroConfig.setUnknownTypeResolver(type -> "string")
// * </code>
// * IllegalArgumentException is thrown by default.
// **/
// public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {
// this.unknownTypeResolver = unknownTypeResolver;
// return this;
// }
//
// public Function<String, String> getUnknownTypeResolver() {
// return unknownTypeResolver;
// }
//
// /**
// * Set a callback that will be called after avro model was built.
// * Schema model is ready by this point, but you can still modify it by adding custom properties.
// */
// public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {
// this.avroSchemaPostProcessor = avroSchemaPostProcessor;
// return this;
// }
//
// public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {
// return avroSchemaPostProcessor;
// }
//
// /**
// * Set to true to use SQL comments at table and field level as optional avro doc fields.
// */
// public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {
// this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;
// return this;
// }
//
// public boolean isUseSqlCommentsAsDoc() {
// return useSqlCommentsAsDoc;
// }
//
// }
// Path: src/main/java/com/at/avro/AvroField.java
import com.at.avro.config.AvroConfig;
import org.apache.commons.lang3.StringUtils;
import schemacrawler.schema.Column;
import java.util.StringJoiner;
package com.at.avro;
/**
* @author artur@callfire.com
*/
public class AvroField {
private static final Object NOT_SET = new Object();
private String name;
private AvroType type;
private Object defaultValue = NOT_SET;
private String doc;
| public AvroField(Column column, AvroConfig avroConfig) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/types/Date.java | // Path: src/main/java/com/at/avro/config/AvroConfig.java
// public class AvroConfig {
//
// private boolean representEnumsAsStrings = false;
// private boolean nullableTrueByDefault = false;
// private boolean allFieldsDefaultNull = false;
// private boolean useSqlCommentsAsDoc = false;
//
// private Class<?> decimalTypeClass = BigDecimal.class;
// private Class<?> dateTypeClass = Date.class;
//
// private final String namespace;
//
// private Function<String, String> schemaNameMapper = tableName -> tableName;
// private Function<String, String> fieldNameMapper = columnName -> columnName;
// private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); };
// private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};
//
// public AvroConfig(String namespace) {
// this.namespace = namespace;
// }
//
// /**
// * Provide custom schema name resolver function which takes DB table name as an input.
// * Table name is used by default.
// */
// public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {
// this.schemaNameMapper = schemaNameMapper;
// return this;
// }
//
// public Function<String, String> getSchemaNameMapper() {
// return schemaNameMapper;
// }
//
// /**
// * Provide custom field names resolver function which takes DB column name as an input.
// * Column name is used by default.
// */
// public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {
// this.fieldNameMapper = fieldNameMapper;
// return this;
// }
//
// public Function<String, String> getFieldNameMapper() {
// return fieldNameMapper;
// }
//
// /**
// * Resolve 'enum' type to 'string' instead of 'enum'.
// */
// public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {
// this.representEnumsAsStrings = representEnumsAsStrings;
// return this;
// }
//
// public boolean representEnumsAsStrings() {
// return representEnumsAsStrings;
// }
//
// /**
// * Set to true to make all fields default to null. DB column definition is used by default.
// */
// public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {
// this.allFieldsDefaultNull = allFieldsDefaultNull;
// return this;
// }
//
// public boolean isAllFieldsDefaultNull() {
// return allFieldsDefaultNull;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// /**
// * Set to true to make all fields nullable in avro schema. DB column definition is used by default.
// */
// public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {
// this.nullableTrueByDefault = nullableTrueByDefault;
// return this;
// }
//
// public boolean isNullableTrueByDefault() {
// return nullableTrueByDefault;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for dates.
// */
// public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {
// this.dateTypeClass = dateTypeClass;
// return this;
// }
//
// public Class<?> getDateTypeClass() {
// return dateTypeClass;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for decimals.
// */
// public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {
// this.decimalTypeClass = decimalTypeClass;
// return this;
// }
//
// public Class<?> getDecimalTypeClass() {
// return decimalTypeClass;
// }
//
// /**
// * Provide mapper for unknown db types. Throws IllegalArgumentException by default.
// * For example, if you want to default all unknown types to string:
// * <code>
// * avroConfig.setUnknownTypeResolver(type -> "string")
// * </code>
// * IllegalArgumentException is thrown by default.
// **/
// public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {
// this.unknownTypeResolver = unknownTypeResolver;
// return this;
// }
//
// public Function<String, String> getUnknownTypeResolver() {
// return unknownTypeResolver;
// }
//
// /**
// * Set a callback that will be called after avro model was built.
// * Schema model is ready by this point, but you can still modify it by adding custom properties.
// */
// public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {
// this.avroSchemaPostProcessor = avroSchemaPostProcessor;
// return this;
// }
//
// public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {
// return avroSchemaPostProcessor;
// }
//
// /**
// * Set to true to use SQL comments at table and field level as optional avro doc fields.
// */
// public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {
// this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;
// return this;
// }
//
// public boolean isUseSqlCommentsAsDoc() {
// return useSqlCommentsAsDoc;
// }
//
// }
| import com.at.avro.config.AvroConfig;
import schemacrawler.schema.Column; | package com.at.avro.types;
/**
* @author artur@callfire.com
*/
public class Date extends Type {
private final String logicalType = "timestamp-millis";
private final String javaClass;
| // Path: src/main/java/com/at/avro/config/AvroConfig.java
// public class AvroConfig {
//
// private boolean representEnumsAsStrings = false;
// private boolean nullableTrueByDefault = false;
// private boolean allFieldsDefaultNull = false;
// private boolean useSqlCommentsAsDoc = false;
//
// private Class<?> decimalTypeClass = BigDecimal.class;
// private Class<?> dateTypeClass = Date.class;
//
// private final String namespace;
//
// private Function<String, String> schemaNameMapper = tableName -> tableName;
// private Function<String, String> fieldNameMapper = columnName -> columnName;
// private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); };
// private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};
//
// public AvroConfig(String namespace) {
// this.namespace = namespace;
// }
//
// /**
// * Provide custom schema name resolver function which takes DB table name as an input.
// * Table name is used by default.
// */
// public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {
// this.schemaNameMapper = schemaNameMapper;
// return this;
// }
//
// public Function<String, String> getSchemaNameMapper() {
// return schemaNameMapper;
// }
//
// /**
// * Provide custom field names resolver function which takes DB column name as an input.
// * Column name is used by default.
// */
// public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {
// this.fieldNameMapper = fieldNameMapper;
// return this;
// }
//
// public Function<String, String> getFieldNameMapper() {
// return fieldNameMapper;
// }
//
// /**
// * Resolve 'enum' type to 'string' instead of 'enum'.
// */
// public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {
// this.representEnumsAsStrings = representEnumsAsStrings;
// return this;
// }
//
// public boolean representEnumsAsStrings() {
// return representEnumsAsStrings;
// }
//
// /**
// * Set to true to make all fields default to null. DB column definition is used by default.
// */
// public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {
// this.allFieldsDefaultNull = allFieldsDefaultNull;
// return this;
// }
//
// public boolean isAllFieldsDefaultNull() {
// return allFieldsDefaultNull;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// /**
// * Set to true to make all fields nullable in avro schema. DB column definition is used by default.
// */
// public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {
// this.nullableTrueByDefault = nullableTrueByDefault;
// return this;
// }
//
// public boolean isNullableTrueByDefault() {
// return nullableTrueByDefault;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for dates.
// */
// public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {
// this.dateTypeClass = dateTypeClass;
// return this;
// }
//
// public Class<?> getDateTypeClass() {
// return dateTypeClass;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for decimals.
// */
// public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {
// this.decimalTypeClass = decimalTypeClass;
// return this;
// }
//
// public Class<?> getDecimalTypeClass() {
// return decimalTypeClass;
// }
//
// /**
// * Provide mapper for unknown db types. Throws IllegalArgumentException by default.
// * For example, if you want to default all unknown types to string:
// * <code>
// * avroConfig.setUnknownTypeResolver(type -> "string")
// * </code>
// * IllegalArgumentException is thrown by default.
// **/
// public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {
// this.unknownTypeResolver = unknownTypeResolver;
// return this;
// }
//
// public Function<String, String> getUnknownTypeResolver() {
// return unknownTypeResolver;
// }
//
// /**
// * Set a callback that will be called after avro model was built.
// * Schema model is ready by this point, but you can still modify it by adding custom properties.
// */
// public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {
// this.avroSchemaPostProcessor = avroSchemaPostProcessor;
// return this;
// }
//
// public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {
// return avroSchemaPostProcessor;
// }
//
// /**
// * Set to true to use SQL comments at table and field level as optional avro doc fields.
// */
// public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {
// this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;
// return this;
// }
//
// public boolean isUseSqlCommentsAsDoc() {
// return useSqlCommentsAsDoc;
// }
//
// }
// Path: src/main/java/com/at/avro/types/Date.java
import com.at.avro.config.AvroConfig;
import schemacrawler.schema.Column;
package com.at.avro.types;
/**
* @author artur@callfire.com
*/
public class Date extends Type {
private final String logicalType = "timestamp-millis";
private final String javaClass;
| public Date(Column column, AvroConfig config) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/formatters/EnumFormatter.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Enum.java
// public class Enum extends Type {
//
// private final String name;
// private final String[] symbols;
//
// public Enum(Column column) {
// super("enum");
// this.name = column.getName();
//
// String allowedValues = column.getAttribute("COLUMN_TYPE").toString();
// this.symbols = allowedValues
// .replaceFirst("enum", "")
// .replaceFirst("ENUM", "")
// .replace(")", "")
// .replace("(", "")
// .split(",");
//
// for (int i = 0; i < symbols.length; i++) {
// symbols[i] = symbols[i].trim().replaceAll("'", "");
// }
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getSymbols() {
// return symbols;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + getName() + "[" + Arrays.toString(getSymbols()) + "]";
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Enum; | package com.at.avro.formatters;
/**
* @author artur@callfire.com
*/
public class EnumFormatter implements Formatter<Enum> {
@Override | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Enum.java
// public class Enum extends Type {
//
// private final String name;
// private final String[] symbols;
//
// public Enum(Column column) {
// super("enum");
// this.name = column.getName();
//
// String allowedValues = column.getAttribute("COLUMN_TYPE").toString();
// this.symbols = allowedValues
// .replaceFirst("enum", "")
// .replaceFirst("ENUM", "")
// .replace(")", "")
// .replace("(", "")
// .split(",");
//
// for (int i = 0; i < symbols.length; i++) {
// symbols[i] = symbols[i].trim().replaceAll("'", "");
// }
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getSymbols() {
// return symbols;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + getName() + "[" + Arrays.toString(getSymbols()) + "]";
// }
// }
// Path: src/main/java/com/at/avro/formatters/EnumFormatter.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Enum;
package com.at.avro.formatters;
/**
* @author artur@callfire.com
*/
public class EnumFormatter implements Formatter<Enum> {
@Override | public String toJson(Enum anEnum, FormatterConfig config) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/AvroSchema.java | // Path: src/main/java/com/at/avro/config/AvroConfig.java
// public class AvroConfig {
//
// private boolean representEnumsAsStrings = false;
// private boolean nullableTrueByDefault = false;
// private boolean allFieldsDefaultNull = false;
// private boolean useSqlCommentsAsDoc = false;
//
// private Class<?> decimalTypeClass = BigDecimal.class;
// private Class<?> dateTypeClass = Date.class;
//
// private final String namespace;
//
// private Function<String, String> schemaNameMapper = tableName -> tableName;
// private Function<String, String> fieldNameMapper = columnName -> columnName;
// private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); };
// private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};
//
// public AvroConfig(String namespace) {
// this.namespace = namespace;
// }
//
// /**
// * Provide custom schema name resolver function which takes DB table name as an input.
// * Table name is used by default.
// */
// public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {
// this.schemaNameMapper = schemaNameMapper;
// return this;
// }
//
// public Function<String, String> getSchemaNameMapper() {
// return schemaNameMapper;
// }
//
// /**
// * Provide custom field names resolver function which takes DB column name as an input.
// * Column name is used by default.
// */
// public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {
// this.fieldNameMapper = fieldNameMapper;
// return this;
// }
//
// public Function<String, String> getFieldNameMapper() {
// return fieldNameMapper;
// }
//
// /**
// * Resolve 'enum' type to 'string' instead of 'enum'.
// */
// public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {
// this.representEnumsAsStrings = representEnumsAsStrings;
// return this;
// }
//
// public boolean representEnumsAsStrings() {
// return representEnumsAsStrings;
// }
//
// /**
// * Set to true to make all fields default to null. DB column definition is used by default.
// */
// public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {
// this.allFieldsDefaultNull = allFieldsDefaultNull;
// return this;
// }
//
// public boolean isAllFieldsDefaultNull() {
// return allFieldsDefaultNull;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// /**
// * Set to true to make all fields nullable in avro schema. DB column definition is used by default.
// */
// public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {
// this.nullableTrueByDefault = nullableTrueByDefault;
// return this;
// }
//
// public boolean isNullableTrueByDefault() {
// return nullableTrueByDefault;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for dates.
// */
// public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {
// this.dateTypeClass = dateTypeClass;
// return this;
// }
//
// public Class<?> getDateTypeClass() {
// return dateTypeClass;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for decimals.
// */
// public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {
// this.decimalTypeClass = decimalTypeClass;
// return this;
// }
//
// public Class<?> getDecimalTypeClass() {
// return decimalTypeClass;
// }
//
// /**
// * Provide mapper for unknown db types. Throws IllegalArgumentException by default.
// * For example, if you want to default all unknown types to string:
// * <code>
// * avroConfig.setUnknownTypeResolver(type -> "string")
// * </code>
// * IllegalArgumentException is thrown by default.
// **/
// public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {
// this.unknownTypeResolver = unknownTypeResolver;
// return this;
// }
//
// public Function<String, String> getUnknownTypeResolver() {
// return unknownTypeResolver;
// }
//
// /**
// * Set a callback that will be called after avro model was built.
// * Schema model is ready by this point, but you can still modify it by adding custom properties.
// */
// public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {
// this.avroSchemaPostProcessor = avroSchemaPostProcessor;
// return this;
// }
//
// public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {
// return avroSchemaPostProcessor;
// }
//
// /**
// * Set to true to use SQL comments at table and field level as optional avro doc fields.
// */
// public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {
// this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;
// return this;
// }
//
// public boolean isUseSqlCommentsAsDoc() {
// return useSqlCommentsAsDoc;
// }
//
// }
| import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import com.at.avro.config.AvroConfig;
import org.apache.commons.lang3.StringUtils;
import schemacrawler.schema.Column;
import schemacrawler.schema.Table; | package com.at.avro;
/**
* @author artur@callfire.com
*/
public class AvroSchema {
private final String name;
private final String namespace;
private final String doc;
private List<AvroField> fields;
private Map<String, String> customProperties = new LinkedHashMap<>();
| // Path: src/main/java/com/at/avro/config/AvroConfig.java
// public class AvroConfig {
//
// private boolean representEnumsAsStrings = false;
// private boolean nullableTrueByDefault = false;
// private boolean allFieldsDefaultNull = false;
// private boolean useSqlCommentsAsDoc = false;
//
// private Class<?> decimalTypeClass = BigDecimal.class;
// private Class<?> dateTypeClass = Date.class;
//
// private final String namespace;
//
// private Function<String, String> schemaNameMapper = tableName -> tableName;
// private Function<String, String> fieldNameMapper = columnName -> columnName;
// private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); };
// private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};
//
// public AvroConfig(String namespace) {
// this.namespace = namespace;
// }
//
// /**
// * Provide custom schema name resolver function which takes DB table name as an input.
// * Table name is used by default.
// */
// public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {
// this.schemaNameMapper = schemaNameMapper;
// return this;
// }
//
// public Function<String, String> getSchemaNameMapper() {
// return schemaNameMapper;
// }
//
// /**
// * Provide custom field names resolver function which takes DB column name as an input.
// * Column name is used by default.
// */
// public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {
// this.fieldNameMapper = fieldNameMapper;
// return this;
// }
//
// public Function<String, String> getFieldNameMapper() {
// return fieldNameMapper;
// }
//
// /**
// * Resolve 'enum' type to 'string' instead of 'enum'.
// */
// public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {
// this.representEnumsAsStrings = representEnumsAsStrings;
// return this;
// }
//
// public boolean representEnumsAsStrings() {
// return representEnumsAsStrings;
// }
//
// /**
// * Set to true to make all fields default to null. DB column definition is used by default.
// */
// public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {
// this.allFieldsDefaultNull = allFieldsDefaultNull;
// return this;
// }
//
// public boolean isAllFieldsDefaultNull() {
// return allFieldsDefaultNull;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// /**
// * Set to true to make all fields nullable in avro schema. DB column definition is used by default.
// */
// public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {
// this.nullableTrueByDefault = nullableTrueByDefault;
// return this;
// }
//
// public boolean isNullableTrueByDefault() {
// return nullableTrueByDefault;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for dates.
// */
// public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {
// this.dateTypeClass = dateTypeClass;
// return this;
// }
//
// public Class<?> getDateTypeClass() {
// return dateTypeClass;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for decimals.
// */
// public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {
// this.decimalTypeClass = decimalTypeClass;
// return this;
// }
//
// public Class<?> getDecimalTypeClass() {
// return decimalTypeClass;
// }
//
// /**
// * Provide mapper for unknown db types. Throws IllegalArgumentException by default.
// * For example, if you want to default all unknown types to string:
// * <code>
// * avroConfig.setUnknownTypeResolver(type -> "string")
// * </code>
// * IllegalArgumentException is thrown by default.
// **/
// public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {
// this.unknownTypeResolver = unknownTypeResolver;
// return this;
// }
//
// public Function<String, String> getUnknownTypeResolver() {
// return unknownTypeResolver;
// }
//
// /**
// * Set a callback that will be called after avro model was built.
// * Schema model is ready by this point, but you can still modify it by adding custom properties.
// */
// public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {
// this.avroSchemaPostProcessor = avroSchemaPostProcessor;
// return this;
// }
//
// public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {
// return avroSchemaPostProcessor;
// }
//
// /**
// * Set to true to use SQL comments at table and field level as optional avro doc fields.
// */
// public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {
// this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;
// return this;
// }
//
// public boolean isUseSqlCommentsAsDoc() {
// return useSqlCommentsAsDoc;
// }
//
// }
// Path: src/main/java/com/at/avro/AvroSchema.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import com.at.avro.config.AvroConfig;
import org.apache.commons.lang3.StringUtils;
import schemacrawler.schema.Column;
import schemacrawler.schema.Table;
package com.at.avro;
/**
* @author artur@callfire.com
*/
public class AvroSchema {
private final String name;
private final String namespace;
private final String doc;
private List<AvroField> fields;
private Map<String, String> customProperties = new LinkedHashMap<>();
| public AvroSchema(Table table, AvroConfig avroConfig) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/formatters/DateFormatter.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Date.java
// public class Date extends Type {
//
// private final String logicalType = "timestamp-millis";
// private final String javaClass;
//
// public Date(Column column, AvroConfig config) {
// super("long");
// this.javaClass = config.getDateTypeClass().getCanonicalName();
// }
//
// public String getLogicalType() {
// return logicalType;
// }
//
// public String getJavaClass() {
// return javaClass;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + getLogicalType();
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Date; | package com.at.avro.formatters;
/**
* @author artur@callfire.com
*/
public class DateFormatter implements Formatter<Date> {
@Override | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Date.java
// public class Date extends Type {
//
// private final String logicalType = "timestamp-millis";
// private final String javaClass;
//
// public Date(Column column, AvroConfig config) {
// super("long");
// this.javaClass = config.getDateTypeClass().getCanonicalName();
// }
//
// public String getLogicalType() {
// return logicalType;
// }
//
// public String getJavaClass() {
// return javaClass;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + getLogicalType();
// }
// }
// Path: src/main/java/com/at/avro/formatters/DateFormatter.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Date;
package com.at.avro.formatters;
/**
* @author artur@callfire.com
*/
public class DateFormatter implements Formatter<Date> {
@Override | public String toJson(Date date, FormatterConfig config) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/formatters/DecimalFormatter.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Decimal.java
// public class Decimal extends Type {
//
// private final int precision;
// private final int scale;
// private final String javaClass;
// private final String logicalType = "decimal";
//
// public Decimal(Column column, AvroConfig config) {
// super("string");
// this.precision = column.getSize();
// this.scale = column.getDecimalDigits();
// this.javaClass = config.getDecimalTypeClass().getCanonicalName();
// }
//
// public String getJavaClass() {
// return javaClass;
// }
//
// public String getLogicalType() {
// return logicalType;
// }
//
// public int getPrecision() {
// return precision;
// }
//
// public int getScale() {
// return scale;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + logicalType + "[" + getPrecision() + ":" + getScale() + "]";
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Decimal;
import static java.lang.String.format; | package com.at.avro.formatters;
/**
* @author artur@callfire.com
*/
public class DecimalFormatter implements Formatter<Decimal> {
@Override | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Decimal.java
// public class Decimal extends Type {
//
// private final int precision;
// private final int scale;
// private final String javaClass;
// private final String logicalType = "decimal";
//
// public Decimal(Column column, AvroConfig config) {
// super("string");
// this.precision = column.getSize();
// this.scale = column.getDecimalDigits();
// this.javaClass = config.getDecimalTypeClass().getCanonicalName();
// }
//
// public String getJavaClass() {
// return javaClass;
// }
//
// public String getLogicalType() {
// return logicalType;
// }
//
// public int getPrecision() {
// return precision;
// }
//
// public int getScale() {
// return scale;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + logicalType + "[" + getPrecision() + ":" + getScale() + "]";
// }
// }
// Path: src/main/java/com/at/avro/formatters/DecimalFormatter.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Decimal;
import static java.lang.String.format;
package com.at.avro.formatters;
/**
* @author artur@callfire.com
*/
public class DecimalFormatter implements Formatter<Decimal> {
@Override | public String toJson(Decimal decimal, FormatterConfig config) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/formatters/PrimitiveFormatter.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Primitive.java
// public class Primitive extends Type {
// public Primitive(String primitiveType) {
// super(primitiveType);
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Primitive; | package com.at.avro.formatters;
/**
* @author artur@callfire.com
*/
public class PrimitiveFormatter implements Formatter<Primitive> {
@Override | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Primitive.java
// public class Primitive extends Type {
// public Primitive(String primitiveType) {
// super(primitiveType);
// }
// }
// Path: src/main/java/com/at/avro/formatters/PrimitiveFormatter.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Primitive;
package com.at.avro.formatters;
/**
* @author artur@callfire.com
*/
public class PrimitiveFormatter implements Formatter<Primitive> {
@Override | public String toJson(Primitive primitive, FormatterConfig config) { |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/config/AvroConfig.java | // Path: src/main/java/com/at/avro/AvroSchema.java
// public class AvroSchema {
// private final String name;
// private final String namespace;
// private final String doc;
//
// private List<AvroField> fields;
//
// private Map<String, String> customProperties = new LinkedHashMap<>();
//
// public AvroSchema(Table table, AvroConfig avroConfig) {
// this.name = avroConfig.getSchemaNameMapper().apply(table.getName());
// this.namespace = avroConfig.getNamespace();
// this.doc = avroConfig.isUseSqlCommentsAsDoc() ? table.getRemarks() : null;
// this.fields = new ArrayList<>(table.getColumns().size());
//
// for (Column column : table.getColumns()) {
// this.fields.add(new AvroField(column, avroConfig));
// }
//
// avroConfig.getAvroSchemaPostProcessor().accept(this, table);
// }
//
// public String getName() {
// return name;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// public String getDoc() {
// return doc;
// }
//
// public boolean isDocSet() {
// return StringUtils.isNotBlank(doc);
// }
//
// public List<AvroField> getFields() {
// return fields;
// }
//
// public void addCustomProperty(String name, String value) {
// customProperties.put(name, value);
// }
//
// public Map<String, String> getCustomProperties() {
// return customProperties;
// }
//
// @Override
// public String toString() {
// StringJoiner joiner = new StringJoiner(", ", AvroSchema.class.getSimpleName() + "[", "]")
// .add("name='" + name + "'")
// .add("namespace='" + namespace + "'");
//
// if (isDocSet()) {
// joiner.add("doc='" + doc + "'");
// }
// joiner
// .add("fields=" + fields)
// .add("customProperties=" + customProperties);
//
// return joiner.toString();
// }
// }
| import java.math.BigDecimal;
import java.util.Date;
import java.util.function.BiConsumer;
import java.util.function.Function;
import com.at.avro.AvroSchema;
import schemacrawler.schema.Table; | package com.at.avro.config;
/**
* Configuration that allows avro model tweaking. Model is then used to generate schemas.
*
* @author artur@callfire.com
*/
public class AvroConfig {
private boolean representEnumsAsStrings = false;
private boolean nullableTrueByDefault = false;
private boolean allFieldsDefaultNull = false;
private boolean useSqlCommentsAsDoc = false;
private Class<?> decimalTypeClass = BigDecimal.class;
private Class<?> dateTypeClass = Date.class;
private final String namespace;
private Function<String, String> schemaNameMapper = tableName -> tableName;
private Function<String, String> fieldNameMapper = columnName -> columnName;
private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); }; | // Path: src/main/java/com/at/avro/AvroSchema.java
// public class AvroSchema {
// private final String name;
// private final String namespace;
// private final String doc;
//
// private List<AvroField> fields;
//
// private Map<String, String> customProperties = new LinkedHashMap<>();
//
// public AvroSchema(Table table, AvroConfig avroConfig) {
// this.name = avroConfig.getSchemaNameMapper().apply(table.getName());
// this.namespace = avroConfig.getNamespace();
// this.doc = avroConfig.isUseSqlCommentsAsDoc() ? table.getRemarks() : null;
// this.fields = new ArrayList<>(table.getColumns().size());
//
// for (Column column : table.getColumns()) {
// this.fields.add(new AvroField(column, avroConfig));
// }
//
// avroConfig.getAvroSchemaPostProcessor().accept(this, table);
// }
//
// public String getName() {
// return name;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// public String getDoc() {
// return doc;
// }
//
// public boolean isDocSet() {
// return StringUtils.isNotBlank(doc);
// }
//
// public List<AvroField> getFields() {
// return fields;
// }
//
// public void addCustomProperty(String name, String value) {
// customProperties.put(name, value);
// }
//
// public Map<String, String> getCustomProperties() {
// return customProperties;
// }
//
// @Override
// public String toString() {
// StringJoiner joiner = new StringJoiner(", ", AvroSchema.class.getSimpleName() + "[", "]")
// .add("name='" + name + "'")
// .add("namespace='" + namespace + "'");
//
// if (isDocSet()) {
// joiner.add("doc='" + doc + "'");
// }
// joiner
// .add("fields=" + fields)
// .add("customProperties=" + customProperties);
//
// return joiner.toString();
// }
// }
// Path: src/main/java/com/at/avro/config/AvroConfig.java
import java.math.BigDecimal;
import java.util.Date;
import java.util.function.BiConsumer;
import java.util.function.Function;
import com.at.avro.AvroSchema;
import schemacrawler.schema.Table;
package com.at.avro.config;
/**
* Configuration that allows avro model tweaking. Model is then used to generate schemas.
*
* @author artur@callfire.com
*/
public class AvroConfig {
private boolean representEnumsAsStrings = false;
private boolean nullableTrueByDefault = false;
private boolean allFieldsDefaultNull = false;
private boolean useSqlCommentsAsDoc = false;
private Class<?> decimalTypeClass = BigDecimal.class;
private Class<?> dateTypeClass = Date.class;
private final String namespace;
private Function<String, String> schemaNameMapper = tableName -> tableName;
private Function<String, String> fieldNameMapper = columnName -> columnName;
private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); }; | private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {}; |
artur-tamazian/avro-schema-generator | src/test/java/com/at/avro/formatters/EnumFormatterTest.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Enum.java
// public class Enum extends Type {
//
// private final String name;
// private final String[] symbols;
//
// public Enum(Column column) {
// super("enum");
// this.name = column.getName();
//
// String allowedValues = column.getAttribute("COLUMN_TYPE").toString();
// this.symbols = allowedValues
// .replaceFirst("enum", "")
// .replaceFirst("ENUM", "")
// .replace(")", "")
// .replace("(", "")
// .split(",");
//
// for (int i = 0; i < symbols.length; i++) {
// symbols[i] = symbols[i].trim().replaceAll("'", "");
// }
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getSymbols() {
// return symbols;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + getName() + "[" + Arrays.toString(getSymbols()) + "]";
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Enum;
import org.junit.Test;
import schemacrawler.schema.Column;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | package com.at.avro.formatters;
/**
* @author Art
*/
public class EnumFormatterTest {
@Test
public void testEnumFormatting() throws Exception {
Column column = mock(Column.class);
when(column.getName()).thenReturn("someEnum");
when(column.getAttribute("COLUMN_TYPE")).thenReturn("ENUM('value1', 'value2')");
| // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Enum.java
// public class Enum extends Type {
//
// private final String name;
// private final String[] symbols;
//
// public Enum(Column column) {
// super("enum");
// this.name = column.getName();
//
// String allowedValues = column.getAttribute("COLUMN_TYPE").toString();
// this.symbols = allowedValues
// .replaceFirst("enum", "")
// .replaceFirst("ENUM", "")
// .replace(")", "")
// .replace("(", "")
// .split(",");
//
// for (int i = 0; i < symbols.length; i++) {
// symbols[i] = symbols[i].trim().replaceAll("'", "");
// }
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getSymbols() {
// return symbols;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + getName() + "[" + Arrays.toString(getSymbols()) + "]";
// }
// }
// Path: src/test/java/com/at/avro/formatters/EnumFormatterTest.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Enum;
import org.junit.Test;
import schemacrawler.schema.Column;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package com.at.avro.formatters;
/**
* @author Art
*/
public class EnumFormatterTest {
@Test
public void testEnumFormatting() throws Exception {
Column column = mock(Column.class);
when(column.getName()).thenReturn("someEnum");
when(column.getAttribute("COLUMN_TYPE")).thenReturn("ENUM('value1', 'value2')");
| Enum anEnum = new Enum(column); |
artur-tamazian/avro-schema-generator | src/test/java/com/at/avro/formatters/EnumFormatterTest.java | // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Enum.java
// public class Enum extends Type {
//
// private final String name;
// private final String[] symbols;
//
// public Enum(Column column) {
// super("enum");
// this.name = column.getName();
//
// String allowedValues = column.getAttribute("COLUMN_TYPE").toString();
// this.symbols = allowedValues
// .replaceFirst("enum", "")
// .replaceFirst("ENUM", "")
// .replace(")", "")
// .replace("(", "")
// .split(",");
//
// for (int i = 0; i < symbols.length; i++) {
// symbols[i] = symbols[i].trim().replaceAll("'", "");
// }
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getSymbols() {
// return symbols;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + getName() + "[" + Arrays.toString(getSymbols()) + "]";
// }
// }
| import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Enum;
import org.junit.Test;
import schemacrawler.schema.Column;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | package com.at.avro.formatters;
/**
* @author Art
*/
public class EnumFormatterTest {
@Test
public void testEnumFormatting() throws Exception {
Column column = mock(Column.class);
when(column.getName()).thenReturn("someEnum");
when(column.getAttribute("COLUMN_TYPE")).thenReturn("ENUM('value1', 'value2')");
Enum anEnum = new Enum(column);
assertThat(anEnum.getName(), is("someEnum"));
assertThat(anEnum.getSymbols()[0], is("value1"));
assertThat(anEnum.getSymbols()[1], is("value2"));
| // Path: src/main/java/com/at/avro/config/FormatterConfig.java
// public class FormatterConfig {
//
// private String indent;
// private String lineSeparator;
// private String colon;
// private boolean prettyPrintFields;
// private boolean prettyPrintSchema;
//
// private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{
// put(AvroSchema.class, new SchemaFormatter());
// put(AvroField.class, new FieldFormatter());
// put(AvroType.class, new TypeFormatter());
// put(Date.class, new DateFormatter());
// put(Enum.class, new EnumFormatter());
// put(Primitive.class, new PrimitiveFormatter());
// put(Decimal.class, new DecimalFormatter());
// put(Array.class, new ArrayFormatter());
// }};
//
// private FormatterConfig() {
// }
//
// public String indent() {
// return indent;
// }
//
// public String indent(int times) {
// String result = "";
// for (int i = 0; i < times; i++) {
// result += indent();
// }
// return result;
// }
//
// public String colon() {
// return colon;
// }
//
// public String lineSeparator() {
// return lineSeparator;
// }
//
// public boolean prettyPrintFields() {
// return prettyPrintFields;
// }
//
// public boolean prettyPrintSchema() {
// return prettyPrintSchema;
// }
//
// public <T> Formatter<T> getFormatter(T dto) {
// if (!formatters.containsKey(dto.getClass())) {
// throw new IllegalArgumentException("Formatter not found for " + dto.getClass().getSimpleName());
// }
// return formatters.get(dto.getClass());
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public static class Builder {
// private Map<Class, Formatter> formatters = new HashMap<>();
// private boolean prettyPrintSchema = true;
// private boolean prettyPrintFields = false;
// private boolean addSpaceAfterColon = true;
// private String indent = " ";
//
// public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {
// formatters.put(dtoClass, formatter);
// return this;
// }
//
// /** False - to print schema in one line, true - to print it nicely formatted. */
// public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {
// this.prettyPrintSchema = prettyPrintSchema;
// return this;
// }
//
// /**
// * When false - each field will be written as one line, even if pretty printing of schema is set to true.
// * if prettyPrintSchema is false, prettyPrintFields is ignored.
// */
// public Builder setPrettyPrintFields(boolean prettyPrintFields) {
// this.prettyPrintFields = prettyPrintFields;
// return this;
// }
//
// /** Set indent value for pretty printing. */
// public Builder setIndent(String indent) {
// this.indent = indent;
// return this;
// }
//
// public FormatterConfig build() {
// FormatterConfig config = new FormatterConfig();
// config.formatters.putAll(this.formatters);
// config.lineSeparator = prettyPrintSchema ? "\n" : "";
// config.colon = addSpaceAfterColon ? ": " : ":";
// config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;
// config.prettyPrintSchema = prettyPrintSchema;
// config.indent = prettyPrintSchema ? indent : "";
// return config;
// }
// }
// }
//
// Path: src/main/java/com/at/avro/types/Enum.java
// public class Enum extends Type {
//
// private final String name;
// private final String[] symbols;
//
// public Enum(Column column) {
// super("enum");
// this.name = column.getName();
//
// String allowedValues = column.getAttribute("COLUMN_TYPE").toString();
// this.symbols = allowedValues
// .replaceFirst("enum", "")
// .replaceFirst("ENUM", "")
// .replace(")", "")
// .replace("(", "")
// .split(",");
//
// for (int i = 0; i < symbols.length; i++) {
// symbols[i] = symbols[i].trim().replaceAll("'", "");
// }
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getSymbols() {
// return symbols;
// }
//
// @Override
// public String toString() {
// return super.toString() + ": " + getName() + "[" + Arrays.toString(getSymbols()) + "]";
// }
// }
// Path: src/test/java/com/at/avro/formatters/EnumFormatterTest.java
import com.at.avro.config.FormatterConfig;
import com.at.avro.types.Enum;
import org.junit.Test;
import schemacrawler.schema.Column;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package com.at.avro.formatters;
/**
* @author Art
*/
public class EnumFormatterTest {
@Test
public void testEnumFormatting() throws Exception {
Column column = mock(Column.class);
when(column.getName()).thenReturn("someEnum");
when(column.getAttribute("COLUMN_TYPE")).thenReturn("ENUM('value1', 'value2')");
Enum anEnum = new Enum(column);
assertThat(anEnum.getName(), is("someEnum"));
assertThat(anEnum.getSymbols()[0], is("value1"));
assertThat(anEnum.getSymbols()[1], is("value2"));
| String json = new EnumFormatter().toJson(anEnum, FormatterConfig.builder().build()); |
artur-tamazian/avro-schema-generator | src/main/java/com/at/avro/types/Decimal.java | // Path: src/main/java/com/at/avro/config/AvroConfig.java
// public class AvroConfig {
//
// private boolean representEnumsAsStrings = false;
// private boolean nullableTrueByDefault = false;
// private boolean allFieldsDefaultNull = false;
// private boolean useSqlCommentsAsDoc = false;
//
// private Class<?> decimalTypeClass = BigDecimal.class;
// private Class<?> dateTypeClass = Date.class;
//
// private final String namespace;
//
// private Function<String, String> schemaNameMapper = tableName -> tableName;
// private Function<String, String> fieldNameMapper = columnName -> columnName;
// private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); };
// private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};
//
// public AvroConfig(String namespace) {
// this.namespace = namespace;
// }
//
// /**
// * Provide custom schema name resolver function which takes DB table name as an input.
// * Table name is used by default.
// */
// public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {
// this.schemaNameMapper = schemaNameMapper;
// return this;
// }
//
// public Function<String, String> getSchemaNameMapper() {
// return schemaNameMapper;
// }
//
// /**
// * Provide custom field names resolver function which takes DB column name as an input.
// * Column name is used by default.
// */
// public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {
// this.fieldNameMapper = fieldNameMapper;
// return this;
// }
//
// public Function<String, String> getFieldNameMapper() {
// return fieldNameMapper;
// }
//
// /**
// * Resolve 'enum' type to 'string' instead of 'enum'.
// */
// public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {
// this.representEnumsAsStrings = representEnumsAsStrings;
// return this;
// }
//
// public boolean representEnumsAsStrings() {
// return representEnumsAsStrings;
// }
//
// /**
// * Set to true to make all fields default to null. DB column definition is used by default.
// */
// public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {
// this.allFieldsDefaultNull = allFieldsDefaultNull;
// return this;
// }
//
// public boolean isAllFieldsDefaultNull() {
// return allFieldsDefaultNull;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// /**
// * Set to true to make all fields nullable in avro schema. DB column definition is used by default.
// */
// public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {
// this.nullableTrueByDefault = nullableTrueByDefault;
// return this;
// }
//
// public boolean isNullableTrueByDefault() {
// return nullableTrueByDefault;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for dates.
// */
// public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {
// this.dateTypeClass = dateTypeClass;
// return this;
// }
//
// public Class<?> getDateTypeClass() {
// return dateTypeClass;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for decimals.
// */
// public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {
// this.decimalTypeClass = decimalTypeClass;
// return this;
// }
//
// public Class<?> getDecimalTypeClass() {
// return decimalTypeClass;
// }
//
// /**
// * Provide mapper for unknown db types. Throws IllegalArgumentException by default.
// * For example, if you want to default all unknown types to string:
// * <code>
// * avroConfig.setUnknownTypeResolver(type -> "string")
// * </code>
// * IllegalArgumentException is thrown by default.
// **/
// public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {
// this.unknownTypeResolver = unknownTypeResolver;
// return this;
// }
//
// public Function<String, String> getUnknownTypeResolver() {
// return unknownTypeResolver;
// }
//
// /**
// * Set a callback that will be called after avro model was built.
// * Schema model is ready by this point, but you can still modify it by adding custom properties.
// */
// public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {
// this.avroSchemaPostProcessor = avroSchemaPostProcessor;
// return this;
// }
//
// public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {
// return avroSchemaPostProcessor;
// }
//
// /**
// * Set to true to use SQL comments at table and field level as optional avro doc fields.
// */
// public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {
// this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;
// return this;
// }
//
// public boolean isUseSqlCommentsAsDoc() {
// return useSqlCommentsAsDoc;
// }
//
// }
| import com.at.avro.config.AvroConfig;
import schemacrawler.schema.Column; | package com.at.avro.types;
/**
* @author artur@callfire.com
*/
public class Decimal extends Type {
private final int precision;
private final int scale;
private final String javaClass;
private final String logicalType = "decimal";
| // Path: src/main/java/com/at/avro/config/AvroConfig.java
// public class AvroConfig {
//
// private boolean representEnumsAsStrings = false;
// private boolean nullableTrueByDefault = false;
// private boolean allFieldsDefaultNull = false;
// private boolean useSqlCommentsAsDoc = false;
//
// private Class<?> decimalTypeClass = BigDecimal.class;
// private Class<?> dateTypeClass = Date.class;
//
// private final String namespace;
//
// private Function<String, String> schemaNameMapper = tableName -> tableName;
// private Function<String, String> fieldNameMapper = columnName -> columnName;
// private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException("unknown data type: " + dbType); };
// private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};
//
// public AvroConfig(String namespace) {
// this.namespace = namespace;
// }
//
// /**
// * Provide custom schema name resolver function which takes DB table name as an input.
// * Table name is used by default.
// */
// public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {
// this.schemaNameMapper = schemaNameMapper;
// return this;
// }
//
// public Function<String, String> getSchemaNameMapper() {
// return schemaNameMapper;
// }
//
// /**
// * Provide custom field names resolver function which takes DB column name as an input.
// * Column name is used by default.
// */
// public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {
// this.fieldNameMapper = fieldNameMapper;
// return this;
// }
//
// public Function<String, String> getFieldNameMapper() {
// return fieldNameMapper;
// }
//
// /**
// * Resolve 'enum' type to 'string' instead of 'enum'.
// */
// public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {
// this.representEnumsAsStrings = representEnumsAsStrings;
// return this;
// }
//
// public boolean representEnumsAsStrings() {
// return representEnumsAsStrings;
// }
//
// /**
// * Set to true to make all fields default to null. DB column definition is used by default.
// */
// public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {
// this.allFieldsDefaultNull = allFieldsDefaultNull;
// return this;
// }
//
// public boolean isAllFieldsDefaultNull() {
// return allFieldsDefaultNull;
// }
//
// public String getNamespace() {
// return namespace;
// }
//
// /**
// * Set to true to make all fields nullable in avro schema. DB column definition is used by default.
// */
// public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {
// this.nullableTrueByDefault = nullableTrueByDefault;
// return this;
// }
//
// public boolean isNullableTrueByDefault() {
// return nullableTrueByDefault;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for dates.
// */
// public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {
// this.dateTypeClass = dateTypeClass;
// return this;
// }
//
// public Class<?> getDateTypeClass() {
// return dateTypeClass;
// }
//
// /**
// * Sets a "java-class" property in this fields definition.
// * This might be used by avro java code generator to use the class you want for decimals.
// */
// public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {
// this.decimalTypeClass = decimalTypeClass;
// return this;
// }
//
// public Class<?> getDecimalTypeClass() {
// return decimalTypeClass;
// }
//
// /**
// * Provide mapper for unknown db types. Throws IllegalArgumentException by default.
// * For example, if you want to default all unknown types to string:
// * <code>
// * avroConfig.setUnknownTypeResolver(type -> "string")
// * </code>
// * IllegalArgumentException is thrown by default.
// **/
// public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {
// this.unknownTypeResolver = unknownTypeResolver;
// return this;
// }
//
// public Function<String, String> getUnknownTypeResolver() {
// return unknownTypeResolver;
// }
//
// /**
// * Set a callback that will be called after avro model was built.
// * Schema model is ready by this point, but you can still modify it by adding custom properties.
// */
// public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {
// this.avroSchemaPostProcessor = avroSchemaPostProcessor;
// return this;
// }
//
// public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {
// return avroSchemaPostProcessor;
// }
//
// /**
// * Set to true to use SQL comments at table and field level as optional avro doc fields.
// */
// public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {
// this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;
// return this;
// }
//
// public boolean isUseSqlCommentsAsDoc() {
// return useSqlCommentsAsDoc;
// }
//
// }
// Path: src/main/java/com/at/avro/types/Decimal.java
import com.at.avro.config.AvroConfig;
import schemacrawler.schema.Column;
package com.at.avro.types;
/**
* @author artur@callfire.com
*/
public class Decimal extends Type {
private final int precision;
private final int scale;
private final String javaClass;
private final String logicalType = "decimal";
| public Decimal(Column column, AvroConfig config) { |
genepi/imputationserver | src/main/java/genepi/imputationserver/steps/FailureNotification.java | // Path: src/main/java/genepi/imputationserver/util/DefaultPreferenceStore.java
// public class DefaultPreferenceStore {
//
// private Properties properties = new Properties(defaults());
//
// public DefaultPreferenceStore(Configuration configuration) {
// load(configuration);
// }
//
// public void load(File file) {
// try {
// properties.load(new FileInputStream(file));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public DefaultPreferenceStore() {
//
// }
//
// public void load(Configuration configuration) {
// Map<String, String> pairs = configuration.getValByRegex("cloudgene.*");
// for (String key : pairs.keySet()) {
// String cleanKey = key.replace("cloudgene.", "");
// String value = pairs.get(key);
// properties.setProperty(cleanKey, value);
// }
// }
//
// public void write(Configuration configuration) {
//
// for (Object key : properties.keySet()) {
// String newKey = "cloudgene." + key.toString();
// String value = properties.getProperty(key.toString());
// configuration.set(newKey, value);
// }
//
// }
//
// public String getString(String key) {
// return properties.getProperty(key);
// }
//
// public void setString(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Set<Object> getKeys() {
// return new HashSet<Object>(Collections.list(properties.propertyNames()));
// }
//
// public static Properties defaults() {
//
// Properties defaults = new Properties();
// defaults.setProperty("chunksize", "20000000");
// defaults.setProperty("phasing.window", "5000000");
// defaults.setProperty("minimac.window", "500000");
// defaults.setProperty("minimac.sendmail", "no");
// defaults.setProperty("server.url", "https://imputationserver.sph.umich.edu");
// defaults.setProperty("minimac.tmp", "/tmp");
// defaults.setProperty("minimac.command",
// "--refHaps ${ref} --haps ${vcf} --start ${start} --end ${end} --window ${window} --prefix ${prefix} --chr ${chr} --cpus 1 --noPhoneHome --format GT,DS,GP --allTypedSites --meta --minRatio 0.00001 ${chr =='MT' ? '--myChromosome ' + chr : ''} ${unphased ? '--unphasedOutput' : ''} ${mapMinimac != null ? '--referenceEstimates --map ' + mapMinimac : ''}");
// defaults.setProperty("eagle.command",
// "--vcfRef ${ref} --vcfTarget ${vcf} --geneticMapFile ${map} --outPrefix ${prefix} --bpStart ${start} --bpEnd ${end} --allowRefAltSwap --vcfOutFormat z --keepMissingPloidyX");
// defaults.setProperty("beagle.command",
// "-jar ${beagle} ref=${ref} gt=${vcf} out=${prefix} nthreads=1 chrom=${chr}:${start}-${end} map=${map} impute=false");
// defaults.setProperty("ref.fasta", "v37");
// defaults.setProperty("contact.name", "Christian Fuchsberger");
// defaults.setProperty("contact.email", "cfuchsb@umich.edu");
// defaults.setProperty("hg38Tohg19", "chains/hg38ToHg19.over.chain.gz");
// defaults.setProperty("hg19Tohg38", "chains/hg19ToHg38.over.chain.gz");
// defaults.setProperty("sanitycheck", "yes");
//
// return defaults;
// }
//
// }
| import java.io.File;
import cloudgene.sdk.internal.WorkflowContext;
import cloudgene.sdk.internal.WorkflowStep;
import genepi.imputationserver.util.DefaultPreferenceStore;
import genepi.io.FileUtil; | package genepi.imputationserver.steps;
public class FailureNotification extends WorkflowStep {
@Override
public boolean run(WorkflowContext context) {
Object mail = context.getData("cloudgene.user.mail");
Object name = context.getData("cloudgene.user.name");
String step = context.getData("cloudgene.failedStep.classname").toString();
// load job.config
String folder = getFolder(FailureNotification.class);
File jobConfig = new File(FileUtil.path(folder, "job.config")); | // Path: src/main/java/genepi/imputationserver/util/DefaultPreferenceStore.java
// public class DefaultPreferenceStore {
//
// private Properties properties = new Properties(defaults());
//
// public DefaultPreferenceStore(Configuration configuration) {
// load(configuration);
// }
//
// public void load(File file) {
// try {
// properties.load(new FileInputStream(file));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public DefaultPreferenceStore() {
//
// }
//
// public void load(Configuration configuration) {
// Map<String, String> pairs = configuration.getValByRegex("cloudgene.*");
// for (String key : pairs.keySet()) {
// String cleanKey = key.replace("cloudgene.", "");
// String value = pairs.get(key);
// properties.setProperty(cleanKey, value);
// }
// }
//
// public void write(Configuration configuration) {
//
// for (Object key : properties.keySet()) {
// String newKey = "cloudgene." + key.toString();
// String value = properties.getProperty(key.toString());
// configuration.set(newKey, value);
// }
//
// }
//
// public String getString(String key) {
// return properties.getProperty(key);
// }
//
// public void setString(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Set<Object> getKeys() {
// return new HashSet<Object>(Collections.list(properties.propertyNames()));
// }
//
// public static Properties defaults() {
//
// Properties defaults = new Properties();
// defaults.setProperty("chunksize", "20000000");
// defaults.setProperty("phasing.window", "5000000");
// defaults.setProperty("minimac.window", "500000");
// defaults.setProperty("minimac.sendmail", "no");
// defaults.setProperty("server.url", "https://imputationserver.sph.umich.edu");
// defaults.setProperty("minimac.tmp", "/tmp");
// defaults.setProperty("minimac.command",
// "--refHaps ${ref} --haps ${vcf} --start ${start} --end ${end} --window ${window} --prefix ${prefix} --chr ${chr} --cpus 1 --noPhoneHome --format GT,DS,GP --allTypedSites --meta --minRatio 0.00001 ${chr =='MT' ? '--myChromosome ' + chr : ''} ${unphased ? '--unphasedOutput' : ''} ${mapMinimac != null ? '--referenceEstimates --map ' + mapMinimac : ''}");
// defaults.setProperty("eagle.command",
// "--vcfRef ${ref} --vcfTarget ${vcf} --geneticMapFile ${map} --outPrefix ${prefix} --bpStart ${start} --bpEnd ${end} --allowRefAltSwap --vcfOutFormat z --keepMissingPloidyX");
// defaults.setProperty("beagle.command",
// "-jar ${beagle} ref=${ref} gt=${vcf} out=${prefix} nthreads=1 chrom=${chr}:${start}-${end} map=${map} impute=false");
// defaults.setProperty("ref.fasta", "v37");
// defaults.setProperty("contact.name", "Christian Fuchsberger");
// defaults.setProperty("contact.email", "cfuchsb@umich.edu");
// defaults.setProperty("hg38Tohg19", "chains/hg38ToHg19.over.chain.gz");
// defaults.setProperty("hg19Tohg38", "chains/hg19ToHg38.over.chain.gz");
// defaults.setProperty("sanitycheck", "yes");
//
// return defaults;
// }
//
// }
// Path: src/main/java/genepi/imputationserver/steps/FailureNotification.java
import java.io.File;
import cloudgene.sdk.internal.WorkflowContext;
import cloudgene.sdk.internal.WorkflowStep;
import genepi.imputationserver.util.DefaultPreferenceStore;
import genepi.io.FileUtil;
package genepi.imputationserver.steps;
public class FailureNotification extends WorkflowStep {
@Override
public boolean run(WorkflowContext context) {
Object mail = context.getData("cloudgene.user.mail");
Object name = context.getData("cloudgene.user.name");
String step = context.getData("cloudgene.failedStep.classname").toString();
// load job.config
String folder = getFolder(FailureNotification.class);
File jobConfig = new File(FileUtil.path(folder, "job.config")); | DefaultPreferenceStore store = new DefaultPreferenceStore(); |
genepi/imputationserver | src/main/java/genepi/imputationserver/tools/LegendFileLiftOverTool.java | // Path: src/main/java/genepi/imputationserver/util/LegendFileLiftOver.java
// public class LegendFileLiftOver {
//
// public static class LegendFileLiftOverResults{
//
// public Vector<String> errors;
//
// public int snpsWritten;
//
// }
//
// public static LegendFileLiftOverResults liftOver(String input, String output, String chainFile, String tempDir,
// String chromosome) throws IOException {
//
// LineReader reader = new LineReader(input);
// GzipLineWriter writer = new GzipLineWriter(output);
//
// LiftOver liftOver = new LiftOver(new File(chainFile));
//
// Vector<String> errors = new Vector<String>();
// Vector<String> buffer = new Vector<String>();
//
// // read file and perform lift over
// while (reader.next()) {
// String line = reader.get();
// if (line.startsWith("id")) {
// writer.write(line);
// } else {
//
// String[] tiles = line.split(" ", 3);
// Interval source = new Interval("chr" + chromosome, Integer.parseInt(tiles[1]),
// Integer.parseInt(tiles[1]) + 1, false, chromosome + ":" + tiles[1]);
// Interval target = liftOver.liftOver(source);
// if (target != null) {
// if (source.getContig().equals(target.getContig())) {
// buffer.add(tiles[0] + " " + target.getStart() + " " + tiles[2]);
// } else {
// errors.add(target.getContig() + ":" + tiles[1] + "\t" + "LiftOver" + "\t"
// + "On different chromosome after LiftOver. SNP removed.");
// }
// } else {
// errors.add(tiles[0] + ":" + tiles[1] + "\t" + "LiftOver" + "\t" + "LiftOver failed. SNP removed.");
// }
// }
//
// }
//
// // sort legend file by position
// Collections.sort(buffer, new Comparator<String>() {
// @Override
// public int compare(String o1, String o2) {
// String[] tiles1 = o1.split(" ", 3);
// String[] tiles2 = o2.split(" ", 3);
// int position1 = Integer.parseInt(tiles1[1]);
// int position2 = Integer.parseInt(tiles2[1]);
// return Integer.compare(position1, position2);
// }
// });
//
// // write file
// for (String line : buffer) {
// writer.write(line);
// }
//
// reader.close();
// writer.close();
//
// LegendFileLiftOverResults result = new LegendFileLiftOverResults();
// result.errors = errors;
// result.snpsWritten = buffer.size();
//
// return result;
// }
//
// }
//
// Path: src/main/java/genepi/imputationserver/util/LegendFileLiftOver.java
// public static class LegendFileLiftOverResults{
//
// public Vector<String> errors;
//
// public int snpsWritten;
//
// }
| import genepi.base.Tool;
import genepi.imputationserver.util.LegendFileLiftOver;
import genepi.imputationserver.util.LegendFileLiftOver.LegendFileLiftOverResults;
import genepi.io.text.LineWriter; | package genepi.imputationserver.tools;
public class LegendFileLiftOverTool extends Tool {
public LegendFileLiftOverTool(String[] args) {
super(args);
}
@Override
public void createParameters() {
addParameter("input", "input vcf file");
addParameter("output", "output vcf file");
addParameter("chr", "chromosome");
addParameter("chain", "chain file");
}
@Override
public void init() {
System.out.println("LegendFile LiftOver Tool");
System.out.println("");
}
@Override
public int run() {
String input = getValue("input").toString();
String output = getValue("output").toString();
String chain = getValue("chain").toString();
String chromosome = getValue("chr").toString();
try { | // Path: src/main/java/genepi/imputationserver/util/LegendFileLiftOver.java
// public class LegendFileLiftOver {
//
// public static class LegendFileLiftOverResults{
//
// public Vector<String> errors;
//
// public int snpsWritten;
//
// }
//
// public static LegendFileLiftOverResults liftOver(String input, String output, String chainFile, String tempDir,
// String chromosome) throws IOException {
//
// LineReader reader = new LineReader(input);
// GzipLineWriter writer = new GzipLineWriter(output);
//
// LiftOver liftOver = new LiftOver(new File(chainFile));
//
// Vector<String> errors = new Vector<String>();
// Vector<String> buffer = new Vector<String>();
//
// // read file and perform lift over
// while (reader.next()) {
// String line = reader.get();
// if (line.startsWith("id")) {
// writer.write(line);
// } else {
//
// String[] tiles = line.split(" ", 3);
// Interval source = new Interval("chr" + chromosome, Integer.parseInt(tiles[1]),
// Integer.parseInt(tiles[1]) + 1, false, chromosome + ":" + tiles[1]);
// Interval target = liftOver.liftOver(source);
// if (target != null) {
// if (source.getContig().equals(target.getContig())) {
// buffer.add(tiles[0] + " " + target.getStart() + " " + tiles[2]);
// } else {
// errors.add(target.getContig() + ":" + tiles[1] + "\t" + "LiftOver" + "\t"
// + "On different chromosome after LiftOver. SNP removed.");
// }
// } else {
// errors.add(tiles[0] + ":" + tiles[1] + "\t" + "LiftOver" + "\t" + "LiftOver failed. SNP removed.");
// }
// }
//
// }
//
// // sort legend file by position
// Collections.sort(buffer, new Comparator<String>() {
// @Override
// public int compare(String o1, String o2) {
// String[] tiles1 = o1.split(" ", 3);
// String[] tiles2 = o2.split(" ", 3);
// int position1 = Integer.parseInt(tiles1[1]);
// int position2 = Integer.parseInt(tiles2[1]);
// return Integer.compare(position1, position2);
// }
// });
//
// // write file
// for (String line : buffer) {
// writer.write(line);
// }
//
// reader.close();
// writer.close();
//
// LegendFileLiftOverResults result = new LegendFileLiftOverResults();
// result.errors = errors;
// result.snpsWritten = buffer.size();
//
// return result;
// }
//
// }
//
// Path: src/main/java/genepi/imputationserver/util/LegendFileLiftOver.java
// public static class LegendFileLiftOverResults{
//
// public Vector<String> errors;
//
// public int snpsWritten;
//
// }
// Path: src/main/java/genepi/imputationserver/tools/LegendFileLiftOverTool.java
import genepi.base.Tool;
import genepi.imputationserver.util.LegendFileLiftOver;
import genepi.imputationserver.util.LegendFileLiftOver.LegendFileLiftOverResults;
import genepi.io.text.LineWriter;
package genepi.imputationserver.tools;
public class LegendFileLiftOverTool extends Tool {
public LegendFileLiftOverTool(String[] args) {
super(args);
}
@Override
public void createParameters() {
addParameter("input", "input vcf file");
addParameter("output", "output vcf file");
addParameter("chr", "chromosome");
addParameter("chain", "chain file");
}
@Override
public void init() {
System.out.println("LegendFile LiftOver Tool");
System.out.println("");
}
@Override
public int run() {
String input = getValue("input").toString();
String output = getValue("output").toString();
String chain = getValue("chain").toString();
String chromosome = getValue("chr").toString();
try { | LegendFileLiftOverResults results = LegendFileLiftOver.liftOver(input, output, chain, "", chromosome); |
genepi/imputationserver | src/main/java/genepi/imputationserver/tools/LegendFileLiftOverTool.java | // Path: src/main/java/genepi/imputationserver/util/LegendFileLiftOver.java
// public class LegendFileLiftOver {
//
// public static class LegendFileLiftOverResults{
//
// public Vector<String> errors;
//
// public int snpsWritten;
//
// }
//
// public static LegendFileLiftOverResults liftOver(String input, String output, String chainFile, String tempDir,
// String chromosome) throws IOException {
//
// LineReader reader = new LineReader(input);
// GzipLineWriter writer = new GzipLineWriter(output);
//
// LiftOver liftOver = new LiftOver(new File(chainFile));
//
// Vector<String> errors = new Vector<String>();
// Vector<String> buffer = new Vector<String>();
//
// // read file and perform lift over
// while (reader.next()) {
// String line = reader.get();
// if (line.startsWith("id")) {
// writer.write(line);
// } else {
//
// String[] tiles = line.split(" ", 3);
// Interval source = new Interval("chr" + chromosome, Integer.parseInt(tiles[1]),
// Integer.parseInt(tiles[1]) + 1, false, chromosome + ":" + tiles[1]);
// Interval target = liftOver.liftOver(source);
// if (target != null) {
// if (source.getContig().equals(target.getContig())) {
// buffer.add(tiles[0] + " " + target.getStart() + " " + tiles[2]);
// } else {
// errors.add(target.getContig() + ":" + tiles[1] + "\t" + "LiftOver" + "\t"
// + "On different chromosome after LiftOver. SNP removed.");
// }
// } else {
// errors.add(tiles[0] + ":" + tiles[1] + "\t" + "LiftOver" + "\t" + "LiftOver failed. SNP removed.");
// }
// }
//
// }
//
// // sort legend file by position
// Collections.sort(buffer, new Comparator<String>() {
// @Override
// public int compare(String o1, String o2) {
// String[] tiles1 = o1.split(" ", 3);
// String[] tiles2 = o2.split(" ", 3);
// int position1 = Integer.parseInt(tiles1[1]);
// int position2 = Integer.parseInt(tiles2[1]);
// return Integer.compare(position1, position2);
// }
// });
//
// // write file
// for (String line : buffer) {
// writer.write(line);
// }
//
// reader.close();
// writer.close();
//
// LegendFileLiftOverResults result = new LegendFileLiftOverResults();
// result.errors = errors;
// result.snpsWritten = buffer.size();
//
// return result;
// }
//
// }
//
// Path: src/main/java/genepi/imputationserver/util/LegendFileLiftOver.java
// public static class LegendFileLiftOverResults{
//
// public Vector<String> errors;
//
// public int snpsWritten;
//
// }
| import genepi.base.Tool;
import genepi.imputationserver.util.LegendFileLiftOver;
import genepi.imputationserver.util.LegendFileLiftOver.LegendFileLiftOverResults;
import genepi.io.text.LineWriter; | package genepi.imputationserver.tools;
public class LegendFileLiftOverTool extends Tool {
public LegendFileLiftOverTool(String[] args) {
super(args);
}
@Override
public void createParameters() {
addParameter("input", "input vcf file");
addParameter("output", "output vcf file");
addParameter("chr", "chromosome");
addParameter("chain", "chain file");
}
@Override
public void init() {
System.out.println("LegendFile LiftOver Tool");
System.out.println("");
}
@Override
public int run() {
String input = getValue("input").toString();
String output = getValue("output").toString();
String chain = getValue("chain").toString();
String chromosome = getValue("chr").toString();
try { | // Path: src/main/java/genepi/imputationserver/util/LegendFileLiftOver.java
// public class LegendFileLiftOver {
//
// public static class LegendFileLiftOverResults{
//
// public Vector<String> errors;
//
// public int snpsWritten;
//
// }
//
// public static LegendFileLiftOverResults liftOver(String input, String output, String chainFile, String tempDir,
// String chromosome) throws IOException {
//
// LineReader reader = new LineReader(input);
// GzipLineWriter writer = new GzipLineWriter(output);
//
// LiftOver liftOver = new LiftOver(new File(chainFile));
//
// Vector<String> errors = new Vector<String>();
// Vector<String> buffer = new Vector<String>();
//
// // read file and perform lift over
// while (reader.next()) {
// String line = reader.get();
// if (line.startsWith("id")) {
// writer.write(line);
// } else {
//
// String[] tiles = line.split(" ", 3);
// Interval source = new Interval("chr" + chromosome, Integer.parseInt(tiles[1]),
// Integer.parseInt(tiles[1]) + 1, false, chromosome + ":" + tiles[1]);
// Interval target = liftOver.liftOver(source);
// if (target != null) {
// if (source.getContig().equals(target.getContig())) {
// buffer.add(tiles[0] + " " + target.getStart() + " " + tiles[2]);
// } else {
// errors.add(target.getContig() + ":" + tiles[1] + "\t" + "LiftOver" + "\t"
// + "On different chromosome after LiftOver. SNP removed.");
// }
// } else {
// errors.add(tiles[0] + ":" + tiles[1] + "\t" + "LiftOver" + "\t" + "LiftOver failed. SNP removed.");
// }
// }
//
// }
//
// // sort legend file by position
// Collections.sort(buffer, new Comparator<String>() {
// @Override
// public int compare(String o1, String o2) {
// String[] tiles1 = o1.split(" ", 3);
// String[] tiles2 = o2.split(" ", 3);
// int position1 = Integer.parseInt(tiles1[1]);
// int position2 = Integer.parseInt(tiles2[1]);
// return Integer.compare(position1, position2);
// }
// });
//
// // write file
// for (String line : buffer) {
// writer.write(line);
// }
//
// reader.close();
// writer.close();
//
// LegendFileLiftOverResults result = new LegendFileLiftOverResults();
// result.errors = errors;
// result.snpsWritten = buffer.size();
//
// return result;
// }
//
// }
//
// Path: src/main/java/genepi/imputationserver/util/LegendFileLiftOver.java
// public static class LegendFileLiftOverResults{
//
// public Vector<String> errors;
//
// public int snpsWritten;
//
// }
// Path: src/main/java/genepi/imputationserver/tools/LegendFileLiftOverTool.java
import genepi.base.Tool;
import genepi.imputationserver.util.LegendFileLiftOver;
import genepi.imputationserver.util.LegendFileLiftOver.LegendFileLiftOverResults;
import genepi.io.text.LineWriter;
package genepi.imputationserver.tools;
public class LegendFileLiftOverTool extends Tool {
public LegendFileLiftOverTool(String[] args) {
super(args);
}
@Override
public void createParameters() {
addParameter("input", "input vcf file");
addParameter("output", "output vcf file");
addParameter("chr", "chromosome");
addParameter("chain", "chain file");
}
@Override
public void init() {
System.out.println("LegendFile LiftOver Tool");
System.out.println("");
}
@Override
public int run() {
String input = getValue("input").toString();
String output = getValue("output").toString();
String chain = getValue("chain").toString();
String chromosome = getValue("chr").toString();
try { | LegendFileLiftOverResults results = LegendFileLiftOver.liftOver(input, output, chain, "", chromosome); |
genepi/imputationserver | src/main/java/genepi/imputationserver/tools/VcfLiftOverTool.java | // Path: src/main/java/genepi/imputationserver/steps/vcf/VcfLiftOverFast.java
// public class VcfLiftOverFast {
//
// private static final int MAX_RECORDS_IN_RAM = 1000;
//
// public static Vector<String> liftOver(String input, String output, String chainFile, String tempDir)
// throws IOException {
//
// LineReader reader = new LineReader(input);
//
// LiftOver liftOver = new LiftOver(new File(chainFile));
//
// Vector<String> errors = new Vector<String>();
//
// SortingCollection<VcfLine> sorter = VcfLineSortingCollection.newInstance(MAX_RECORDS_IN_RAM, tempDir);
//
// BGzipLineWriter writer = new BGzipLineWriter(output);
// while (reader.next()) {
// String line = reader.get();
// if (line.startsWith("#")) {
// writer.write(line);
// } else {
//
// VcfLine vcfLine = new VcfLine(line);
// String contig = "";
// String newContig = "";
//
// if (vcfLine.getContig().equals("chr23")) {
// vcfLine.setContig("chrX");
// }
// if (vcfLine.getContig().equals("23")) {
// vcfLine.setContig("X");
// }
//
// if (vcfLine.getContig().startsWith("chr")) {
// contig = vcfLine.getContig();
// newContig = vcfLine.getContig().replaceAll("chr", "");
//
// } else {
// contig = "chr" + vcfLine.getContig();
// newContig = "chr" + vcfLine.getContig();
// }
// Interval source = new Interval(contig, vcfLine.getPosition(), vcfLine.getPosition() + 1, false,
// vcfLine.getContig() + ":" + vcfLine.getPosition());
// Interval target = liftOver.liftOver(source);
// if (target != null) {
// if (source.getContig().equals(target.getContig())) {
// vcfLine.setContig(newContig);
// vcfLine.setPosition(target.getStart());
// sorter.add(vcfLine);
// } else {
// errors.add(vcfLine.getContig() + ":" + vcfLine.getPosition() + "\t" + "LiftOver" + "\t"
// + "On different chromosome after LiftOver. SNP removed.");
// }
// } else {
// errors.add(vcfLine.getContig() + ":" + vcfLine.getPosition() + "\t" + "LiftOver" + "\t"
// + "LiftOver failed. SNP removed.");
// }
// }
//
// }
// reader.close();
// sorter.doneAdding();
//
// int pos = -1;
// for (VcfLine vcfLine : sorter) {
// if (vcfLine.getPosition() < pos) {
// throw new IOException("Sorting VCF file after Liftover failed.");
// }
// writer.write(vcfLine.getLine());
// pos = vcfLine.getPosition();
// }
// writer.close();
// sorter.cleanup();
//
// return errors;
// }
//
// }
| import genepi.base.Tool;
import genepi.imputationserver.steps.vcf.VcfLiftOverFast; | package genepi.imputationserver.tools;
public class VcfLiftOverTool extends Tool {
public VcfLiftOverTool(String[] args) {
super(args);
}
@Override
public void createParameters() {
addParameter("input", "input vcf file");
addParameter("output", "output vcf file");
addParameter("chain", "chain file");
}
@Override
public void init() {
System.out.println("VcfLiftOver Tool");
System.out.println("");
}
@Override
public int run() {
String input = getValue("input").toString();
String output = getValue("output").toString();
String chain = getValue("chain").toString();
try { | // Path: src/main/java/genepi/imputationserver/steps/vcf/VcfLiftOverFast.java
// public class VcfLiftOverFast {
//
// private static final int MAX_RECORDS_IN_RAM = 1000;
//
// public static Vector<String> liftOver(String input, String output, String chainFile, String tempDir)
// throws IOException {
//
// LineReader reader = new LineReader(input);
//
// LiftOver liftOver = new LiftOver(new File(chainFile));
//
// Vector<String> errors = new Vector<String>();
//
// SortingCollection<VcfLine> sorter = VcfLineSortingCollection.newInstance(MAX_RECORDS_IN_RAM, tempDir);
//
// BGzipLineWriter writer = new BGzipLineWriter(output);
// while (reader.next()) {
// String line = reader.get();
// if (line.startsWith("#")) {
// writer.write(line);
// } else {
//
// VcfLine vcfLine = new VcfLine(line);
// String contig = "";
// String newContig = "";
//
// if (vcfLine.getContig().equals("chr23")) {
// vcfLine.setContig("chrX");
// }
// if (vcfLine.getContig().equals("23")) {
// vcfLine.setContig("X");
// }
//
// if (vcfLine.getContig().startsWith("chr")) {
// contig = vcfLine.getContig();
// newContig = vcfLine.getContig().replaceAll("chr", "");
//
// } else {
// contig = "chr" + vcfLine.getContig();
// newContig = "chr" + vcfLine.getContig();
// }
// Interval source = new Interval(contig, vcfLine.getPosition(), vcfLine.getPosition() + 1, false,
// vcfLine.getContig() + ":" + vcfLine.getPosition());
// Interval target = liftOver.liftOver(source);
// if (target != null) {
// if (source.getContig().equals(target.getContig())) {
// vcfLine.setContig(newContig);
// vcfLine.setPosition(target.getStart());
// sorter.add(vcfLine);
// } else {
// errors.add(vcfLine.getContig() + ":" + vcfLine.getPosition() + "\t" + "LiftOver" + "\t"
// + "On different chromosome after LiftOver. SNP removed.");
// }
// } else {
// errors.add(vcfLine.getContig() + ":" + vcfLine.getPosition() + "\t" + "LiftOver" + "\t"
// + "LiftOver failed. SNP removed.");
// }
// }
//
// }
// reader.close();
// sorter.doneAdding();
//
// int pos = -1;
// for (VcfLine vcfLine : sorter) {
// if (vcfLine.getPosition() < pos) {
// throw new IOException("Sorting VCF file after Liftover failed.");
// }
// writer.write(vcfLine.getLine());
// pos = vcfLine.getPosition();
// }
// writer.close();
// sorter.cleanup();
//
// return errors;
// }
//
// }
// Path: src/main/java/genepi/imputationserver/tools/VcfLiftOverTool.java
import genepi.base.Tool;
import genepi.imputationserver.steps.vcf.VcfLiftOverFast;
package genepi.imputationserver.tools;
public class VcfLiftOverTool extends Tool {
public VcfLiftOverTool(String[] args) {
super(args);
}
@Override
public void createParameters() {
addParameter("input", "input vcf file");
addParameter("output", "output vcf file");
addParameter("chain", "chain file");
}
@Override
public void init() {
System.out.println("VcfLiftOver Tool");
System.out.println("");
}
@Override
public int run() {
String input = getValue("input").toString();
String output = getValue("output").toString();
String chain = getValue("chain").toString();
try { | VcfLiftOverFast.liftOver(input, output, chain, "./"); |
genepi/imputationserver | src/main/java/genepi/imputationserver/steps/vcf/VcfLiftOverFast.java | // Path: src/main/java/genepi/imputationserver/steps/vcf/sort/VcfLine.java
// public class VcfLine {
//
// private String data;
//
// private String contig;
//
// private int position;
//
// public VcfLine(String line) {
// String tiles[] = line.split("\t", 3);
// this.contig = tiles[0];
// this.position = Integer.parseInt(tiles[1]);
// this.data = tiles[2];
// }
//
// public String getLine() {
// return this.contig + "\t" + this.position + "\t" + this.data;
// }
//
// public int getPosition() {
// return position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public void setContig(String contig) {
// this.contig = contig;
// }
//
// public String getContig() {
// return contig;
// }
//
// }
//
// Path: src/main/java/genepi/imputationserver/steps/vcf/sort/VcfLineSortingCollection.java
// public class VcfLineSortingCollection {
//
// public static SortingCollection<VcfLine> newInstance(int maxRecords, String tempDir) {
// return SortingCollection.newInstance(VcfLine.class, new VcfLineCodec(), new VcfLineComparator(), maxRecords,
// new File(tempDir));
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.Vector;
import genepi.imputationserver.steps.vcf.sort.VcfLine;
import genepi.imputationserver.steps.vcf.sort.VcfLineSortingCollection;
import genepi.io.text.LineReader;
import htsjdk.samtools.liftover.LiftOver;
import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.SortingCollection; | package genepi.imputationserver.steps.vcf;
public class VcfLiftOverFast {
private static final int MAX_RECORDS_IN_RAM = 1000;
public static Vector<String> liftOver(String input, String output, String chainFile, String tempDir)
throws IOException {
LineReader reader = new LineReader(input);
LiftOver liftOver = new LiftOver(new File(chainFile));
Vector<String> errors = new Vector<String>();
| // Path: src/main/java/genepi/imputationserver/steps/vcf/sort/VcfLine.java
// public class VcfLine {
//
// private String data;
//
// private String contig;
//
// private int position;
//
// public VcfLine(String line) {
// String tiles[] = line.split("\t", 3);
// this.contig = tiles[0];
// this.position = Integer.parseInt(tiles[1]);
// this.data = tiles[2];
// }
//
// public String getLine() {
// return this.contig + "\t" + this.position + "\t" + this.data;
// }
//
// public int getPosition() {
// return position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public void setContig(String contig) {
// this.contig = contig;
// }
//
// public String getContig() {
// return contig;
// }
//
// }
//
// Path: src/main/java/genepi/imputationserver/steps/vcf/sort/VcfLineSortingCollection.java
// public class VcfLineSortingCollection {
//
// public static SortingCollection<VcfLine> newInstance(int maxRecords, String tempDir) {
// return SortingCollection.newInstance(VcfLine.class, new VcfLineCodec(), new VcfLineComparator(), maxRecords,
// new File(tempDir));
// }
//
// }
// Path: src/main/java/genepi/imputationserver/steps/vcf/VcfLiftOverFast.java
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import genepi.imputationserver.steps.vcf.sort.VcfLine;
import genepi.imputationserver.steps.vcf.sort.VcfLineSortingCollection;
import genepi.io.text.LineReader;
import htsjdk.samtools.liftover.LiftOver;
import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.SortingCollection;
package genepi.imputationserver.steps.vcf;
public class VcfLiftOverFast {
private static final int MAX_RECORDS_IN_RAM = 1000;
public static Vector<String> liftOver(String input, String output, String chainFile, String tempDir)
throws IOException {
LineReader reader = new LineReader(input);
LiftOver liftOver = new LiftOver(new File(chainFile));
Vector<String> errors = new Vector<String>();
| SortingCollection<VcfLine> sorter = VcfLineSortingCollection.newInstance(MAX_RECORDS_IN_RAM, tempDir); |
genepi/imputationserver | src/main/java/genepi/imputationserver/steps/vcf/VcfLiftOverFast.java | // Path: src/main/java/genepi/imputationserver/steps/vcf/sort/VcfLine.java
// public class VcfLine {
//
// private String data;
//
// private String contig;
//
// private int position;
//
// public VcfLine(String line) {
// String tiles[] = line.split("\t", 3);
// this.contig = tiles[0];
// this.position = Integer.parseInt(tiles[1]);
// this.data = tiles[2];
// }
//
// public String getLine() {
// return this.contig + "\t" + this.position + "\t" + this.data;
// }
//
// public int getPosition() {
// return position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public void setContig(String contig) {
// this.contig = contig;
// }
//
// public String getContig() {
// return contig;
// }
//
// }
//
// Path: src/main/java/genepi/imputationserver/steps/vcf/sort/VcfLineSortingCollection.java
// public class VcfLineSortingCollection {
//
// public static SortingCollection<VcfLine> newInstance(int maxRecords, String tempDir) {
// return SortingCollection.newInstance(VcfLine.class, new VcfLineCodec(), new VcfLineComparator(), maxRecords,
// new File(tempDir));
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.Vector;
import genepi.imputationserver.steps.vcf.sort.VcfLine;
import genepi.imputationserver.steps.vcf.sort.VcfLineSortingCollection;
import genepi.io.text.LineReader;
import htsjdk.samtools.liftover.LiftOver;
import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.SortingCollection; | package genepi.imputationserver.steps.vcf;
public class VcfLiftOverFast {
private static final int MAX_RECORDS_IN_RAM = 1000;
public static Vector<String> liftOver(String input, String output, String chainFile, String tempDir)
throws IOException {
LineReader reader = new LineReader(input);
LiftOver liftOver = new LiftOver(new File(chainFile));
Vector<String> errors = new Vector<String>();
| // Path: src/main/java/genepi/imputationserver/steps/vcf/sort/VcfLine.java
// public class VcfLine {
//
// private String data;
//
// private String contig;
//
// private int position;
//
// public VcfLine(String line) {
// String tiles[] = line.split("\t", 3);
// this.contig = tiles[0];
// this.position = Integer.parseInt(tiles[1]);
// this.data = tiles[2];
// }
//
// public String getLine() {
// return this.contig + "\t" + this.position + "\t" + this.data;
// }
//
// public int getPosition() {
// return position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public void setContig(String contig) {
// this.contig = contig;
// }
//
// public String getContig() {
// return contig;
// }
//
// }
//
// Path: src/main/java/genepi/imputationserver/steps/vcf/sort/VcfLineSortingCollection.java
// public class VcfLineSortingCollection {
//
// public static SortingCollection<VcfLine> newInstance(int maxRecords, String tempDir) {
// return SortingCollection.newInstance(VcfLine.class, new VcfLineCodec(), new VcfLineComparator(), maxRecords,
// new File(tempDir));
// }
//
// }
// Path: src/main/java/genepi/imputationserver/steps/vcf/VcfLiftOverFast.java
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import genepi.imputationserver.steps.vcf.sort.VcfLine;
import genepi.imputationserver.steps.vcf.sort.VcfLineSortingCollection;
import genepi.io.text.LineReader;
import htsjdk.samtools.liftover.LiftOver;
import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.SortingCollection;
package genepi.imputationserver.steps.vcf;
public class VcfLiftOverFast {
private static final int MAX_RECORDS_IN_RAM = 1000;
public static Vector<String> liftOver(String input, String output, String chainFile, String tempDir)
throws IOException {
LineReader reader = new LineReader(input);
LiftOver liftOver = new LiftOver(new File(chainFile));
Vector<String> errors = new Vector<String>();
| SortingCollection<VcfLine> sorter = VcfLineSortingCollection.newInstance(MAX_RECORDS_IN_RAM, tempDir); |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/common/HoconConfigUtilsTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String asConfigKey(String path) {
// return ((path != null) && !path.startsWith("\"") && path.contains("."))
// ? "\"" + path + "\""
// : path;
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static String asConfigPath(String key) {
// return stripQuotes(key);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static Map<String, String> getStringMap(Config config, String key) {
// ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
// try {
// for (String value : config.getStringList(key)) {
// builder.put(value, value);
// }
// } catch (ConfigException.WrongType e) {
// Config nestedConfig = config.getConfig(key);
// for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) {
// String nestedKey = entry.getKey();
// String quotelessKey = stripQuotes(nestedKey);
// try {
// builder.put(quotelessKey, nestedConfig.getString(nestedKey));
// } catch (ConfigException.WrongType ignore) {
// LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey);
// }
// }
// }
// return builder.build();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String stripQuotes(String key) {
// return ((key != null) && key.startsWith("\"") && (key.length() > 1) && key.endsWith("\""))
// ? key.substring(1, key.length() - 1)
// : key;
// }
| import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigKey;
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigPath;
import static com.cloudera.director.aws.common.HoconConfigUtils.getStringMap;
import static com.cloudera.director.aws.common.HoconConfigUtils.stripQuotes;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigException;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.junit.Assert.fail;
import org.junit.Test; | // (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.common;
/**
* Tests {@code ConfigUtils}.
*/
public class HoconConfigUtilsTest {
@Test
public void testAsConfigKey() { | // Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String asConfigKey(String path) {
// return ((path != null) && !path.startsWith("\"") && path.contains("."))
// ? "\"" + path + "\""
// : path;
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static String asConfigPath(String key) {
// return stripQuotes(key);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static Map<String, String> getStringMap(Config config, String key) {
// ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
// try {
// for (String value : config.getStringList(key)) {
// builder.put(value, value);
// }
// } catch (ConfigException.WrongType e) {
// Config nestedConfig = config.getConfig(key);
// for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) {
// String nestedKey = entry.getKey();
// String quotelessKey = stripQuotes(nestedKey);
// try {
// builder.put(quotelessKey, nestedConfig.getString(nestedKey));
// } catch (ConfigException.WrongType ignore) {
// LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey);
// }
// }
// }
// return builder.build();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String stripQuotes(String key) {
// return ((key != null) && key.startsWith("\"") && (key.length() > 1) && key.endsWith("\""))
// ? key.substring(1, key.length() - 1)
// : key;
// }
// Path: tests/src/test/java/com/cloudera/director/aws/common/HoconConfigUtilsTest.java
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigKey;
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigPath;
import static com.cloudera.director.aws.common.HoconConfigUtils.getStringMap;
import static com.cloudera.director.aws.common.HoconConfigUtils.stripQuotes;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigException;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.junit.Assert.fail;
import org.junit.Test;
// (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.common;
/**
* Tests {@code ConfigUtils}.
*/
public class HoconConfigUtilsTest {
@Test
public void testAsConfigKey() { | assertThat(asConfigKey(null)).isNull(); |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/common/HoconConfigUtilsTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String asConfigKey(String path) {
// return ((path != null) && !path.startsWith("\"") && path.contains("."))
// ? "\"" + path + "\""
// : path;
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static String asConfigPath(String key) {
// return stripQuotes(key);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static Map<String, String> getStringMap(Config config, String key) {
// ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
// try {
// for (String value : config.getStringList(key)) {
// builder.put(value, value);
// }
// } catch (ConfigException.WrongType e) {
// Config nestedConfig = config.getConfig(key);
// for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) {
// String nestedKey = entry.getKey();
// String quotelessKey = stripQuotes(nestedKey);
// try {
// builder.put(quotelessKey, nestedConfig.getString(nestedKey));
// } catch (ConfigException.WrongType ignore) {
// LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey);
// }
// }
// }
// return builder.build();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String stripQuotes(String key) {
// return ((key != null) && key.startsWith("\"") && (key.length() > 1) && key.endsWith("\""))
// ? key.substring(1, key.length() - 1)
// : key;
// }
| import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigKey;
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigPath;
import static com.cloudera.director.aws.common.HoconConfigUtils.getStringMap;
import static com.cloudera.director.aws.common.HoconConfigUtils.stripQuotes;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigException;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.junit.Assert.fail;
import org.junit.Test; | // (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.common;
/**
* Tests {@code ConfigUtils}.
*/
public class HoconConfigUtilsTest {
@Test
public void testAsConfigKey() {
assertThat(asConfigKey(null)).isNull();
assertThat(asConfigKey("")).isEqualTo("");
assertThat(asConfigKey("\"")).isEqualTo("\"");
assertThat(asConfigKey("a")).isEqualTo("a");
assertThat(asConfigKey("a.b")).isEqualTo("\"a.b\"");
assertThat(asConfigKey("\"a.b\"")).isEqualTo("\"a.b\"");
}
@Test
public void testAsConfigPath() { | // Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String asConfigKey(String path) {
// return ((path != null) && !path.startsWith("\"") && path.contains("."))
// ? "\"" + path + "\""
// : path;
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static String asConfigPath(String key) {
// return stripQuotes(key);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static Map<String, String> getStringMap(Config config, String key) {
// ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
// try {
// for (String value : config.getStringList(key)) {
// builder.put(value, value);
// }
// } catch (ConfigException.WrongType e) {
// Config nestedConfig = config.getConfig(key);
// for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) {
// String nestedKey = entry.getKey();
// String quotelessKey = stripQuotes(nestedKey);
// try {
// builder.put(quotelessKey, nestedConfig.getString(nestedKey));
// } catch (ConfigException.WrongType ignore) {
// LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey);
// }
// }
// }
// return builder.build();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String stripQuotes(String key) {
// return ((key != null) && key.startsWith("\"") && (key.length() > 1) && key.endsWith("\""))
// ? key.substring(1, key.length() - 1)
// : key;
// }
// Path: tests/src/test/java/com/cloudera/director/aws/common/HoconConfigUtilsTest.java
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigKey;
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigPath;
import static com.cloudera.director.aws.common.HoconConfigUtils.getStringMap;
import static com.cloudera.director.aws.common.HoconConfigUtils.stripQuotes;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigException;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.junit.Assert.fail;
import org.junit.Test;
// (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.common;
/**
* Tests {@code ConfigUtils}.
*/
public class HoconConfigUtilsTest {
@Test
public void testAsConfigKey() {
assertThat(asConfigKey(null)).isNull();
assertThat(asConfigKey("")).isEqualTo("");
assertThat(asConfigKey("\"")).isEqualTo("\"");
assertThat(asConfigKey("a")).isEqualTo("a");
assertThat(asConfigKey("a.b")).isEqualTo("\"a.b\"");
assertThat(asConfigKey("\"a.b\"")).isEqualTo("\"a.b\"");
}
@Test
public void testAsConfigPath() { | assertThat(asConfigPath(null)).isNull(); |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/common/HoconConfigUtilsTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String asConfigKey(String path) {
// return ((path != null) && !path.startsWith("\"") && path.contains("."))
// ? "\"" + path + "\""
// : path;
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static String asConfigPath(String key) {
// return stripQuotes(key);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static Map<String, String> getStringMap(Config config, String key) {
// ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
// try {
// for (String value : config.getStringList(key)) {
// builder.put(value, value);
// }
// } catch (ConfigException.WrongType e) {
// Config nestedConfig = config.getConfig(key);
// for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) {
// String nestedKey = entry.getKey();
// String quotelessKey = stripQuotes(nestedKey);
// try {
// builder.put(quotelessKey, nestedConfig.getString(nestedKey));
// } catch (ConfigException.WrongType ignore) {
// LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey);
// }
// }
// }
// return builder.build();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String stripQuotes(String key) {
// return ((key != null) && key.startsWith("\"") && (key.length() > 1) && key.endsWith("\""))
// ? key.substring(1, key.length() - 1)
// : key;
// }
| import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigKey;
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigPath;
import static com.cloudera.director.aws.common.HoconConfigUtils.getStringMap;
import static com.cloudera.director.aws.common.HoconConfigUtils.stripQuotes;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigException;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.junit.Assert.fail;
import org.junit.Test; | // (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.common;
/**
* Tests {@code ConfigUtils}.
*/
public class HoconConfigUtilsTest {
@Test
public void testAsConfigKey() {
assertThat(asConfigKey(null)).isNull();
assertThat(asConfigKey("")).isEqualTo("");
assertThat(asConfigKey("\"")).isEqualTo("\"");
assertThat(asConfigKey("a")).isEqualTo("a");
assertThat(asConfigKey("a.b")).isEqualTo("\"a.b\"");
assertThat(asConfigKey("\"a.b\"")).isEqualTo("\"a.b\"");
}
@Test
public void testAsConfigPath() {
assertThat(asConfigPath(null)).isNull();
assertThat(asConfigPath("")).isEqualTo("");
assertThat(asConfigPath("a")).isEqualTo("a");
assertThat(asConfigPath("\"")).isEqualTo("\"");
assertThat(asConfigPath("\"a")).isEqualTo("\"a");
assertThat(asConfigPath("\"a.b\"")).isEqualTo("a.b");
}
@Test
public void testStripQuotes() { | // Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String asConfigKey(String path) {
// return ((path != null) && !path.startsWith("\"") && path.contains("."))
// ? "\"" + path + "\""
// : path;
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static String asConfigPath(String key) {
// return stripQuotes(key);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static Map<String, String> getStringMap(Config config, String key) {
// ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
// try {
// for (String value : config.getStringList(key)) {
// builder.put(value, value);
// }
// } catch (ConfigException.WrongType e) {
// Config nestedConfig = config.getConfig(key);
// for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) {
// String nestedKey = entry.getKey();
// String quotelessKey = stripQuotes(nestedKey);
// try {
// builder.put(quotelessKey, nestedConfig.getString(nestedKey));
// } catch (ConfigException.WrongType ignore) {
// LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey);
// }
// }
// }
// return builder.build();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String stripQuotes(String key) {
// return ((key != null) && key.startsWith("\"") && (key.length() > 1) && key.endsWith("\""))
// ? key.substring(1, key.length() - 1)
// : key;
// }
// Path: tests/src/test/java/com/cloudera/director/aws/common/HoconConfigUtilsTest.java
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigKey;
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigPath;
import static com.cloudera.director.aws.common.HoconConfigUtils.getStringMap;
import static com.cloudera.director.aws.common.HoconConfigUtils.stripQuotes;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigException;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.junit.Assert.fail;
import org.junit.Test;
// (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.common;
/**
* Tests {@code ConfigUtils}.
*/
public class HoconConfigUtilsTest {
@Test
public void testAsConfigKey() {
assertThat(asConfigKey(null)).isNull();
assertThat(asConfigKey("")).isEqualTo("");
assertThat(asConfigKey("\"")).isEqualTo("\"");
assertThat(asConfigKey("a")).isEqualTo("a");
assertThat(asConfigKey("a.b")).isEqualTo("\"a.b\"");
assertThat(asConfigKey("\"a.b\"")).isEqualTo("\"a.b\"");
}
@Test
public void testAsConfigPath() {
assertThat(asConfigPath(null)).isNull();
assertThat(asConfigPath("")).isEqualTo("");
assertThat(asConfigPath("a")).isEqualTo("a");
assertThat(asConfigPath("\"")).isEqualTo("\"");
assertThat(asConfigPath("\"a")).isEqualTo("\"a");
assertThat(asConfigPath("\"a.b\"")).isEqualTo("a.b");
}
@Test
public void testStripQuotes() { | assertThat(stripQuotes(null)).isNull(); |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/common/HoconConfigUtilsTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String asConfigKey(String path) {
// return ((path != null) && !path.startsWith("\"") && path.contains("."))
// ? "\"" + path + "\""
// : path;
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static String asConfigPath(String key) {
// return stripQuotes(key);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static Map<String, String> getStringMap(Config config, String key) {
// ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
// try {
// for (String value : config.getStringList(key)) {
// builder.put(value, value);
// }
// } catch (ConfigException.WrongType e) {
// Config nestedConfig = config.getConfig(key);
// for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) {
// String nestedKey = entry.getKey();
// String quotelessKey = stripQuotes(nestedKey);
// try {
// builder.put(quotelessKey, nestedConfig.getString(nestedKey));
// } catch (ConfigException.WrongType ignore) {
// LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey);
// }
// }
// }
// return builder.build();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String stripQuotes(String key) {
// return ((key != null) && key.startsWith("\"") && (key.length() > 1) && key.endsWith("\""))
// ? key.substring(1, key.length() - 1)
// : key;
// }
| import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigKey;
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigPath;
import static com.cloudera.director.aws.common.HoconConfigUtils.getStringMap;
import static com.cloudera.director.aws.common.HoconConfigUtils.stripQuotes;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigException;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.junit.Assert.fail;
import org.junit.Test; | @Test
public void testGettersWithConfigPath() {
Config config =
ConfigFactory.parseString("{\n quux: {\n baz: {\n x:y\n }\n }\n}");
try {
config.getString("\"quux.baz\"");
fail("Found \"quux.baz\" unexpectedly.");
} catch (ConfigException.Missing ignore) {
}
assertThat(config.getConfig(asConfigPath("\"quux.baz\""))
.getString(asConfigKey("x"))).isEqualTo("y");
}
@Test
public void testGettersWithStripQuotes() {
Config config =
ConfigFactory.parseString("{\n quux: {\n baz: {\n x:y\n }\n }\n}");
try {
config.getString("\"quux.baz\"");
fail("Found \"quux.baz\" unexpectedly.");
} catch (ConfigException.Missing ignore) {
}
assertThat(config.getConfig(stripQuotes("\"quux\"")).
getConfig(stripQuotes("\"baz\"")).getString(asConfigKey("x"))).isEqualTo("y");
}
@Test
public void testGetStringMap() {
Config config = ConfigFactory.parseString(
"{\n quux: {\n baz: {\n x:y\n },\n \"w\":z\n }\n a: [1, 2]\n b:3\n}"); | // Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String asConfigKey(String path) {
// return ((path != null) && !path.startsWith("\"") && path.contains("."))
// ? "\"" + path + "\""
// : path;
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static String asConfigPath(String key) {
// return stripQuotes(key);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// public static Map<String, String> getStringMap(Config config, String key) {
// ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
// try {
// for (String value : config.getStringList(key)) {
// builder.put(value, value);
// }
// } catch (ConfigException.WrongType e) {
// Config nestedConfig = config.getConfig(key);
// for (Map.Entry<String, ConfigValue> entry : nestedConfig.root().entrySet()) {
// String nestedKey = entry.getKey();
// String quotelessKey = stripQuotes(nestedKey);
// try {
// builder.put(quotelessKey, nestedConfig.getString(nestedKey));
// } catch (ConfigException.WrongType ignore) {
// LOG.warn("Ignoring non-string-valued key: '{}'", quotelessKey);
// }
// }
// }
// return builder.build();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/HoconConfigUtils.java
// @SuppressWarnings("PMD.UselessParentheses")
// public static String stripQuotes(String key) {
// return ((key != null) && key.startsWith("\"") && (key.length() > 1) && key.endsWith("\""))
// ? key.substring(1, key.length() - 1)
// : key;
// }
// Path: tests/src/test/java/com/cloudera/director/aws/common/HoconConfigUtilsTest.java
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigKey;
import static com.cloudera.director.aws.common.HoconConfigUtils.asConfigPath;
import static com.cloudera.director.aws.common.HoconConfigUtils.getStringMap;
import static com.cloudera.director.aws.common.HoconConfigUtils.stripQuotes;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigException;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.junit.Assert.fail;
import org.junit.Test;
@Test
public void testGettersWithConfigPath() {
Config config =
ConfigFactory.parseString("{\n quux: {\n baz: {\n x:y\n }\n }\n}");
try {
config.getString("\"quux.baz\"");
fail("Found \"quux.baz\" unexpectedly.");
} catch (ConfigException.Missing ignore) {
}
assertThat(config.getConfig(asConfigPath("\"quux.baz\""))
.getString(asConfigKey("x"))).isEqualTo("y");
}
@Test
public void testGettersWithStripQuotes() {
Config config =
ConfigFactory.parseString("{\n quux: {\n baz: {\n x:y\n }\n }\n}");
try {
config.getString("\"quux.baz\"");
fail("Found \"quux.baz\" unexpectedly.");
} catch (ConfigException.Missing ignore) {
}
assertThat(config.getConfig(stripQuotes("\"quux\"")).
getConfig(stripQuotes("\"baz\"")).getString(asConfigKey("x"))).isEqualTo("y");
}
@Test
public void testGetStringMap() {
Config config = ConfigFactory.parseString(
"{\n quux: {\n baz: {\n x:y\n },\n \"w\":z\n }\n a: [1, 2]\n b:3\n}"); | assertThat(getStringMap(config, "quux")).containsOnly(entry("w", "z")); |
cloudera/director-aws-plugin | provider/src/main/java/com/cloudera/director/aws/ec2/ebs/EBSMetadata.java | // Path: provider/src/main/java/com/cloudera/director/aws/common/PropertyResolvers.java
// public final class PropertyResolvers {
//
// private static final String BUILT_IN_NAME = "built-in";
// private static final String CUSTOM_NAME_PREFIX = "custom";
//
// private PropertyResolvers() {
// }
//
// /**
// * Creates a new property resolver with no properties.
// *
// * @return new property resolver
// */
// public static PropertyResolver newEmptyPropertyResolver() {
// return new PropertySourcesPropertyResolver(new MutablePropertySources());
// }
//
// /**
// * Creates a new property resolver that gets properties from the given map.
// *
// * @param m property map
// * @return new property resolver
// * @throws NullPointerException if the map is null
// */
// public static PropertyResolver newMapPropertyResolver(Map<String, String> m) {
// checkNotNull(m, "map is null");
// MutablePropertySources sources = new MutablePropertySources();
// sources.addFirst(new MapPropertySource("map",
// ImmutableMap.copyOf(m)));
// return new PropertySourcesPropertyResolver(sources);
// }
//
// /**
// * Creates a property resolver that pulls from multiple property resource
// * locations. The first "built-in" location must be successfully loaded, but
// * all other "custom" locations may fail to load.
// *
// * @param builtInResourceLocation lowest precedence, required resource
// * location for properties
// * @param customResourceLocations additional resource locations for
// * properties, in increasing order of precedence
// * @return new property resolver
// * @throws IOException if the built-in resource location could not be loaded
// * @throws NullPointerException if any resource location is null
// */
// public static PropertyResolver newMultiResourcePropertyResolver(String builtInResourceLocation,
// String... customResourceLocations)
// throws IOException {
// return newMultiResourcePropertyResolver(true, builtInResourceLocation,
// customResourceLocations);
// }
//
// /**
// * Creates a property resolver that pulls from multiple property resource
// * locations. The first "built-in" location must be successfully loaded, but
// * all other "custom" locations must load only if {code}allowMissing{code} is
// * false.
// *
// * @param allowMissing true to allow custom resource locations to fail to load
// * @param builtInResourceLocation lowest precedence, required resource
// * location for properties
// * @param customResourceLocations additional resource locations for
// * properties, in increasing order of precedence
// * @return new property resolver
// * @throws IOException if the built-in resource location could not be loaded,
// * or if {code}allowMissing{code} is false and any custom resource location
// * fails to load
// * @throws NullPointerException if any resource location is null
// */
// public static PropertyResolver newMultiResourcePropertyResolver(boolean allowMissing,
// String builtInResourceLocation,
// String... customResourceLocations)
// throws IOException {
// MutablePropertySources sources = new MutablePropertySources();
// checkNotNull(builtInResourceLocation, "builtInResourceLocation is null");
// sources.addLast(buildPropertySource(BUILT_IN_NAME, builtInResourceLocation,
// false));
// String lastname = BUILT_IN_NAME;
// int customCtr = 1;
// for (String loc : customResourceLocations) {
// checkNotNull(loc, "customResourceLocations[" + (customCtr - 1) +
// "] is null");
// String thisname = CUSTOM_NAME_PREFIX + customCtr++;
// PropertySource source = buildPropertySource(thisname, loc, allowMissing);
// if (source != null) {
// sources.addBefore(lastname, source);
// lastname = thisname;
// }
// }
//
// return new PropertySourcesPropertyResolver(sources);
// }
//
// private static PropertySource buildPropertySource(String name, String loc,
// boolean allowMissing)
// throws IOException {
// try {
// return new ResourcePropertySource(name, loc,
// PropertyResolvers.class.getClassLoader());
// } catch (IOException e) {
// if (allowMissing) {
// return null;
// }
// throw new IOException("Unable to load " + name +
// " properties from " + loc, e);
// }
// }
//
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.cloudera.director.aws.common.PropertyResolvers;
import com.cloudera.director.spi.v2.model.ConfigurationProperty;
import com.cloudera.director.spi.v2.model.Configured;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.cloudera.director.spi.v2.model.util.ChildLocalizationContext;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.cloudera.director.spi.v2.model.util.SimpleConfigurationPropertyBuilder;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertyResolver; | }
File getCustomEbsMetadataFile(String ebsMetadataPath) {
File ebsMetadataPathFile = new File(ebsMetadataPath);
return ebsMetadataPathFile.isAbsolute() ?
ebsMetadataPathFile :
new File(configurationDirectory, ebsMetadataPath);
}
public void setCustomEbsMetadataPath(String ebsMetadataPath) {
if (ebsMetadataPath != null) {
LOG.info("Overriding ebsMetadataPath={} (default {})",
ebsMetadataPath, DEFAULT_CUSTOM_EBS_METADATA_PATH);
checkArgument(getCustomEbsMetadataFile(ebsMetadataPath).exists(),
"Custom EBS metadata path " +
ebsMetadataPath + " does not exist");
this.ebsMetadataPath = ebsMetadataPath;
}
}
}
public static class EBSMetadataConfig {
public static final String BUILT_IN_LOCATION =
"classpath:/com/cloudera/director/aws/ec2/ebs/ebsmetadata.properties";
protected EBSMetadataConfigProperties ebsMetadataConfigProperties;
public PropertyResolver ebsMetadataResolver() {
try { | // Path: provider/src/main/java/com/cloudera/director/aws/common/PropertyResolvers.java
// public final class PropertyResolvers {
//
// private static final String BUILT_IN_NAME = "built-in";
// private static final String CUSTOM_NAME_PREFIX = "custom";
//
// private PropertyResolvers() {
// }
//
// /**
// * Creates a new property resolver with no properties.
// *
// * @return new property resolver
// */
// public static PropertyResolver newEmptyPropertyResolver() {
// return new PropertySourcesPropertyResolver(new MutablePropertySources());
// }
//
// /**
// * Creates a new property resolver that gets properties from the given map.
// *
// * @param m property map
// * @return new property resolver
// * @throws NullPointerException if the map is null
// */
// public static PropertyResolver newMapPropertyResolver(Map<String, String> m) {
// checkNotNull(m, "map is null");
// MutablePropertySources sources = new MutablePropertySources();
// sources.addFirst(new MapPropertySource("map",
// ImmutableMap.copyOf(m)));
// return new PropertySourcesPropertyResolver(sources);
// }
//
// /**
// * Creates a property resolver that pulls from multiple property resource
// * locations. The first "built-in" location must be successfully loaded, but
// * all other "custom" locations may fail to load.
// *
// * @param builtInResourceLocation lowest precedence, required resource
// * location for properties
// * @param customResourceLocations additional resource locations for
// * properties, in increasing order of precedence
// * @return new property resolver
// * @throws IOException if the built-in resource location could not be loaded
// * @throws NullPointerException if any resource location is null
// */
// public static PropertyResolver newMultiResourcePropertyResolver(String builtInResourceLocation,
// String... customResourceLocations)
// throws IOException {
// return newMultiResourcePropertyResolver(true, builtInResourceLocation,
// customResourceLocations);
// }
//
// /**
// * Creates a property resolver that pulls from multiple property resource
// * locations. The first "built-in" location must be successfully loaded, but
// * all other "custom" locations must load only if {code}allowMissing{code} is
// * false.
// *
// * @param allowMissing true to allow custom resource locations to fail to load
// * @param builtInResourceLocation lowest precedence, required resource
// * location for properties
// * @param customResourceLocations additional resource locations for
// * properties, in increasing order of precedence
// * @return new property resolver
// * @throws IOException if the built-in resource location could not be loaded,
// * or if {code}allowMissing{code} is false and any custom resource location
// * fails to load
// * @throws NullPointerException if any resource location is null
// */
// public static PropertyResolver newMultiResourcePropertyResolver(boolean allowMissing,
// String builtInResourceLocation,
// String... customResourceLocations)
// throws IOException {
// MutablePropertySources sources = new MutablePropertySources();
// checkNotNull(builtInResourceLocation, "builtInResourceLocation is null");
// sources.addLast(buildPropertySource(BUILT_IN_NAME, builtInResourceLocation,
// false));
// String lastname = BUILT_IN_NAME;
// int customCtr = 1;
// for (String loc : customResourceLocations) {
// checkNotNull(loc, "customResourceLocations[" + (customCtr - 1) +
// "] is null");
// String thisname = CUSTOM_NAME_PREFIX + customCtr++;
// PropertySource source = buildPropertySource(thisname, loc, allowMissing);
// if (source != null) {
// sources.addBefore(lastname, source);
// lastname = thisname;
// }
// }
//
// return new PropertySourcesPropertyResolver(sources);
// }
//
// private static PropertySource buildPropertySource(String name, String loc,
// boolean allowMissing)
// throws IOException {
// try {
// return new ResourcePropertySource(name, loc,
// PropertyResolvers.class.getClassLoader());
// } catch (IOException e) {
// if (allowMissing) {
// return null;
// }
// throw new IOException("Unable to load " + name +
// " properties from " + loc, e);
// }
// }
//
// }
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/ebs/EBSMetadata.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.cloudera.director.aws.common.PropertyResolvers;
import com.cloudera.director.spi.v2.model.ConfigurationProperty;
import com.cloudera.director.spi.v2.model.Configured;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.cloudera.director.spi.v2.model.util.ChildLocalizationContext;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.cloudera.director.spi.v2.model.util.SimpleConfigurationPropertyBuilder;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertyResolver;
}
File getCustomEbsMetadataFile(String ebsMetadataPath) {
File ebsMetadataPathFile = new File(ebsMetadataPath);
return ebsMetadataPathFile.isAbsolute() ?
ebsMetadataPathFile :
new File(configurationDirectory, ebsMetadataPath);
}
public void setCustomEbsMetadataPath(String ebsMetadataPath) {
if (ebsMetadataPath != null) {
LOG.info("Overriding ebsMetadataPath={} (default {})",
ebsMetadataPath, DEFAULT_CUSTOM_EBS_METADATA_PATH);
checkArgument(getCustomEbsMetadataFile(ebsMetadataPath).exists(),
"Custom EBS metadata path " +
ebsMetadataPath + " does not exist");
this.ebsMetadataPath = ebsMetadataPath;
}
}
}
public static class EBSMetadataConfig {
public static final String BUILT_IN_LOCATION =
"classpath:/com/cloudera/director/aws/ec2/ebs/ebsmetadata.properties";
protected EBSMetadataConfigProperties ebsMetadataConfigProperties;
public PropertyResolver ebsMetadataResolver() {
try { | return PropertyResolvers.newMultiResourcePropertyResolver( |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/ec2/EC2RetryerTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// @VisibleForTesting
// static Duration getTimeout(DateTime timeout) {
// DateTime now = DateTime.now();
//
// if (timeout.isBefore(now)) {
// return Duration.ZERO;
// }
//
// return new Interval(now, timeout).toDuration();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// public static <T> T retryUntil(Callable<T> func)
// throws InterruptedException, RetryException, ExecutionException {
// return retryUntil(func, DEFAULT_TIMEOUT);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/common/EC2Exceptions.java
// public static final String INVALID_INSTANCE_ID_NOT_FOUND = "InvalidInstanceID.NotFound";
| import org.junit.Test;
import static com.cloudera.director.aws.ec2.EC2Retryer.getTimeout;
import static com.cloudera.director.aws.ec2.EC2Retryer.retryUntil;
import static com.cloudera.director.aws.ec2.common.EC2Exceptions.INVALID_INSTANCE_ID_NOT_FOUND;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.shaded.com.amazonaws.AmazonServiceException;
import com.cloudera.director.aws.shaded.org.joda.time.DateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; | // (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.ec2;
@SuppressWarnings("unchecked")
public class EC2RetryerTest {
@Test
public void testRetrySucceeds() throws Exception { | // Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// @VisibleForTesting
// static Duration getTimeout(DateTime timeout) {
// DateTime now = DateTime.now();
//
// if (timeout.isBefore(now)) {
// return Duration.ZERO;
// }
//
// return new Interval(now, timeout).toDuration();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// public static <T> T retryUntil(Callable<T> func)
// throws InterruptedException, RetryException, ExecutionException {
// return retryUntil(func, DEFAULT_TIMEOUT);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/common/EC2Exceptions.java
// public static final String INVALID_INSTANCE_ID_NOT_FOUND = "InvalidInstanceID.NotFound";
// Path: tests/src/test/java/com/cloudera/director/aws/ec2/EC2RetryerTest.java
import org.junit.Test;
import static com.cloudera.director.aws.ec2.EC2Retryer.getTimeout;
import static com.cloudera.director.aws.ec2.EC2Retryer.retryUntil;
import static com.cloudera.director.aws.ec2.common.EC2Exceptions.INVALID_INSTANCE_ID_NOT_FOUND;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.shaded.com.amazonaws.AmazonServiceException;
import com.cloudera.director.aws.shaded.org.joda.time.DateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
// (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.ec2;
@SuppressWarnings("unchecked")
public class EC2RetryerTest {
@Test
public void testRetrySucceeds() throws Exception { | AmazonServiceException exception = new AmazonServiceException(INVALID_INSTANCE_ID_NOT_FOUND); |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/ec2/EC2RetryerTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// @VisibleForTesting
// static Duration getTimeout(DateTime timeout) {
// DateTime now = DateTime.now();
//
// if (timeout.isBefore(now)) {
// return Duration.ZERO;
// }
//
// return new Interval(now, timeout).toDuration();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// public static <T> T retryUntil(Callable<T> func)
// throws InterruptedException, RetryException, ExecutionException {
// return retryUntil(func, DEFAULT_TIMEOUT);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/common/EC2Exceptions.java
// public static final String INVALID_INSTANCE_ID_NOT_FOUND = "InvalidInstanceID.NotFound";
| import org.junit.Test;
import static com.cloudera.director.aws.ec2.EC2Retryer.getTimeout;
import static com.cloudera.director.aws.ec2.EC2Retryer.retryUntil;
import static com.cloudera.director.aws.ec2.common.EC2Exceptions.INVALID_INSTANCE_ID_NOT_FOUND;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.shaded.com.amazonaws.AmazonServiceException;
import com.cloudera.director.aws.shaded.org.joda.time.DateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; | // (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.ec2;
@SuppressWarnings("unchecked")
public class EC2RetryerTest {
@Test
public void testRetrySucceeds() throws Exception {
AmazonServiceException exception = new AmazonServiceException(INVALID_INSTANCE_ID_NOT_FOUND);
exception.setErrorCode(INVALID_INSTANCE_ID_NOT_FOUND);
Integer result = 1;
Callable<Integer> task = mock(Callable.class);
when(task.call())
.thenThrow(exception)
.thenThrow(exception)
.thenReturn(result);
| // Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// @VisibleForTesting
// static Duration getTimeout(DateTime timeout) {
// DateTime now = DateTime.now();
//
// if (timeout.isBefore(now)) {
// return Duration.ZERO;
// }
//
// return new Interval(now, timeout).toDuration();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// public static <T> T retryUntil(Callable<T> func)
// throws InterruptedException, RetryException, ExecutionException {
// return retryUntil(func, DEFAULT_TIMEOUT);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/common/EC2Exceptions.java
// public static final String INVALID_INSTANCE_ID_NOT_FOUND = "InvalidInstanceID.NotFound";
// Path: tests/src/test/java/com/cloudera/director/aws/ec2/EC2RetryerTest.java
import org.junit.Test;
import static com.cloudera.director.aws.ec2.EC2Retryer.getTimeout;
import static com.cloudera.director.aws.ec2.EC2Retryer.retryUntil;
import static com.cloudera.director.aws.ec2.common.EC2Exceptions.INVALID_INSTANCE_ID_NOT_FOUND;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.shaded.com.amazonaws.AmazonServiceException;
import com.cloudera.director.aws.shaded.org.joda.time.DateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
// (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.ec2;
@SuppressWarnings("unchecked")
public class EC2RetryerTest {
@Test
public void testRetrySucceeds() throws Exception {
AmazonServiceException exception = new AmazonServiceException(INVALID_INSTANCE_ID_NOT_FOUND);
exception.setErrorCode(INVALID_INSTANCE_ID_NOT_FOUND);
Integer result = 1;
Callable<Integer> task = mock(Callable.class);
when(task.call())
.thenThrow(exception)
.thenThrow(exception)
.thenReturn(result);
| assertThat(result).isEqualTo(retryUntil(task)); |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/ec2/EC2RetryerTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// @VisibleForTesting
// static Duration getTimeout(DateTime timeout) {
// DateTime now = DateTime.now();
//
// if (timeout.isBefore(now)) {
// return Duration.ZERO;
// }
//
// return new Interval(now, timeout).toDuration();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// public static <T> T retryUntil(Callable<T> func)
// throws InterruptedException, RetryException, ExecutionException {
// return retryUntil(func, DEFAULT_TIMEOUT);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/common/EC2Exceptions.java
// public static final String INVALID_INSTANCE_ID_NOT_FOUND = "InvalidInstanceID.NotFound";
| import org.junit.Test;
import static com.cloudera.director.aws.ec2.EC2Retryer.getTimeout;
import static com.cloudera.director.aws.ec2.EC2Retryer.retryUntil;
import static com.cloudera.director.aws.ec2.common.EC2Exceptions.INVALID_INSTANCE_ID_NOT_FOUND;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.shaded.com.amazonaws.AmazonServiceException;
import com.cloudera.director.aws.shaded.org.joda.time.DateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; | Callable<Integer> task = mock(Callable.class);
when(task.call()).thenThrow(exception);
Thread t = new Thread(currentThread::interrupt);
t.start();
try {
retryUntil(task);
fail("expected exception didn't thrown");
} catch (InterruptedException e) {
verify(task, atLeastOnce()).call();
}
}
@Test
public void testOtherExceptionWillNotTriggerRetry() throws Exception {
Callable<Integer> task = mock(Callable.class);
when(task.call()).thenThrow(new RuntimeException());
try {
retryUntil(task);
fail("expected exception didn't thrown");
} catch (ExecutionException e) {
assertThat(RuntimeException.class.isInstance(e.getCause())).isTrue();
verify(task, times(1)).call();
}
}
@Test
public void testGetDuration() { | // Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// @VisibleForTesting
// static Duration getTimeout(DateTime timeout) {
// DateTime now = DateTime.now();
//
// if (timeout.isBefore(now)) {
// return Duration.ZERO;
// }
//
// return new Interval(now, timeout).toDuration();
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/EC2Retryer.java
// public static <T> T retryUntil(Callable<T> func)
// throws InterruptedException, RetryException, ExecutionException {
// return retryUntil(func, DEFAULT_TIMEOUT);
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/ec2/common/EC2Exceptions.java
// public static final String INVALID_INSTANCE_ID_NOT_FOUND = "InvalidInstanceID.NotFound";
// Path: tests/src/test/java/com/cloudera/director/aws/ec2/EC2RetryerTest.java
import org.junit.Test;
import static com.cloudera.director.aws.ec2.EC2Retryer.getTimeout;
import static com.cloudera.director.aws.ec2.EC2Retryer.retryUntil;
import static com.cloudera.director.aws.ec2.common.EC2Exceptions.INVALID_INSTANCE_ID_NOT_FOUND;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.shaded.com.amazonaws.AmazonServiceException;
import com.cloudera.director.aws.shaded.org.joda.time.DateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
Callable<Integer> task = mock(Callable.class);
when(task.call()).thenThrow(exception);
Thread t = new Thread(currentThread::interrupt);
t.start();
try {
retryUntil(task);
fail("expected exception didn't thrown");
} catch (InterruptedException e) {
verify(task, atLeastOnce()).call();
}
}
@Test
public void testOtherExceptionWillNotTriggerRetry() throws Exception {
Callable<Integer> task = mock(Callable.class);
when(task.call()).thenThrow(new RuntimeException());
try {
retryUntil(task);
fail("expected exception didn't thrown");
} catch (ExecutionException e) {
assertThat(RuntimeException.class.isInstance(e.getCause())).isTrue();
verify(task, times(1)).call();
}
}
@Test
public void testGetDuration() { | getTimeout(DateTime.now().plus(10L)); |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/rds/RDSEndpointsTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/rds/RDSEndpoints.java
// public enum RDSEndpointsConfigurationPropertyToken
// implements com.cloudera.director.spi.v2.model.ConfigurationPropertyToken {
//
// /**
// * Path for the custom RDS endpoints file. Relative paths are based on the
// * plugin configuration directory.
// */
// CUSTOM_ENDPOINTS_PATH(new SimpleConfigurationPropertyBuilder()
// .configKey("customEndpointsPath")
// .name("Custom endpoints path")
// .defaultDescription("The path for the custom RDS endpoints. Relative paths are based " +
// "on the plugin configuration directory.")
// .build());
//
// /**
// * The configuration property.
// */
// private final ConfigurationProperty configurationProperty;
//
// /**
// * Creates a configuration property token with the specified parameters.
// *
// * @param configurationProperty the configuration property
// */
// RDSEndpointsConfigurationPropertyToken(
// ConfigurationProperty configurationProperty) {
// this.configurationProperty = configurationProperty;
// }
//
// @Override
// public ConfigurationProperty unwrap() {
// return configurationProperty;
// }
// }
| import static com.cloudera.director.aws.AWSLauncher.DEFAULT_PLUGIN_LOCALIZATION_CONTEXT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import com.cloudera.director.aws.rds.RDSEndpoints.RDSEndpointsConfigProperties.RDSEndpointsConfigurationPropertyToken;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import java.io.File;
import java.util.Map;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; | // (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.rds;
/**
* Unit test for {@link RDSEndpoints}.
*/
public class RDSEndpointsTest {
private final Map<String, String> configurationMap = ImmutableMap.<String, String>builder() | // Path: provider/src/main/java/com/cloudera/director/aws/rds/RDSEndpoints.java
// public enum RDSEndpointsConfigurationPropertyToken
// implements com.cloudera.director.spi.v2.model.ConfigurationPropertyToken {
//
// /**
// * Path for the custom RDS endpoints file. Relative paths are based on the
// * plugin configuration directory.
// */
// CUSTOM_ENDPOINTS_PATH(new SimpleConfigurationPropertyBuilder()
// .configKey("customEndpointsPath")
// .name("Custom endpoints path")
// .defaultDescription("The path for the custom RDS endpoints. Relative paths are based " +
// "on the plugin configuration directory.")
// .build());
//
// /**
// * The configuration property.
// */
// private final ConfigurationProperty configurationProperty;
//
// /**
// * Creates a configuration property token with the specified parameters.
// *
// * @param configurationProperty the configuration property
// */
// RDSEndpointsConfigurationPropertyToken(
// ConfigurationProperty configurationProperty) {
// this.configurationProperty = configurationProperty;
// }
//
// @Override
// public ConfigurationProperty unwrap() {
// return configurationProperty;
// }
// }
// Path: tests/src/test/java/com/cloudera/director/aws/rds/RDSEndpointsTest.java
import static com.cloudera.director.aws.AWSLauncher.DEFAULT_PLUGIN_LOCALIZATION_CONTEXT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import com.cloudera.director.aws.rds.RDSEndpoints.RDSEndpointsConfigProperties.RDSEndpointsConfigurationPropertyToken;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import java.io.File;
import java.util.Map;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
// (c) Copyright 2015 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.rds;
/**
* Unit test for {@link RDSEndpoints}.
*/
public class RDSEndpointsTest {
private final Map<String, String> configurationMap = ImmutableMap.<String, String>builder() | .put(RDSEndpointsConfigurationPropertyToken.CUSTOM_ENDPOINTS_PATH.unwrap().getConfigKey(), |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/rds/RDSEncryptionInstanceClassesTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/rds/RDSEncryptionInstanceClasses.java
// public enum ConfigurationPropertyToken
// implements com.cloudera.director.spi.v2.model.ConfigurationPropertyToken {
//
// /**
// * Path for the custom RDS encryption instance classes file. Relative
// * paths are based on the plugin configuration directory.
// */
// CUSTOM_ENCRYPTION_INSTANCE_CLASSES_PATH(new SimpleConfigurationPropertyBuilder()
// .configKey("customEncryptionInstanceClassesPath")
// .name("Custom encryption instance classes path")
// .defaultDescription("The path for the custom list of RDS encryption instance classes. " +
// "Relative paths are based on the plugin configuration directory.")
// .build());
//
// /**
// * The configuration property.
// */
// private final ConfigurationProperty configurationProperty;
//
// /**
// * Creates a configuration property token with the specified parameters.
// *
// * @param configurationProperty the configuration property
// */
// ConfigurationPropertyToken(ConfigurationProperty configurationProperty) {
// this.configurationProperty = configurationProperty;
// }
//
// @Override
// public ConfigurationProperty unwrap() {
// return configurationProperty;
// }
// }
| import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import com.cloudera.director.aws.rds.RDSEncryptionInstanceClasses.ConfigurationPropertyToken;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.cloudera.director.spi.v2.model.util.DefaultLocalizationContext;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Locale; | // (c) Copyright 2016 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.rds;
public class RDSEncryptionInstanceClassesTest {
private final Map<String, String> configurationMap = ImmutableMap.<String, String>builder() | // Path: provider/src/main/java/com/cloudera/director/aws/rds/RDSEncryptionInstanceClasses.java
// public enum ConfigurationPropertyToken
// implements com.cloudera.director.spi.v2.model.ConfigurationPropertyToken {
//
// /**
// * Path for the custom RDS encryption instance classes file. Relative
// * paths are based on the plugin configuration directory.
// */
// CUSTOM_ENCRYPTION_INSTANCE_CLASSES_PATH(new SimpleConfigurationPropertyBuilder()
// .configKey("customEncryptionInstanceClassesPath")
// .name("Custom encryption instance classes path")
// .defaultDescription("The path for the custom list of RDS encryption instance classes. " +
// "Relative paths are based on the plugin configuration directory.")
// .build());
//
// /**
// * The configuration property.
// */
// private final ConfigurationProperty configurationProperty;
//
// /**
// * Creates a configuration property token with the specified parameters.
// *
// * @param configurationProperty the configuration property
// */
// ConfigurationPropertyToken(ConfigurationProperty configurationProperty) {
// this.configurationProperty = configurationProperty;
// }
//
// @Override
// public ConfigurationProperty unwrap() {
// return configurationProperty;
// }
// }
// Path: tests/src/test/java/com/cloudera/director/aws/rds/RDSEncryptionInstanceClassesTest.java
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import com.cloudera.director.aws.rds.RDSEncryptionInstanceClasses.ConfigurationPropertyToken;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.cloudera.director.spi.v2.model.util.DefaultLocalizationContext;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Locale;
// (c) Copyright 2016 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.rds;
public class RDSEncryptionInstanceClassesTest {
private final Map<String, String> configurationMap = ImmutableMap.<String, String>builder() | .put(ConfigurationPropertyToken.CUSTOM_ENCRYPTION_INSTANCE_CLASSES_PATH.unwrap().getConfigKey(), |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/test/LiveTestProperties.java | // Path: provider/src/main/java/com/cloudera/director/aws/STSAssumeNRolesSessionCredentialsProvider.java
// static public class RoleConfiguration {
// private final String roleArn;
// private final String roleSessionName;
// private final String roleExternalId;
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// */
// public RoleConfiguration(String roleArn, String roleSessionName) {
// this(roleArn, roleSessionName, null);
// }
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// * @param roleExternalId role external Id
// */
// public RoleConfiguration(String roleArn, String roleSessionName, String roleExternalId) {
// checkArgument(!isEmpty(roleArn), "roleArn is empty");
// checkArgument(!isEmpty(roleSessionName), "roleSessionName is empty");
//
// this.roleArn = roleArn;
// this.roleSessionName = roleSessionName;
// this.roleExternalId = roleExternalId;
// }
//
// /**
// * Gets role session name.
// *
// * @return role session name
// */
// public String getRoleSessionName() {
// return roleSessionName;
// }
//
// /**
// * Gets role external Id.
// *
// * @return role external Id
// */
// public String getRoleExternalId() {
// return roleExternalId;
// }
//
// /**
// * Gets role Arn.
// *
// * @return role Arn
// */
// public String getRoleArn() {
// return roleArn;
// }
//
// @Override
// public String toString() {
// return "RoleConfiguration{" +
// "roleArn='" + roleArn + '\'' +
// ", roleSessionName='" + roleSessionName + '\'' +
// ", roleExternalId='" + roleExternalId + '\'' +
// '}';
// }
// }
| import static org.junit.Assert.fail;
import com.cloudera.director.aws.STSAssumeNRolesSessionCredentialsProvider.RoleConfiguration;
import com.google.common.collect.ImmutableList;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties; | // (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.test;
/**
* Encapsulates configuration properties needed to run live tests on AWS.
*/
public class LiveTestProperties {
private String testRegion;
private String testSubnet;
private String testSecurityGroup;
private String testKmsKeyArn;
// live test properties for delegated role access | // Path: provider/src/main/java/com/cloudera/director/aws/STSAssumeNRolesSessionCredentialsProvider.java
// static public class RoleConfiguration {
// private final String roleArn;
// private final String roleSessionName;
// private final String roleExternalId;
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// */
// public RoleConfiguration(String roleArn, String roleSessionName) {
// this(roleArn, roleSessionName, null);
// }
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// * @param roleExternalId role external Id
// */
// public RoleConfiguration(String roleArn, String roleSessionName, String roleExternalId) {
// checkArgument(!isEmpty(roleArn), "roleArn is empty");
// checkArgument(!isEmpty(roleSessionName), "roleSessionName is empty");
//
// this.roleArn = roleArn;
// this.roleSessionName = roleSessionName;
// this.roleExternalId = roleExternalId;
// }
//
// /**
// * Gets role session name.
// *
// * @return role session name
// */
// public String getRoleSessionName() {
// return roleSessionName;
// }
//
// /**
// * Gets role external Id.
// *
// * @return role external Id
// */
// public String getRoleExternalId() {
// return roleExternalId;
// }
//
// /**
// * Gets role Arn.
// *
// * @return role Arn
// */
// public String getRoleArn() {
// return roleArn;
// }
//
// @Override
// public String toString() {
// return "RoleConfiguration{" +
// "roleArn='" + roleArn + '\'' +
// ", roleSessionName='" + roleSessionName + '\'' +
// ", roleExternalId='" + roleExternalId + '\'' +
// '}';
// }
// }
// Path: tests/src/test/java/com/cloudera/director/aws/test/LiveTestProperties.java
import static org.junit.Assert.fail;
import com.cloudera.director.aws.STSAssumeNRolesSessionCredentialsProvider.RoleConfiguration;
import com.google.common.collect.ImmutableList;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
// (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.test;
/**
* Encapsulates configuration properties needed to run live tests on AWS.
*/
public class LiveTestProperties {
private String testRegion;
private String testSubnet;
private String testSecurityGroup;
private String testKmsKeyArn;
// live test properties for delegated role access | private List<RoleConfiguration> delegatedRoleConfigurations; |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/STSRolesTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/STSAssumeNRolesSessionCredentialsProvider.java
// static public class RoleConfiguration {
// private final String roleArn;
// private final String roleSessionName;
// private final String roleExternalId;
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// */
// public RoleConfiguration(String roleArn, String roleSessionName) {
// this(roleArn, roleSessionName, null);
// }
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// * @param roleExternalId role external Id
// */
// public RoleConfiguration(String roleArn, String roleSessionName, String roleExternalId) {
// checkArgument(!isEmpty(roleArn), "roleArn is empty");
// checkArgument(!isEmpty(roleSessionName), "roleSessionName is empty");
//
// this.roleArn = roleArn;
// this.roleSessionName = roleSessionName;
// this.roleExternalId = roleExternalId;
// }
//
// /**
// * Gets role session name.
// *
// * @return role session name
// */
// public String getRoleSessionName() {
// return roleSessionName;
// }
//
// /**
// * Gets role external Id.
// *
// * @return role external Id
// */
// public String getRoleExternalId() {
// return roleExternalId;
// }
//
// /**
// * Gets role Arn.
// *
// * @return role Arn
// */
// public String getRoleArn() {
// return roleArn;
// }
//
// @Override
// public String toString() {
// return "RoleConfiguration{" +
// "roleArn='" + roleArn + '\'' +
// ", roleSessionName='" + roleSessionName + '\'' +
// ", roleExternalId='" + roleExternalId + '\'' +
// '}';
// }
// }
| import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.assertj.core.api.Assertions.assertThat;
import com.cloudera.director.aws.STSAssumeNRolesSessionCredentialsProvider.RoleConfiguration;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import com.google.common.base.Function;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import org.junit.Rule; | // (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws;
public class STSRolesTest {
private static final String ROLE = "roleSwitch";
private static final String ROLE_ARN = "arn:aws:iam::123456789012:role/" + ROLE;
private static final String QUOTED_ROLE_ARN = "\"" + ROLE_ARN + "\"";
private static final String ROLE_SESSION_NAME = "reader";
private static final String ROLE_EXTERNAL_ID = "token";
@Rule
public TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();
@Test
public void testParseConfigWithArnSessionNameAndExternalId() throws IOException {
Function<PrintWriter, Void> writer = new Function<PrintWriter, Void>() {
@Override
public Void apply(PrintWriter printWriter) {
printWriter.println(" {");
printWriter.println(" " + STSRoles.ROLE_ARN + ": " + QUOTED_ROLE_ARN);
printWriter.println(" " + STSRoles.ROLE_SESSION_NAME + ": " + ROLE_SESSION_NAME);
printWriter.println(" " + STSRoles.ROLE_EXTERNAL_ID + ": " + ROLE_EXTERNAL_ID);
printWriter.println(" }");
return null;
}
};
Function<STSRoles, Void> assertions = new Function<STSRoles, Void>() {
@Override
public Void apply(STSRoles stsRoles) {
assertThat(stsRoles.getRoleConfigurations()).isNotNull();
assertThat(stsRoles.getRoleConfigurations().size()).isEqualTo(1);
| // Path: provider/src/main/java/com/cloudera/director/aws/STSAssumeNRolesSessionCredentialsProvider.java
// static public class RoleConfiguration {
// private final String roleArn;
// private final String roleSessionName;
// private final String roleExternalId;
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// */
// public RoleConfiguration(String roleArn, String roleSessionName) {
// this(roleArn, roleSessionName, null);
// }
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// * @param roleExternalId role external Id
// */
// public RoleConfiguration(String roleArn, String roleSessionName, String roleExternalId) {
// checkArgument(!isEmpty(roleArn), "roleArn is empty");
// checkArgument(!isEmpty(roleSessionName), "roleSessionName is empty");
//
// this.roleArn = roleArn;
// this.roleSessionName = roleSessionName;
// this.roleExternalId = roleExternalId;
// }
//
// /**
// * Gets role session name.
// *
// * @return role session name
// */
// public String getRoleSessionName() {
// return roleSessionName;
// }
//
// /**
// * Gets role external Id.
// *
// * @return role external Id
// */
// public String getRoleExternalId() {
// return roleExternalId;
// }
//
// /**
// * Gets role Arn.
// *
// * @return role Arn
// */
// public String getRoleArn() {
// return roleArn;
// }
//
// @Override
// public String toString() {
// return "RoleConfiguration{" +
// "roleArn='" + roleArn + '\'' +
// ", roleSessionName='" + roleSessionName + '\'' +
// ", roleExternalId='" + roleExternalId + '\'' +
// '}';
// }
// }
// Path: tests/src/test/java/com/cloudera/director/aws/STSRolesTest.java
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.assertj.core.api.Assertions.assertThat;
import com.cloudera.director.aws.STSAssumeNRolesSessionCredentialsProvider.RoleConfiguration;
import com.cloudera.director.aws.shaded.com.typesafe.config.Config;
import com.cloudera.director.aws.shaded.com.typesafe.config.ConfigFactory;
import com.google.common.base.Function;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import org.junit.Rule;
// (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws;
public class STSRolesTest {
private static final String ROLE = "roleSwitch";
private static final String ROLE_ARN = "arn:aws:iam::123456789012:role/" + ROLE;
private static final String QUOTED_ROLE_ARN = "\"" + ROLE_ARN + "\"";
private static final String ROLE_SESSION_NAME = "reader";
private static final String ROLE_EXTERNAL_ID = "token";
@Rule
public TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();
@Test
public void testParseConfigWithArnSessionNameAndExternalId() throws IOException {
Function<PrintWriter, Void> writer = new Function<PrintWriter, Void>() {
@Override
public Void apply(PrintWriter printWriter) {
printWriter.println(" {");
printWriter.println(" " + STSRoles.ROLE_ARN + ": " + QUOTED_ROLE_ARN);
printWriter.println(" " + STSRoles.ROLE_SESSION_NAME + ": " + ROLE_SESSION_NAME);
printWriter.println(" " + STSRoles.ROLE_EXTERNAL_ID + ": " + ROLE_EXTERNAL_ID);
printWriter.println(" }");
return null;
}
};
Function<STSRoles, Void> assertions = new Function<STSRoles, Void>() {
@Override
public Void apply(STSRoles stsRoles) {
assertThat(stsRoles.getRoleConfigurations()).isNotNull();
assertThat(stsRoles.getRoleConfigurations().size()).isEqualTo(1);
| RoleConfiguration roleConfiguration = stsRoles.getRoleConfigurations().get(0); |
cloudera/director-aws-plugin | provider/src/main/java/com/cloudera/director/aws/STSRoles.java | // Path: provider/src/main/java/com/cloudera/director/aws/STSAssumeNRolesSessionCredentialsProvider.java
// static public class RoleConfiguration {
// private final String roleArn;
// private final String roleSessionName;
// private final String roleExternalId;
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// */
// public RoleConfiguration(String roleArn, String roleSessionName) {
// this(roleArn, roleSessionName, null);
// }
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// * @param roleExternalId role external Id
// */
// public RoleConfiguration(String roleArn, String roleSessionName, String roleExternalId) {
// checkArgument(!isEmpty(roleArn), "roleArn is empty");
// checkArgument(!isEmpty(roleSessionName), "roleSessionName is empty");
//
// this.roleArn = roleArn;
// this.roleSessionName = roleSessionName;
// this.roleExternalId = roleExternalId;
// }
//
// /**
// * Gets role session name.
// *
// * @return role session name
// */
// public String getRoleSessionName() {
// return roleSessionName;
// }
//
// /**
// * Gets role external Id.
// *
// * @return role external Id
// */
// public String getRoleExternalId() {
// return roleExternalId;
// }
//
// /**
// * Gets role Arn.
// *
// * @return role Arn
// */
// public String getRoleArn() {
// return roleArn;
// }
//
// @Override
// public String toString() {
// return "RoleConfiguration{" +
// "roleArn='" + roleArn + '\'' +
// ", roleSessionName='" + roleSessionName + '\'' +
// ", roleExternalId='" + roleExternalId + '\'' +
// '}';
// }
// }
| import static java.util.Objects.requireNonNull;
import com.cloudera.director.aws.STSAssumeNRolesSessionCredentialsProvider.RoleConfiguration;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.typesafe.config.Config;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.annotation.Nonnull; | // (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws;
/**
* STS role configuration holder.
*/
public class STSRoles {
public static final STSRoles DEFAULT = new STSRoles(Collections.emptyList());
@VisibleForTesting
static final String ROLE_ARN = "roleArn";
@VisibleForTesting
static final String ROLE_SESSION_NAME = "roleSessionName";
@VisibleForTesting
static final String ROLE_EXTERNAL_ID = "roleExternalId";
| // Path: provider/src/main/java/com/cloudera/director/aws/STSAssumeNRolesSessionCredentialsProvider.java
// static public class RoleConfiguration {
// private final String roleArn;
// private final String roleSessionName;
// private final String roleExternalId;
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// */
// public RoleConfiguration(String roleArn, String roleSessionName) {
// this(roleArn, roleSessionName, null);
// }
//
// /**
// * Creates an instance of role configuration.
// *
// * @param roleArn role Arn
// * @param roleSessionName role session name
// * @param roleExternalId role external Id
// */
// public RoleConfiguration(String roleArn, String roleSessionName, String roleExternalId) {
// checkArgument(!isEmpty(roleArn), "roleArn is empty");
// checkArgument(!isEmpty(roleSessionName), "roleSessionName is empty");
//
// this.roleArn = roleArn;
// this.roleSessionName = roleSessionName;
// this.roleExternalId = roleExternalId;
// }
//
// /**
// * Gets role session name.
// *
// * @return role session name
// */
// public String getRoleSessionName() {
// return roleSessionName;
// }
//
// /**
// * Gets role external Id.
// *
// * @return role external Id
// */
// public String getRoleExternalId() {
// return roleExternalId;
// }
//
// /**
// * Gets role Arn.
// *
// * @return role Arn
// */
// public String getRoleArn() {
// return roleArn;
// }
//
// @Override
// public String toString() {
// return "RoleConfiguration{" +
// "roleArn='" + roleArn + '\'' +
// ", roleSessionName='" + roleSessionName + '\'' +
// ", roleExternalId='" + roleExternalId + '\'' +
// '}';
// }
// }
// Path: provider/src/main/java/com/cloudera/director/aws/STSRoles.java
import static java.util.Objects.requireNonNull;
import com.cloudera.director.aws.STSAssumeNRolesSessionCredentialsProvider.RoleConfiguration;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.typesafe.config.Config;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.annotation.Nonnull;
// (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws;
/**
* STS role configuration holder.
*/
public class STSRoles {
public static final STSRoles DEFAULT = new STSRoles(Collections.emptyList());
@VisibleForTesting
static final String ROLE_ARN = "roleArn";
@VisibleForTesting
static final String ROLE_SESSION_NAME = "roleSessionName";
@VisibleForTesting
static final String ROLE_EXTERNAL_ID = "roleExternalId";
| private final List<RoleConfiguration> roleConfigurations; |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/test/TestInstanceTemplate.java | // Path: provider/src/main/java/com/cloudera/director/aws/Tags.java
// public final class Tags {
//
// /**
// * Director tags for cloud resources.
// */
// public enum ResourceTags {
// /**
// * The name of the resource.
// */
// RESOURCE_NAME("Name"),
//
// /**
// * The virtual instance ID as generated by Cloudera Altus Director.
// */
// CLOUDERA_DIRECTOR_ID("Cloudera-Director-Id"),
//
// /**
// * The virtual instance ID as generated by Cloudera Altus Director.
// */
// CLOUDERA_DIRECTOR_TEMPLATE_NAME("Cloudera-Director-Template-Name");
//
// private final String tagName;
//
// ResourceTags(String tagName) {
// this.tagName = tagName;
// }
//
// /**
// * Gets the tag's key.
// * Note that you should always call this method to get the tag's key, and not the
// * {@link ResourceTags#valueOf(String)} method.
// *
// * @return tag's key name
// */
// public String getTagKey() {
// return tagName;
// }
// }
//
// /**
// * Director tags specifically for cloud instances.
// */
// public enum InstanceTags {
// /**
// * The instance owner.
// */
// OWNER("owner");
//
// private final String tagName;
//
// InstanceTags(String tagName) {
// this.tagName = tagName;
// }
//
// /**
// * Gets the tag's key.
// * Note that you should always call this method to get the tag's key, and not the
// * {@link InstanceTags#valueOf(String)} method.
// *
// * @return tag's key name
// */
// public String getTagKey() {
// return tagName;
// }
// }
//
//
// /**
// * Private constructor to prevent instantiation.
// */
// private Tags() {
// }
// }
| import static com.cloudera.director.spi.v2.model.InstanceTemplate.InstanceTemplateConfigurationPropertyToken.INSTANCE_NAME_PREFIX;
import com.cloudera.director.aws.Tags;
import com.cloudera.director.spi.v2.model.ConfigurationPropertyToken;
import java.util.LinkedHashMap;
import java.util.Map; | // (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.test;
/**
* Convenience class to store instance template configs and tags.
*/
public class TestInstanceTemplate {
private String templateName;
private Map<String, String> configs;
private Map<String, String> tags;
public void addConfig(ConfigurationPropertyToken propertyToken, String value) {
if (value != null) {
configs.put(propertyToken.unwrap().getConfigKey(), value);
}
}
public void addTag(String tagKey, String tagValue) {
tags.put(tagKey, tagValue);
}
/**
* Constructor, will set an owner tag and instance name prefix based
* on the current user name.
*/
public TestInstanceTemplate() {
configs = new LinkedHashMap<>();
tags = new LinkedHashMap<>();
String username = System.getProperty("user.name");
templateName = username + "-test";
addConfig(INSTANCE_NAME_PREFIX, templateName); | // Path: provider/src/main/java/com/cloudera/director/aws/Tags.java
// public final class Tags {
//
// /**
// * Director tags for cloud resources.
// */
// public enum ResourceTags {
// /**
// * The name of the resource.
// */
// RESOURCE_NAME("Name"),
//
// /**
// * The virtual instance ID as generated by Cloudera Altus Director.
// */
// CLOUDERA_DIRECTOR_ID("Cloudera-Director-Id"),
//
// /**
// * The virtual instance ID as generated by Cloudera Altus Director.
// */
// CLOUDERA_DIRECTOR_TEMPLATE_NAME("Cloudera-Director-Template-Name");
//
// private final String tagName;
//
// ResourceTags(String tagName) {
// this.tagName = tagName;
// }
//
// /**
// * Gets the tag's key.
// * Note that you should always call this method to get the tag's key, and not the
// * {@link ResourceTags#valueOf(String)} method.
// *
// * @return tag's key name
// */
// public String getTagKey() {
// return tagName;
// }
// }
//
// /**
// * Director tags specifically for cloud instances.
// */
// public enum InstanceTags {
// /**
// * The instance owner.
// */
// OWNER("owner");
//
// private final String tagName;
//
// InstanceTags(String tagName) {
// this.tagName = tagName;
// }
//
// /**
// * Gets the tag's key.
// * Note that you should always call this method to get the tag's key, and not the
// * {@link InstanceTags#valueOf(String)} method.
// *
// * @return tag's key name
// */
// public String getTagKey() {
// return tagName;
// }
// }
//
//
// /**
// * Private constructor to prevent instantiation.
// */
// private Tags() {
// }
// }
// Path: tests/src/test/java/com/cloudera/director/aws/test/TestInstanceTemplate.java
import static com.cloudera.director.spi.v2.model.InstanceTemplate.InstanceTemplateConfigurationPropertyToken.INSTANCE_NAME_PREFIX;
import com.cloudera.director.aws.Tags;
import com.cloudera.director.spi.v2.model.ConfigurationPropertyToken;
import java.util.LinkedHashMap;
import java.util.Map;
// (c) Copyright 2017 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.director.aws.test;
/**
* Convenience class to store instance template configs and tags.
*/
public class TestInstanceTemplate {
private String templateName;
private Map<String, String> configs;
private Map<String, String> tags;
public void addConfig(ConfigurationPropertyToken propertyToken, String value) {
if (value != null) {
configs.put(propertyToken.unwrap().getConfigKey(), value);
}
}
public void addTag(String tagKey, String tagValue) {
tags.put(tagKey, tagValue);
}
/**
* Constructor, will set an owner tag and instance name prefix based
* on the current user name.
*/
public TestInstanceTemplate() {
configs = new LinkedHashMap<>();
tags = new LinkedHashMap<>();
String username = System.getProperty("user.name");
templateName = username + "-test";
addConfig(INSTANCE_NAME_PREFIX, templateName); | addTag(Tags.InstanceTags.OWNER.getTagKey(), username); |
cloudera/director-aws-plugin | provider/src/main/java/com/cloudera/director/aws/rds/RDSEndpoints.java | // Path: provider/src/main/java/com/cloudera/director/aws/common/PropertyResolvers.java
// public final class PropertyResolvers {
//
// private static final String BUILT_IN_NAME = "built-in";
// private static final String CUSTOM_NAME_PREFIX = "custom";
//
// private PropertyResolvers() {
// }
//
// /**
// * Creates a new property resolver with no properties.
// *
// * @return new property resolver
// */
// public static PropertyResolver newEmptyPropertyResolver() {
// return new PropertySourcesPropertyResolver(new MutablePropertySources());
// }
//
// /**
// * Creates a new property resolver that gets properties from the given map.
// *
// * @param m property map
// * @return new property resolver
// * @throws NullPointerException if the map is null
// */
// public static PropertyResolver newMapPropertyResolver(Map<String, String> m) {
// checkNotNull(m, "map is null");
// MutablePropertySources sources = new MutablePropertySources();
// sources.addFirst(new MapPropertySource("map",
// ImmutableMap.copyOf(m)));
// return new PropertySourcesPropertyResolver(sources);
// }
//
// /**
// * Creates a property resolver that pulls from multiple property resource
// * locations. The first "built-in" location must be successfully loaded, but
// * all other "custom" locations may fail to load.
// *
// * @param builtInResourceLocation lowest precedence, required resource
// * location for properties
// * @param customResourceLocations additional resource locations for
// * properties, in increasing order of precedence
// * @return new property resolver
// * @throws IOException if the built-in resource location could not be loaded
// * @throws NullPointerException if any resource location is null
// */
// public static PropertyResolver newMultiResourcePropertyResolver(String builtInResourceLocation,
// String... customResourceLocations)
// throws IOException {
// return newMultiResourcePropertyResolver(true, builtInResourceLocation,
// customResourceLocations);
// }
//
// /**
// * Creates a property resolver that pulls from multiple property resource
// * locations. The first "built-in" location must be successfully loaded, but
// * all other "custom" locations must load only if {code}allowMissing{code} is
// * false.
// *
// * @param allowMissing true to allow custom resource locations to fail to load
// * @param builtInResourceLocation lowest precedence, required resource
// * location for properties
// * @param customResourceLocations additional resource locations for
// * properties, in increasing order of precedence
// * @return new property resolver
// * @throws IOException if the built-in resource location could not be loaded,
// * or if {code}allowMissing{code} is false and any custom resource location
// * fails to load
// * @throws NullPointerException if any resource location is null
// */
// public static PropertyResolver newMultiResourcePropertyResolver(boolean allowMissing,
// String builtInResourceLocation,
// String... customResourceLocations)
// throws IOException {
// MutablePropertySources sources = new MutablePropertySources();
// checkNotNull(builtInResourceLocation, "builtInResourceLocation is null");
// sources.addLast(buildPropertySource(BUILT_IN_NAME, builtInResourceLocation,
// false));
// String lastname = BUILT_IN_NAME;
// int customCtr = 1;
// for (String loc : customResourceLocations) {
// checkNotNull(loc, "customResourceLocations[" + (customCtr - 1) +
// "] is null");
// String thisname = CUSTOM_NAME_PREFIX + customCtr++;
// PropertySource source = buildPropertySource(thisname, loc, allowMissing);
// if (source != null) {
// sources.addBefore(lastname, source);
// lastname = thisname;
// }
// }
//
// return new PropertySourcesPropertyResolver(sources);
// }
//
// private static PropertySource buildPropertySource(String name, String loc,
// boolean allowMissing)
// throws IOException {
// try {
// return new ResourcePropertySource(name, loc,
// PropertyResolvers.class.getClassLoader());
// } catch (IOException e) {
// if (allowMissing) {
// return null;
// }
// throw new IOException("Unable to load " + name +
// " properties from " + loc, e);
// }
// }
//
// }
| import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertyResolver;
import static com.google.common.base.Preconditions.checkArgument;
import com.cloudera.director.aws.common.PropertyResolvers;
import com.cloudera.director.spi.v2.model.ConfigurationProperty;
import com.cloudera.director.spi.v2.model.Configured;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.cloudera.director.spi.v2.model.util.ChildLocalizationContext;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.cloudera.director.spi.v2.model.util.SimpleConfigurationPropertyBuilder;
import com.google.common.base.Function;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.Map; | }
File getCustomEndpointsFile(String customEndpointsPath) {
File customEndpointsPathFile = new File(customEndpointsPath);
return customEndpointsPathFile.isAbsolute() ?
customEndpointsPathFile :
new File(configurationDirectory, customEndpointsPath);
}
public void setCustomEndpointsPath(String customEndpointsPath) {
if (customEndpointsPath != null) {
LOG.info("Overriding customEndpointsPath={} (default {})",
customEndpointsPath, DEFAULT_CUSTOM_ENDPOINTS_PATH);
checkArgument(getCustomEndpointsFile(customEndpointsPath).exists(),
"Custom RDS endpoints path " +
customEndpointsPath + " does not exist");
this.customEndpointsPath = customEndpointsPath;
}
}
}
public static class RDSEndpointsConfig {
public static final String BUILT_IN_LOCATION =
"classpath:/com/cloudera/director/aws/rds/endpoints.properties";
protected RDSEndpointsConfigProperties rdsEndpointsConfigProperties;
public PropertyResolver rdsEndpointsResolver() {
try { | // Path: provider/src/main/java/com/cloudera/director/aws/common/PropertyResolvers.java
// public final class PropertyResolvers {
//
// private static final String BUILT_IN_NAME = "built-in";
// private static final String CUSTOM_NAME_PREFIX = "custom";
//
// private PropertyResolvers() {
// }
//
// /**
// * Creates a new property resolver with no properties.
// *
// * @return new property resolver
// */
// public static PropertyResolver newEmptyPropertyResolver() {
// return new PropertySourcesPropertyResolver(new MutablePropertySources());
// }
//
// /**
// * Creates a new property resolver that gets properties from the given map.
// *
// * @param m property map
// * @return new property resolver
// * @throws NullPointerException if the map is null
// */
// public static PropertyResolver newMapPropertyResolver(Map<String, String> m) {
// checkNotNull(m, "map is null");
// MutablePropertySources sources = new MutablePropertySources();
// sources.addFirst(new MapPropertySource("map",
// ImmutableMap.copyOf(m)));
// return new PropertySourcesPropertyResolver(sources);
// }
//
// /**
// * Creates a property resolver that pulls from multiple property resource
// * locations. The first "built-in" location must be successfully loaded, but
// * all other "custom" locations may fail to load.
// *
// * @param builtInResourceLocation lowest precedence, required resource
// * location for properties
// * @param customResourceLocations additional resource locations for
// * properties, in increasing order of precedence
// * @return new property resolver
// * @throws IOException if the built-in resource location could not be loaded
// * @throws NullPointerException if any resource location is null
// */
// public static PropertyResolver newMultiResourcePropertyResolver(String builtInResourceLocation,
// String... customResourceLocations)
// throws IOException {
// return newMultiResourcePropertyResolver(true, builtInResourceLocation,
// customResourceLocations);
// }
//
// /**
// * Creates a property resolver that pulls from multiple property resource
// * locations. The first "built-in" location must be successfully loaded, but
// * all other "custom" locations must load only if {code}allowMissing{code} is
// * false.
// *
// * @param allowMissing true to allow custom resource locations to fail to load
// * @param builtInResourceLocation lowest precedence, required resource
// * location for properties
// * @param customResourceLocations additional resource locations for
// * properties, in increasing order of precedence
// * @return new property resolver
// * @throws IOException if the built-in resource location could not be loaded,
// * or if {code}allowMissing{code} is false and any custom resource location
// * fails to load
// * @throws NullPointerException if any resource location is null
// */
// public static PropertyResolver newMultiResourcePropertyResolver(boolean allowMissing,
// String builtInResourceLocation,
// String... customResourceLocations)
// throws IOException {
// MutablePropertySources sources = new MutablePropertySources();
// checkNotNull(builtInResourceLocation, "builtInResourceLocation is null");
// sources.addLast(buildPropertySource(BUILT_IN_NAME, builtInResourceLocation,
// false));
// String lastname = BUILT_IN_NAME;
// int customCtr = 1;
// for (String loc : customResourceLocations) {
// checkNotNull(loc, "customResourceLocations[" + (customCtr - 1) +
// "] is null");
// String thisname = CUSTOM_NAME_PREFIX + customCtr++;
// PropertySource source = buildPropertySource(thisname, loc, allowMissing);
// if (source != null) {
// sources.addBefore(lastname, source);
// lastname = thisname;
// }
// }
//
// return new PropertySourcesPropertyResolver(sources);
// }
//
// private static PropertySource buildPropertySource(String name, String loc,
// boolean allowMissing)
// throws IOException {
// try {
// return new ResourcePropertySource(name, loc,
// PropertyResolvers.class.getClassLoader());
// } catch (IOException e) {
// if (allowMissing) {
// return null;
// }
// throw new IOException("Unable to load " + name +
// " properties from " + loc, e);
// }
// }
//
// }
// Path: provider/src/main/java/com/cloudera/director/aws/rds/RDSEndpoints.java
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertyResolver;
import static com.google.common.base.Preconditions.checkArgument;
import com.cloudera.director.aws.common.PropertyResolvers;
import com.cloudera.director.spi.v2.model.ConfigurationProperty;
import com.cloudera.director.spi.v2.model.Configured;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.cloudera.director.spi.v2.model.util.ChildLocalizationContext;
import com.cloudera.director.spi.v2.model.util.SimpleConfiguration;
import com.cloudera.director.spi.v2.model.util.SimpleConfigurationPropertyBuilder;
import com.google.common.base.Function;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.Map;
}
File getCustomEndpointsFile(String customEndpointsPath) {
File customEndpointsPathFile = new File(customEndpointsPath);
return customEndpointsPathFile.isAbsolute() ?
customEndpointsPathFile :
new File(configurationDirectory, customEndpointsPath);
}
public void setCustomEndpointsPath(String customEndpointsPath) {
if (customEndpointsPath != null) {
LOG.info("Overriding customEndpointsPath={} (default {})",
customEndpointsPath, DEFAULT_CUSTOM_ENDPOINTS_PATH);
checkArgument(getCustomEndpointsFile(customEndpointsPath).exists(),
"Custom RDS endpoints path " +
customEndpointsPath + " does not exist");
this.customEndpointsPath = customEndpointsPath;
}
}
}
public static class RDSEndpointsConfig {
public static final String BUILT_IN_LOCATION =
"classpath:/com/cloudera/director/aws/rds/endpoints.properties";
protected RDSEndpointsConfigProperties rdsEndpointsConfigProperties;
public PropertyResolver rdsEndpointsResolver() {
try { | return PropertyResolvers.newMultiResourcePropertyResolver( |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContextTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContext.java
// public static class ResourceBundleLocalizationContextFactory implements Factory {
//
// /**
// * The resource bundle resolver.
// */
// private final ResourceBundleResolver resourceBundleResolver;
//
// /**
// * Creates a resource bundle localization context factory with the specified parameters.
// *
// * @param resourceBundleResolver the resource bundle resolver
// */
// public ResourceBundleLocalizationContextFactory(ResourceBundleResolver resourceBundleResolver) {
// this.resourceBundleResolver = resourceBundleResolver;
// }
//
// @Override
// public LocalizationContext createRootLocalizationContext(Locale locale) {
// return new ResourceBundleLocalizationContext(
// locale, "", resourceBundleResolver.getBundle(BUNDLE_BASE_NAME, locale));
// }
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContext.java
// public interface ResourceBundleResolver {
//
// /**
// * The default resource bundle resolver.
// */
// ResourceBundleResolver DEFAULT = (baseName, locale) -> {
// try {
// return ResourceBundle.getBundle("com.cloudera.director.aws." + baseName, locale);
// } catch (MissingResourceException e) {
// LOG.warn("Could not load resource bundle '{}' for locale {}", baseName, locale);
// return null;
// }
// };
//
// /**
// * Returns the specified resource bundle for the specified locale, or {@code null} if there
// * is no such resource bundle.
// *
// * @param baseName the base name of the resource bundle
// * @param locale the locale
// * @return the specified resource bundle for the specified locale, or {@code null} if there
// * is no such resource bundle
// */
// ResourceBundle getBundle(String baseName, Locale locale);
// }
| import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.common.ResourceBundleLocalizationContext.ResourceBundleLocalizationContextFactory;
import com.cloudera.director.aws.common.ResourceBundleLocalizationContext.ResourceBundleResolver;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.google.common.collect.Maps;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle; | assertThat(localizationContext.localize("y")).isEqualTo("y");
assertThat(localizationContext.localize("yam", "y")).isEqualTo("xylophone");
assertThat(localizationContext.localize("yam", "y", "z")).isEqualTo("eggzaktly");
assertThat(localizationContext.localize("yam", "z")).isEqualTo("yam");
}
@Test
public void testWithResourceNoBundle() {
ResourceBundleLocalizationContext localizationContext =
new ResourceBundleLocalizationContext(Locale.getDefault(), "x", null);
assertThat(localizationContext.localize(null)).isNull();
assertThat(localizationContext.localize("")).isEqualTo("");
assertThat(localizationContext.localize("foo")).isEqualTo("foo");
assertThat(localizationContext.localize("y")).isEqualTo("y");
assertThat(localizationContext.localize("yam", "y")).isEqualTo("yam");
assertThat(localizationContext.localize("yam", "y", "z")).isEqualTo("yam");
assertThat(localizationContext.localize("yam", "z")).isEqualTo("yam");
}
@Test
public void testLocalization() {
Locale locale1 = new Locale("en");
MockStringResourceBundle resourceBundle1 = new MockStringResourceBundle();
resourceBundle1.put("y", "xylophone");
resourceBundle1.put("y.z", "eggzaktly");
Locale locale2 = new Locale("fr");
MockStringResourceBundle resourceBundle2 = new MockStringResourceBundle(resourceBundle1);
resourceBundle2.put("y.z", "not eggzaktly");
| // Path: provider/src/main/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContext.java
// public static class ResourceBundleLocalizationContextFactory implements Factory {
//
// /**
// * The resource bundle resolver.
// */
// private final ResourceBundleResolver resourceBundleResolver;
//
// /**
// * Creates a resource bundle localization context factory with the specified parameters.
// *
// * @param resourceBundleResolver the resource bundle resolver
// */
// public ResourceBundleLocalizationContextFactory(ResourceBundleResolver resourceBundleResolver) {
// this.resourceBundleResolver = resourceBundleResolver;
// }
//
// @Override
// public LocalizationContext createRootLocalizationContext(Locale locale) {
// return new ResourceBundleLocalizationContext(
// locale, "", resourceBundleResolver.getBundle(BUNDLE_BASE_NAME, locale));
// }
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContext.java
// public interface ResourceBundleResolver {
//
// /**
// * The default resource bundle resolver.
// */
// ResourceBundleResolver DEFAULT = (baseName, locale) -> {
// try {
// return ResourceBundle.getBundle("com.cloudera.director.aws." + baseName, locale);
// } catch (MissingResourceException e) {
// LOG.warn("Could not load resource bundle '{}' for locale {}", baseName, locale);
// return null;
// }
// };
//
// /**
// * Returns the specified resource bundle for the specified locale, or {@code null} if there
// * is no such resource bundle.
// *
// * @param baseName the base name of the resource bundle
// * @param locale the locale
// * @return the specified resource bundle for the specified locale, or {@code null} if there
// * is no such resource bundle
// */
// ResourceBundle getBundle(String baseName, Locale locale);
// }
// Path: tests/src/test/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContextTest.java
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.common.ResourceBundleLocalizationContext.ResourceBundleLocalizationContextFactory;
import com.cloudera.director.aws.common.ResourceBundleLocalizationContext.ResourceBundleResolver;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.google.common.collect.Maps;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
assertThat(localizationContext.localize("y")).isEqualTo("y");
assertThat(localizationContext.localize("yam", "y")).isEqualTo("xylophone");
assertThat(localizationContext.localize("yam", "y", "z")).isEqualTo("eggzaktly");
assertThat(localizationContext.localize("yam", "z")).isEqualTo("yam");
}
@Test
public void testWithResourceNoBundle() {
ResourceBundleLocalizationContext localizationContext =
new ResourceBundleLocalizationContext(Locale.getDefault(), "x", null);
assertThat(localizationContext.localize(null)).isNull();
assertThat(localizationContext.localize("")).isEqualTo("");
assertThat(localizationContext.localize("foo")).isEqualTo("foo");
assertThat(localizationContext.localize("y")).isEqualTo("y");
assertThat(localizationContext.localize("yam", "y")).isEqualTo("yam");
assertThat(localizationContext.localize("yam", "y", "z")).isEqualTo("yam");
assertThat(localizationContext.localize("yam", "z")).isEqualTo("yam");
}
@Test
public void testLocalization() {
Locale locale1 = new Locale("en");
MockStringResourceBundle resourceBundle1 = new MockStringResourceBundle();
resourceBundle1.put("y", "xylophone");
resourceBundle1.put("y.z", "eggzaktly");
Locale locale2 = new Locale("fr");
MockStringResourceBundle resourceBundle2 = new MockStringResourceBundle(resourceBundle1);
resourceBundle2.put("y.z", "not eggzaktly");
| ResourceBundleResolver resolver = mock(ResourceBundleResolver.class); |
cloudera/director-aws-plugin | tests/src/test/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContextTest.java | // Path: provider/src/main/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContext.java
// public static class ResourceBundleLocalizationContextFactory implements Factory {
//
// /**
// * The resource bundle resolver.
// */
// private final ResourceBundleResolver resourceBundleResolver;
//
// /**
// * Creates a resource bundle localization context factory with the specified parameters.
// *
// * @param resourceBundleResolver the resource bundle resolver
// */
// public ResourceBundleLocalizationContextFactory(ResourceBundleResolver resourceBundleResolver) {
// this.resourceBundleResolver = resourceBundleResolver;
// }
//
// @Override
// public LocalizationContext createRootLocalizationContext(Locale locale) {
// return new ResourceBundleLocalizationContext(
// locale, "", resourceBundleResolver.getBundle(BUNDLE_BASE_NAME, locale));
// }
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContext.java
// public interface ResourceBundleResolver {
//
// /**
// * The default resource bundle resolver.
// */
// ResourceBundleResolver DEFAULT = (baseName, locale) -> {
// try {
// return ResourceBundle.getBundle("com.cloudera.director.aws." + baseName, locale);
// } catch (MissingResourceException e) {
// LOG.warn("Could not load resource bundle '{}' for locale {}", baseName, locale);
// return null;
// }
// };
//
// /**
// * Returns the specified resource bundle for the specified locale, or {@code null} if there
// * is no such resource bundle.
// *
// * @param baseName the base name of the resource bundle
// * @param locale the locale
// * @return the specified resource bundle for the specified locale, or {@code null} if there
// * is no such resource bundle
// */
// ResourceBundle getBundle(String baseName, Locale locale);
// }
| import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.common.ResourceBundleLocalizationContext.ResourceBundleLocalizationContextFactory;
import com.cloudera.director.aws.common.ResourceBundleLocalizationContext.ResourceBundleResolver;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.google.common.collect.Maps;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle; | }
@Test
public void testWithResourceNoBundle() {
ResourceBundleLocalizationContext localizationContext =
new ResourceBundleLocalizationContext(Locale.getDefault(), "x", null);
assertThat(localizationContext.localize(null)).isNull();
assertThat(localizationContext.localize("")).isEqualTo("");
assertThat(localizationContext.localize("foo")).isEqualTo("foo");
assertThat(localizationContext.localize("y")).isEqualTo("y");
assertThat(localizationContext.localize("yam", "y")).isEqualTo("yam");
assertThat(localizationContext.localize("yam", "y", "z")).isEqualTo("yam");
assertThat(localizationContext.localize("yam", "z")).isEqualTo("yam");
}
@Test
public void testLocalization() {
Locale locale1 = new Locale("en");
MockStringResourceBundle resourceBundle1 = new MockStringResourceBundle();
resourceBundle1.put("y", "xylophone");
resourceBundle1.put("y.z", "eggzaktly");
Locale locale2 = new Locale("fr");
MockStringResourceBundle resourceBundle2 = new MockStringResourceBundle(resourceBundle1);
resourceBundle2.put("y.z", "not eggzaktly");
ResourceBundleResolver resolver = mock(ResourceBundleResolver.class);
when(resolver.getBundle(anyString(), eq(locale1))).thenReturn(resourceBundle1);
when(resolver.getBundle(anyString(), eq(locale2))).thenReturn(resourceBundle2);
| // Path: provider/src/main/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContext.java
// public static class ResourceBundleLocalizationContextFactory implements Factory {
//
// /**
// * The resource bundle resolver.
// */
// private final ResourceBundleResolver resourceBundleResolver;
//
// /**
// * Creates a resource bundle localization context factory with the specified parameters.
// *
// * @param resourceBundleResolver the resource bundle resolver
// */
// public ResourceBundleLocalizationContextFactory(ResourceBundleResolver resourceBundleResolver) {
// this.resourceBundleResolver = resourceBundleResolver;
// }
//
// @Override
// public LocalizationContext createRootLocalizationContext(Locale locale) {
// return new ResourceBundleLocalizationContext(
// locale, "", resourceBundleResolver.getBundle(BUNDLE_BASE_NAME, locale));
// }
// }
//
// Path: provider/src/main/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContext.java
// public interface ResourceBundleResolver {
//
// /**
// * The default resource bundle resolver.
// */
// ResourceBundleResolver DEFAULT = (baseName, locale) -> {
// try {
// return ResourceBundle.getBundle("com.cloudera.director.aws." + baseName, locale);
// } catch (MissingResourceException e) {
// LOG.warn("Could not load resource bundle '{}' for locale {}", baseName, locale);
// return null;
// }
// };
//
// /**
// * Returns the specified resource bundle for the specified locale, or {@code null} if there
// * is no such resource bundle.
// *
// * @param baseName the base name of the resource bundle
// * @param locale the locale
// * @return the specified resource bundle for the specified locale, or {@code null} if there
// * is no such resource bundle
// */
// ResourceBundle getBundle(String baseName, Locale locale);
// }
// Path: tests/src/test/java/com/cloudera/director/aws/common/ResourceBundleLocalizationContextTest.java
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.cloudera.director.aws.common.ResourceBundleLocalizationContext.ResourceBundleLocalizationContextFactory;
import com.cloudera.director.aws.common.ResourceBundleLocalizationContext.ResourceBundleResolver;
import com.cloudera.director.spi.v2.model.LocalizationContext;
import com.google.common.collect.Maps;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
}
@Test
public void testWithResourceNoBundle() {
ResourceBundleLocalizationContext localizationContext =
new ResourceBundleLocalizationContext(Locale.getDefault(), "x", null);
assertThat(localizationContext.localize(null)).isNull();
assertThat(localizationContext.localize("")).isEqualTo("");
assertThat(localizationContext.localize("foo")).isEqualTo("foo");
assertThat(localizationContext.localize("y")).isEqualTo("y");
assertThat(localizationContext.localize("yam", "y")).isEqualTo("yam");
assertThat(localizationContext.localize("yam", "y", "z")).isEqualTo("yam");
assertThat(localizationContext.localize("yam", "z")).isEqualTo("yam");
}
@Test
public void testLocalization() {
Locale locale1 = new Locale("en");
MockStringResourceBundle resourceBundle1 = new MockStringResourceBundle();
resourceBundle1.put("y", "xylophone");
resourceBundle1.put("y.z", "eggzaktly");
Locale locale2 = new Locale("fr");
MockStringResourceBundle resourceBundle2 = new MockStringResourceBundle(resourceBundle1);
resourceBundle2.put("y.z", "not eggzaktly");
ResourceBundleResolver resolver = mock(ResourceBundleResolver.class);
when(resolver.getBundle(anyString(), eq(locale1))).thenReturn(resourceBundle1);
when(resolver.getBundle(anyString(), eq(locale2))).thenReturn(resourceBundle2);
| ResourceBundleLocalizationContextFactory factory = |
twitter/joauth | src/main/java/com/twitter/joauth/keyvalue/KeyValueParser.java | // Path: src/main/java/com/twitter/joauth/Request.java
// public interface Request {
//
// public String authHeader();
// public String body();
// public String contentType();
// public String host();
// public String method();
// public String path();
// public int port();
// public String queryString();
// public String scheme();
//
// public static interface ParsedRequestFactory {
// ParsedRequest parsedRequest(Request request, List<Pair> params);
// }
//
// public final ParsedRequestFactory factory = new ParsedRequestFactory() {
// @Override
// public ParsedRequest parsedRequest(Request request, List<Pair> params) {
// return new ParsedRequest(
// (request.scheme() == null) ? null : request.scheme().toUpperCase(),
// request.host(),
// request.port(),
// (request.method() == null) ? null : request.method().toUpperCase(),
// request.path(),
// params
// );
// }
// };
//
// public static class Pair {
// public final String key;
// public final String value;
//
// public Pair(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Pair pair = (Pair) o;
//
// if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
// if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key != null ? key.hashCode() : 0;
// result = 31 * result + (value != null ? value.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Pair{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// public static class ParsedRequest {
// private final String scheme;
// private final String host;
// private final int port;
// private final String verb;
// private final String path;
// private final List<Pair> params;
//
// public ParsedRequest(String scheme, String host, int port, String verb, String path, List<Pair> params) {
// this.scheme = scheme;
// this.host = host;
// this.port = port;
// this.verb = verb;
// this.path = path;
// this.params = Collections.unmodifiableList(params);
// }
//
// public String scheme() { return scheme; }
// public String host() { return host; }
// public int port() { return port; }
// public String verb() { return verb; }
// public String path() { return path; }
// public List<Pair> params() { return params; }
//
// @Override
// public String toString() {
// return "ParsedRequest{" +
// "scheme='" + scheme + '\'' +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", verb='" + verb + '\'' +
// ", path='" + path + '\'' +
// ", params=" + params +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ParsedRequest that = (ParsedRequest) o;
//
// if (port != that.port) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (params != null ? !params.equals(that.params) : that.params != null) return false;
// if (path != null ? !path.equals(that.path) : that.path != null) return false;
// if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) return false;
// if (verb != null ? !verb.equals(that.verb) : that.verb != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = scheme != null ? scheme.hashCode() : 0;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + port;
// result = 31 * result + (verb != null ? verb.hashCode() : 0);
// result = 31 * result + (path != null ? path.hashCode() : 0);
// result = 31 * result + (params != null ? params.hashCode() : 0);
// return result;
// }
// }
// }
| import java.util.List;
import com.twitter.joauth.Request; | for (String token : tokens) {
String[] keyAndValue = token.split(kvDelimiter);
switch (keyAndValue.length) {
case 2:
if (!empty(keyAndValue[0])) {
for (KeyValueHandler handler : handlers) handler.handle(keyAndValue[0], keyAndValue[1]);
}
break;
case 1:
if (!empty(keyAndValue[0])) {
for (KeyValueHandler handler : handlers) handler.handle(keyAndValue[0], "");
}
break;
default:
//ignore ?
break;
}
}
}
private boolean empty(String str) {
return str == null || str.length() == 0;
}
}
/**
* For testing. Calls the KeyValueParsers with the same List of key/value pairs every time
*/
//TODO: This is not used, remove?
public static class ConstKeyValueParser implements KeyValueParser { | // Path: src/main/java/com/twitter/joauth/Request.java
// public interface Request {
//
// public String authHeader();
// public String body();
// public String contentType();
// public String host();
// public String method();
// public String path();
// public int port();
// public String queryString();
// public String scheme();
//
// public static interface ParsedRequestFactory {
// ParsedRequest parsedRequest(Request request, List<Pair> params);
// }
//
// public final ParsedRequestFactory factory = new ParsedRequestFactory() {
// @Override
// public ParsedRequest parsedRequest(Request request, List<Pair> params) {
// return new ParsedRequest(
// (request.scheme() == null) ? null : request.scheme().toUpperCase(),
// request.host(),
// request.port(),
// (request.method() == null) ? null : request.method().toUpperCase(),
// request.path(),
// params
// );
// }
// };
//
// public static class Pair {
// public final String key;
// public final String value;
//
// public Pair(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Pair pair = (Pair) o;
//
// if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
// if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key != null ? key.hashCode() : 0;
// result = 31 * result + (value != null ? value.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Pair{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// public static class ParsedRequest {
// private final String scheme;
// private final String host;
// private final int port;
// private final String verb;
// private final String path;
// private final List<Pair> params;
//
// public ParsedRequest(String scheme, String host, int port, String verb, String path, List<Pair> params) {
// this.scheme = scheme;
// this.host = host;
// this.port = port;
// this.verb = verb;
// this.path = path;
// this.params = Collections.unmodifiableList(params);
// }
//
// public String scheme() { return scheme; }
// public String host() { return host; }
// public int port() { return port; }
// public String verb() { return verb; }
// public String path() { return path; }
// public List<Pair> params() { return params; }
//
// @Override
// public String toString() {
// return "ParsedRequest{" +
// "scheme='" + scheme + '\'' +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", verb='" + verb + '\'' +
// ", path='" + path + '\'' +
// ", params=" + params +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ParsedRequest that = (ParsedRequest) o;
//
// if (port != that.port) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (params != null ? !params.equals(that.params) : that.params != null) return false;
// if (path != null ? !path.equals(that.path) : that.path != null) return false;
// if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) return false;
// if (verb != null ? !verb.equals(that.verb) : that.verb != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = scheme != null ? scheme.hashCode() : 0;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + port;
// result = 31 * result + (verb != null ? verb.hashCode() : 0);
// result = 31 * result + (path != null ? path.hashCode() : 0);
// result = 31 * result + (params != null ? params.hashCode() : 0);
// return result;
// }
// }
// }
// Path: src/main/java/com/twitter/joauth/keyvalue/KeyValueParser.java
import java.util.List;
import com.twitter.joauth.Request;
for (String token : tokens) {
String[] keyAndValue = token.split(kvDelimiter);
switch (keyAndValue.length) {
case 2:
if (!empty(keyAndValue[0])) {
for (KeyValueHandler handler : handlers) handler.handle(keyAndValue[0], keyAndValue[1]);
}
break;
case 1:
if (!empty(keyAndValue[0])) {
for (KeyValueHandler handler : handlers) handler.handle(keyAndValue[0], "");
}
break;
default:
//ignore ?
break;
}
}
}
private boolean empty(String str) {
return str == null || str.length() == 0;
}
}
/**
* For testing. Calls the KeyValueParsers with the same List of key/value pairs every time
*/
//TODO: This is not used, remove?
public static class ConstKeyValueParser implements KeyValueParser { | private final List<Request.Pair> pairs; |
twitter/joauth | src/test/java/com/twitter/joauth/keyvalue/KeyValueHandlerTest.java | // Path: src/main/java/com/twitter/joauth/Request.java
// public interface Request {
//
// public String authHeader();
// public String body();
// public String contentType();
// public String host();
// public String method();
// public String path();
// public int port();
// public String queryString();
// public String scheme();
//
// public static interface ParsedRequestFactory {
// ParsedRequest parsedRequest(Request request, List<Pair> params);
// }
//
// public final ParsedRequestFactory factory = new ParsedRequestFactory() {
// @Override
// public ParsedRequest parsedRequest(Request request, List<Pair> params) {
// return new ParsedRequest(
// (request.scheme() == null) ? null : request.scheme().toUpperCase(),
// request.host(),
// request.port(),
// (request.method() == null) ? null : request.method().toUpperCase(),
// request.path(),
// params
// );
// }
// };
//
// public static class Pair {
// public final String key;
// public final String value;
//
// public Pair(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Pair pair = (Pair) o;
//
// if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
// if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key != null ? key.hashCode() : 0;
// result = 31 * result + (value != null ? value.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Pair{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// public static class ParsedRequest {
// private final String scheme;
// private final String host;
// private final int port;
// private final String verb;
// private final String path;
// private final List<Pair> params;
//
// public ParsedRequest(String scheme, String host, int port, String verb, String path, List<Pair> params) {
// this.scheme = scheme;
// this.host = host;
// this.port = port;
// this.verb = verb;
// this.path = path;
// this.params = Collections.unmodifiableList(params);
// }
//
// public String scheme() { return scheme; }
// public String host() { return host; }
// public int port() { return port; }
// public String verb() { return verb; }
// public String path() { return path; }
// public List<Pair> params() { return params; }
//
// @Override
// public String toString() {
// return "ParsedRequest{" +
// "scheme='" + scheme + '\'' +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", verb='" + verb + '\'' +
// ", path='" + path + '\'' +
// ", params=" + params +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ParsedRequest that = (ParsedRequest) o;
//
// if (port != that.port) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (params != null ? !params.equals(that.params) : that.params != null) return false;
// if (path != null ? !path.equals(that.path) : that.path != null) return false;
// if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) return false;
// if (verb != null ? !verb.equals(that.verb) : that.verb != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = scheme != null ? scheme.hashCode() : 0;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + port;
// result = 31 * result + (verb != null ? verb.hashCode() : 0);
// result = 31 * result + (path != null ? path.hashCode() : 0);
// result = 31 * result + (params != null ? params.hashCode() : 0);
// return result;
// }
// }
// }
| import com.twitter.joauth.Request;
import org.junit.Test;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.HashMap;
import static org.junit.Assert.assertEquals; | // Copyright 2011 Twitter, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
package com.twitter.joauth.keyvalue;
public class KeyValueHandlerTest {
@Test
public void testSingleKeyValueHandler() {
KeyValueHandler.SingleKeyValueHandler handler = new KeyValueHandler.SingleKeyValueHandler();
handler.handle("foo", "bar");
handler.handle("foo", "baz");
handler.handle("a", "b");
HashMap<String, String> map = new HashMap<String, String>();
map.put("foo", "baz");
map.put("a", "b");
assertEquals("use last value for key", handler.toMap(), map);
}
@Test
public void testDuplicateKeyValueHandler() {
KeyValueHandler.DuplicateKeyValueHandler handler = new KeyValueHandler.DuplicateKeyValueHandler();
handler.handle("foo", "bar");
handler.handle("foo", "baz");
handler.handle("a", "b"); | // Path: src/main/java/com/twitter/joauth/Request.java
// public interface Request {
//
// public String authHeader();
// public String body();
// public String contentType();
// public String host();
// public String method();
// public String path();
// public int port();
// public String queryString();
// public String scheme();
//
// public static interface ParsedRequestFactory {
// ParsedRequest parsedRequest(Request request, List<Pair> params);
// }
//
// public final ParsedRequestFactory factory = new ParsedRequestFactory() {
// @Override
// public ParsedRequest parsedRequest(Request request, List<Pair> params) {
// return new ParsedRequest(
// (request.scheme() == null) ? null : request.scheme().toUpperCase(),
// request.host(),
// request.port(),
// (request.method() == null) ? null : request.method().toUpperCase(),
// request.path(),
// params
// );
// }
// };
//
// public static class Pair {
// public final String key;
// public final String value;
//
// public Pair(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Pair pair = (Pair) o;
//
// if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
// if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key != null ? key.hashCode() : 0;
// result = 31 * result + (value != null ? value.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Pair{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// public static class ParsedRequest {
// private final String scheme;
// private final String host;
// private final int port;
// private final String verb;
// private final String path;
// private final List<Pair> params;
//
// public ParsedRequest(String scheme, String host, int port, String verb, String path, List<Pair> params) {
// this.scheme = scheme;
// this.host = host;
// this.port = port;
// this.verb = verb;
// this.path = path;
// this.params = Collections.unmodifiableList(params);
// }
//
// public String scheme() { return scheme; }
// public String host() { return host; }
// public int port() { return port; }
// public String verb() { return verb; }
// public String path() { return path; }
// public List<Pair> params() { return params; }
//
// @Override
// public String toString() {
// return "ParsedRequest{" +
// "scheme='" + scheme + '\'' +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", verb='" + verb + '\'' +
// ", path='" + path + '\'' +
// ", params=" + params +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ParsedRequest that = (ParsedRequest) o;
//
// if (port != that.port) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (params != null ? !params.equals(that.params) : that.params != null) return false;
// if (path != null ? !path.equals(that.path) : that.path != null) return false;
// if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) return false;
// if (verb != null ? !verb.equals(that.verb) : that.verb != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = scheme != null ? scheme.hashCode() : 0;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + port;
// result = 31 * result + (verb != null ? verb.hashCode() : 0);
// result = 31 * result + (path != null ? path.hashCode() : 0);
// result = 31 * result + (params != null ? params.hashCode() : 0);
// return result;
// }
// }
// }
// Path: src/test/java/com/twitter/joauth/keyvalue/KeyValueHandlerTest.java
import com.twitter.joauth.Request;
import org.junit.Test;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
// Copyright 2011 Twitter, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
package com.twitter.joauth.keyvalue;
public class KeyValueHandlerTest {
@Test
public void testSingleKeyValueHandler() {
KeyValueHandler.SingleKeyValueHandler handler = new KeyValueHandler.SingleKeyValueHandler();
handler.handle("foo", "bar");
handler.handle("foo", "baz");
handler.handle("a", "b");
HashMap<String, String> map = new HashMap<String, String>();
map.put("foo", "baz");
map.put("a", "b");
assertEquals("use last value for key", handler.toMap(), map);
}
@Test
public void testDuplicateKeyValueHandler() {
KeyValueHandler.DuplicateKeyValueHandler handler = new KeyValueHandler.DuplicateKeyValueHandler();
handler.handle("foo", "bar");
handler.handle("foo", "baz");
handler.handle("a", "b"); | ArrayList<Request.Pair> result = new ArrayList<Request.Pair>(); |
twitter/joauth | src/test/java/com/twitter/joauth/keyvalue/KeyValueParserTest.java | // Path: src/main/java/com/twitter/joauth/Request.java
// public interface Request {
//
// public String authHeader();
// public String body();
// public String contentType();
// public String host();
// public String method();
// public String path();
// public int port();
// public String queryString();
// public String scheme();
//
// public static interface ParsedRequestFactory {
// ParsedRequest parsedRequest(Request request, List<Pair> params);
// }
//
// public final ParsedRequestFactory factory = new ParsedRequestFactory() {
// @Override
// public ParsedRequest parsedRequest(Request request, List<Pair> params) {
// return new ParsedRequest(
// (request.scheme() == null) ? null : request.scheme().toUpperCase(),
// request.host(),
// request.port(),
// (request.method() == null) ? null : request.method().toUpperCase(),
// request.path(),
// params
// );
// }
// };
//
// public static class Pair {
// public final String key;
// public final String value;
//
// public Pair(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Pair pair = (Pair) o;
//
// if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
// if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key != null ? key.hashCode() : 0;
// result = 31 * result + (value != null ? value.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Pair{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// public static class ParsedRequest {
// private final String scheme;
// private final String host;
// private final int port;
// private final String verb;
// private final String path;
// private final List<Pair> params;
//
// public ParsedRequest(String scheme, String host, int port, String verb, String path, List<Pair> params) {
// this.scheme = scheme;
// this.host = host;
// this.port = port;
// this.verb = verb;
// this.path = path;
// this.params = Collections.unmodifiableList(params);
// }
//
// public String scheme() { return scheme; }
// public String host() { return host; }
// public int port() { return port; }
// public String verb() { return verb; }
// public String path() { return path; }
// public List<Pair> params() { return params; }
//
// @Override
// public String toString() {
// return "ParsedRequest{" +
// "scheme='" + scheme + '\'' +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", verb='" + verb + '\'' +
// ", path='" + path + '\'' +
// ", params=" + params +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ParsedRequest that = (ParsedRequest) o;
//
// if (port != that.port) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (params != null ? !params.equals(that.params) : that.params != null) return false;
// if (path != null ? !path.equals(that.path) : that.path != null) return false;
// if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) return false;
// if (verb != null ? !verb.equals(that.verb) : that.verb != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = scheme != null ? scheme.hashCode() : 0;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + port;
// result = 31 * result + (verb != null ? verb.hashCode() : 0);
// result = 31 * result + (path != null ? path.hashCode() : 0);
// result = 31 * result + (params != null ? params.hashCode() : 0);
// return result;
// }
// }
// }
| import static org.mockito.Mockito.*;
import java.util.ArrayList;
import com.twitter.joauth.Request;
import org.junit.Test; | // Copyright 2011 Twitter, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
package com.twitter.joauth.keyvalue;
public class KeyValueParserTest {
KeyValueHandler handler = mock(KeyValueHandler.class);
ArrayList<KeyValueHandler> handlers = initKeyValueHandlers();
private ArrayList<KeyValueHandler> initKeyValueHandlers() {
ArrayList<KeyValueHandler> list = new ArrayList<KeyValueHandler>();
list.add(handler);
return list;
}
@Test
public void testConstKeyValueParser() { | // Path: src/main/java/com/twitter/joauth/Request.java
// public interface Request {
//
// public String authHeader();
// public String body();
// public String contentType();
// public String host();
// public String method();
// public String path();
// public int port();
// public String queryString();
// public String scheme();
//
// public static interface ParsedRequestFactory {
// ParsedRequest parsedRequest(Request request, List<Pair> params);
// }
//
// public final ParsedRequestFactory factory = new ParsedRequestFactory() {
// @Override
// public ParsedRequest parsedRequest(Request request, List<Pair> params) {
// return new ParsedRequest(
// (request.scheme() == null) ? null : request.scheme().toUpperCase(),
// request.host(),
// request.port(),
// (request.method() == null) ? null : request.method().toUpperCase(),
// request.path(),
// params
// );
// }
// };
//
// public static class Pair {
// public final String key;
// public final String value;
//
// public Pair(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Pair pair = (Pair) o;
//
// if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
// if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key != null ? key.hashCode() : 0;
// result = 31 * result + (value != null ? value.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Pair{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// public static class ParsedRequest {
// private final String scheme;
// private final String host;
// private final int port;
// private final String verb;
// private final String path;
// private final List<Pair> params;
//
// public ParsedRequest(String scheme, String host, int port, String verb, String path, List<Pair> params) {
// this.scheme = scheme;
// this.host = host;
// this.port = port;
// this.verb = verb;
// this.path = path;
// this.params = Collections.unmodifiableList(params);
// }
//
// public String scheme() { return scheme; }
// public String host() { return host; }
// public int port() { return port; }
// public String verb() { return verb; }
// public String path() { return path; }
// public List<Pair> params() { return params; }
//
// @Override
// public String toString() {
// return "ParsedRequest{" +
// "scheme='" + scheme + '\'' +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", verb='" + verb + '\'' +
// ", path='" + path + '\'' +
// ", params=" + params +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ParsedRequest that = (ParsedRequest) o;
//
// if (port != that.port) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (params != null ? !params.equals(that.params) : that.params != null) return false;
// if (path != null ? !path.equals(that.path) : that.path != null) return false;
// if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) return false;
// if (verb != null ? !verb.equals(that.verb) : that.verb != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = scheme != null ? scheme.hashCode() : 0;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + port;
// result = 31 * result + (verb != null ? verb.hashCode() : 0);
// result = 31 * result + (path != null ? path.hashCode() : 0);
// result = 31 * result + (params != null ? params.hashCode() : 0);
// return result;
// }
// }
// }
// Path: src/test/java/com/twitter/joauth/keyvalue/KeyValueParserTest.java
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import com.twitter.joauth.Request;
import org.junit.Test;
// Copyright 2011 Twitter, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
package com.twitter.joauth.keyvalue;
public class KeyValueParserTest {
KeyValueHandler handler = mock(KeyValueHandler.class);
ArrayList<KeyValueHandler> handlers = initKeyValueHandlers();
private ArrayList<KeyValueHandler> initKeyValueHandlers() {
ArrayList<KeyValueHandler> list = new ArrayList<KeyValueHandler>();
list.add(handler);
return list;
}
@Test
public void testConstKeyValueParser() { | ArrayList<Request.Pair> requestPairs = new ArrayList<Request.Pair>(); |
twitter/joauth | src/main/java/com/twitter/joauth/keyvalue/KeyValueHandler.java | // Path: src/main/java/com/twitter/joauth/Request.java
// public interface Request {
//
// public String authHeader();
// public String body();
// public String contentType();
// public String host();
// public String method();
// public String path();
// public int port();
// public String queryString();
// public String scheme();
//
// public static interface ParsedRequestFactory {
// ParsedRequest parsedRequest(Request request, List<Pair> params);
// }
//
// public final ParsedRequestFactory factory = new ParsedRequestFactory() {
// @Override
// public ParsedRequest parsedRequest(Request request, List<Pair> params) {
// return new ParsedRequest(
// (request.scheme() == null) ? null : request.scheme().toUpperCase(),
// request.host(),
// request.port(),
// (request.method() == null) ? null : request.method().toUpperCase(),
// request.path(),
// params
// );
// }
// };
//
// public static class Pair {
// public final String key;
// public final String value;
//
// public Pair(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Pair pair = (Pair) o;
//
// if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
// if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key != null ? key.hashCode() : 0;
// result = 31 * result + (value != null ? value.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Pair{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// public static class ParsedRequest {
// private final String scheme;
// private final String host;
// private final int port;
// private final String verb;
// private final String path;
// private final List<Pair> params;
//
// public ParsedRequest(String scheme, String host, int port, String verb, String path, List<Pair> params) {
// this.scheme = scheme;
// this.host = host;
// this.port = port;
// this.verb = verb;
// this.path = path;
// this.params = Collections.unmodifiableList(params);
// }
//
// public String scheme() { return scheme; }
// public String host() { return host; }
// public int port() { return port; }
// public String verb() { return verb; }
// public String path() { return path; }
// public List<Pair> params() { return params; }
//
// @Override
// public String toString() {
// return "ParsedRequest{" +
// "scheme='" + scheme + '\'' +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", verb='" + verb + '\'' +
// ", path='" + path + '\'' +
// ", params=" + params +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ParsedRequest that = (ParsedRequest) o;
//
// if (port != that.port) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (params != null ? !params.equals(that.params) : that.params != null) return false;
// if (path != null ? !path.equals(that.path) : that.path != null) return false;
// if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) return false;
// if (verb != null ? !verb.equals(that.verb) : that.verb != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = scheme != null ? scheme.hashCode() : 0;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + port;
// result = 31 * result + (verb != null ? verb.hashCode() : 0);
// result = 31 * result + (path != null ? path.hashCode() : 0);
// result = 31 * result + (params != null ? params.hashCode() : 0);
// return result;
// }
// }
// }
| import java.util.*;
import com.twitter.joauth.Request; | // Copyright 2011 Twitter, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
package com.twitter.joauth.keyvalue;
/**
* KeyValueHandler is a trait for a callback with a key and a value.
* What you do with the key and value are up to you.
*/
public interface KeyValueHandler {
public void handle(String key, String value);
public final KeyValueHandler NULL_KEY_VALUE_HANDLER = new NullKeyValueHandler();
static class NullKeyValueHandler implements KeyValueHandler {
@Override
public void handle(String key, String value) {
}
}
/**
* DuplicateKeyValueHandler produces a List[(String, String)] of key
* value pairs, allowing duplicate values for keys.
*/
public static class DuplicateKeyValueHandler implements KeyValueHandler { | // Path: src/main/java/com/twitter/joauth/Request.java
// public interface Request {
//
// public String authHeader();
// public String body();
// public String contentType();
// public String host();
// public String method();
// public String path();
// public int port();
// public String queryString();
// public String scheme();
//
// public static interface ParsedRequestFactory {
// ParsedRequest parsedRequest(Request request, List<Pair> params);
// }
//
// public final ParsedRequestFactory factory = new ParsedRequestFactory() {
// @Override
// public ParsedRequest parsedRequest(Request request, List<Pair> params) {
// return new ParsedRequest(
// (request.scheme() == null) ? null : request.scheme().toUpperCase(),
// request.host(),
// request.port(),
// (request.method() == null) ? null : request.method().toUpperCase(),
// request.path(),
// params
// );
// }
// };
//
// public static class Pair {
// public final String key;
// public final String value;
//
// public Pair(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Pair pair = (Pair) o;
//
// if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
// if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key != null ? key.hashCode() : 0;
// result = 31 * result + (value != null ? value.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Pair{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// public static class ParsedRequest {
// private final String scheme;
// private final String host;
// private final int port;
// private final String verb;
// private final String path;
// private final List<Pair> params;
//
// public ParsedRequest(String scheme, String host, int port, String verb, String path, List<Pair> params) {
// this.scheme = scheme;
// this.host = host;
// this.port = port;
// this.verb = verb;
// this.path = path;
// this.params = Collections.unmodifiableList(params);
// }
//
// public String scheme() { return scheme; }
// public String host() { return host; }
// public int port() { return port; }
// public String verb() { return verb; }
// public String path() { return path; }
// public List<Pair> params() { return params; }
//
// @Override
// public String toString() {
// return "ParsedRequest{" +
// "scheme='" + scheme + '\'' +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", verb='" + verb + '\'' +
// ", path='" + path + '\'' +
// ", params=" + params +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ParsedRequest that = (ParsedRequest) o;
//
// if (port != that.port) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (params != null ? !params.equals(that.params) : that.params != null) return false;
// if (path != null ? !path.equals(that.path) : that.path != null) return false;
// if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) return false;
// if (verb != null ? !verb.equals(that.verb) : that.verb != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = scheme != null ? scheme.hashCode() : 0;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + port;
// result = 31 * result + (verb != null ? verb.hashCode() : 0);
// result = 31 * result + (path != null ? path.hashCode() : 0);
// result = 31 * result + (params != null ? params.hashCode() : 0);
// return result;
// }
// }
// }
// Path: src/main/java/com/twitter/joauth/keyvalue/KeyValueHandler.java
import java.util.*;
import com.twitter.joauth.Request;
// Copyright 2011 Twitter, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
package com.twitter.joauth.keyvalue;
/**
* KeyValueHandler is a trait for a callback with a key and a value.
* What you do with the key and value are up to you.
*/
public interface KeyValueHandler {
public void handle(String key, String value);
public final KeyValueHandler NULL_KEY_VALUE_HANDLER = new NullKeyValueHandler();
static class NullKeyValueHandler implements KeyValueHandler {
@Override
public void handle(String key, String value) {
}
}
/**
* DuplicateKeyValueHandler produces a List[(String, String)] of key
* value pairs, allowing duplicate values for keys.
*/
public static class DuplicateKeyValueHandler implements KeyValueHandler { | private final List<Request.Pair> buffer = new ArrayList<Request.Pair>(); |
DiceTechJobs/SolrPlugins | src/main/java/org/dice/solrenhancements/functionqueries/TermIntersectsValueSourceParser.java | // Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
| import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.valuesource.DoubleConstValueSource;
import org.apache.solr.common.SolrException;
import org.apache.solr.search.FunctionQParser;
import org.apache.solr.search.SyntaxError;
import org.apache.solr.search.ValueSourceParser;
import org.dice.solrenhancements.TermExtractionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set; |
return new TermIntersectsValueSource(paramInfo.field, paramInfo.analyzer, paramInfo.terms, paramInfo.similarity);
}
private static ParamInfo parseTerm(FunctionQParser fp) throws SyntaxError {
ParamInfo paramInfo = new ParamInfo();
paramInfo.field = fp.parseArg();
String textVal = fp.parseArg();
if(textVal == null || textVal.trim().length() == 0){
return paramInfo;
}
if(fp.hasMoreArguments()){
String similarity = fp.parseArg().toLowerCase().trim();
if( !similarity.equals(SimilarityType.DOC_LEN) &&
!similarity.equals(SimilarityType.PARAM_LEN) &&
!similarity.equals(SimilarityType.DICE) &&
!similarity.equals(SimilarityType.JACCARD)){
log.error(String.format("Invalid similarity class: %s. Defaulting to %s", similarity, SimilarityType.DOC_LEN));
similarity = SimilarityType.DOC_LEN;
}
paramInfo.similarity = similarity;
}
// need to do analysis on the term
Analyzer analyzer = fp.getReq().getSchema().getIndexAnalyzer();
paramInfo.analyzer = analyzer;
try { | // Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
// Path: src/main/java/org/dice/solrenhancements/functionqueries/TermIntersectsValueSourceParser.java
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.valuesource.DoubleConstValueSource;
import org.apache.solr.common.SolrException;
import org.apache.solr.search.FunctionQParser;
import org.apache.solr.search.SyntaxError;
import org.apache.solr.search.ValueSourceParser;
import org.dice.solrenhancements.TermExtractionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
return new TermIntersectsValueSource(paramInfo.field, paramInfo.analyzer, paramInfo.terms, paramInfo.similarity);
}
private static ParamInfo parseTerm(FunctionQParser fp) throws SyntaxError {
ParamInfo paramInfo = new ParamInfo();
paramInfo.field = fp.parseArg();
String textVal = fp.parseArg();
if(textVal == null || textVal.trim().length() == 0){
return paramInfo;
}
if(fp.hasMoreArguments()){
String similarity = fp.parseArg().toLowerCase().trim();
if( !similarity.equals(SimilarityType.DOC_LEN) &&
!similarity.equals(SimilarityType.PARAM_LEN) &&
!similarity.equals(SimilarityType.DICE) &&
!similarity.equals(SimilarityType.JACCARD)){
log.error(String.format("Invalid similarity class: %s. Defaulting to %s", similarity, SimilarityType.DOC_LEN));
similarity = SimilarityType.DOC_LEN;
}
paramInfo.similarity = similarity;
}
// need to do analysis on the term
Analyzer analyzer = fp.getReq().getSchema().getIndexAnalyzer();
paramInfo.analyzer = analyzer;
try { | List<String> terms = TermExtractionHelper.getTermsFromString(analyzer, paramInfo.field, textVal); |
DiceTechJobs/SolrPlugins | src/main/java/org/dice/solrenhancements/functionqueries/FieldIndexedValueSource.java | // Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
| import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.IntDocValues;
import org.apache.lucene.queries.function.docvalues.StrDocValues;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.dice.solrenhancements.TermExtractionHelper;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; | StringBuilder sb = new StringBuilder();
try {
if(!tryExtractTermsFromTermVector(docNum, indexedField, ir, sb)) {
extractTermsFromField(docNum, indexedField, ir, sb);
}
String values = sb.toString().trim();
if(values.length() == 0){
return "";
}
return values.substring(0, sb.length()-DELIM.length());
}
catch (Exception ex)
{
throw new RuntimeException("caught exception in function " + description()+" : doc=" + docNum, ex);
}
}
private void extractTermsFromField(int docNum, String indexedField, IndexReader ir, StringBuilder sb) throws IOException {
Set<String> fields = new HashSet<String>();
fields.add(indexedField);
Document d = ir.document(docNum, fields);
IndexableField field = d.getField(indexedField);
if (field == null) {
return;
}
| // Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
// Path: src/main/java/org/dice/solrenhancements/functionqueries/FieldIndexedValueSource.java
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.IntDocValues;
import org.apache.lucene.queries.function.docvalues.StrDocValues;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.dice.solrenhancements.TermExtractionHelper;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
StringBuilder sb = new StringBuilder();
try {
if(!tryExtractTermsFromTermVector(docNum, indexedField, ir, sb)) {
extractTermsFromField(docNum, indexedField, ir, sb);
}
String values = sb.toString().trim();
if(values.length() == 0){
return "";
}
return values.substring(0, sb.length()-DELIM.length());
}
catch (Exception ex)
{
throw new RuntimeException("caught exception in function " + description()+" : doc=" + docNum, ex);
}
}
private void extractTermsFromField(int docNum, String indexedField, IndexReader ir, StringBuilder sb) throws IOException {
Set<String> fields = new HashSet<String>();
fields.add(indexedField);
Document d = ir.document(docNum, fields);
IndexableField field = d.getField(indexedField);
if (field == null) {
return;
}
| List<String> terms = TermExtractionHelper.getTermsFromField(analyzer, field); |
DiceTechJobs/SolrPlugins | src/test/java/org/dice/parsing/InteractiveConsole.java | // Path: src/main/java/org/dice/parsing/ast/Expression.java
// public interface Expression {
// public String evaluate();
// }
| import org.dice.parsing.ast.Expression;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; | package org.dice.parsing;
/**
* Created by simon.hughes on 4/13/16.
*/
public class InteractiveConsole {
public static void main(String[] args) throws IOException {
String get_title_prompt = "Please enter search query to parse:";
String user_input = get_user_input(get_title_prompt);
while (!user_input.equals("exit") && !user_input.trim().equals(""))
{
try{
RecursiveDescentParser parser = new RecursiveDescentParser(new Lexer(user_input), "*:*"); | // Path: src/main/java/org/dice/parsing/ast/Expression.java
// public interface Expression {
// public String evaluate();
// }
// Path: src/test/java/org/dice/parsing/InteractiveConsole.java
import org.dice.parsing.ast.Expression;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
package org.dice.parsing;
/**
* Created by simon.hughes on 4/13/16.
*/
public class InteractiveConsole {
public static void main(String[] args) throws IOException {
String get_title_prompt = "Please enter search query to parse:";
String user_input = get_user_input(get_title_prompt);
while (!user_input.equals("exit") && !user_input.trim().equals(""))
{
try{
RecursiveDescentParser parser = new RecursiveDescentParser(new Lexer(user_input), "*:*"); | Expression ast = parser.parse(); |
DiceTechJobs/SolrPlugins | src/main/java/org/dice/solrenhancements/machinelearning/FeatureExtractor.java | // Path: src/main/java/org/dice/helper/DefaultHashTable.java
// public class DefaultHashTable<K,V> extends Hashtable<K,V> {
//
// private final Supplier<V> _supplier;
// public DefaultHashTable(V defaultVal)
// {
// // need to make this final
// final V defaultValCopy = defaultVal;
// _supplier = new Supplier<V>() {
// public V get() {
// return defaultValCopy;
// }
// };
// }
//
// public DefaultHashTable(V defaultVal, Map<K,V> map){
// super(map);
// final V defaultValCopy = defaultVal;
// _supplier = new Supplier<V>() {
// @Override
// public V get() {
// return defaultValCopy;
// }
// };
// }
//
// public DefaultHashTable(Supplier<V> supplier)
// {
// _supplier = supplier;
// }
//
// public DefaultHashTable(Supplier<V> supplier, Map<K,V> map)
// {
// super(map);
// _supplier = supplier;
// }
//
// @Override
// public V get(Object key)
// {
// if(!this.containsKey(key))
// {
// super.put((K)key, this._supplier.get());
// }
// return super.get(key);
// }
// }
//
// Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
| import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.dice.helper.DefaultHashTable;
import org.dice.solrenhancements.TermExtractionHelper;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier; | package org.dice.solrenhancements.machinelearning;
/**
* Created by simon.hughes on 2/1/17.
*/
public class FeatureExtractor {
private final IndexReader ir;
private final String[] fields;
private Map<String, Map<String, Integer>> featureMap = null;
private Analyzer analyzer = null;
private final int minDf;
public static class LABELS {
public static final String POSITIVE = "POSITIVE";
public static final String NEGATIVE = "NEGATIVE";
}
public FeatureExtractor(IndexReader ir, String[] fields, Analyzer analyzer, int minDf){
this.ir = ir;
this.fields = fields;
this.analyzer = analyzer;
this.minDf = minDf;
this.featureMap = createFeatureMap();
}
public FeatureExtractor extractFeaturesFromDocuments(Set<Integer> docIds, String featureLabel) throws IOException {
this.extractFeaturesFromDocuments(docIds, featureLabel, this.featureMap);
return this;
}
public Map<String, Map<String, Integer>> getFeatureMap(){
return featureMap;
}
public void resetFeatures(){
this.featureMap = createFeatureMap();
}
private final static Map<String, Map<String, Integer>> createFeatureMap(){ | // Path: src/main/java/org/dice/helper/DefaultHashTable.java
// public class DefaultHashTable<K,V> extends Hashtable<K,V> {
//
// private final Supplier<V> _supplier;
// public DefaultHashTable(V defaultVal)
// {
// // need to make this final
// final V defaultValCopy = defaultVal;
// _supplier = new Supplier<V>() {
// public V get() {
// return defaultValCopy;
// }
// };
// }
//
// public DefaultHashTable(V defaultVal, Map<K,V> map){
// super(map);
// final V defaultValCopy = defaultVal;
// _supplier = new Supplier<V>() {
// @Override
// public V get() {
// return defaultValCopy;
// }
// };
// }
//
// public DefaultHashTable(Supplier<V> supplier)
// {
// _supplier = supplier;
// }
//
// public DefaultHashTable(Supplier<V> supplier, Map<K,V> map)
// {
// super(map);
// _supplier = supplier;
// }
//
// @Override
// public V get(Object key)
// {
// if(!this.containsKey(key))
// {
// super.put((K)key, this._supplier.get());
// }
// return super.get(key);
// }
// }
//
// Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
// Path: src/main/java/org/dice/solrenhancements/machinelearning/FeatureExtractor.java
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.dice.helper.DefaultHashTable;
import org.dice.solrenhancements.TermExtractionHelper;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
package org.dice.solrenhancements.machinelearning;
/**
* Created by simon.hughes on 2/1/17.
*/
public class FeatureExtractor {
private final IndexReader ir;
private final String[] fields;
private Map<String, Map<String, Integer>> featureMap = null;
private Analyzer analyzer = null;
private final int minDf;
public static class LABELS {
public static final String POSITIVE = "POSITIVE";
public static final String NEGATIVE = "NEGATIVE";
}
public FeatureExtractor(IndexReader ir, String[] fields, Analyzer analyzer, int minDf){
this.ir = ir;
this.fields = fields;
this.analyzer = analyzer;
this.minDf = minDf;
this.featureMap = createFeatureMap();
}
public FeatureExtractor extractFeaturesFromDocuments(Set<Integer> docIds, String featureLabel) throws IOException {
this.extractFeaturesFromDocuments(docIds, featureLabel, this.featureMap);
return this;
}
public Map<String, Map<String, Integer>> getFeatureMap(){
return featureMap;
}
public void resetFeatures(){
this.featureMap = createFeatureMap();
}
private final static Map<String, Map<String, Integer>> createFeatureMap(){ | return new DefaultHashTable<String, Map<String, Integer>>(new Supplier<Map<String, Integer>>() { |
DiceTechJobs/SolrPlugins | src/main/java/org/dice/solrenhancements/machinelearning/FeatureExtractor.java | // Path: src/main/java/org/dice/helper/DefaultHashTable.java
// public class DefaultHashTable<K,V> extends Hashtable<K,V> {
//
// private final Supplier<V> _supplier;
// public DefaultHashTable(V defaultVal)
// {
// // need to make this final
// final V defaultValCopy = defaultVal;
// _supplier = new Supplier<V>() {
// public V get() {
// return defaultValCopy;
// }
// };
// }
//
// public DefaultHashTable(V defaultVal, Map<K,V> map){
// super(map);
// final V defaultValCopy = defaultVal;
// _supplier = new Supplier<V>() {
// @Override
// public V get() {
// return defaultValCopy;
// }
// };
// }
//
// public DefaultHashTable(Supplier<V> supplier)
// {
// _supplier = supplier;
// }
//
// public DefaultHashTable(Supplier<V> supplier, Map<K,V> map)
// {
// super(map);
// _supplier = supplier;
// }
//
// @Override
// public V get(Object key)
// {
// if(!this.containsKey(key))
// {
// super.put((K)key, this._supplier.get());
// }
// return super.get(key);
// }
// }
//
// Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
| import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.dice.helper.DefaultHashTable;
import org.dice.solrenhancements.TermExtractionHelper;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier; |
private void extractFeaturesFromDocuments(Set<Integer> docIds, String featureLabel, Map<String, Map<String,Integer>> featureMap) throws IOException {
for(Integer id: docIds){
extractFeaturesFromDocument(id, ir, featureLabel, featureMap);
}
}
private void extractFeaturesFromDocument(int docNum, IndexReader ir, String featureLabel, Map<String, Map<String,Integer>> featureMap) throws IOException {
if(fields == null || fields.length == 0){
return;
}
final Fields vectors = ir.getTermVectors(docNum);
final Document document = ir.document(docNum);
for (String fieldName : fields) {
Terms vector = null;
if (vectors != null) {
vector = vectors.terms(fieldName);
}
// field does not store term vector info
// even if term vectors enabled, need to extract payload from regular field reader
if (vector == null) {
IndexableField docFields[] = document.getFields(fieldName);
for (IndexableField field : docFields) {
final String stringValue = field.stringValue();
if (stringValue != null) { | // Path: src/main/java/org/dice/helper/DefaultHashTable.java
// public class DefaultHashTable<K,V> extends Hashtable<K,V> {
//
// private final Supplier<V> _supplier;
// public DefaultHashTable(V defaultVal)
// {
// // need to make this final
// final V defaultValCopy = defaultVal;
// _supplier = new Supplier<V>() {
// public V get() {
// return defaultValCopy;
// }
// };
// }
//
// public DefaultHashTable(V defaultVal, Map<K,V> map){
// super(map);
// final V defaultValCopy = defaultVal;
// _supplier = new Supplier<V>() {
// @Override
// public V get() {
// return defaultValCopy;
// }
// };
// }
//
// public DefaultHashTable(Supplier<V> supplier)
// {
// _supplier = supplier;
// }
//
// public DefaultHashTable(Supplier<V> supplier, Map<K,V> map)
// {
// super(map);
// _supplier = supplier;
// }
//
// @Override
// public V get(Object key)
// {
// if(!this.containsKey(key))
// {
// super.put((K)key, this._supplier.get());
// }
// return super.get(key);
// }
// }
//
// Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
// Path: src/main/java/org/dice/solrenhancements/machinelearning/FeatureExtractor.java
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.dice.helper.DefaultHashTable;
import org.dice.solrenhancements.TermExtractionHelper;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
private void extractFeaturesFromDocuments(Set<Integer> docIds, String featureLabel, Map<String, Map<String,Integer>> featureMap) throws IOException {
for(Integer id: docIds){
extractFeaturesFromDocument(id, ir, featureLabel, featureMap);
}
}
private void extractFeaturesFromDocument(int docNum, IndexReader ir, String featureLabel, Map<String, Map<String,Integer>> featureMap) throws IOException {
if(fields == null || fields.length == 0){
return;
}
final Fields vectors = ir.getTermVectors(docNum);
final Document document = ir.document(docNum);
for (String fieldName : fields) {
Terms vector = null;
if (vectors != null) {
vector = vectors.terms(fieldName);
}
// field does not store term vector info
// even if term vectors enabled, need to extract payload from regular field reader
if (vector == null) {
IndexableField docFields[] = document.getFields(fieldName);
for (IndexableField field : docFields) {
final String stringValue = field.stringValue();
if (stringValue != null) { | List<String> lstTerms = TermExtractionHelper.getTermsFromString(analyzer, fieldName, stringValue); |
DiceTechJobs/SolrPlugins | src/main/java/org/dice/parsing/RecursiveDescentParser.java | // Path: src/main/java/org/dice/parsing/ast/Expression.java
// public interface Expression {
// public String evaluate();
// }
//
// Path: src/main/java/org/dice/parsing/ast/operands/Operand.java
// public class Operand implements Expression {
// protected String value;
//
// public Operand(String value) {
// this.value = value;
// }
//
// public String evaluate() {
// return String.format("%s", value);
// }
//
// @Override
// public String toString(){
// return this.evaluate();
// }
// }
| import org.apache.commons.lang.StringUtils;
import org.dice.parsing.ast.Expression;
import org.dice.parsing.ast.operands.Operand;
import org.dice.parsing.ast.operators.*;
import java.util.HashSet;
import java.util.Set; | package org.dice.parsing;
/**
* Created by simon.hughes on 4/12/16.
*/
public class RecursiveDescentParser {
private Lexer lexer;
private int symbol;
// used whenever a malformed expression is missing an expected token
private final String missingTokenValue; | // Path: src/main/java/org/dice/parsing/ast/Expression.java
// public interface Expression {
// public String evaluate();
// }
//
// Path: src/main/java/org/dice/parsing/ast/operands/Operand.java
// public class Operand implements Expression {
// protected String value;
//
// public Operand(String value) {
// this.value = value;
// }
//
// public String evaluate() {
// return String.format("%s", value);
// }
//
// @Override
// public String toString(){
// return this.evaluate();
// }
// }
// Path: src/main/java/org/dice/parsing/RecursiveDescentParser.java
import org.apache.commons.lang.StringUtils;
import org.dice.parsing.ast.Expression;
import org.dice.parsing.ast.operands.Operand;
import org.dice.parsing.ast.operators.*;
import java.util.HashSet;
import java.util.Set;
package org.dice.parsing;
/**
* Created by simon.hughes on 4/12/16.
*/
public class RecursiveDescentParser {
private Lexer lexer;
private int symbol;
// used whenever a malformed expression is missing an expected token
private final String missingTokenValue; | private Expression root; |
DiceTechJobs/SolrPlugins | src/main/java/org/dice/parsing/RecursiveDescentParser.java | // Path: src/main/java/org/dice/parsing/ast/Expression.java
// public interface Expression {
// public String evaluate();
// }
//
// Path: src/main/java/org/dice/parsing/ast/operands/Operand.java
// public class Operand implements Expression {
// protected String value;
//
// public Operand(String value) {
// this.value = value;
// }
//
// public String evaluate() {
// return String.format("%s", value);
// }
//
// @Override
// public String toString(){
// return this.evaluate();
// }
// }
| import org.apache.commons.lang.StringUtils;
import org.dice.parsing.ast.Expression;
import org.dice.parsing.ast.operands.Operand;
import org.dice.parsing.ast.operators.*;
import java.util.HashSet;
import java.util.Set; |
private void sequenceExpression(){
term();
while (symbol == Lexer.TOKEN || symbol == Lexer.QUOTE || symbol == Lexer.FIELD) {
Expression left = root;
processTerminal();
Expression right = root;
root = new Or(left, right);
}
}
private boolean isNotQuoteOrEOF(int symbol){
return symbol != Lexer.QUOTE && symbol != Lexer.EOF;
}
private void quotedExpression() {
StringBuilder quotedPhrase = new StringBuilder();
// read all symbols (including boolean operators and parens) until a quote is reached.
// if no quote reached, eat the rest of the expression as quoted phrase (what else can we do?)
while(isNotQuoteOrEOF(symbol = lexer.nextSymbol())){
// use just the string representations
quotedPhrase.append(lexer.toString()).append(SPACE);
}
String phrase = quotedPhrase.toString().trim();
if(StringUtils.isBlank(phrase)) {
errors.add(ParserErrors.MissingQuoteCharacter.value);
}
// insert with empty string if needed (otherwise you have a hanging AND or OR
// - (java AND "") is better than (java AND ) | // Path: src/main/java/org/dice/parsing/ast/Expression.java
// public interface Expression {
// public String evaluate();
// }
//
// Path: src/main/java/org/dice/parsing/ast/operands/Operand.java
// public class Operand implements Expression {
// protected String value;
//
// public Operand(String value) {
// this.value = value;
// }
//
// public String evaluate() {
// return String.format("%s", value);
// }
//
// @Override
// public String toString(){
// return this.evaluate();
// }
// }
// Path: src/main/java/org/dice/parsing/RecursiveDescentParser.java
import org.apache.commons.lang.StringUtils;
import org.dice.parsing.ast.Expression;
import org.dice.parsing.ast.operands.Operand;
import org.dice.parsing.ast.operators.*;
import java.util.HashSet;
import java.util.Set;
private void sequenceExpression(){
term();
while (symbol == Lexer.TOKEN || symbol == Lexer.QUOTE || symbol == Lexer.FIELD) {
Expression left = root;
processTerminal();
Expression right = root;
root = new Or(left, right);
}
}
private boolean isNotQuoteOrEOF(int symbol){
return symbol != Lexer.QUOTE && symbol != Lexer.EOF;
}
private void quotedExpression() {
StringBuilder quotedPhrase = new StringBuilder();
// read all symbols (including boolean operators and parens) until a quote is reached.
// if no quote reached, eat the rest of the expression as quoted phrase (what else can we do?)
while(isNotQuoteOrEOF(symbol = lexer.nextSymbol())){
// use just the string representations
quotedPhrase.append(lexer.toString()).append(SPACE);
}
String phrase = quotedPhrase.toString().trim();
if(StringUtils.isBlank(phrase)) {
errors.add(ParserErrors.MissingQuoteCharacter.value);
}
// insert with empty string if needed (otherwise you have a hanging AND or OR
// - (java AND "") is better than (java AND ) | root = new Quote(new Operand(phrase)); |
DiceTechJobs/SolrPlugins | src/main/java/org/dice/solrenhancements/functionqueries/TermIntersectsValueSource.java | // Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
| import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.FloatDocValues;
import org.dice.solrenhancements.TermExtractionHelper;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; | package org.dice.solrenhancements.functionqueries;
/**
* Created by simon.hughes on 2/20/17.
*/
public class TermIntersectsValueSource extends ValueSource {
private final String indexedField;
private final Analyzer analyzer;
private final Set<String> valuesToIntersect;
private final String similarity;
public TermIntersectsValueSource(String indexedField, Analyzer analyzer, Set<String> valuesToIntersect, String similarity) {
this.indexedField = indexedField;
this.analyzer = analyzer;
this.valuesToIntersect = valuesToIntersect;
this.similarity = similarity;
}
public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException {
final IndexReader ir = readerContext.reader();
final String indexedField = this.indexedField;
return new FloatDocValues(this) {
public float floatVal(int docNum) {
if(valuesToIntersect.size() == 0){
return 0;
}
HashSet<String> fieldValues = null;
try {
final Fields vectors= ir.getTermVectors(docNum);
if (vectors != null) {
if (vectors != null) {
Terms vector = vectors.terms(indexedField);
if (vector != null) { | // Path: src/main/java/org/dice/solrenhancements/TermExtractionHelper.java
// public class TermExtractionHelper {
//
// public static List<String> getTermsFromField(Analyzer analyzer, IndexableField field) throws IOException {
// TokenStream ts = null;
// try {
// ArrayList<String> terms = new ArrayList<String>();
//
// ts = field.tokenStream(analyzer, ts);
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// terms.add(termAtt.toString());
// }
// ts.end();
// return terms;
// }
// finally {
// if(ts != null){
// IOUtils.closeWhileHandlingException(ts);
// }
// }
// }
//
// public static List<String> getTermsFromString(Analyzer analyzer, String fieldName, String fieldValue)
// throws IOException {
//
// final StringReader reader = new StringReader(fieldValue);
// ArrayList<String> terms = new ArrayList<String>();
// TokenStream ts = analyzer.tokenStream(fieldName, reader);
// try {
// // for every token
// CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
// ts.reset();
// while (ts.incrementToken()) {
// String term = termAtt.toString();
// terms.add(term);
// }
// ts.end();
// } finally {
// IOUtils.closeWhileHandlingException(ts);
// }
// return terms;
// }
//
// public static List<String> getTermsFromTermVectorField(Terms vector) throws IOException {
// ArrayList<String> terms = new ArrayList<String>();
//
// final TermsEnum termsEnum = vector.iterator();
// CharsRefBuilder spare = new CharsRefBuilder();
// BytesRef text;
//
// while((text = termsEnum.next()) != null) {
// spare.copyUTF8Bytes(text);
// final String term = spare.toString();
// terms.add(term);
// }
// return terms;
// }
// }
// Path: src/main/java/org/dice/solrenhancements/functionqueries/TermIntersectsValueSource.java
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.FloatDocValues;
import org.dice.solrenhancements.TermExtractionHelper;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
package org.dice.solrenhancements.functionqueries;
/**
* Created by simon.hughes on 2/20/17.
*/
public class TermIntersectsValueSource extends ValueSource {
private final String indexedField;
private final Analyzer analyzer;
private final Set<String> valuesToIntersect;
private final String similarity;
public TermIntersectsValueSource(String indexedField, Analyzer analyzer, Set<String> valuesToIntersect, String similarity) {
this.indexedField = indexedField;
this.analyzer = analyzer;
this.valuesToIntersect = valuesToIntersect;
this.similarity = similarity;
}
public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException {
final IndexReader ir = readerContext.reader();
final String indexedField = this.indexedField;
return new FloatDocValues(this) {
public float floatVal(int docNum) {
if(valuesToIntersect.size() == 0){
return 0;
}
HashSet<String> fieldValues = null;
try {
final Fields vectors= ir.getTermVectors(docNum);
if (vectors != null) {
if (vectors != null) {
Terms vector = vectors.terms(indexedField);
if (vector != null) { | fieldValues = new HashSet<String>(TermExtractionHelper.getTermsFromTermVectorField(vector)); |
DiceTechJobs/SolrPlugins | src/test/java/org/dice/parsing/TestRecursiveDescentParser.java | // Path: src/main/java/org/dice/parsing/ast/Expression.java
// public interface Expression {
// public String evaluate();
// }
| import org.dice.parsing.ast.Expression;
import org.junit.Test;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static junit.framework.TestCase.assertEquals; | assertEquals("(java AND sql)", parseWithoutErrors("java and sql"));
assertEquals("(java AND sql)", parseWithoutErrors("java aNd sql"));
assertEquals("(java AND sql)", parseWithoutErrors("java AND sql"));
assertEquals("(java OR sql)", parseWithoutErrors("java or sql"));
assertEquals("(java OR sql)", parseWithoutErrors("java oR sql"));
assertEquals("(java OR sql)", parseWithoutErrors("java Or sql"));
assertEquals("(java OR sql)", parseWithoutErrors("java OR sql"));
}
@Test
public void enforcesOperatorPrecedence(){
assertEquals("((java AND sql) OR ruby)", parseWithoutErrors("java and sql or ruby"));
assertEquals("(java OR (sql AND ruby))", parseWithoutErrors("java or sql AnD ruby"));
}
@Test
// Note that solr always parses NOT correctly as it's a unary operator (and the reasons for the
// issues with boolean operator precedence resolve around converting boolean to unary operators
public void parsesNotOperator(){
// Note - see comments above
assertEquals("NOT java", parseWithoutErrors("not java"));
assertEquals("(NOT java AND sql)", parseWithoutErrors("not java and sql"));
assertEquals("((NOT java AND sql) OR ruby)", parseWithoutErrors("not java and sql or ruby"));
assertEquals("(NOT (java AND sql) OR ruby)", parseWithoutErrors("not (java and sql) or ruby"));
}
private String parseWithoutErrors(String input){
RecursiveDescentParser parser = new RecursiveDescentParser(new Lexer(input), WILDCARD_TOKEN); | // Path: src/main/java/org/dice/parsing/ast/Expression.java
// public interface Expression {
// public String evaluate();
// }
// Path: src/test/java/org/dice/parsing/TestRecursiveDescentParser.java
import org.dice.parsing.ast.Expression;
import org.junit.Test;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static junit.framework.TestCase.assertEquals;
assertEquals("(java AND sql)", parseWithoutErrors("java and sql"));
assertEquals("(java AND sql)", parseWithoutErrors("java aNd sql"));
assertEquals("(java AND sql)", parseWithoutErrors("java AND sql"));
assertEquals("(java OR sql)", parseWithoutErrors("java or sql"));
assertEquals("(java OR sql)", parseWithoutErrors("java oR sql"));
assertEquals("(java OR sql)", parseWithoutErrors("java Or sql"));
assertEquals("(java OR sql)", parseWithoutErrors("java OR sql"));
}
@Test
public void enforcesOperatorPrecedence(){
assertEquals("((java AND sql) OR ruby)", parseWithoutErrors("java and sql or ruby"));
assertEquals("(java OR (sql AND ruby))", parseWithoutErrors("java or sql AnD ruby"));
}
@Test
// Note that solr always parses NOT correctly as it's a unary operator (and the reasons for the
// issues with boolean operator precedence resolve around converting boolean to unary operators
public void parsesNotOperator(){
// Note - see comments above
assertEquals("NOT java", parseWithoutErrors("not java"));
assertEquals("(NOT java AND sql)", parseWithoutErrors("not java and sql"));
assertEquals("((NOT java AND sql) OR ruby)", parseWithoutErrors("not java and sql or ruby"));
assertEquals("(NOT (java AND sql) OR ruby)", parseWithoutErrors("not (java and sql) or ruby"));
}
private String parseWithoutErrors(String input){
RecursiveDescentParser parser = new RecursiveDescentParser(new Lexer(input), WILDCARD_TOKEN); | final Expression ast = parser.parse(); |
466152112/HappyResearch | happyresearch/src/main/java/happy/research/cf/DefaultCF_mt.java | // Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum DatasetMode {
// all("All"), coldUsers("Cold Users"), heavyUsers("Heavy Users"), opinUsers("Opin. Users"), blackSheep(
// "Black Sheep"), nicheItems("Niche Items"), contrItems("Contr. Items"), batch("Batch"), userDegree(
// "user-degree"), itemDegree("item-degree");
//
// public String label = null;
//
// DatasetMode(String _label) {
// this.label = _label;
// }
//
// }
//
// Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum ValidateMethod {
// leave_one_out, cross_validation
// }
| import happy.coding.io.FileIO;
import happy.coding.io.Logs;
import happy.research.cf.ConfigParams.DatasetMode;
import happy.research.cf.ConfigParams.ValidateMethod;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
| threads = new Thread[numThreads];
pf = new Performance(methodId);
return runMultiThreads();
}
protected abstract Performance runMultiThreads() throws Exception;
protected void makeDirPaths() throws Exception {
int horizon = params.TRUST_PROPERGATION_LENGTH;
String trustDir = (params.TIDALTRUST ? "TT" : "MT") + horizon;
String trustDir2 = params.TIDALTRUST ? "TidalTrust" : "MoleTrust";
String trustDir0 = null;
if (params.auto_trust_sets)
trustDir0 = current_trust_name;
String[] trustDirs = null;
if (params.auto_trust_sets) {
trustDirs = new String[] { Dataset.TEMP_DIRECTORY, trustDir, trustDir0, trustDir2 };
} else {
trustDirs = new String[] { Dataset.TEMP_DIRECTORY, trustDir, trustDir2 };
}
trustDirPath = FileIO.makeDirPath(trustDirs);
FileIO.makeDirectory(trustDirPath);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void prepTestRatings() {
| // Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum DatasetMode {
// all("All"), coldUsers("Cold Users"), heavyUsers("Heavy Users"), opinUsers("Opin. Users"), blackSheep(
// "Black Sheep"), nicheItems("Niche Items"), contrItems("Contr. Items"), batch("Batch"), userDegree(
// "user-degree"), itemDegree("item-degree");
//
// public String label = null;
//
// DatasetMode(String _label) {
// this.label = _label;
// }
//
// }
//
// Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum ValidateMethod {
// leave_one_out, cross_validation
// }
// Path: happyresearch/src/main/java/happy/research/cf/DefaultCF_mt.java
import happy.coding.io.FileIO;
import happy.coding.io.Logs;
import happy.research.cf.ConfigParams.DatasetMode;
import happy.research.cf.ConfigParams.ValidateMethod;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
threads = new Thread[numThreads];
pf = new Performance(methodId);
return runMultiThreads();
}
protected abstract Performance runMultiThreads() throws Exception;
protected void makeDirPaths() throws Exception {
int horizon = params.TRUST_PROPERGATION_LENGTH;
String trustDir = (params.TIDALTRUST ? "TT" : "MT") + horizon;
String trustDir2 = params.TIDALTRUST ? "TidalTrust" : "MoleTrust";
String trustDir0 = null;
if (params.auto_trust_sets)
trustDir0 = current_trust_name;
String[] trustDirs = null;
if (params.auto_trust_sets) {
trustDirs = new String[] { Dataset.TEMP_DIRECTORY, trustDir, trustDir0, trustDir2 };
} else {
trustDirs = new String[] { Dataset.TEMP_DIRECTORY, trustDir, trustDir2 };
}
trustDirPath = FileIO.makeDirPath(trustDirs);
FileIO.makeDirectory(trustDirPath);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void prepTestRatings() {
| if (params.VALIDATE_METHOD == ValidateMethod.leave_one_out)
|
466152112/HappyResearch | happyresearch/src/main/java/happy/research/cf/DefaultCF_mt.java | // Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum DatasetMode {
// all("All"), coldUsers("Cold Users"), heavyUsers("Heavy Users"), opinUsers("Opin. Users"), blackSheep(
// "Black Sheep"), nicheItems("Niche Items"), contrItems("Contr. Items"), batch("Batch"), userDegree(
// "user-degree"), itemDegree("item-degree");
//
// public String label = null;
//
// DatasetMode(String _label) {
// this.label = _label;
// }
//
// }
//
// Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum ValidateMethod {
// leave_one_out, cross_validation
// }
| import happy.coding.io.FileIO;
import happy.coding.io.Logs;
import happy.research.cf.ConfigParams.DatasetMode;
import happy.research.cf.ConfigParams.ValidateMethod;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
|
if (params.auto_trust_sets) {
trustDirs = new String[] { Dataset.TEMP_DIRECTORY, trustDir, trustDir0, trustDir2 };
} else {
trustDirs = new String[] { Dataset.TEMP_DIRECTORY, trustDir, trustDir2 };
}
trustDirPath = FileIO.makeDirPath(trustDirs);
FileIO.makeDirectory(trustDirPath);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void prepTestRatings() {
if (params.VALIDATE_METHOD == ValidateMethod.leave_one_out)
super.prepTestRatings();
else if (testRatings == null) {
String testSet = Dataset.DIRECTORY + params.TEST_SET;
Logs.debug("Loading test set {}", testSet);
testRatings = new ArrayList<>();
Map<String, Map<String, Rating>> userMap = null;
Map<String, Map<String, Rating>> itemMap = null;
try {
Map[] data = Dataset.loadTestSet(testSet);
userMap = data[0];
itemMap = data[1];
} catch (Exception e) {
e.printStackTrace();
}
| // Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum DatasetMode {
// all("All"), coldUsers("Cold Users"), heavyUsers("Heavy Users"), opinUsers("Opin. Users"), blackSheep(
// "Black Sheep"), nicheItems("Niche Items"), contrItems("Contr. Items"), batch("Batch"), userDegree(
// "user-degree"), itemDegree("item-degree");
//
// public String label = null;
//
// DatasetMode(String _label) {
// this.label = _label;
// }
//
// }
//
// Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum ValidateMethod {
// leave_one_out, cross_validation
// }
// Path: happyresearch/src/main/java/happy/research/cf/DefaultCF_mt.java
import happy.coding.io.FileIO;
import happy.coding.io.Logs;
import happy.research.cf.ConfigParams.DatasetMode;
import happy.research.cf.ConfigParams.ValidateMethod;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
if (params.auto_trust_sets) {
trustDirs = new String[] { Dataset.TEMP_DIRECTORY, trustDir, trustDir0, trustDir2 };
} else {
trustDirs = new String[] { Dataset.TEMP_DIRECTORY, trustDir, trustDir2 };
}
trustDirPath = FileIO.makeDirPath(trustDirs);
FileIO.makeDirectory(trustDirPath);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void prepTestRatings() {
if (params.VALIDATE_METHOD == ValidateMethod.leave_one_out)
super.prepTestRatings();
else if (testRatings == null) {
String testSet = Dataset.DIRECTORY + params.TEST_SET;
Logs.debug("Loading test set {}", testSet);
testRatings = new ArrayList<>();
Map<String, Map<String, Rating>> userMap = null;
Map<String, Map<String, Rating>> itemMap = null;
try {
Map[] data = Dataset.loadTestSet(testSet);
userMap = data[0];
itemMap = data[1];
} catch (Exception e) {
e.printStackTrace();
}
| if (params.DATASET_MODE == DatasetMode.nicheItems || params.DATASET_MODE == DatasetMode.contrItems) {
|
466152112/HappyResearch | happyresearch/src/main/java/happy/research/utils/TidalTrust.java | // Path: happyresearch/src/main/java/happy/research/cf/TrustRating.java
// public class TrustRating
// {
// private String trustor;
// private String trustee;
// private double rating;
//
// public String getTrustor()
// {
// return trustor;
// }
//
// public void setTrustor(String trustor)
// {
// this.trustor = trustor;
// }
//
// public String getTrustee()
// {
// return trustee;
// }
//
// public void setTrustee(String trustee)
// {
// this.trustee = trustee;
// }
//
// public double getRating()
// {
// return rating;
// }
//
// public void setRating(double rating)
// {
// this.rating = rating;
// }
//
// @Override
// public String toString()
// {
// return trustor + " " + trustee + " " + rating;
// }
//
// }
| import happy.research.cf.TrustRating;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
| package happy.research.utils;
public class TidalTrust
{
/**
* TidalTrust algorithm to infer trust
*
* @param userTNsMap
* {user, {trustors}} map
* @param userTrustorsMap
* @param userRatingsMap
* {user, {trust ratings}} map
* @param source
* source user
* @param sink
* target user
* @param maxDepth
* maximum length of the searching path
* @return
*/
@SuppressWarnings({ "unchecked" })
public static Map<String, Double> runAlgorithm(Map<String, Map<String, Double>> userTrusteesMap,
| // Path: happyresearch/src/main/java/happy/research/cf/TrustRating.java
// public class TrustRating
// {
// private String trustor;
// private String trustee;
// private double rating;
//
// public String getTrustor()
// {
// return trustor;
// }
//
// public void setTrustor(String trustor)
// {
// this.trustor = trustor;
// }
//
// public String getTrustee()
// {
// return trustee;
// }
//
// public void setTrustee(String trustee)
// {
// this.trustee = trustee;
// }
//
// public double getRating()
// {
// return rating;
// }
//
// public void setRating(double rating)
// {
// this.rating = rating;
// }
//
// @Override
// public String toString()
// {
// return trustor + " " + trustee + " " + rating;
// }
//
// }
// Path: happyresearch/src/main/java/happy/research/utils/TidalTrust.java
import happy.research.cf.TrustRating;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
package happy.research.utils;
public class TidalTrust
{
/**
* TidalTrust algorithm to infer trust
*
* @param userTNsMap
* {user, {trustors}} map
* @param userTrustorsMap
* @param userRatingsMap
* {user, {trust ratings}} map
* @param source
* source user
* @param sink
* target user
* @param maxDepth
* maximum length of the searching path
* @return
*/
@SuppressWarnings({ "unchecked" })
public static Map<String, Double> runAlgorithm(Map<String, Map<String, Double>> userTrusteesMap,
| Map<String, Map<String, Double>> userTrustorsMap, Map<String, List<TrustRating>> userRatingsMap,
|
466152112/HappyResearch | happyresearch/src/main/java/happy/research/pgp/AbstractPGP.java | // Path: happyresearch/src/main/java/happy/research/pgp/PGPNode.java
// public static enum SignerType
// {
// ExperiencedSigner, MediumSigner, NewbieSigner
// };
| import happy.coding.math.Randoms;
import happy.research.pgp.PGPNode.SignerType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.MaxIterationsExceededException;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.analysis.integration.SimpsonIntegrator;
import org.apache.log4j.Logger;
| if (Arrays.binarySearch(honestIndexArray, i) >= 0)
node.setHonestType(PGPNode.HonestType.Honest);
else if (Arrays.binarySearch(neutralIndexArray, i) >= 0)
node.setHonestType(PGPNode.HonestType.Neutral);
else {
node.setHonestType(PGPNode.HonestType.Dishonest);
}
if (Arrays.binarySearch(littleMistakeIndexArray, i) >= 0)
node.setMistakeType(PGPNode.MistakeSingerType.Little);
else if (Arrays.binarySearch(neutralMistakeIndexArray, i) >= 0)
node.setMistakeType(PGPNode.MistakeSingerType.Neutral);
else
node.setMistakeType(PGPNode.MistakeSingerType.Many);
nodes.add(node);
}
return nodes;
}
private static int[] xpSign(List<PGPNode> nodes, EnvironmentParams params) throws Exception
{
int numSigners = (int) (numNodes * params.ratExperiencedSigner + 0.5);
int[] signerIndexArray = Randoms.nextIntArray(numSigners, numNodes, null);
for (int i = 0; i < signerIndexArray.length; i++)
{
// signer
int signerIndex = signerIndexArray[i];
PGPNode signer = nodes.get(signerIndex);
| // Path: happyresearch/src/main/java/happy/research/pgp/PGPNode.java
// public static enum SignerType
// {
// ExperiencedSigner, MediumSigner, NewbieSigner
// };
// Path: happyresearch/src/main/java/happy/research/pgp/AbstractPGP.java
import happy.coding.math.Randoms;
import happy.research.pgp.PGPNode.SignerType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.MaxIterationsExceededException;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.analysis.integration.SimpsonIntegrator;
import org.apache.log4j.Logger;
if (Arrays.binarySearch(honestIndexArray, i) >= 0)
node.setHonestType(PGPNode.HonestType.Honest);
else if (Arrays.binarySearch(neutralIndexArray, i) >= 0)
node.setHonestType(PGPNode.HonestType.Neutral);
else {
node.setHonestType(PGPNode.HonestType.Dishonest);
}
if (Arrays.binarySearch(littleMistakeIndexArray, i) >= 0)
node.setMistakeType(PGPNode.MistakeSingerType.Little);
else if (Arrays.binarySearch(neutralMistakeIndexArray, i) >= 0)
node.setMistakeType(PGPNode.MistakeSingerType.Neutral);
else
node.setMistakeType(PGPNode.MistakeSingerType.Many);
nodes.add(node);
}
return nodes;
}
private static int[] xpSign(List<PGPNode> nodes, EnvironmentParams params) throws Exception
{
int numSigners = (int) (numNodes * params.ratExperiencedSigner + 0.5);
int[] signerIndexArray = Randoms.nextIntArray(numSigners, numNodes, null);
for (int i = 0; i < signerIndexArray.length; i++)
{
// signer
int signerIndex = signerIndexArray[i];
PGPNode signer = nodes.get(signerIndex);
| signer.setSignerType(SignerType.ExperiencedSigner);
|
466152112/HappyResearch | happyresearch/src/main/java/happy/research/cf/ConfigParams.java | // Path: happyresearch/src/main/java/happy/research/utils/SimUtils.java
// public enum SimMethod {
// COS, PCC, MSD, CPC, SRC, BS, PIP, SM, iufCOS, caPCC
// };
| import happy.coding.io.FileIO;
import happy.coding.io.Logs;
import happy.coding.io.Strings;
import happy.coding.system.Dates;
import happy.coding.system.Systems;
import happy.research.utils.SimUtils.SimMethod;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
| public double COGTRUST_ALPHA = 0.0;
public double COGTRUST_BIAS = 0.0;
public double COGTRUST_EPSILON = 0.0;
public double X_SIGMA = 0;
public String TRAIN_SET = null;
public String TEST_SET = null;
public enum DatasetMode {
all("All"), coldUsers("Cold Users"), heavyUsers("Heavy Users"), opinUsers("Opin. Users"), blackSheep(
"Black Sheep"), nicheItems("Niche Items"), contrItems("Contr. Items"), batch("Batch"), userDegree(
"user-degree"), itemDegree("item-degree");
public String label = null;
DatasetMode(String _label) {
this.label = _label;
}
}
public enum ValidateMethod {
leave_one_out, cross_validation
}
public enum PredictMethod {
weighted_average, resnick_formula, remove_bias
}
| // Path: happyresearch/src/main/java/happy/research/utils/SimUtils.java
// public enum SimMethod {
// COS, PCC, MSD, CPC, SRC, BS, PIP, SM, iufCOS, caPCC
// };
// Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
import happy.coding.io.FileIO;
import happy.coding.io.Logs;
import happy.coding.io.Strings;
import happy.coding.system.Dates;
import happy.coding.system.Systems;
import happy.research.utils.SimUtils.SimMethod;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public double COGTRUST_ALPHA = 0.0;
public double COGTRUST_BIAS = 0.0;
public double COGTRUST_EPSILON = 0.0;
public double X_SIGMA = 0;
public String TRAIN_SET = null;
public String TEST_SET = null;
public enum DatasetMode {
all("All"), coldUsers("Cold Users"), heavyUsers("Heavy Users"), opinUsers("Opin. Users"), blackSheep(
"Black Sheep"), nicheItems("Niche Items"), contrItems("Contr. Items"), batch("Batch"), userDegree(
"user-degree"), itemDegree("item-degree");
public String label = null;
DatasetMode(String _label) {
this.label = _label;
}
}
public enum ValidateMethod {
leave_one_out, cross_validation
}
public enum PredictMethod {
weighted_average, resnick_formula, remove_bias
}
| public SimMethod SIMILARITY_METHOD = SimMethod.PCC;
|
466152112/HappyResearch | happyresearch/src/main/java/happy/research/cf/ClassicCF_mt.java | // Path: happyresearch/src/main/java/happy/research/utils/SimUtils.java
// public enum SimMethod {
// COS, PCC, MSD, CPC, SRC, BS, PIP, SM, iufCOS, caPCC
// };
| import happy.research.utils.SimUtils.SimMethod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
| {
String userB = users.get(j);
Map<String, Rating> bsRatings = userRatingsMap.get(userB);
if (bsRatings == null || bsRatings.size() < 1) continue;
for (Entry<String, Rating> en : asRatings.entrySet())
{
String ai = en.getKey();
Rating ar = en.getValue();
if (bsRatings.containsKey(ai))
{
double asRating = ar.getRating();
double bsRating = bsRatings.get(ai).getRating();
double distance = Math.abs(asRating - bsRating);
int num = distanceNumMap.get(distance);
distanceNumMap.put(distance, num + 1);
}
}
}
}
return distanceNumMap;
}
@Override
protected Performance runMultiThreads() throws Exception
{
| // Path: happyresearch/src/main/java/happy/research/utils/SimUtils.java
// public enum SimMethod {
// COS, PCC, MSD, CPC, SRC, BS, PIP, SM, iufCOS, caPCC
// };
// Path: happyresearch/src/main/java/happy/research/cf/ClassicCF_mt.java
import happy.research.utils.SimUtils.SimMethod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
{
String userB = users.get(j);
Map<String, Rating> bsRatings = userRatingsMap.get(userB);
if (bsRatings == null || bsRatings.size() < 1) continue;
for (Entry<String, Rating> en : asRatings.entrySet())
{
String ai = en.getKey();
Rating ar = en.getValue();
if (bsRatings.containsKey(ai))
{
double asRating = ar.getRating();
double bsRating = bsRatings.get(ai).getRating();
double distance = Math.abs(asRating - bsRating);
int num = distanceNumMap.get(distance);
distanceNumMap.put(distance, num + 1);
}
}
}
}
return distanceNumMap;
}
@Override
protected Performance runMultiThreads() throws Exception
{
| if (params.SIMILARITY_METHOD == SimMethod.BS) distanceNum = probeDistanceNums();
|
466152112/HappyResearch | happyresearch/src/main/java/happy/research/cf/TSF_t.java | // Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum PredictMethod {
// weighted_average, resnick_formula, remove_bias
// }
| import happy.coding.math.Sims;
import happy.coding.system.Debug;
import happy.research.cf.ConfigParams.PredictMethod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
| package happy.research.cf;
public class TSF_t extends Thread_t
{
public TSF_t(int id)
{
super(id);
}
@Override
protected Map<String, Double>[] buildModel(Rating testRating)
{
return null;
}
@Override
protected void runLeaveOneOut()
{
for (Rating testRating : threadRatings)
{
reportProgress(numRating);
String user = testRating.getUserId();
String item = testRating.getItemId();
double meanA = 0.0;
Map<String, Rating> asRatings = userRatingsMap.get(user);
| // Path: happyresearch/src/main/java/happy/research/cf/ConfigParams.java
// public enum PredictMethod {
// weighted_average, resnick_formula, remove_bias
// }
// Path: happyresearch/src/main/java/happy/research/cf/TSF_t.java
import happy.coding.math.Sims;
import happy.coding.system.Debug;
import happy.research.cf.ConfigParams.PredictMethod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
package happy.research.cf;
public class TSF_t extends Thread_t
{
public TSF_t(int id)
{
super(id);
}
@Override
protected Map<String, Double>[] buildModel(Rating testRating)
{
return null;
}
@Override
protected void runLeaveOneOut()
{
for (Rating testRating : threadRatings)
{
reportProgress(numRating);
String user = testRating.getUserId();
String item = testRating.getItemId();
double meanA = 0.0;
Map<String, Rating> asRatings = userRatingsMap.get(user);
| if (params.PREDICT_METHOD == PredictMethod.resnick_formula)
|
digitalpetri/modbus | modbus-codec/src/main/java/com/digitalpetri/modbus/codec/ModbusTcpPayload.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/ModbusPdu.java
// public interface ModbusPdu {
//
// FunctionCode getFunctionCode();
//
// }
| import com.digitalpetri.modbus.ModbusPdu; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.codec;
public class ModbusTcpPayload {
private final short transactionId;
private final short unitId; | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/ModbusPdu.java
// public interface ModbusPdu {
//
// FunctionCode getFunctionCode();
//
// }
// Path: modbus-codec/src/main/java/com/digitalpetri/modbus/codec/ModbusTcpPayload.java
import com.digitalpetri.modbus.ModbusPdu;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.codec;
public class ModbusTcpPayload {
private final short transactionId;
private final short unitId; | private final ModbusPdu modbusPdu; |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteMultipleRegistersRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import java.nio.ByteBuffer;
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function code is used to write a block of contiguous registers (1 to 123 registers) in a remote device.
* <p>
* The requested written values are specified in the request data field. Data is packed as two bytes per register.
*/
public class WriteMultipleRegistersRequest extends ByteBufModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public WriteMultipleRegistersRequest(int address, int quantity, byte[] values) {
this(address, quantity, Unpooled.wrappedBuffer(values));
}
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public WriteMultipleRegistersRequest(int address, int quantity, ByteBuffer values) {
this(address, quantity, Unpooled.wrappedBuffer(values));
}
/**
* Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
*
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public WriteMultipleRegistersRequest(int address, int quantity, ByteBuf values) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteMultipleRegistersRequest.java
import java.nio.ByteBuffer;
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function code is used to write a block of contiguous registers (1 to 123 registers) in a remote device.
* <p>
* The requested written values are specified in the request data field. Data is packed as two bytes per register.
*/
public class WriteMultipleRegistersRequest extends ByteBufModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public WriteMultipleRegistersRequest(int address, int quantity, byte[] values) {
this(address, quantity, Unpooled.wrappedBuffer(values));
}
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public WriteMultipleRegistersRequest(int address, int quantity, ByteBuffer values) {
this(address, quantity, Unpooled.wrappedBuffer(values));
}
/**
* Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
*
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public WriteMultipleRegistersRequest(int address, int quantity, ByteBuf values) { | super(values, FunctionCode.WriteMultipleRegisters); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadWriteMultipleRegistersRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import java.nio.ByteBuffer;
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; | /*
* Copyright 2016 Kevin Herron
* Copyright 2020 SeRo Systems GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function code is used to write a block of contiguous registers (1 to 123 registers) in a remote device.
* <p>
* The requested written values are specified in the request data field. Data is packed as two bytes per register.
*/
public class ReadWriteMultipleRegistersRequest extends ByteBufModbusRequest {
private final int readAddress;
private final int readQuantity;
private final int writeAddress;
private final int writeQuantity;
/**
* @param readAddress 0x0000 to 0xFFFF (0 to 65535)
* @param readQuantity 0x0001 to 0x007B (1 to 123)
* @param writeAddress 0x0000 to 0xFFFF (0 to 65535)
* @param writeQuantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public ReadWriteMultipleRegistersRequest(int readAddress, int readQuantity, int writeAddress, int writeQuantity,
byte[] values) {
this(readAddress, readQuantity, writeAddress, writeQuantity, Unpooled.wrappedBuffer(values));
}
/**
* @param readAddress 0x0000 to 0xFFFF (0 to 65535)
* @param readQuantity 0x0001 to 0x007B (1 to 123)
* @param writeAddress 0x0000 to 0xFFFF (0 to 65535)
* @param writeQuantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public ReadWriteMultipleRegistersRequest(int readAddress, int readQuantity, int writeAddress, int writeQuantity,
ByteBuffer values) {
this(readAddress, readQuantity, writeAddress, writeQuantity, Unpooled.wrappedBuffer(values));
}
/**
* Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
*
* @param readAddress 0x0000 to 0xFFFF (0 to 65535)
* @param readQuantity 0x0001 to 0x007B (1 to 123)
* @param writeAddress 0x0000 to 0xFFFF (0 to 65535)
* @param writeQuantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public ReadWriteMultipleRegistersRequest(int readAddress, int readQuantity, int writeAddress, int writeQuantity,
ByteBuf values) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadWriteMultipleRegistersRequest.java
import java.nio.ByteBuffer;
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
/*
* Copyright 2016 Kevin Herron
* Copyright 2020 SeRo Systems GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function code is used to write a block of contiguous registers (1 to 123 registers) in a remote device.
* <p>
* The requested written values are specified in the request data field. Data is packed as two bytes per register.
*/
public class ReadWriteMultipleRegistersRequest extends ByteBufModbusRequest {
private final int readAddress;
private final int readQuantity;
private final int writeAddress;
private final int writeQuantity;
/**
* @param readAddress 0x0000 to 0xFFFF (0 to 65535)
* @param readQuantity 0x0001 to 0x007B (1 to 123)
* @param writeAddress 0x0000 to 0xFFFF (0 to 65535)
* @param writeQuantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public ReadWriteMultipleRegistersRequest(int readAddress, int readQuantity, int writeAddress, int writeQuantity,
byte[] values) {
this(readAddress, readQuantity, writeAddress, writeQuantity, Unpooled.wrappedBuffer(values));
}
/**
* @param readAddress 0x0000 to 0xFFFF (0 to 65535)
* @param readQuantity 0x0001 to 0x007B (1 to 123)
* @param writeAddress 0x0000 to 0xFFFF (0 to 65535)
* @param writeQuantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public ReadWriteMultipleRegistersRequest(int readAddress, int readQuantity, int writeAddress, int writeQuantity,
ByteBuffer values) {
this(readAddress, readQuantity, writeAddress, writeQuantity, Unpooled.wrappedBuffer(values));
}
/**
* Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
*
* @param readAddress 0x0000 to 0xFFFF (0 to 65535)
* @param readQuantity 0x0001 to 0x007B (1 to 123)
* @param writeAddress 0x0000 to 0xFFFF (0 to 65535)
* @param writeQuantity 0x0001 to 0x007B (1 to 123)
* @param values buffer of at least N bytes, where N = quantity * 2
*/
public ReadWriteMultipleRegistersRequest(int readAddress, int readQuantity, int writeAddress, int writeQuantity,
ByteBuf values) { | super(values, FunctionCode.ReadWriteMultipleRegisters); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/WriteMultipleCoilsResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response returns the function code, starting address, and quantity of coils forced.
*/
public class WriteMultipleCoilsResponse extends SimpleModbusResponse {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07B0 (1 to 2000)
*/
public WriteMultipleCoilsResponse(int address, int quantity) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/WriteMultipleCoilsResponse.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response returns the function code, starting address, and quantity of coils forced.
*/
public class WriteMultipleCoilsResponse extends SimpleModbusResponse {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07B0 (1 to 2000)
*/
public WriteMultipleCoilsResponse(int address, int quantity) { | super(FunctionCode.WriteMultipleCoils); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/ExceptionResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/ExceptionCode.java
// public enum ExceptionCode {
//
// IllegalFunction(0x01),
// IllegalDataAddress(0x02),
// IllegalDataValue(0x03),
// SlaveDeviceFailure(0x04),
// Acknowledge(0x05),
// SlaveDeviceBusy(0x06),
// MemoryParityError(0x08),
// GatewayPathUnavailable(0x0A),
// GatewayTargetDeviceFailedToResponse(0x0B);
//
// private final int code;
//
// ExceptionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<ExceptionCode> fromCode(int code) {
// switch (code) {
// case 0x01: return Optional.of(IllegalFunction);
// case 0x02: return Optional.of(IllegalDataAddress);
// case 0x03: return Optional.of(IllegalDataValue);
// case 0x04: return Optional.of(SlaveDeviceFailure);
// case 0x05: return Optional.of(Acknowledge);
// case 0x06: return Optional.of(SlaveDeviceBusy);
// case 0x08: return Optional.of(MemoryParityError);
// case 0x0A: return Optional.of(GatewayPathUnavailable);
// case 0x0B: return Optional.of(GatewayTargetDeviceFailedToResponse);
// }
//
// return Optional.empty();
// }
//
// }
//
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.ExceptionCode;
import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ExceptionResponse extends SimpleModbusResponse {
private final ExceptionCode exceptionCode;
| // Path: modbus-core/src/main/java/com/digitalpetri/modbus/ExceptionCode.java
// public enum ExceptionCode {
//
// IllegalFunction(0x01),
// IllegalDataAddress(0x02),
// IllegalDataValue(0x03),
// SlaveDeviceFailure(0x04),
// Acknowledge(0x05),
// SlaveDeviceBusy(0x06),
// MemoryParityError(0x08),
// GatewayPathUnavailable(0x0A),
// GatewayTargetDeviceFailedToResponse(0x0B);
//
// private final int code;
//
// ExceptionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<ExceptionCode> fromCode(int code) {
// switch (code) {
// case 0x01: return Optional.of(IllegalFunction);
// case 0x02: return Optional.of(IllegalDataAddress);
// case 0x03: return Optional.of(IllegalDataValue);
// case 0x04: return Optional.of(SlaveDeviceFailure);
// case 0x05: return Optional.of(Acknowledge);
// case 0x06: return Optional.of(SlaveDeviceBusy);
// case 0x08: return Optional.of(MemoryParityError);
// case 0x0A: return Optional.of(GatewayPathUnavailable);
// case 0x0B: return Optional.of(GatewayTargetDeviceFailedToResponse);
// }
//
// return Optional.empty();
// }
//
// }
//
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/ExceptionResponse.java
import com.digitalpetri.modbus.ExceptionCode;
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ExceptionResponse extends SimpleModbusResponse {
private final ExceptionCode exceptionCode;
| public ExceptionResponse(FunctionCode functionCode, ExceptionCode exceptionCode) { |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadInputRegistersResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadInputRegistersResponse extends ByteBufModbusResponse {
public ReadInputRegistersResponse(ByteBuf registers) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadInputRegistersResponse.java
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadInputRegistersResponse extends ByteBufModbusResponse {
public ReadInputRegistersResponse(ByteBuf registers) { | super(registers, FunctionCode.ReadInputRegisters); |
digitalpetri/modbus | modbus-codec/src/test/java/com/digitalpetri/modbus/codec/ModbusRequestDecoderTest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteMultipleRegistersRequest.java
// public class WriteMultipleRegistersRequest extends ByteBufModbusRequest {
//
// private final int address;
// private final int quantity;
//
// /**
// * @param address 0x0000 to 0xFFFF (0 to 65535)
// * @param quantity 0x0001 to 0x007B (1 to 123)
// * @param values buffer of at least N bytes, where N = quantity * 2
// */
// public WriteMultipleRegistersRequest(int address, int quantity, byte[] values) {
// this(address, quantity, Unpooled.wrappedBuffer(values));
// }
//
// /**
// * @param address 0x0000 to 0xFFFF (0 to 65535)
// * @param quantity 0x0001 to 0x007B (1 to 123)
// * @param values buffer of at least N bytes, where N = quantity * 2
// */
// public WriteMultipleRegistersRequest(int address, int quantity, ByteBuffer values) {
// this(address, quantity, Unpooled.wrappedBuffer(values));
// }
//
// /**
// * Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
// *
// * @param address 0x0000 to 0xFFFF (0 to 65535)
// * @param quantity 0x0001 to 0x007B (1 to 123)
// * @param values buffer of at least N bytes, where N = quantity * 2
// */
// public WriteMultipleRegistersRequest(int address, int quantity, ByteBuf values) {
// super(values, FunctionCode.WriteMultipleRegisters);
//
// this.address = address;
// this.quantity = quantity;
// }
//
// public int getAddress() {
// return address;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public ByteBuf getValues() {
// return super.content();
// }
//
// }
| import com.digitalpetri.modbus.requests.WriteMultipleRegistersRequest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; | package com.digitalpetri.modbus.codec;
public class ModbusRequestDecoderTest {
@Test
public void testDecodeWriteMultipleRegistersRequest() {
ModbusRequestEncoder encoder = new ModbusRequestEncoder();
| // Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteMultipleRegistersRequest.java
// public class WriteMultipleRegistersRequest extends ByteBufModbusRequest {
//
// private final int address;
// private final int quantity;
//
// /**
// * @param address 0x0000 to 0xFFFF (0 to 65535)
// * @param quantity 0x0001 to 0x007B (1 to 123)
// * @param values buffer of at least N bytes, where N = quantity * 2
// */
// public WriteMultipleRegistersRequest(int address, int quantity, byte[] values) {
// this(address, quantity, Unpooled.wrappedBuffer(values));
// }
//
// /**
// * @param address 0x0000 to 0xFFFF (0 to 65535)
// * @param quantity 0x0001 to 0x007B (1 to 123)
// * @param values buffer of at least N bytes, where N = quantity * 2
// */
// public WriteMultipleRegistersRequest(int address, int quantity, ByteBuffer values) {
// this(address, quantity, Unpooled.wrappedBuffer(values));
// }
//
// /**
// * Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
// *
// * @param address 0x0000 to 0xFFFF (0 to 65535)
// * @param quantity 0x0001 to 0x007B (1 to 123)
// * @param values buffer of at least N bytes, where N = quantity * 2
// */
// public WriteMultipleRegistersRequest(int address, int quantity, ByteBuf values) {
// super(values, FunctionCode.WriteMultipleRegisters);
//
// this.address = address;
// this.quantity = quantity;
// }
//
// public int getAddress() {
// return address;
// }
//
// public int getQuantity() {
// return quantity;
// }
//
// public ByteBuf getValues() {
// return super.content();
// }
//
// }
// Path: modbus-codec/src/test/java/com/digitalpetri/modbus/codec/ModbusRequestDecoderTest.java
import com.digitalpetri.modbus.requests.WriteMultipleRegistersRequest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
package com.digitalpetri.modbus.codec;
public class ModbusRequestDecoderTest {
@Test
public void testDecodeWriteMultipleRegistersRequest() {
ModbusRequestEncoder encoder = new ModbusRequestEncoder();
| WriteMultipleRegistersRequest request = new WriteMultipleRegistersRequest( |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadInputRegistersRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to read from 1 to 125 contiguous input registers in a remote device. The Request PDU
* specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at
* zero. Therefore input registers numbered 1-16 are addressed as 0-15.
*/
public class ReadInputRegistersRequest extends SimpleModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007D (1 to 125)
*/
public ReadInputRegistersRequest(int address, int quantity) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadInputRegistersRequest.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to read from 1 to 125 contiguous input registers in a remote device. The Request PDU
* specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at
* zero. Therefore input registers numbered 1-16 are addressed as 0-15.
*/
public class ReadInputRegistersRequest extends SimpleModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007D (1 to 125)
*/
public ReadInputRegistersRequest(int address, int quantity) { | super(FunctionCode.ReadInputRegisters); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/WriteSingleRegisterResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response is an echo of the request, returned after the register contents have been written.
*/
public class WriteSingleRegisterResponse extends SimpleModbusResponse {
private final int address;
private final int value;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param value 0x0000 to 0xFFFF (0 to 65535)
*/
public WriteSingleRegisterResponse(int address, int value) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/WriteSingleRegisterResponse.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response is an echo of the request, returned after the register contents have been written.
*/
public class WriteSingleRegisterResponse extends SimpleModbusResponse {
private final int address;
private final int value;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param value 0x0000 to 0xFFFF (0 to 65535)
*/
public WriteSingleRegisterResponse(int address, int value) { | super(FunctionCode.WriteSingleRegister); |
digitalpetri/modbus | modbus-codec/src/main/java/com/digitalpetri/modbus/codec/ModbusTcpCodec.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/ModbusPdu.java
// public interface ModbusPdu {
//
// FunctionCode getFunctionCode();
//
// }
//
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/UnsupportedPdu.java
// public class UnsupportedPdu implements ModbusPdu {
//
// private final FunctionCode functionCode;
//
// public UnsupportedPdu(FunctionCode functionCode) {
// this.functionCode = functionCode;
// }
//
// @Override
// public FunctionCode getFunctionCode() {
// return functionCode;
// }
//
// }
| import java.util.List;
import com.digitalpetri.modbus.ModbusPdu;
import com.digitalpetri.modbus.UnsupportedPdu;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | @Override
protected void encode(ChannelHandlerContext ctx, ModbusTcpPayload payload, ByteBuf buffer) {
int headerStartIndex = buffer.writerIndex();
buffer.writeZero(MbapHeader.LENGTH);
int pduStartIndex = buffer.writerIndex();
encoder.encode(payload.getModbusPdu(), buffer);
int pduLength = buffer.writerIndex() - pduStartIndex;
MbapHeader header = new MbapHeader(
payload.getTransactionId(),
pduLength + 1,
payload.getUnitId()
);
int currentWriterIndex = buffer.writerIndex();
buffer.writerIndex(headerStartIndex);
MbapHeader.encode(header, buffer);
buffer.writerIndex(currentWriterIndex);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
int startIndex = buffer.readerIndex();
while (buffer.readableBytes() >= HeaderLength &&
buffer.readableBytes() >= getLength(buffer, startIndex) + HeaderSize) {
try {
MbapHeader mbapHeader = MbapHeader.decode(buffer); | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/ModbusPdu.java
// public interface ModbusPdu {
//
// FunctionCode getFunctionCode();
//
// }
//
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/UnsupportedPdu.java
// public class UnsupportedPdu implements ModbusPdu {
//
// private final FunctionCode functionCode;
//
// public UnsupportedPdu(FunctionCode functionCode) {
// this.functionCode = functionCode;
// }
//
// @Override
// public FunctionCode getFunctionCode() {
// return functionCode;
// }
//
// }
// Path: modbus-codec/src/main/java/com/digitalpetri/modbus/codec/ModbusTcpCodec.java
import java.util.List;
import com.digitalpetri.modbus.ModbusPdu;
import com.digitalpetri.modbus.UnsupportedPdu;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Override
protected void encode(ChannelHandlerContext ctx, ModbusTcpPayload payload, ByteBuf buffer) {
int headerStartIndex = buffer.writerIndex();
buffer.writeZero(MbapHeader.LENGTH);
int pduStartIndex = buffer.writerIndex();
encoder.encode(payload.getModbusPdu(), buffer);
int pduLength = buffer.writerIndex() - pduStartIndex;
MbapHeader header = new MbapHeader(
payload.getTransactionId(),
pduLength + 1,
payload.getUnitId()
);
int currentWriterIndex = buffer.writerIndex();
buffer.writerIndex(headerStartIndex);
MbapHeader.encode(header, buffer);
buffer.writerIndex(currentWriterIndex);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
int startIndex = buffer.readerIndex();
while (buffer.readableBytes() >= HeaderLength &&
buffer.readableBytes() >= getLength(buffer, startIndex) + HeaderSize) {
try {
MbapHeader mbapHeader = MbapHeader.decode(buffer); | ModbusPdu modbusPdu = decoder.decode(buffer); |
digitalpetri/modbus | modbus-codec/src/main/java/com/digitalpetri/modbus/codec/ModbusTcpCodec.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/ModbusPdu.java
// public interface ModbusPdu {
//
// FunctionCode getFunctionCode();
//
// }
//
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/UnsupportedPdu.java
// public class UnsupportedPdu implements ModbusPdu {
//
// private final FunctionCode functionCode;
//
// public UnsupportedPdu(FunctionCode functionCode) {
// this.functionCode = functionCode;
// }
//
// @Override
// public FunctionCode getFunctionCode() {
// return functionCode;
// }
//
// }
| import java.util.List;
import com.digitalpetri.modbus.ModbusPdu;
import com.digitalpetri.modbus.UnsupportedPdu;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | int headerStartIndex = buffer.writerIndex();
buffer.writeZero(MbapHeader.LENGTH);
int pduStartIndex = buffer.writerIndex();
encoder.encode(payload.getModbusPdu(), buffer);
int pduLength = buffer.writerIndex() - pduStartIndex;
MbapHeader header = new MbapHeader(
payload.getTransactionId(),
pduLength + 1,
payload.getUnitId()
);
int currentWriterIndex = buffer.writerIndex();
buffer.writerIndex(headerStartIndex);
MbapHeader.encode(header, buffer);
buffer.writerIndex(currentWriterIndex);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
int startIndex = buffer.readerIndex();
while (buffer.readableBytes() >= HeaderLength &&
buffer.readableBytes() >= getLength(buffer, startIndex) + HeaderSize) {
try {
MbapHeader mbapHeader = MbapHeader.decode(buffer);
ModbusPdu modbusPdu = decoder.decode(buffer);
| // Path: modbus-core/src/main/java/com/digitalpetri/modbus/ModbusPdu.java
// public interface ModbusPdu {
//
// FunctionCode getFunctionCode();
//
// }
//
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/UnsupportedPdu.java
// public class UnsupportedPdu implements ModbusPdu {
//
// private final FunctionCode functionCode;
//
// public UnsupportedPdu(FunctionCode functionCode) {
// this.functionCode = functionCode;
// }
//
// @Override
// public FunctionCode getFunctionCode() {
// return functionCode;
// }
//
// }
// Path: modbus-codec/src/main/java/com/digitalpetri/modbus/codec/ModbusTcpCodec.java
import java.util.List;
import com.digitalpetri.modbus.ModbusPdu;
import com.digitalpetri.modbus.UnsupportedPdu;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
int headerStartIndex = buffer.writerIndex();
buffer.writeZero(MbapHeader.LENGTH);
int pduStartIndex = buffer.writerIndex();
encoder.encode(payload.getModbusPdu(), buffer);
int pduLength = buffer.writerIndex() - pduStartIndex;
MbapHeader header = new MbapHeader(
payload.getTransactionId(),
pduLength + 1,
payload.getUnitId()
);
int currentWriterIndex = buffer.writerIndex();
buffer.writerIndex(headerStartIndex);
MbapHeader.encode(header, buffer);
buffer.writerIndex(currentWriterIndex);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
int startIndex = buffer.readerIndex();
while (buffer.readableBytes() >= HeaderLength &&
buffer.readableBytes() >= getLength(buffer, startIndex) + HeaderSize) {
try {
MbapHeader mbapHeader = MbapHeader.decode(buffer);
ModbusPdu modbusPdu = decoder.decode(buffer);
| if (modbusPdu instanceof UnsupportedPdu) { |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadDiscreteInputsResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadDiscreteInputsResponse extends ByteBufModbusResponse {
public ReadDiscreteInputsResponse(ByteBuf data) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadDiscreteInputsResponse.java
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadDiscreteInputsResponse extends ByteBufModbusResponse {
public ReadDiscreteInputsResponse(ByteBuf data) { | super(data, FunctionCode.ReadDiscreteInputs); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/WriteSingleCoilResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response is an echo of the request, returned after the coil state has been written.
*/
public class WriteSingleCoilResponse extends SimpleModbusResponse {
private final int address;
private final int value;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param value true or false (0xFF00 or 0x0000)
*/
public WriteSingleCoilResponse(int address, int value) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/WriteSingleCoilResponse.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response is an echo of the request, returned after the coil state has been written.
*/
public class WriteSingleCoilResponse extends SimpleModbusResponse {
private final int address;
private final int value;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param value true or false (0xFF00 or 0x0000)
*/
public WriteSingleCoilResponse(int address, int value) { | super(FunctionCode.WriteSingleCoil); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadCoilsRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to read from 1 to 2000 contiguous status of coils in a remote device. The Request PDU
* specifies the starting address, i.e. the address of the first coil specified, and the number of coils. In the PDU
* Coils are addressed starting at zero. Therefore coils numbered 1-16 are addressed as 0-15.
*/
public class ReadCoilsRequest extends SimpleModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07D0 (1 to 2000)
*/
public ReadCoilsRequest(int address, int quantity) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadCoilsRequest.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to read from 1 to 2000 contiguous status of coils in a remote device. The Request PDU
* specifies the starting address, i.e. the address of the first coil specified, and the number of coils. In the PDU
* Coils are addressed starting at zero. Therefore coils numbered 1-16 are addressed as 0-15.
*/
public class ReadCoilsRequest extends SimpleModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07D0 (1 to 2000)
*/
public ReadCoilsRequest(int address, int quantity) { | super(FunctionCode.ReadCoils); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/WriteMultipleRegistersResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response returns the function code, starting address, and quantity of registers written.
*/
public class WriteMultipleRegistersResponse extends SimpleModbusResponse {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007B (1 to 123)
*/
public WriteMultipleRegistersResponse(int address, int quantity) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/WriteMultipleRegistersResponse.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response returns the function code, starting address, and quantity of registers written.
*/
public class WriteMultipleRegistersResponse extends SimpleModbusResponse {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007B (1 to 123)
*/
public WriteMultipleRegistersResponse(int address, int quantity) { | super(FunctionCode.WriteMultipleRegisters); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadDiscreteInputsRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device. The
* Request PDU specifies the starting address, i.e. the address of the first input specified, and the number of inputs.
* In the PDU Discrete Inputs are addressed starting at zero. Therefore Discrete inputs numbered 1-16 are addressed as
* 0-15.
*/
public class ReadDiscreteInputsRequest extends SimpleModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07D0 (1 to 2000)
*/
public ReadDiscreteInputsRequest(int address, int quantity) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadDiscreteInputsRequest.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device. The
* Request PDU specifies the starting address, i.e. the address of the first input specified, and the number of inputs.
* In the PDU Discrete Inputs are addressed starting at zero. Therefore Discrete inputs numbered 1-16 are addressed as
* 0-15.
*/
public class ReadDiscreteInputsRequest extends SimpleModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07D0 (1 to 2000)
*/
public ReadDiscreteInputsRequest(int address, int quantity) { | super(FunctionCode.ReadDiscreteInputs); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadCoilsResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadCoilsResponse extends ByteBufModbusResponse {
public ReadCoilsResponse(ByteBuf coilStatus) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadCoilsResponse.java
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadCoilsResponse extends ByteBufModbusResponse {
public ReadCoilsResponse(ByteBuf coilStatus) { | super(coilStatus, FunctionCode.ReadCoils); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadHoldingRegistersRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to read the contents of a contiguous block of holding registers in a remote device. The
* Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed
* starting at zero. Therefore registers numbered 1-16 are addressed as 0-15.
*/
public class ReadHoldingRegistersRequest extends SimpleModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007D (1 to 125)
*/
public ReadHoldingRegistersRequest(int address, int quantity) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/ReadHoldingRegistersRequest.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to read the contents of a contiguous block of holding registers in a remote device. The
* Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed
* starting at zero. Therefore registers numbered 1-16 are addressed as 0-15.
*/
public class ReadHoldingRegistersRequest extends SimpleModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x007D (1 to 125)
*/
public ReadHoldingRegistersRequest(int address, int quantity) { | super(FunctionCode.ReadHoldingRegisters); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadHoldingRegistersResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadHoldingRegistersResponse extends ByteBufModbusResponse {
public ReadHoldingRegistersResponse(ByteBuf registers) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadHoldingRegistersResponse.java
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadHoldingRegistersResponse extends ByteBufModbusResponse {
public ReadHoldingRegistersResponse(ByteBuf registers) { | super(registers, FunctionCode.ReadHoldingRegisters); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadWriteMultipleRegistersResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf; | /*
* Copyright 2016 Kevin Herron
* Copyright 2020 SeRo Systems GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadWriteMultipleRegistersResponse extends ByteBufModbusResponse {
public ReadWriteMultipleRegistersResponse(ByteBuf registers) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/ReadWriteMultipleRegistersResponse.java
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
/*
* Copyright 2016 Kevin Herron
* Copyright 2020 SeRo Systems GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
public class ReadWriteMultipleRegistersResponse extends ByteBufModbusResponse {
public ReadWriteMultipleRegistersResponse(ByteBuf registers) { | super(registers, FunctionCode.ReadWriteMultipleRegisters); |
digitalpetri/modbus | modbus-examples/src/main/java/com/digitalpetri/modbus/examples/MasterSlaveThroughput.java | // Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/master/MasterExample.java
// public class MasterExample {
//
// public static void main(String[] args) {
// new MasterExample(100, 100).start();
// }
//
// private final Logger logger = LoggerFactory.getLogger(getClass());
//
// private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
//
// private final List<ModbusTcpMaster> masters = new CopyOnWriteArrayList<>();
// private volatile boolean started = false;
//
// private final int nMasters;
// private final int nRequests;
//
// public MasterExample(int nMasters, int nRequests) {
// this.nMasters = nMasters;
// this.nRequests = nRequests;
// }
//
// public void start() {
// started = true;
//
// ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("localhost")
// .setPort(50200)
// .build();
//
// new Thread(() -> {
// while (started) {
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// double mean = 0.0;
// double oneMinute = 0.0;
//
// for (ModbusTcpMaster master : masters) {
// mean += master.getResponseTimer().getMeanRate();
// oneMinute += master.getResponseTimer().getOneMinuteRate();
// }
//
// logger.info("Mean rate={}, 1m rate={}", mean, oneMinute);
// }
// }).start();
//
// for (int i = 0; i < nMasters; i++) {
// ModbusTcpMaster master = new ModbusTcpMaster(config);
// master.connect();
//
// masters.add(master);
//
// for (int j = 0; j < nRequests; j++) {
// sendAndReceive(master);
// }
// }
// }
//
// private void sendAndReceive(ModbusTcpMaster master) {
// if (!started) return;
//
// CompletableFuture<ReadHoldingRegistersResponse> future =
// master.sendRequest(new ReadHoldingRegistersRequest(0, 10), 0);
//
// future.whenCompleteAsync((response, ex) -> {
// if (response != null) {
// ReferenceCountUtil.release(response);
// } else {
// logger.error("Completed exceptionally, message={}", ex.getMessage(), ex);
// }
// scheduler.schedule(() -> sendAndReceive(master), 1, TimeUnit.SECONDS);
// }, Modbus.sharedExecutor());
// }
//
// public void stop() {
// started = false;
// masters.forEach(ModbusTcpMaster::disconnect);
// masters.clear();
// }
//
// }
//
// Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/slave/SlaveExample.java
// public class SlaveExample {
//
// public static void main(String[] args) throws ExecutionException, InterruptedException {
// final SlaveExample slaveExample = new SlaveExample();
//
// slaveExample.start();
//
// Runtime.getRuntime().addShutdownHook(new Thread("modbus-slave-shutdown-hook") {
// @Override
// public void run() {
// slaveExample.stop();
// }
// });
//
// Thread.sleep(Integer.MAX_VALUE);
// }
//
// private final Logger logger = LoggerFactory.getLogger(getClass());
//
// private final ModbusTcpSlaveConfig config = new ModbusTcpSlaveConfig.Builder().build();
// private final ModbusTcpSlave slave = new ModbusTcpSlave(config);
//
// public SlaveExample() {}
//
// public void start() throws ExecutionException, InterruptedException {
// slave.setRequestHandler(new ServiceRequestHandler() {
// @Override
// public void onReadHoldingRegisters(ServiceRequest<ReadHoldingRegistersRequest, ReadHoldingRegistersResponse> service) {
// String clientRemoteAddress = service.getChannel().remoteAddress().toString();
// String clientIp = clientRemoteAddress.replaceAll(".*/(.*):.*", "$1");
// String clientPort = clientRemoteAddress.replaceAll(".*:(.*)", "$1");
//
// ReadHoldingRegistersRequest request = service.getRequest();
//
// ByteBuf registers = PooledByteBufAllocator.DEFAULT.buffer(request.getQuantity());
//
// for (int i = 0; i < request.getQuantity(); i++) {
// registers.writeShort(i);
// }
//
// service.sendResponse(new ReadHoldingRegistersResponse(registers));
//
// ReferenceCountUtil.release(request);
// }
// });
//
// slave.bind("localhost", 50200).get();
// }
//
// public void stop() {
// slave.shutdown();
// }
//
// }
| import java.util.concurrent.ExecutionException;
import com.digitalpetri.modbus.examples.master.MasterExample;
import com.digitalpetri.modbus.examples.slave.SlaveExample; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.examples;
public class MasterSlaveThroughput {
public static final int N_MASTERS = 100;
public static final int N_REQUESTS = 100;
public static void main(String[] args) throws ExecutionException, InterruptedException { | // Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/master/MasterExample.java
// public class MasterExample {
//
// public static void main(String[] args) {
// new MasterExample(100, 100).start();
// }
//
// private final Logger logger = LoggerFactory.getLogger(getClass());
//
// private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
//
// private final List<ModbusTcpMaster> masters = new CopyOnWriteArrayList<>();
// private volatile boolean started = false;
//
// private final int nMasters;
// private final int nRequests;
//
// public MasterExample(int nMasters, int nRequests) {
// this.nMasters = nMasters;
// this.nRequests = nRequests;
// }
//
// public void start() {
// started = true;
//
// ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("localhost")
// .setPort(50200)
// .build();
//
// new Thread(() -> {
// while (started) {
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// double mean = 0.0;
// double oneMinute = 0.0;
//
// for (ModbusTcpMaster master : masters) {
// mean += master.getResponseTimer().getMeanRate();
// oneMinute += master.getResponseTimer().getOneMinuteRate();
// }
//
// logger.info("Mean rate={}, 1m rate={}", mean, oneMinute);
// }
// }).start();
//
// for (int i = 0; i < nMasters; i++) {
// ModbusTcpMaster master = new ModbusTcpMaster(config);
// master.connect();
//
// masters.add(master);
//
// for (int j = 0; j < nRequests; j++) {
// sendAndReceive(master);
// }
// }
// }
//
// private void sendAndReceive(ModbusTcpMaster master) {
// if (!started) return;
//
// CompletableFuture<ReadHoldingRegistersResponse> future =
// master.sendRequest(new ReadHoldingRegistersRequest(0, 10), 0);
//
// future.whenCompleteAsync((response, ex) -> {
// if (response != null) {
// ReferenceCountUtil.release(response);
// } else {
// logger.error("Completed exceptionally, message={}", ex.getMessage(), ex);
// }
// scheduler.schedule(() -> sendAndReceive(master), 1, TimeUnit.SECONDS);
// }, Modbus.sharedExecutor());
// }
//
// public void stop() {
// started = false;
// masters.forEach(ModbusTcpMaster::disconnect);
// masters.clear();
// }
//
// }
//
// Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/slave/SlaveExample.java
// public class SlaveExample {
//
// public static void main(String[] args) throws ExecutionException, InterruptedException {
// final SlaveExample slaveExample = new SlaveExample();
//
// slaveExample.start();
//
// Runtime.getRuntime().addShutdownHook(new Thread("modbus-slave-shutdown-hook") {
// @Override
// public void run() {
// slaveExample.stop();
// }
// });
//
// Thread.sleep(Integer.MAX_VALUE);
// }
//
// private final Logger logger = LoggerFactory.getLogger(getClass());
//
// private final ModbusTcpSlaveConfig config = new ModbusTcpSlaveConfig.Builder().build();
// private final ModbusTcpSlave slave = new ModbusTcpSlave(config);
//
// public SlaveExample() {}
//
// public void start() throws ExecutionException, InterruptedException {
// slave.setRequestHandler(new ServiceRequestHandler() {
// @Override
// public void onReadHoldingRegisters(ServiceRequest<ReadHoldingRegistersRequest, ReadHoldingRegistersResponse> service) {
// String clientRemoteAddress = service.getChannel().remoteAddress().toString();
// String clientIp = clientRemoteAddress.replaceAll(".*/(.*):.*", "$1");
// String clientPort = clientRemoteAddress.replaceAll(".*:(.*)", "$1");
//
// ReadHoldingRegistersRequest request = service.getRequest();
//
// ByteBuf registers = PooledByteBufAllocator.DEFAULT.buffer(request.getQuantity());
//
// for (int i = 0; i < request.getQuantity(); i++) {
// registers.writeShort(i);
// }
//
// service.sendResponse(new ReadHoldingRegistersResponse(registers));
//
// ReferenceCountUtil.release(request);
// }
// });
//
// slave.bind("localhost", 50200).get();
// }
//
// public void stop() {
// slave.shutdown();
// }
//
// }
// Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/MasterSlaveThroughput.java
import java.util.concurrent.ExecutionException;
import com.digitalpetri.modbus.examples.master.MasterExample;
import com.digitalpetri.modbus.examples.slave.SlaveExample;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.examples;
public class MasterSlaveThroughput {
public static final int N_MASTERS = 100;
public static final int N_REQUESTS = 100;
public static void main(String[] args) throws ExecutionException, InterruptedException { | new SlaveExample().start(); |
digitalpetri/modbus | modbus-examples/src/main/java/com/digitalpetri/modbus/examples/MasterSlaveThroughput.java | // Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/master/MasterExample.java
// public class MasterExample {
//
// public static void main(String[] args) {
// new MasterExample(100, 100).start();
// }
//
// private final Logger logger = LoggerFactory.getLogger(getClass());
//
// private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
//
// private final List<ModbusTcpMaster> masters = new CopyOnWriteArrayList<>();
// private volatile boolean started = false;
//
// private final int nMasters;
// private final int nRequests;
//
// public MasterExample(int nMasters, int nRequests) {
// this.nMasters = nMasters;
// this.nRequests = nRequests;
// }
//
// public void start() {
// started = true;
//
// ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("localhost")
// .setPort(50200)
// .build();
//
// new Thread(() -> {
// while (started) {
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// double mean = 0.0;
// double oneMinute = 0.0;
//
// for (ModbusTcpMaster master : masters) {
// mean += master.getResponseTimer().getMeanRate();
// oneMinute += master.getResponseTimer().getOneMinuteRate();
// }
//
// logger.info("Mean rate={}, 1m rate={}", mean, oneMinute);
// }
// }).start();
//
// for (int i = 0; i < nMasters; i++) {
// ModbusTcpMaster master = new ModbusTcpMaster(config);
// master.connect();
//
// masters.add(master);
//
// for (int j = 0; j < nRequests; j++) {
// sendAndReceive(master);
// }
// }
// }
//
// private void sendAndReceive(ModbusTcpMaster master) {
// if (!started) return;
//
// CompletableFuture<ReadHoldingRegistersResponse> future =
// master.sendRequest(new ReadHoldingRegistersRequest(0, 10), 0);
//
// future.whenCompleteAsync((response, ex) -> {
// if (response != null) {
// ReferenceCountUtil.release(response);
// } else {
// logger.error("Completed exceptionally, message={}", ex.getMessage(), ex);
// }
// scheduler.schedule(() -> sendAndReceive(master), 1, TimeUnit.SECONDS);
// }, Modbus.sharedExecutor());
// }
//
// public void stop() {
// started = false;
// masters.forEach(ModbusTcpMaster::disconnect);
// masters.clear();
// }
//
// }
//
// Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/slave/SlaveExample.java
// public class SlaveExample {
//
// public static void main(String[] args) throws ExecutionException, InterruptedException {
// final SlaveExample slaveExample = new SlaveExample();
//
// slaveExample.start();
//
// Runtime.getRuntime().addShutdownHook(new Thread("modbus-slave-shutdown-hook") {
// @Override
// public void run() {
// slaveExample.stop();
// }
// });
//
// Thread.sleep(Integer.MAX_VALUE);
// }
//
// private final Logger logger = LoggerFactory.getLogger(getClass());
//
// private final ModbusTcpSlaveConfig config = new ModbusTcpSlaveConfig.Builder().build();
// private final ModbusTcpSlave slave = new ModbusTcpSlave(config);
//
// public SlaveExample() {}
//
// public void start() throws ExecutionException, InterruptedException {
// slave.setRequestHandler(new ServiceRequestHandler() {
// @Override
// public void onReadHoldingRegisters(ServiceRequest<ReadHoldingRegistersRequest, ReadHoldingRegistersResponse> service) {
// String clientRemoteAddress = service.getChannel().remoteAddress().toString();
// String clientIp = clientRemoteAddress.replaceAll(".*/(.*):.*", "$1");
// String clientPort = clientRemoteAddress.replaceAll(".*:(.*)", "$1");
//
// ReadHoldingRegistersRequest request = service.getRequest();
//
// ByteBuf registers = PooledByteBufAllocator.DEFAULT.buffer(request.getQuantity());
//
// for (int i = 0; i < request.getQuantity(); i++) {
// registers.writeShort(i);
// }
//
// service.sendResponse(new ReadHoldingRegistersResponse(registers));
//
// ReferenceCountUtil.release(request);
// }
// });
//
// slave.bind("localhost", 50200).get();
// }
//
// public void stop() {
// slave.shutdown();
// }
//
// }
| import java.util.concurrent.ExecutionException;
import com.digitalpetri.modbus.examples.master.MasterExample;
import com.digitalpetri.modbus.examples.slave.SlaveExample; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.examples;
public class MasterSlaveThroughput {
public static final int N_MASTERS = 100;
public static final int N_REQUESTS = 100;
public static void main(String[] args) throws ExecutionException, InterruptedException {
new SlaveExample().start(); | // Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/master/MasterExample.java
// public class MasterExample {
//
// public static void main(String[] args) {
// new MasterExample(100, 100).start();
// }
//
// private final Logger logger = LoggerFactory.getLogger(getClass());
//
// private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
//
// private final List<ModbusTcpMaster> masters = new CopyOnWriteArrayList<>();
// private volatile boolean started = false;
//
// private final int nMasters;
// private final int nRequests;
//
// public MasterExample(int nMasters, int nRequests) {
// this.nMasters = nMasters;
// this.nRequests = nRequests;
// }
//
// public void start() {
// started = true;
//
// ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("localhost")
// .setPort(50200)
// .build();
//
// new Thread(() -> {
// while (started) {
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// double mean = 0.0;
// double oneMinute = 0.0;
//
// for (ModbusTcpMaster master : masters) {
// mean += master.getResponseTimer().getMeanRate();
// oneMinute += master.getResponseTimer().getOneMinuteRate();
// }
//
// logger.info("Mean rate={}, 1m rate={}", mean, oneMinute);
// }
// }).start();
//
// for (int i = 0; i < nMasters; i++) {
// ModbusTcpMaster master = new ModbusTcpMaster(config);
// master.connect();
//
// masters.add(master);
//
// for (int j = 0; j < nRequests; j++) {
// sendAndReceive(master);
// }
// }
// }
//
// private void sendAndReceive(ModbusTcpMaster master) {
// if (!started) return;
//
// CompletableFuture<ReadHoldingRegistersResponse> future =
// master.sendRequest(new ReadHoldingRegistersRequest(0, 10), 0);
//
// future.whenCompleteAsync((response, ex) -> {
// if (response != null) {
// ReferenceCountUtil.release(response);
// } else {
// logger.error("Completed exceptionally, message={}", ex.getMessage(), ex);
// }
// scheduler.schedule(() -> sendAndReceive(master), 1, TimeUnit.SECONDS);
// }, Modbus.sharedExecutor());
// }
//
// public void stop() {
// started = false;
// masters.forEach(ModbusTcpMaster::disconnect);
// masters.clear();
// }
//
// }
//
// Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/slave/SlaveExample.java
// public class SlaveExample {
//
// public static void main(String[] args) throws ExecutionException, InterruptedException {
// final SlaveExample slaveExample = new SlaveExample();
//
// slaveExample.start();
//
// Runtime.getRuntime().addShutdownHook(new Thread("modbus-slave-shutdown-hook") {
// @Override
// public void run() {
// slaveExample.stop();
// }
// });
//
// Thread.sleep(Integer.MAX_VALUE);
// }
//
// private final Logger logger = LoggerFactory.getLogger(getClass());
//
// private final ModbusTcpSlaveConfig config = new ModbusTcpSlaveConfig.Builder().build();
// private final ModbusTcpSlave slave = new ModbusTcpSlave(config);
//
// public SlaveExample() {}
//
// public void start() throws ExecutionException, InterruptedException {
// slave.setRequestHandler(new ServiceRequestHandler() {
// @Override
// public void onReadHoldingRegisters(ServiceRequest<ReadHoldingRegistersRequest, ReadHoldingRegistersResponse> service) {
// String clientRemoteAddress = service.getChannel().remoteAddress().toString();
// String clientIp = clientRemoteAddress.replaceAll(".*/(.*):.*", "$1");
// String clientPort = clientRemoteAddress.replaceAll(".*:(.*)", "$1");
//
// ReadHoldingRegistersRequest request = service.getRequest();
//
// ByteBuf registers = PooledByteBufAllocator.DEFAULT.buffer(request.getQuantity());
//
// for (int i = 0; i < request.getQuantity(); i++) {
// registers.writeShort(i);
// }
//
// service.sendResponse(new ReadHoldingRegistersResponse(registers));
//
// ReferenceCountUtil.release(request);
// }
// });
//
// slave.bind("localhost", 50200).get();
// }
//
// public void stop() {
// slave.shutdown();
// }
//
// }
// Path: modbus-examples/src/main/java/com/digitalpetri/modbus/examples/MasterSlaveThroughput.java
import java.util.concurrent.ExecutionException;
import com.digitalpetri.modbus.examples.master.MasterExample;
import com.digitalpetri.modbus.examples.slave.SlaveExample;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.examples;
public class MasterSlaveThroughput {
public static final int N_MASTERS = 100;
public static final int N_REQUESTS = 100;
public static void main(String[] args) throws ExecutionException, InterruptedException {
new SlaveExample().start(); | new MasterExample(N_MASTERS, N_REQUESTS).start(); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteSingleCoilRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to write a single output to either ON or OFF in a remote device.
* <p>
* The requested ON/OFF state is specified by a constant in the request data field. A value of 0xFF00 requests the
* output to be ON. A value of 0x0000 requests it to be OFF. All other values are illegal and will not affect the output.
* <p>
* The Request PDU specifies the address of the coil to be forced. Coils are addressed starting at zero. Therefore coil
* numbered 1 is addressed as 0. The requested ON/OFF state is specified by a constant in the Coil Value field. A value
* of 0XFF00 requests the coil to be ON. A value of 0X0000 requests the coil to be off. All other values are illegal and
* will not affect the coil.
*/
public class WriteSingleCoilRequest extends SimpleModbusRequest {
private final int address;
private final int value;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param value true or false (0xFF00 or 0x0000)
*/
public WriteSingleCoilRequest(int address, boolean value) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteSingleCoilRequest.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to write a single output to either ON or OFF in a remote device.
* <p>
* The requested ON/OFF state is specified by a constant in the request data field. A value of 0xFF00 requests the
* output to be ON. A value of 0x0000 requests it to be OFF. All other values are illegal and will not affect the output.
* <p>
* The Request PDU specifies the address of the coil to be forced. Coils are addressed starting at zero. Therefore coil
* numbered 1 is addressed as 0. The requested ON/OFF state is specified by a constant in the Coil Value field. A value
* of 0XFF00 requests the coil to be ON. A value of 0X0000 requests the coil to be off. All other values are illegal and
* will not affect the coil.
*/
public class WriteSingleCoilRequest extends SimpleModbusRequest {
private final int address;
private final int value;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param value true or false (0xFF00 or 0x0000)
*/
public WriteSingleCoilRequest(int address, boolean value) { | super(FunctionCode.WriteSingleCoil); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/MaskWriteRegisterRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to modify the contents of a specified holding register using a combination of an AND mask, an
* OR mask, and the register's current contents. The function can be used to set or clear individual bits in the
* register.
* <p>
* The request specifies the holding register to be written, the data to be used as the AND mask, and the data to be
* used as the OR mask. Registers are addressed starting at zero. Therefore registers 1-16 are addressed as 0-15.
* <p>
* The function’s algorithm is:
* Result = (Current Contents AND And_Mask) OR (Or_Mask AND (NOT And_Mask))
*/
public class MaskWriteRegisterRequest extends SimpleModbusRequest {
private final int address;
private final int andMask;
private final int orMask;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param andMask 0x0000 to 0xFFFF (0 to 65535)
* @param orMask 0x0000 to 0xFFFF (0 to 65535)
*/
public MaskWriteRegisterRequest(int address, int andMask, int orMask) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/MaskWriteRegisterRequest.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to modify the contents of a specified holding register using a combination of an AND mask, an
* OR mask, and the register's current contents. The function can be used to set or clear individual bits in the
* register.
* <p>
* The request specifies the holding register to be written, the data to be used as the AND mask, and the data to be
* used as the OR mask. Registers are addressed starting at zero. Therefore registers 1-16 are addressed as 0-15.
* <p>
* The function’s algorithm is:
* Result = (Current Contents AND And_Mask) OR (Or_Mask AND (NOT And_Mask))
*/
public class MaskWriteRegisterRequest extends SimpleModbusRequest {
private final int address;
private final int andMask;
private final int orMask;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param andMask 0x0000 to 0xFFFF (0 to 65535)
* @param orMask 0x0000 to 0xFFFF (0 to 65535)
*/
public MaskWriteRegisterRequest(int address, int andMask, int orMask) { | super(FunctionCode.MaskWriteRegister); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteMultipleCoilsRequest.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import java.nio.ByteBuffer;
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to force each coil in a sequence of coils to either ON or OFF in a remote device. The Request
* PDU specifies the coil references to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is
* addressed as 0.
* <p>
* The requested ON/OFF states are specified by contents of the request data field. A logical '1' in a bit position of
* the field requests the corresponding output to be ON. A logical '0' requests it to be OFF.
*/
public class WriteMultipleCoilsRequest extends ByteBufModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07B0 (1 to 2000)
* @param values buffer of at least N bytes, where N = (quantity + 7) / 8
*/
public WriteMultipleCoilsRequest(int address, int quantity, byte[] values) {
this(address, quantity, Unpooled.wrappedBuffer(values));
}
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07B0 (1 to 2000)
* @param values buffer of at least N bytes, where N = (quantity + 7) / 8
*/
public WriteMultipleCoilsRequest(int address, int quantity, ByteBuffer values) {
this(address, quantity, Unpooled.wrappedBuffer(values));
}
/**
* Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
*
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07B0 (1 to 2000)
* @param values buffer of at least N bytes, where N = (quantity + 7) / 8
*/
public WriteMultipleCoilsRequest(int address, int quantity, ByteBuf values) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/requests/WriteMultipleCoilsRequest.java
import java.nio.ByteBuffer;
import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.requests;
/**
* This function is used to force each coil in a sequence of coils to either ON or OFF in a remote device. The Request
* PDU specifies the coil references to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is
* addressed as 0.
* <p>
* The requested ON/OFF states are specified by contents of the request data field. A logical '1' in a bit position of
* the field requests the corresponding output to be ON. A logical '0' requests it to be OFF.
*/
public class WriteMultipleCoilsRequest extends ByteBufModbusRequest {
private final int address;
private final int quantity;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07B0 (1 to 2000)
* @param values buffer of at least N bytes, where N = (quantity + 7) / 8
*/
public WriteMultipleCoilsRequest(int address, int quantity, byte[] values) {
this(address, quantity, Unpooled.wrappedBuffer(values));
}
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07B0 (1 to 2000)
* @param values buffer of at least N bytes, where N = (quantity + 7) / 8
*/
public WriteMultipleCoilsRequest(int address, int quantity, ByteBuffer values) {
this(address, quantity, Unpooled.wrappedBuffer(values));
}
/**
* Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
*
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param quantity 0x0001 to 0x07B0 (1 to 2000)
* @param values buffer of at least N bytes, where N = (quantity + 7) / 8
*/
public WriteMultipleCoilsRequest(int address, int quantity, ByteBuf values) { | super(values, FunctionCode.WriteMultipleCoils); |
digitalpetri/modbus | modbus-core/src/main/java/com/digitalpetri/modbus/responses/MaskWriteRegisterResponse.java | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
| import com.digitalpetri.modbus.FunctionCode; | /*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response is an echo of the request. The response is returned after the register has been written.
*/
public class MaskWriteRegisterResponse extends SimpleModbusResponse {
private final int address;
private final int andMask;
private final int orMask;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param andMask 0x0000 to 0xFFFF (0 to 65535)
* @param orMask 0x0000 to 0xFFFF (0 to 65535)
*/
public MaskWriteRegisterResponse(int address, int andMask, int orMask) { | // Path: modbus-core/src/main/java/com/digitalpetri/modbus/FunctionCode.java
// public enum FunctionCode {
//
// ReadCoils(0x01),
// ReadDiscreteInputs(0x02),
// ReadHoldingRegisters(0x03),
// ReadInputRegisters(0x04),
// WriteSingleCoil(0x05),
// WriteSingleRegister(0x06),
// ReadExceptionStatus(0x07),
// Diagnostics(0x08),
// GetCommEventCounter(0x0B),
// GetCommEventLog(0x0C),
// WriteMultipleCoils(0x0F),
// WriteMultipleRegisters(0x10),
// ReportSlaveId(0x11),
// ReadFileRecord(0x14),
// WriteFileRecord(0x15),
// MaskWriteRegister(0x16),
// ReadWriteMultipleRegisters(0x17),
// ReadFifoQueue(0x18),
// EncapsulatedInterfaceTransport(0x2B);
//
// private final int code;
//
// FunctionCode(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
//
// public static Optional<FunctionCode> fromCode(int code) {
// switch(code) {
// case 0x01: return Optional.of(ReadCoils);
// case 0x02: return Optional.of(ReadDiscreteInputs);
// case 0x03: return Optional.of(ReadHoldingRegisters);
// case 0x04: return Optional.of(ReadInputRegisters);
// case 0x05: return Optional.of(WriteSingleCoil);
// case 0x06: return Optional.of(WriteSingleRegister);
// case 0x07: return Optional.of(ReadExceptionStatus);
// case 0x08: return Optional.of(Diagnostics);
// case 0x0B: return Optional.of(GetCommEventCounter);
// case 0x0C: return Optional.of(GetCommEventLog);
// case 0x0F: return Optional.of(WriteMultipleCoils);
// case 0x10: return Optional.of(WriteMultipleRegisters);
// case 0x11: return Optional.of(ReportSlaveId);
// case 0x14: return Optional.of(ReadFileRecord);
// case 0x15: return Optional.of(WriteFileRecord);
// case 0x16: return Optional.of(MaskWriteRegister);
// case 0x17: return Optional.of(ReadWriteMultipleRegisters);
// case 0x18: return Optional.of(ReadFifoQueue);
// case 0x2B: return Optional.of(EncapsulatedInterfaceTransport);
// }
//
// return Optional.empty();
// }
//
// public static boolean isExceptionCode(int code) {
// return fromCode(code - 0x80).isPresent();
// }
//
// }
// Path: modbus-core/src/main/java/com/digitalpetri/modbus/responses/MaskWriteRegisterResponse.java
import com.digitalpetri.modbus.FunctionCode;
/*
* Copyright 2016 Kevin Herron
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpetri.modbus.responses;
/**
* The normal response is an echo of the request. The response is returned after the register has been written.
*/
public class MaskWriteRegisterResponse extends SimpleModbusResponse {
private final int address;
private final int andMask;
private final int orMask;
/**
* @param address 0x0000 to 0xFFFF (0 to 65535)
* @param andMask 0x0000 to 0xFFFF (0 to 65535)
* @param orMask 0x0000 to 0xFFFF (0 to 65535)
*/
public MaskWriteRegisterResponse(int address, int andMask, int orMask) { | super(FunctionCode.MaskWriteRegister); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.