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 |
|---|---|---|---|---|---|---|
ralscha/wampspring | src/main/java/ch/rasc/wampspring/broker/SubscriptionRegistry.java | // Path: src/main/java/ch/rasc/wampspring/message/PubSubMessage.java
// public abstract class PubSubMessage extends WampMessage {
//
// private String topicURI;
//
// protected PubSubMessage(WampMessageType type) {
// super(type);
// }
//
// public PubSubMessage(WampMessageType type, String topicURI) {
// super(type);
// this.topicURI = topicURI;
// }
//
// public String getTopicURI() {
// return this.topicURI;
// }
//
// protected void setTopicURI(String topicURI) {
// this.topicURI = topicURI;
// }
//
// @Override
// public String getDestination() {
// return this.topicURI;
// }
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/SubscribeMessage.java
// public class SubscribeMessage extends PubSubMessage {
//
// public SubscribeMessage(String topicURI) {
// super(WampMessageType.SUBSCRIBE, topicURI);
// }
//
// public SubscribeMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public SubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.SUBSCRIBE);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(getTopicURI());
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "SubscribeMessage [topicURI=" + getTopicURI() + "]";
// }
//
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/UnsubscribeMessage.java
// public class UnsubscribeMessage extends PubSubMessage {
//
// private boolean cleanup = false;
//
// public UnsubscribeMessage(String topicURI) {
// super(WampMessageType.UNSUBSCRIBE, topicURI);
// }
//
// public UnsubscribeMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public UnsubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.UNSUBSCRIBE);
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));
// }
//
// /**
// * Creates an internal unsubscribe message. The system creates this message when the
// * WebSocket session ends and sends it to the subscribed message handlers for cleaning
// * up
// *
// * @param sessionId the WebSocket session id
// **/
// public static UnsubscribeMessage createCleanupMessage(WebSocketSession session) {
// UnsubscribeMessage msg = new UnsubscribeMessage("**");
//
// msg.setWebSocketSessionId(session.getId());
// msg.setPrincipal(session.getPrincipal());
// msg.setWampSession(new WampSession(session));
//
// msg.cleanup = true;
//
// return msg;
// }
//
// public boolean isCleanup() {
// return this.cleanup;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(getTopicURI());
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "UnsubscribeMessage [topicURI=" + getTopicURI() + "]";
// }
//
// }
| import java.util.Set;
import ch.rasc.wampspring.message.PubSubMessage;
import ch.rasc.wampspring.message.SubscribeMessage;
import ch.rasc.wampspring.message.UnsubscribeMessage; | /**
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.broker;
/**
* @author Rossen Stoyanchev
* @author Ralph Schaer
*/
public interface SubscriptionRegistry {
/**
* Register a subscription represented by the given message.
* @param subscribeMessage the subscription request
*/
void registerSubscription(SubscribeMessage subscribeMessage);
/**
* Unregister a subscription.
* @param unsubscribeMessage the request to unsubscribe
*/ | // Path: src/main/java/ch/rasc/wampspring/message/PubSubMessage.java
// public abstract class PubSubMessage extends WampMessage {
//
// private String topicURI;
//
// protected PubSubMessage(WampMessageType type) {
// super(type);
// }
//
// public PubSubMessage(WampMessageType type, String topicURI) {
// super(type);
// this.topicURI = topicURI;
// }
//
// public String getTopicURI() {
// return this.topicURI;
// }
//
// protected void setTopicURI(String topicURI) {
// this.topicURI = topicURI;
// }
//
// @Override
// public String getDestination() {
// return this.topicURI;
// }
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/SubscribeMessage.java
// public class SubscribeMessage extends PubSubMessage {
//
// public SubscribeMessage(String topicURI) {
// super(WampMessageType.SUBSCRIBE, topicURI);
// }
//
// public SubscribeMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public SubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.SUBSCRIBE);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(getTopicURI());
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "SubscribeMessage [topicURI=" + getTopicURI() + "]";
// }
//
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/UnsubscribeMessage.java
// public class UnsubscribeMessage extends PubSubMessage {
//
// private boolean cleanup = false;
//
// public UnsubscribeMessage(String topicURI) {
// super(WampMessageType.UNSUBSCRIBE, topicURI);
// }
//
// public UnsubscribeMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public UnsubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.UNSUBSCRIBE);
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));
// }
//
// /**
// * Creates an internal unsubscribe message. The system creates this message when the
// * WebSocket session ends and sends it to the subscribed message handlers for cleaning
// * up
// *
// * @param sessionId the WebSocket session id
// **/
// public static UnsubscribeMessage createCleanupMessage(WebSocketSession session) {
// UnsubscribeMessage msg = new UnsubscribeMessage("**");
//
// msg.setWebSocketSessionId(session.getId());
// msg.setPrincipal(session.getPrincipal());
// msg.setWampSession(new WampSession(session));
//
// msg.cleanup = true;
//
// return msg;
// }
//
// public boolean isCleanup() {
// return this.cleanup;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(getTopicURI());
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "UnsubscribeMessage [topicURI=" + getTopicURI() + "]";
// }
//
// }
// Path: src/main/java/ch/rasc/wampspring/broker/SubscriptionRegistry.java
import java.util.Set;
import ch.rasc.wampspring.message.PubSubMessage;
import ch.rasc.wampspring.message.SubscribeMessage;
import ch.rasc.wampspring.message.UnsubscribeMessage;
/**
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.broker;
/**
* @author Rossen Stoyanchev
* @author Ralph Schaer
*/
public interface SubscriptionRegistry {
/**
* Register a subscription represented by the given message.
* @param subscribeMessage the subscription request
*/
void registerSubscription(SubscribeMessage subscribeMessage);
/**
* Unregister a subscription.
* @param unsubscribeMessage the request to unsubscribe
*/ | void unregisterSubscription(UnsubscribeMessage unsubscribeMessage); |
ralscha/wampspring | src/main/java/ch/rasc/wampspring/broker/SubscriptionRegistry.java | // Path: src/main/java/ch/rasc/wampspring/message/PubSubMessage.java
// public abstract class PubSubMessage extends WampMessage {
//
// private String topicURI;
//
// protected PubSubMessage(WampMessageType type) {
// super(type);
// }
//
// public PubSubMessage(WampMessageType type, String topicURI) {
// super(type);
// this.topicURI = topicURI;
// }
//
// public String getTopicURI() {
// return this.topicURI;
// }
//
// protected void setTopicURI(String topicURI) {
// this.topicURI = topicURI;
// }
//
// @Override
// public String getDestination() {
// return this.topicURI;
// }
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/SubscribeMessage.java
// public class SubscribeMessage extends PubSubMessage {
//
// public SubscribeMessage(String topicURI) {
// super(WampMessageType.SUBSCRIBE, topicURI);
// }
//
// public SubscribeMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public SubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.SUBSCRIBE);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(getTopicURI());
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "SubscribeMessage [topicURI=" + getTopicURI() + "]";
// }
//
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/UnsubscribeMessage.java
// public class UnsubscribeMessage extends PubSubMessage {
//
// private boolean cleanup = false;
//
// public UnsubscribeMessage(String topicURI) {
// super(WampMessageType.UNSUBSCRIBE, topicURI);
// }
//
// public UnsubscribeMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public UnsubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.UNSUBSCRIBE);
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));
// }
//
// /**
// * Creates an internal unsubscribe message. The system creates this message when the
// * WebSocket session ends and sends it to the subscribed message handlers for cleaning
// * up
// *
// * @param sessionId the WebSocket session id
// **/
// public static UnsubscribeMessage createCleanupMessage(WebSocketSession session) {
// UnsubscribeMessage msg = new UnsubscribeMessage("**");
//
// msg.setWebSocketSessionId(session.getId());
// msg.setPrincipal(session.getPrincipal());
// msg.setWampSession(new WampSession(session));
//
// msg.cleanup = true;
//
// return msg;
// }
//
// public boolean isCleanup() {
// return this.cleanup;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(getTopicURI());
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "UnsubscribeMessage [topicURI=" + getTopicURI() + "]";
// }
//
// }
| import java.util.Set;
import ch.rasc.wampspring.message.PubSubMessage;
import ch.rasc.wampspring.message.SubscribeMessage;
import ch.rasc.wampspring.message.UnsubscribeMessage; | /**
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.broker;
/**
* @author Rossen Stoyanchev
* @author Ralph Schaer
*/
public interface SubscriptionRegistry {
/**
* Register a subscription represented by the given message.
* @param subscribeMessage the subscription request
*/
void registerSubscription(SubscribeMessage subscribeMessage);
/**
* Unregister a subscription.
* @param unsubscribeMessage the request to unsubscribe
*/
void unregisterSubscription(UnsubscribeMessage unsubscribeMessage);
/**
* Unregister all subscriptions of the given WebSocket session
*/
void unregisterSession(String webSocketSessionId);
/**
* Find all WebSocket session ids that should receive the given message.
* @param message the message
* @return a {@link Set} of WebSocket session ids, possibly empty.
*/ | // Path: src/main/java/ch/rasc/wampspring/message/PubSubMessage.java
// public abstract class PubSubMessage extends WampMessage {
//
// private String topicURI;
//
// protected PubSubMessage(WampMessageType type) {
// super(type);
// }
//
// public PubSubMessage(WampMessageType type, String topicURI) {
// super(type);
// this.topicURI = topicURI;
// }
//
// public String getTopicURI() {
// return this.topicURI;
// }
//
// protected void setTopicURI(String topicURI) {
// this.topicURI = topicURI;
// }
//
// @Override
// public String getDestination() {
// return this.topicURI;
// }
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/SubscribeMessage.java
// public class SubscribeMessage extends PubSubMessage {
//
// public SubscribeMessage(String topicURI) {
// super(WampMessageType.SUBSCRIBE, topicURI);
// }
//
// public SubscribeMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public SubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.SUBSCRIBE);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(getTopicURI());
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "SubscribeMessage [topicURI=" + getTopicURI() + "]";
// }
//
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/UnsubscribeMessage.java
// public class UnsubscribeMessage extends PubSubMessage {
//
// private boolean cleanup = false;
//
// public UnsubscribeMessage(String topicURI) {
// super(WampMessageType.UNSUBSCRIBE, topicURI);
// }
//
// public UnsubscribeMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public UnsubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.UNSUBSCRIBE);
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));
// }
//
// /**
// * Creates an internal unsubscribe message. The system creates this message when the
// * WebSocket session ends and sends it to the subscribed message handlers for cleaning
// * up
// *
// * @param sessionId the WebSocket session id
// **/
// public static UnsubscribeMessage createCleanupMessage(WebSocketSession session) {
// UnsubscribeMessage msg = new UnsubscribeMessage("**");
//
// msg.setWebSocketSessionId(session.getId());
// msg.setPrincipal(session.getPrincipal());
// msg.setWampSession(new WampSession(session));
//
// msg.cleanup = true;
//
// return msg;
// }
//
// public boolean isCleanup() {
// return this.cleanup;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(getTopicURI());
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "UnsubscribeMessage [topicURI=" + getTopicURI() + "]";
// }
//
// }
// Path: src/main/java/ch/rasc/wampspring/broker/SubscriptionRegistry.java
import java.util.Set;
import ch.rasc.wampspring.message.PubSubMessage;
import ch.rasc.wampspring.message.SubscribeMessage;
import ch.rasc.wampspring.message.UnsubscribeMessage;
/**
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.broker;
/**
* @author Rossen Stoyanchev
* @author Ralph Schaer
*/
public interface SubscriptionRegistry {
/**
* Register a subscription represented by the given message.
* @param subscribeMessage the subscription request
*/
void registerSubscription(SubscribeMessage subscribeMessage);
/**
* Unregister a subscription.
* @param unsubscribeMessage the request to unsubscribe
*/
void unregisterSubscription(UnsubscribeMessage unsubscribeMessage);
/**
* Unregister all subscriptions of the given WebSocket session
*/
void unregisterSession(String webSocketSessionId);
/**
* Find all WebSocket session ids that should receive the given message.
* @param message the message
* @return a {@link Set} of WebSocket session ids, possibly empty.
*/ | Set<String> findSubscriptions(PubSubMessage pubSubMessage); |
ralscha/wampspring | src/test/java/ch/rasc/wampspring/method/DestinationPatternsMessageConditionTest.java | // Path: src/main/java/ch/rasc/wampspring/message/CallMessage.java
// public class CallMessage extends WampMessage {
// private final String callID;
//
// private final String procURI;
//
// private final List<Object> arguments;
//
// public CallMessage(String callID, String procURI, Object... arguments) {
// super(WampMessageType.CALL);
// this.callID = callID;
// this.procURI = procURI;
// if (arguments != null) {
// this.arguments = Arrays.asList(arguments);
// }
// else {
// this.arguments = null;
// }
//
// }
//
// public CallMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public CallMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.CALL);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.callID = jp.getValueAsString();
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.procURI = replacePrefix(jp.getValueAsString(), wampSession);
//
// List<Object> args = new ArrayList<>();
// while (jp.nextToken() != JsonToken.END_ARRAY) {
// args.add(jp.readValueAs(Object.class));
// }
//
// if (!args.isEmpty()) {
// this.arguments = Collections.unmodifiableList(args);
// }
// else {
// this.arguments = null;
// }
// }
//
// public String getCallID() {
// return this.callID;
// }
//
// public String getProcURI() {
// return this.procURI;
// }
//
// public List<Object> getArguments() {
// return this.arguments;
// }
//
// @Override
// public String getDestination() {
// return this.procURI;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(this.callID);
// jg.writeString(this.procURI);
// if (this.arguments != null) {
// for (Object argument : this.arguments) {
// jg.writeObject(argument);
// }
// }
//
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "CallMessage [callID=" + this.callID + ", procURI=" + this.procURI
// + ", arguments=" + this.arguments + "]";
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.UUID;
import org.junit.Test;
import org.springframework.messaging.Message;
import org.springframework.util.AntPathMatcher;
import ch.rasc.wampspring.message.CallMessage; | DestinationPatternsMessageCondition c2 = condition("/foo*");
assertEquals(0, c1.compareTo(c2, messageTo("/foo")));
}
@Test
public void comparePatternSpecificity() {
DestinationPatternsMessageCondition c1 = condition("/fo*");
DestinationPatternsMessageCondition c2 = condition("/foo");
assertEquals(1, c1.compareTo(c2, messageTo("/foo")));
}
@Test
public void compareNumberOfMatchingPatterns() throws Exception {
Message<?> message = messageTo("/foo");
DestinationPatternsMessageCondition c1 = condition("/foo", "/bar");
DestinationPatternsMessageCondition c2 = condition("/foo", "/f*");
DestinationPatternsMessageCondition match1 = c1.getMatchingCondition(message);
DestinationPatternsMessageCondition match2 = c2.getMatchingCondition(message);
assertEquals(1, match1.compareTo(match2, message));
}
private static DestinationPatternsMessageCondition condition(String... patterns) {
return new DestinationPatternsMessageCondition(patterns, new AntPathMatcher());
}
| // Path: src/main/java/ch/rasc/wampspring/message/CallMessage.java
// public class CallMessage extends WampMessage {
// private final String callID;
//
// private final String procURI;
//
// private final List<Object> arguments;
//
// public CallMessage(String callID, String procURI, Object... arguments) {
// super(WampMessageType.CALL);
// this.callID = callID;
// this.procURI = procURI;
// if (arguments != null) {
// this.arguments = Arrays.asList(arguments);
// }
// else {
// this.arguments = null;
// }
//
// }
//
// public CallMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public CallMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.CALL);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.callID = jp.getValueAsString();
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.procURI = replacePrefix(jp.getValueAsString(), wampSession);
//
// List<Object> args = new ArrayList<>();
// while (jp.nextToken() != JsonToken.END_ARRAY) {
// args.add(jp.readValueAs(Object.class));
// }
//
// if (!args.isEmpty()) {
// this.arguments = Collections.unmodifiableList(args);
// }
// else {
// this.arguments = null;
// }
// }
//
// public String getCallID() {
// return this.callID;
// }
//
// public String getProcURI() {
// return this.procURI;
// }
//
// public List<Object> getArguments() {
// return this.arguments;
// }
//
// @Override
// public String getDestination() {
// return this.procURI;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(this.callID);
// jg.writeString(this.procURI);
// if (this.arguments != null) {
// for (Object argument : this.arguments) {
// jg.writeObject(argument);
// }
// }
//
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "CallMessage [callID=" + this.callID + ", procURI=" + this.procURI
// + ", arguments=" + this.arguments + "]";
// }
//
// }
// Path: src/test/java/ch/rasc/wampspring/method/DestinationPatternsMessageConditionTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.UUID;
import org.junit.Test;
import org.springframework.messaging.Message;
import org.springframework.util.AntPathMatcher;
import ch.rasc.wampspring.message.CallMessage;
DestinationPatternsMessageCondition c2 = condition("/foo*");
assertEquals(0, c1.compareTo(c2, messageTo("/foo")));
}
@Test
public void comparePatternSpecificity() {
DestinationPatternsMessageCondition c1 = condition("/fo*");
DestinationPatternsMessageCondition c2 = condition("/foo");
assertEquals(1, c1.compareTo(c2, messageTo("/foo")));
}
@Test
public void compareNumberOfMatchingPatterns() throws Exception {
Message<?> message = messageTo("/foo");
DestinationPatternsMessageCondition c1 = condition("/foo", "/bar");
DestinationPatternsMessageCondition c2 = condition("/foo", "/f*");
DestinationPatternsMessageCondition match1 = c1.getMatchingCondition(message);
DestinationPatternsMessageCondition match2 = c2.getMatchingCondition(message);
assertEquals(1, match1.compareTo(match2, message));
}
private static DestinationPatternsMessageCondition condition(String... patterns) {
return new DestinationPatternsMessageCondition(patterns, new AntPathMatcher());
}
| private static CallMessage messageTo(String destination) { |
ralscha/wampspring | src/main/java/ch/rasc/wampspring/method/WampMessageTypeMessageCondition.java | // Path: src/main/java/ch/rasc/wampspring/message/WampMessageHeader.java
// public enum WampMessageHeader {
// WAMP_MESSAGE_TYPE, PRINCIPAL, WEBSOCKET_SESSION_ID, WAMP_SESSION
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/WampMessageType.java
// public enum WampMessageType {
//
// // Server-to-client Auxiliary
// WELCOME(0),
//
// // Client-to-server Auxiliary
// PREFIX(1),
//
// // Client-to-server RPC
// CALL(2),
//
// // Server-to-client RPC
// CALLRESULT(3),
//
// // Server-to-client RPC
// CALLERROR(4),
//
// // Client-to-server PubSub
// SUBSCRIBE(5),
//
// // Client-to-server PubSub
// UNSUBSCRIBE(6),
//
// // Client-to-server PubSub
// PUBLISH(7),
//
// // Server-to-client PubSub
// EVENT(8);
//
// private final int typeId;
//
// private WampMessageType(int typeId) {
// this.typeId = typeId;
// }
//
// public int getTypeId() {
// return this.typeId;
// }
//
// public static WampMessageType fromTypeId(int typeId) {
// switch (typeId) {
// case 0:
// return WELCOME;
// case 1:
// return PREFIX;
// case 2:
// return CALL;
// case 3:
// return CALLRESULT;
// case 4:
// return CALLERROR;
// case 5:
// return SUBSCRIBE;
// case 6:
// return UNSUBSCRIBE;
// case 7:
// return PUBLISH;
// case 8:
// return EVENT;
// default:
// return null;
// }
//
// }
// }
| import java.util.Arrays;
import java.util.Collection;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.AbstractMessageCondition;
import org.springframework.util.Assert;
import ch.rasc.wampspring.message.WampMessageHeader;
import ch.rasc.wampspring.message.WampMessageType; | /**
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.method;
/**
* A message condition that checks the message type.
*
* @author Rossen Stoyanchev
* @author Ralph Schaer
*/
public class WampMessageTypeMessageCondition
extends AbstractMessageCondition<WampMessageTypeMessageCondition> {
public static final WampMessageTypeMessageCondition CALL = new WampMessageTypeMessageCondition( | // Path: src/main/java/ch/rasc/wampspring/message/WampMessageHeader.java
// public enum WampMessageHeader {
// WAMP_MESSAGE_TYPE, PRINCIPAL, WEBSOCKET_SESSION_ID, WAMP_SESSION
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/WampMessageType.java
// public enum WampMessageType {
//
// // Server-to-client Auxiliary
// WELCOME(0),
//
// // Client-to-server Auxiliary
// PREFIX(1),
//
// // Client-to-server RPC
// CALL(2),
//
// // Server-to-client RPC
// CALLRESULT(3),
//
// // Server-to-client RPC
// CALLERROR(4),
//
// // Client-to-server PubSub
// SUBSCRIBE(5),
//
// // Client-to-server PubSub
// UNSUBSCRIBE(6),
//
// // Client-to-server PubSub
// PUBLISH(7),
//
// // Server-to-client PubSub
// EVENT(8);
//
// private final int typeId;
//
// private WampMessageType(int typeId) {
// this.typeId = typeId;
// }
//
// public int getTypeId() {
// return this.typeId;
// }
//
// public static WampMessageType fromTypeId(int typeId) {
// switch (typeId) {
// case 0:
// return WELCOME;
// case 1:
// return PREFIX;
// case 2:
// return CALL;
// case 3:
// return CALLRESULT;
// case 4:
// return CALLERROR;
// case 5:
// return SUBSCRIBE;
// case 6:
// return UNSUBSCRIBE;
// case 7:
// return PUBLISH;
// case 8:
// return EVENT;
// default:
// return null;
// }
//
// }
// }
// Path: src/main/java/ch/rasc/wampspring/method/WampMessageTypeMessageCondition.java
import java.util.Arrays;
import java.util.Collection;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.AbstractMessageCondition;
import org.springframework.util.Assert;
import ch.rasc.wampspring.message.WampMessageHeader;
import ch.rasc.wampspring.message.WampMessageType;
/**
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.method;
/**
* A message condition that checks the message type.
*
* @author Rossen Stoyanchev
* @author Ralph Schaer
*/
public class WampMessageTypeMessageCondition
extends AbstractMessageCondition<WampMessageTypeMessageCondition> {
public static final WampMessageTypeMessageCondition CALL = new WampMessageTypeMessageCondition( | WampMessageType.CALL); |
ralscha/wampspring | src/main/java/ch/rasc/wampspring/method/WampMessageTypeMessageCondition.java | // Path: src/main/java/ch/rasc/wampspring/message/WampMessageHeader.java
// public enum WampMessageHeader {
// WAMP_MESSAGE_TYPE, PRINCIPAL, WEBSOCKET_SESSION_ID, WAMP_SESSION
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/WampMessageType.java
// public enum WampMessageType {
//
// // Server-to-client Auxiliary
// WELCOME(0),
//
// // Client-to-server Auxiliary
// PREFIX(1),
//
// // Client-to-server RPC
// CALL(2),
//
// // Server-to-client RPC
// CALLRESULT(3),
//
// // Server-to-client RPC
// CALLERROR(4),
//
// // Client-to-server PubSub
// SUBSCRIBE(5),
//
// // Client-to-server PubSub
// UNSUBSCRIBE(6),
//
// // Client-to-server PubSub
// PUBLISH(7),
//
// // Server-to-client PubSub
// EVENT(8);
//
// private final int typeId;
//
// private WampMessageType(int typeId) {
// this.typeId = typeId;
// }
//
// public int getTypeId() {
// return this.typeId;
// }
//
// public static WampMessageType fromTypeId(int typeId) {
// switch (typeId) {
// case 0:
// return WELCOME;
// case 1:
// return PREFIX;
// case 2:
// return CALL;
// case 3:
// return CALLRESULT;
// case 4:
// return CALLERROR;
// case 5:
// return SUBSCRIBE;
// case 6:
// return UNSUBSCRIBE;
// case 7:
// return PUBLISH;
// case 8:
// return EVENT;
// default:
// return null;
// }
//
// }
// }
| import java.util.Arrays;
import java.util.Collection;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.AbstractMessageCondition;
import org.springframework.util.Assert;
import ch.rasc.wampspring.message.WampMessageHeader;
import ch.rasc.wampspring.message.WampMessageType; |
public WampMessageTypeMessageCondition(WampMessageType messageType) {
Assert.notNull(messageType, "MessageType must not be null");
this.messageType = messageType;
}
public WampMessageType getMessageType() {
return this.messageType;
}
@Override
protected Collection<?> getContent() {
return Arrays.asList(this.messageType);
}
@Override
protected String getToStringInfix() {
return " || ";
}
@Override
public WampMessageTypeMessageCondition combine(
WampMessageTypeMessageCondition other) {
return other;
}
@Override
public WampMessageTypeMessageCondition getMatchingCondition(Message<?> message) {
WampMessageType actualMessageType = (WampMessageType) message.getHeaders() | // Path: src/main/java/ch/rasc/wampspring/message/WampMessageHeader.java
// public enum WampMessageHeader {
// WAMP_MESSAGE_TYPE, PRINCIPAL, WEBSOCKET_SESSION_ID, WAMP_SESSION
// }
//
// Path: src/main/java/ch/rasc/wampspring/message/WampMessageType.java
// public enum WampMessageType {
//
// // Server-to-client Auxiliary
// WELCOME(0),
//
// // Client-to-server Auxiliary
// PREFIX(1),
//
// // Client-to-server RPC
// CALL(2),
//
// // Server-to-client RPC
// CALLRESULT(3),
//
// // Server-to-client RPC
// CALLERROR(4),
//
// // Client-to-server PubSub
// SUBSCRIBE(5),
//
// // Client-to-server PubSub
// UNSUBSCRIBE(6),
//
// // Client-to-server PubSub
// PUBLISH(7),
//
// // Server-to-client PubSub
// EVENT(8);
//
// private final int typeId;
//
// private WampMessageType(int typeId) {
// this.typeId = typeId;
// }
//
// public int getTypeId() {
// return this.typeId;
// }
//
// public static WampMessageType fromTypeId(int typeId) {
// switch (typeId) {
// case 0:
// return WELCOME;
// case 1:
// return PREFIX;
// case 2:
// return CALL;
// case 3:
// return CALLRESULT;
// case 4:
// return CALLERROR;
// case 5:
// return SUBSCRIBE;
// case 6:
// return UNSUBSCRIBE;
// case 7:
// return PUBLISH;
// case 8:
// return EVENT;
// default:
// return null;
// }
//
// }
// }
// Path: src/main/java/ch/rasc/wampspring/method/WampMessageTypeMessageCondition.java
import java.util.Arrays;
import java.util.Collection;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.AbstractMessageCondition;
import org.springframework.util.Assert;
import ch.rasc.wampspring.message.WampMessageHeader;
import ch.rasc.wampspring.message.WampMessageType;
public WampMessageTypeMessageCondition(WampMessageType messageType) {
Assert.notNull(messageType, "MessageType must not be null");
this.messageType = messageType;
}
public WampMessageType getMessageType() {
return this.messageType;
}
@Override
protected Collection<?> getContent() {
return Arrays.asList(this.messageType);
}
@Override
protected String getToStringInfix() {
return " || ";
}
@Override
public WampMessageTypeMessageCondition combine(
WampMessageTypeMessageCondition other) {
return other;
}
@Override
public WampMessageTypeMessageCondition getMatchingCondition(Message<?> message) {
WampMessageType actualMessageType = (WampMessageType) message.getHeaders() | .get(WampMessageHeader.WAMP_MESSAGE_TYPE.name()); |
ralscha/wampspring | src/main/java/ch/rasc/wampspring/cra/AuthenticationHandler.java | // Path: src/main/java/ch/rasc/wampspring/message/CallMessage.java
// public class CallMessage extends WampMessage {
// private final String callID;
//
// private final String procURI;
//
// private final List<Object> arguments;
//
// public CallMessage(String callID, String procURI, Object... arguments) {
// super(WampMessageType.CALL);
// this.callID = callID;
// this.procURI = procURI;
// if (arguments != null) {
// this.arguments = Arrays.asList(arguments);
// }
// else {
// this.arguments = null;
// }
//
// }
//
// public CallMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public CallMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.CALL);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.callID = jp.getValueAsString();
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.procURI = replacePrefix(jp.getValueAsString(), wampSession);
//
// List<Object> args = new ArrayList<>();
// while (jp.nextToken() != JsonToken.END_ARRAY) {
// args.add(jp.readValueAs(Object.class));
// }
//
// if (!args.isEmpty()) {
// this.arguments = Collections.unmodifiableList(args);
// }
// else {
// this.arguments = null;
// }
// }
//
// public String getCallID() {
// return this.callID;
// }
//
// public String getProcURI() {
// return this.procURI;
// }
//
// public List<Object> getArguments() {
// return this.arguments;
// }
//
// @Override
// public String getDestination() {
// return this.procURI;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(this.callID);
// jg.writeString(this.procURI);
// if (this.arguments != null) {
// for (Object argument : this.arguments) {
// jg.writeObject(argument);
// }
// }
//
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "CallMessage [callID=" + this.callID + ", procURI=" + this.procURI
// + ", arguments=" + this.arguments + "]";
// }
//
// }
| import java.util.Map;
import ch.rasc.wampspring.annotation.WampCallListener;
import ch.rasc.wampspring.message.CallMessage; | /**
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.cra;
public interface AuthenticationHandler {
@WampCallListener(value = "http://api.wamp.ws/procedure#authreq",
authenticated = false) | // Path: src/main/java/ch/rasc/wampspring/message/CallMessage.java
// public class CallMessage extends WampMessage {
// private final String callID;
//
// private final String procURI;
//
// private final List<Object> arguments;
//
// public CallMessage(String callID, String procURI, Object... arguments) {
// super(WampMessageType.CALL);
// this.callID = callID;
// this.procURI = procURI;
// if (arguments != null) {
// this.arguments = Arrays.asList(arguments);
// }
// else {
// this.arguments = null;
// }
//
// }
//
// public CallMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public CallMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.CALL);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.callID = jp.getValueAsString();
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.procURI = replacePrefix(jp.getValueAsString(), wampSession);
//
// List<Object> args = new ArrayList<>();
// while (jp.nextToken() != JsonToken.END_ARRAY) {
// args.add(jp.readValueAs(Object.class));
// }
//
// if (!args.isEmpty()) {
// this.arguments = Collections.unmodifiableList(args);
// }
// else {
// this.arguments = null;
// }
// }
//
// public String getCallID() {
// return this.callID;
// }
//
// public String getProcURI() {
// return this.procURI;
// }
//
// public List<Object> getArguments() {
// return this.arguments;
// }
//
// @Override
// public String getDestination() {
// return this.procURI;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(this.callID);
// jg.writeString(this.procURI);
// if (this.arguments != null) {
// for (Object argument : this.arguments) {
// jg.writeObject(argument);
// }
// }
//
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "CallMessage [callID=" + this.callID + ", procURI=" + this.procURI
// + ", arguments=" + this.arguments + "]";
// }
//
// }
// Path: src/main/java/ch/rasc/wampspring/cra/AuthenticationHandler.java
import java.util.Map;
import ch.rasc.wampspring.annotation.WampCallListener;
import ch.rasc.wampspring.message.CallMessage;
/**
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.cra;
public interface AuthenticationHandler {
@WampCallListener(value = "http://api.wamp.ws/procedure#authreq",
authenticated = false) | Object handleAuthReq(String authKey, Map<String, Object> extra, CallMessage message); |
ralscha/wampspring | src/test/java/ch/rasc/wampspring/call/CallService.java | // Path: src/main/java/ch/rasc/wampspring/message/CallMessage.java
// public class CallMessage extends WampMessage {
// private final String callID;
//
// private final String procURI;
//
// private final List<Object> arguments;
//
// public CallMessage(String callID, String procURI, Object... arguments) {
// super(WampMessageType.CALL);
// this.callID = callID;
// this.procURI = procURI;
// if (arguments != null) {
// this.arguments = Arrays.asList(arguments);
// }
// else {
// this.arguments = null;
// }
//
// }
//
// public CallMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public CallMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.CALL);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.callID = jp.getValueAsString();
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.procURI = replacePrefix(jp.getValueAsString(), wampSession);
//
// List<Object> args = new ArrayList<>();
// while (jp.nextToken() != JsonToken.END_ARRAY) {
// args.add(jp.readValueAs(Object.class));
// }
//
// if (!args.isEmpty()) {
// this.arguments = Collections.unmodifiableList(args);
// }
// else {
// this.arguments = null;
// }
// }
//
// public String getCallID() {
// return this.callID;
// }
//
// public String getProcURI() {
// return this.procURI;
// }
//
// public List<Object> getArguments() {
// return this.arguments;
// }
//
// @Override
// public String getDestination() {
// return this.procURI;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(this.callID);
// jg.writeString(this.procURI);
// if (this.arguments != null) {
// for (Object argument : this.arguments) {
// jg.writeObject(argument);
// }
// }
//
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "CallMessage [callID=" + this.callID + ", procURI=" + this.procURI
// + ", arguments=" + this.arguments + "]";
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import ch.rasc.wampspring.annotation.WampCallListener;
import ch.rasc.wampspring.message.CallMessage; | /**
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.call;
public class CallService {
@WampCallListener
public void simpleTest(String arg1, Integer arg2) {
assertThat(arg1).isEqualTo("argument");
assertThat(arg2).isEqualTo(12);
}
@WampCallListener(value = "myOwnProcURI") | // Path: src/main/java/ch/rasc/wampspring/message/CallMessage.java
// public class CallMessage extends WampMessage {
// private final String callID;
//
// private final String procURI;
//
// private final List<Object> arguments;
//
// public CallMessage(String callID, String procURI, Object... arguments) {
// super(WampMessageType.CALL);
// this.callID = callID;
// this.procURI = procURI;
// if (arguments != null) {
// this.arguments = Arrays.asList(arguments);
// }
// else {
// this.arguments = null;
// }
//
// }
//
// public CallMessage(JsonParser jp) throws IOException {
// this(jp, null);
// }
//
// public CallMessage(JsonParser jp, WampSession wampSession) throws IOException {
// super(WampMessageType.CALL);
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.callID = jp.getValueAsString();
//
// if (jp.nextToken() != JsonToken.VALUE_STRING) {
// throw new IOException();
// }
// this.procURI = replacePrefix(jp.getValueAsString(), wampSession);
//
// List<Object> args = new ArrayList<>();
// while (jp.nextToken() != JsonToken.END_ARRAY) {
// args.add(jp.readValueAs(Object.class));
// }
//
// if (!args.isEmpty()) {
// this.arguments = Collections.unmodifiableList(args);
// }
// else {
// this.arguments = null;
// }
// }
//
// public String getCallID() {
// return this.callID;
// }
//
// public String getProcURI() {
// return this.procURI;
// }
//
// public List<Object> getArguments() {
// return this.arguments;
// }
//
// @Override
// public String getDestination() {
// return this.procURI;
// }
//
// @Override
// public String toJson(JsonFactory jsonFactory) throws IOException {
// try (StringWriter sw = new StringWriter();
// JsonGenerator jg = jsonFactory.createGenerator(sw)) {
// jg.writeStartArray();
// jg.writeNumber(getTypeId());
// jg.writeString(this.callID);
// jg.writeString(this.procURI);
// if (this.arguments != null) {
// for (Object argument : this.arguments) {
// jg.writeObject(argument);
// }
// }
//
// jg.writeEndArray();
// jg.close();
// return sw.toString();
// }
// }
//
// @Override
// public String toString() {
// return "CallMessage [callID=" + this.callID + ", procURI=" + this.procURI
// + ", arguments=" + this.arguments + "]";
// }
//
// }
// Path: src/test/java/ch/rasc/wampspring/call/CallService.java
import static org.assertj.core.api.Assertions.assertThat;
import ch.rasc.wampspring.annotation.WampCallListener;
import ch.rasc.wampspring.message.CallMessage;
/**
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.call;
public class CallService {
@WampCallListener
public void simpleTest(String arg1, Integer arg2) {
assertThat(arg1).isEqualTo("argument");
assertThat(arg2).isEqualTo(12);
}
@WampCallListener(value = "myOwnProcURI") | public void simpleTest(CallMessage callMessage) { |
rebane621/e621-android | src/main/java/de/e621/rebane/components/listadapter/PostListAdapter.java | // Path: src/main/java/de/e621/rebane/activities/PostsActivity.java
// public class PostsActivity extends PaginatedListActivity
// implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
//
// Menu menu = null;
//
// @Override
// @SuppressLint("MissingSuperCall")
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(R.layout.content_posts, savedInstanceState);
// //setContentView(R.layout.activity_posts);
// postLayoutInflated(this.getClass());
// }
//
// void setPagesize() {
// String pgsize = database.getValue(SettingsActivity.SETTINGPOSTSPERPAGE);
// if (pgsize == null || pgsize.isEmpty()) {
// pagesize = 15;
// database.setValue(SettingsActivity.SETTINGPOSTSPERPAGE, "15");
// } else {
// try {
// pagesize = Integer.valueOf(pgsize);
// } catch (Exception e) {
// pagesize = 15;
// database.setValue(SettingsActivity.SETTINGPOSTSPERPAGE, "15");
// }
// if (pagesize < 1 || pagesize > 100) {
// pagesize = 15;
// database.setValue(SettingsActivity.SETTINGPOSTSPERPAGE, "15");
// }
// }
// }
//
// @Override
// void handleIntent(Intent intent) {
// super.handleIntent(intent);
// //page = intent.getIntExtra(SEARCHQUERYPAGE,1); //done by super
// if (!Intent.ACTION_SEARCH.equals(intent.getAction())) { //true case handled by super
// openDB();
// query = database.getValue(SettingsActivity.SETTINGDEFAULTSEARCH);
// if (query == null) query = "";
// }
//
// if (results==null) searchPosts(query, page);
// }
//
// @Override
// void searchPosts(String escapedQuery, int page) {
// API_URI = "post/index.xml?tags="+escapedQuery+"&page="+ page + "&limit="+pagesize;
// API_LOGIN = true; //for vote meta search
//
// super.searchPosts(escapedQuery, page);
// }
//
// void onSearchResult(XMLNode result, String query, int page) {
// openDB();
// String quality = database.getValue(SettingsActivity.SETTINGPREVIEWQUALITY);
//
// results = new PostListAdapter(this, R.id.txtMid, blacklist.proxyBlacklist(result.getChildren()), quality);
// results.svNumPosts = (result.attributes().contains("count") ? Integer.valueOf(result.getAttribute("count").orElse("")) : 0);
// PostsActivity.this.query = query; PostsActivity.this.page = page;
//
// ActionBar ab = getSupportActionBar();
// ab.setTitle(getResources().getString(R.string.title_posts) + " | " + page);
// ab.setSubtitle(URLDecoder.decode(query));
// //setTitle(getResources().getString(R.string.title_posts) + " " + _page + (_query.equals("")?" | *":" | "+XMLUtils.unescapeXML(_query)));
// }
//
// MenuItem searchMenuItem = null;
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.posts, menu);
// this.menu = menu;
//
// // Get the SearchView and set the searchable configuration
// SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// SearchView searchView = (SearchView) (searchMenuItem = menu.findItem(R.id.action_search)).getActionView();
// if (searchView != null) {
// searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// @Override
// public boolean onQueryTextSubmit(String query) {
// MenuItem searchMenuItem = PostsActivity.this.searchMenuItem;
// if (searchMenuItem != null) {
// searchMenuItem.collapseActionView();
// }
// return false;
// }
// @Override
// public boolean onQueryTextChange(String newText) {
// return true;
// }
// });
// }
// else Toast.makeText(getApplicationContext(), "Could not enable Search!", Toast.LENGTH_LONG).show();
//
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_search) {
// SearchView sv = (SearchView)item.getActionView();
// item.expandActionView();
// sv.setQuery(URLDecoder.decode(query), false);
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// }
| import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.itwookie.XMLreader.XMLNode;
import java.util.List;
import de.e621.rebane.a621.R;
import de.e621.rebane.activities.PostsActivity;
| package de.e621.rebane.components.listadapter;
public class PostListAdapter extends XMLListAdapter {
private String quality;
private int pageoffset;
private String escapedQuery;
| // Path: src/main/java/de/e621/rebane/activities/PostsActivity.java
// public class PostsActivity extends PaginatedListActivity
// implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
//
// Menu menu = null;
//
// @Override
// @SuppressLint("MissingSuperCall")
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(R.layout.content_posts, savedInstanceState);
// //setContentView(R.layout.activity_posts);
// postLayoutInflated(this.getClass());
// }
//
// void setPagesize() {
// String pgsize = database.getValue(SettingsActivity.SETTINGPOSTSPERPAGE);
// if (pgsize == null || pgsize.isEmpty()) {
// pagesize = 15;
// database.setValue(SettingsActivity.SETTINGPOSTSPERPAGE, "15");
// } else {
// try {
// pagesize = Integer.valueOf(pgsize);
// } catch (Exception e) {
// pagesize = 15;
// database.setValue(SettingsActivity.SETTINGPOSTSPERPAGE, "15");
// }
// if (pagesize < 1 || pagesize > 100) {
// pagesize = 15;
// database.setValue(SettingsActivity.SETTINGPOSTSPERPAGE, "15");
// }
// }
// }
//
// @Override
// void handleIntent(Intent intent) {
// super.handleIntent(intent);
// //page = intent.getIntExtra(SEARCHQUERYPAGE,1); //done by super
// if (!Intent.ACTION_SEARCH.equals(intent.getAction())) { //true case handled by super
// openDB();
// query = database.getValue(SettingsActivity.SETTINGDEFAULTSEARCH);
// if (query == null) query = "";
// }
//
// if (results==null) searchPosts(query, page);
// }
//
// @Override
// void searchPosts(String escapedQuery, int page) {
// API_URI = "post/index.xml?tags="+escapedQuery+"&page="+ page + "&limit="+pagesize;
// API_LOGIN = true; //for vote meta search
//
// super.searchPosts(escapedQuery, page);
// }
//
// void onSearchResult(XMLNode result, String query, int page) {
// openDB();
// String quality = database.getValue(SettingsActivity.SETTINGPREVIEWQUALITY);
//
// results = new PostListAdapter(this, R.id.txtMid, blacklist.proxyBlacklist(result.getChildren()), quality);
// results.svNumPosts = (result.attributes().contains("count") ? Integer.valueOf(result.getAttribute("count").orElse("")) : 0);
// PostsActivity.this.query = query; PostsActivity.this.page = page;
//
// ActionBar ab = getSupportActionBar();
// ab.setTitle(getResources().getString(R.string.title_posts) + " | " + page);
// ab.setSubtitle(URLDecoder.decode(query));
// //setTitle(getResources().getString(R.string.title_posts) + " " + _page + (_query.equals("")?" | *":" | "+XMLUtils.unescapeXML(_query)));
// }
//
// MenuItem searchMenuItem = null;
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.posts, menu);
// this.menu = menu;
//
// // Get the SearchView and set the searchable configuration
// SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// SearchView searchView = (SearchView) (searchMenuItem = menu.findItem(R.id.action_search)).getActionView();
// if (searchView != null) {
// searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// @Override
// public boolean onQueryTextSubmit(String query) {
// MenuItem searchMenuItem = PostsActivity.this.searchMenuItem;
// if (searchMenuItem != null) {
// searchMenuItem.collapseActionView();
// }
// return false;
// }
// @Override
// public boolean onQueryTextChange(String newText) {
// return true;
// }
// });
// }
// else Toast.makeText(getApplicationContext(), "Could not enable Search!", Toast.LENGTH_LONG).show();
//
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_search) {
// SearchView sv = (SearchView)item.getActionView();
// item.expandActionView();
// sv.setQuery(URLDecoder.decode(query), false);
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// }
// Path: src/main/java/de/e621/rebane/components/listadapter/PostListAdapter.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.itwookie.XMLreader.XMLNode;
import java.util.List;
import de.e621.rebane.a621.R;
import de.e621.rebane.activities.PostsActivity;
package de.e621.rebane.components.listadapter;
public class PostListAdapter extends XMLListAdapter {
private String quality;
private int pageoffset;
private String escapedQuery;
| public PostListAdapter(PostsActivity context, int textViewResourceId, List<XMLNode> rowDataList, String quality) {
|
rebane621/e621-android | src/main/java/de/e621/rebane/activities/SetsActivity.java | // Path: src/main/java/de/e621/rebane/components/listadapter/CoverListAdapter.java
// public class CoverListAdapter extends XMLListAdapter {
//
// public int getLastPage(int pagesize) {
// return Integer.MAX_VALUE;
// } //can't be retrieved
// String listType;
//
// public CoverListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList, String quality, String type) {
// super(context, textViewResourceId, rowDataList);
// listType = type;
// svNumPosts = Integer.MAX_VALUE; //can't be computed
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// CoverViewHolder holder = new CoverViewHolder();
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.cover_layout, parent, false);
//
// holder.populate(position, convertView, list.get(position), listType);
//
// return convertView;
// }
// }
| import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.itwookie.XMLreader.XMLNode;
import java.net.URLDecoder;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.CoverListAdapter;
| package de.e621.rebane.activities;
public class SetsActivity extends PaginatedListActivity
implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
Menu menu = null;
@Override
@SuppressLint("MissingSuperCall")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(R.layout.content_cover_list, savedInstanceState);
//setContentView(R.layout.activity_posts);
postLayoutInflated(this.getClass());
}
void setPagesize() {
pagesize=50; //hardcoded
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
//page = intent.getIntExtra(SEARCHQUERYPAGE,1); //done by super
//can't search sets in a meaningfull way
if (results==null) searchPosts("", page);
}
@Override
void searchPosts(String escapedQuery, int page) {
API_URI = "set/index.xml?page="+ page;
API_LOGIN = false; //for vote meta search
super.searchPosts(escapedQuery, page);
}
void onSearchResult(XMLNode result, String query, int page) {
openDB();
String quality = database.getValue(SettingsActivity.SETTINGPREVIEWQUALITY); //i would really like to display thumbnails, a bit like a bookshelf
| // Path: src/main/java/de/e621/rebane/components/listadapter/CoverListAdapter.java
// public class CoverListAdapter extends XMLListAdapter {
//
// public int getLastPage(int pagesize) {
// return Integer.MAX_VALUE;
// } //can't be retrieved
// String listType;
//
// public CoverListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList, String quality, String type) {
// super(context, textViewResourceId, rowDataList);
// listType = type;
// svNumPosts = Integer.MAX_VALUE; //can't be computed
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// CoverViewHolder holder = new CoverViewHolder();
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.cover_layout, parent, false);
//
// holder.populate(position, convertView, list.get(position), listType);
//
// return convertView;
// }
// }
// Path: src/main/java/de/e621/rebane/activities/SetsActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.itwookie.XMLreader.XMLNode;
import java.net.URLDecoder;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.CoverListAdapter;
package de.e621.rebane.activities;
public class SetsActivity extends PaginatedListActivity
implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
Menu menu = null;
@Override
@SuppressLint("MissingSuperCall")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(R.layout.content_cover_list, savedInstanceState);
//setContentView(R.layout.activity_posts);
postLayoutInflated(this.getClass());
}
void setPagesize() {
pagesize=50; //hardcoded
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
//page = intent.getIntExtra(SEARCHQUERYPAGE,1); //done by super
//can't search sets in a meaningfull way
if (results==null) searchPosts("", page);
}
@Override
void searchPosts(String escapedQuery, int page) {
API_URI = "set/index.xml?page="+ page;
API_LOGIN = false; //for vote meta search
super.searchPosts(escapedQuery, page);
}
void onSearchResult(XMLNode result, String query, int page) {
openDB();
String quality = database.getValue(SettingsActivity.SETTINGPREVIEWQUALITY); //i would really like to display thumbnails, a bit like a bookshelf
| results = new CoverListAdapter(this, R.id.txtMid, result.getChildren(), quality, "set");
|
rebane621/e621-android | src/main/java/de/e621/rebane/activities/BlipsActivity.java | // Path: src/main/java/de/e621/rebane/components/listadapter/BlipListAdapter.java
// public class BlipListAdapter extends XMLListAdapter {
// FilterManager blacklist;
// String baseURL;
// boolean postLoad;
// public int getLastPage(int pagesize) {
// return 100;
// } //can't be retrieved
//
// public BlipListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList, String baseURL, FilterManager avatarFilter, boolean postLoadUserdata) {
// super(context, textViewResourceId, rowDataList);
// CommentViewHolder.resetAuthorData();
// blacklist = avatarFilter;
// this.baseURL = baseURL;
// postLoad = postLoadUserdata;
// svNumPosts=Integer.MAX_VALUE;
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
//
// BlipViewHolder holder = new BlipViewHolder(getContext(), baseURL, blacklist, postLoad, this);
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.blip_layout, parent, false);
//
// holder.populate(position, convertView, list.get(position));
//
// //return the row view.
// return convertView;
// }
// }
| import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.view.View;
import com.itwookie.XMLreader.XMLNode;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.BlipListAdapter;
|
postLoadUserdata = Boolean.parseBoolean(database.getValue(SettingsActivity.SETTINGFANCYCOMMENTS));
}
@Override void setPagesize() {
pagesize = 50; //given by API
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt(BLIPQUERYPAGE, page);
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
page = intent.getIntExtra(BLIPQUERYPAGE,1);
if (results==null) searchPosts("", page);
}
@Override void searchPosts(String escapedQuery, int page) {
API_URI = "blip/index.xml?page="+page;
API_LOGIN = false;
super.searchPosts(escapedQuery, page);
}
@Override void onSearchResult(XMLNode result, String query, int page) {
| // Path: src/main/java/de/e621/rebane/components/listadapter/BlipListAdapter.java
// public class BlipListAdapter extends XMLListAdapter {
// FilterManager blacklist;
// String baseURL;
// boolean postLoad;
// public int getLastPage(int pagesize) {
// return 100;
// } //can't be retrieved
//
// public BlipListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList, String baseURL, FilterManager avatarFilter, boolean postLoadUserdata) {
// super(context, textViewResourceId, rowDataList);
// CommentViewHolder.resetAuthorData();
// blacklist = avatarFilter;
// this.baseURL = baseURL;
// postLoad = postLoadUserdata;
// svNumPosts=Integer.MAX_VALUE;
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
//
// BlipViewHolder holder = new BlipViewHolder(getContext(), baseURL, blacklist, postLoad, this);
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.blip_layout, parent, false);
//
// holder.populate(position, convertView, list.get(position));
//
// //return the row view.
// return convertView;
// }
// }
// Path: src/main/java/de/e621/rebane/activities/BlipsActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.view.View;
import com.itwookie.XMLreader.XMLNode;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.BlipListAdapter;
postLoadUserdata = Boolean.parseBoolean(database.getValue(SettingsActivity.SETTINGFANCYCOMMENTS));
}
@Override void setPagesize() {
pagesize = 50; //given by API
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt(BLIPQUERYPAGE, page);
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
page = intent.getIntExtra(BLIPQUERYPAGE,1);
if (results==null) searchPosts("", page);
}
@Override void searchPosts(String escapedQuery, int page) {
API_URI = "blip/index.xml?page="+page;
API_LOGIN = false;
super.searchPosts(escapedQuery, page);
}
@Override void onSearchResult(XMLNode result, String query, int page) {
| results = new BlipListAdapter(getApplicationContext(), R.id.lblTitle, result.getChildren(), baseURL, blacklist, postLoadUserdata);
|
rebane621/e621-android | src/main/java/de/e621/rebane/activities/PostsActivity.java | // Path: src/main/java/de/e621/rebane/components/listadapter/PostListAdapter.java
// public class PostListAdapter extends XMLListAdapter {
// private String quality;
// private int pageoffset;
// private String escapedQuery;
//
// public PostListAdapter(PostsActivity context, int textViewResourceId, List<XMLNode> rowDataList, String quality) {
// super(context.getApplicationContext(), textViewResourceId, rowDataList);
// this.quality = quality;
// this.pageoffset = (context.page-1)*context.pagesize;
// this.escapedQuery = context.query;
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// PostListViewHolder holder = new PostListViewHolder(quality, this);
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.preview_layout, parent, false);
//
// holder.populate(position, convertView, list.get(position), pageoffset, escapedQuery);
//
// return convertView;
// }
// }
| import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.itwookie.XMLreader.XMLNode;
import java.net.URLDecoder;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.PostListAdapter;
| database.setValue(SettingsActivity.SETTINGPOSTSPERPAGE, "15");
}
}
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
//page = intent.getIntExtra(SEARCHQUERYPAGE,1); //done by super
if (!Intent.ACTION_SEARCH.equals(intent.getAction())) { //true case handled by super
openDB();
query = database.getValue(SettingsActivity.SETTINGDEFAULTSEARCH);
if (query == null) query = "";
}
if (results==null) searchPosts(query, page);
}
@Override
void searchPosts(String escapedQuery, int page) {
API_URI = "post/index.xml?tags="+escapedQuery+"&page="+ page + "&limit="+pagesize;
API_LOGIN = true; //for vote meta search
super.searchPosts(escapedQuery, page);
}
void onSearchResult(XMLNode result, String query, int page) {
openDB();
String quality = database.getValue(SettingsActivity.SETTINGPREVIEWQUALITY);
| // Path: src/main/java/de/e621/rebane/components/listadapter/PostListAdapter.java
// public class PostListAdapter extends XMLListAdapter {
// private String quality;
// private int pageoffset;
// private String escapedQuery;
//
// public PostListAdapter(PostsActivity context, int textViewResourceId, List<XMLNode> rowDataList, String quality) {
// super(context.getApplicationContext(), textViewResourceId, rowDataList);
// this.quality = quality;
// this.pageoffset = (context.page-1)*context.pagesize;
// this.escapedQuery = context.query;
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// PostListViewHolder holder = new PostListViewHolder(quality, this);
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.preview_layout, parent, false);
//
// holder.populate(position, convertView, list.get(position), pageoffset, escapedQuery);
//
// return convertView;
// }
// }
// Path: src/main/java/de/e621/rebane/activities/PostsActivity.java
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.itwookie.XMLreader.XMLNode;
import java.net.URLDecoder;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.PostListAdapter;
database.setValue(SettingsActivity.SETTINGPOSTSPERPAGE, "15");
}
}
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
//page = intent.getIntExtra(SEARCHQUERYPAGE,1); //done by super
if (!Intent.ACTION_SEARCH.equals(intent.getAction())) { //true case handled by super
openDB();
query = database.getValue(SettingsActivity.SETTINGDEFAULTSEARCH);
if (query == null) query = "";
}
if (results==null) searchPosts(query, page);
}
@Override
void searchPosts(String escapedQuery, int page) {
API_URI = "post/index.xml?tags="+escapedQuery+"&page="+ page + "&limit="+pagesize;
API_LOGIN = true; //for vote meta search
super.searchPosts(escapedQuery, page);
}
void onSearchResult(XMLNode result, String query, int page) {
openDB();
String quality = database.getValue(SettingsActivity.SETTINGPREVIEWQUALITY);
| results = new PostListAdapter(this, R.id.txtMid, blacklist.proxyBlacklist(result.getChildren()), quality);
|
rebane621/e621-android | src/main/java/de/e621/rebane/activities/LauncherActivity.java | // Path: src/main/java/de/e621/rebane/SQLite/SQLiteDB.java
// public class SQLiteDB {
// private SQLiteDatabase database;
// private SQLhelper dbHelper;
// private Context context;
//
// /** Erzeugt eine Neue instanz. Es sollte immer nur eine Instanz gleichzeitig verwendet werden<br>
// * Jedoch ist das hohlen des Context über einen Konstruktor wesentlich angenehmer ;)<br>
// * <br>
// * Anschließen muss die Datenbank mit instanc.open() geöffnet und abschließend mit instance.close()<br>
// * wieder geschlossen werden.
// * */
// public SQLiteDB(Context context) {
// dbHelper = new SQLhelper(this.context = context);
// }
//
// /** Öffnet die Datenbank - nach der bearbeitung .close() nicht vergessen */
// public void open() throws SQLException {
// try {
// if (database == null || !database.isOpen())
// database = dbHelper.getWritableDatabase();
// } catch (Exception e) {
// dbHelper = new SQLhelper(context);
// database = dbHelper.getReadableDatabase();
// }
// }
//
// /** Schließt die datenbank.<br>Ich bin mir nicht sicher, ob überhaupt ein Fehler auftritt, wenn man
// * versucht, daten zu lesen wären die Datenbank geschlossen ist - einfach aufpassen :)
// */
// public void close() {
// dbHelper.close();
// }
//
// /** Speicher ein Key Value Paar.<br>Der Wert für Key wird überschrieben, fals der Key bereits existiert */
// public void setValue(String Key, String Value) {
// //See if key already exists
// Cursor cursor = database.query(SQLhelper.TABLE_NAME, new String[]{ "Key" } , "Key='" + Key + "'", null, null, null, null);
// Boolean got_result = cursor.moveToFirst();
// cursor.close();
//
// if (!got_result) { //Create Key
// ContentValues values = new ContentValues();
// values.put("VALUE", Value);
// values.put("KEY", Key);
// database.insert(SQLhelper.TABLE_NAME, null, values);
// } else { //Update Key
// ContentValues values = new ContentValues();
// values.put("VALUE", Value);
// database.update(SQLhelper.TABLE_NAME, values, "Key='" + Key + "'", null);
// }
// }
//
// /** Holt einen Wert aus der Datenbank.<br>Fals kein Key Value Paar existiert wird null zurück gegeben*/
// public String getValue(String Key) {
// Cursor cursor = database.query(SQLhelper.TABLE_NAME, new String[]{ "Value" } , "Key='" + Key + "'", null, null, null, null);
// if (!cursor.moveToFirst() || cursor.isNull(0)) { cursor.close(); return null; }
// String result = cursor.getString(0);
//
// cursor.close(); return result;
// }
//
// public String[] getStringArray(String key) {
// String raw = getValue(key);
// if (raw == null || raw.isEmpty()) return new String[]{};
// Logger.getLogger("SQLite").info("Getting " + key + " : " + raw);
// return raw.substring(2, raw.length()-2).split("\", \"");
// }
// public void setStringArray(String key, String... array) {
// String raw = "[\"";
// int l1 = array.length-1;
// for (int i = 0; i <= l1; i++) {
// raw += array[i];
// if (i != l1) raw += "\", \"";
// }
// raw += "\"]";
// Logger.getLogger("SQLite").info("Setting " + key + " : " + raw);
// setValue(key, raw);
// }
// }
| import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;
import com.itwookie.XMLreader.XMLNode;
import com.itwookie.XMLreader.XMLTask;
import java.util.logging.Logger;
import de.e621.rebane.SQLite.SQLiteDB;
import de.e621.rebane.a621.R;
| package de.e621.rebane.activities;
public class LauncherActivity extends AppCompatActivity {
public static final String DATABASELASTUPDATE = "LastDayChecked4Updates";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_launcher);
| // Path: src/main/java/de/e621/rebane/SQLite/SQLiteDB.java
// public class SQLiteDB {
// private SQLiteDatabase database;
// private SQLhelper dbHelper;
// private Context context;
//
// /** Erzeugt eine Neue instanz. Es sollte immer nur eine Instanz gleichzeitig verwendet werden<br>
// * Jedoch ist das hohlen des Context über einen Konstruktor wesentlich angenehmer ;)<br>
// * <br>
// * Anschließen muss die Datenbank mit instanc.open() geöffnet und abschließend mit instance.close()<br>
// * wieder geschlossen werden.
// * */
// public SQLiteDB(Context context) {
// dbHelper = new SQLhelper(this.context = context);
// }
//
// /** Öffnet die Datenbank - nach der bearbeitung .close() nicht vergessen */
// public void open() throws SQLException {
// try {
// if (database == null || !database.isOpen())
// database = dbHelper.getWritableDatabase();
// } catch (Exception e) {
// dbHelper = new SQLhelper(context);
// database = dbHelper.getReadableDatabase();
// }
// }
//
// /** Schließt die datenbank.<br>Ich bin mir nicht sicher, ob überhaupt ein Fehler auftritt, wenn man
// * versucht, daten zu lesen wären die Datenbank geschlossen ist - einfach aufpassen :)
// */
// public void close() {
// dbHelper.close();
// }
//
// /** Speicher ein Key Value Paar.<br>Der Wert für Key wird überschrieben, fals der Key bereits existiert */
// public void setValue(String Key, String Value) {
// //See if key already exists
// Cursor cursor = database.query(SQLhelper.TABLE_NAME, new String[]{ "Key" } , "Key='" + Key + "'", null, null, null, null);
// Boolean got_result = cursor.moveToFirst();
// cursor.close();
//
// if (!got_result) { //Create Key
// ContentValues values = new ContentValues();
// values.put("VALUE", Value);
// values.put("KEY", Key);
// database.insert(SQLhelper.TABLE_NAME, null, values);
// } else { //Update Key
// ContentValues values = new ContentValues();
// values.put("VALUE", Value);
// database.update(SQLhelper.TABLE_NAME, values, "Key='" + Key + "'", null);
// }
// }
//
// /** Holt einen Wert aus der Datenbank.<br>Fals kein Key Value Paar existiert wird null zurück gegeben*/
// public String getValue(String Key) {
// Cursor cursor = database.query(SQLhelper.TABLE_NAME, new String[]{ "Value" } , "Key='" + Key + "'", null, null, null, null);
// if (!cursor.moveToFirst() || cursor.isNull(0)) { cursor.close(); return null; }
// String result = cursor.getString(0);
//
// cursor.close(); return result;
// }
//
// public String[] getStringArray(String key) {
// String raw = getValue(key);
// if (raw == null || raw.isEmpty()) return new String[]{};
// Logger.getLogger("SQLite").info("Getting " + key + " : " + raw);
// return raw.substring(2, raw.length()-2).split("\", \"");
// }
// public void setStringArray(String key, String... array) {
// String raw = "[\"";
// int l1 = array.length-1;
// for (int i = 0; i <= l1; i++) {
// raw += array[i];
// if (i != l1) raw += "\", \"";
// }
// raw += "\"]";
// Logger.getLogger("SQLite").info("Setting " + key + " : " + raw);
// setValue(key, raw);
// }
// }
// Path: src/main/java/de/e621/rebane/activities/LauncherActivity.java
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;
import com.itwookie.XMLreader.XMLNode;
import com.itwookie.XMLreader.XMLTask;
import java.util.logging.Logger;
import de.e621.rebane.SQLite.SQLiteDB;
import de.e621.rebane.a621.R;
package de.e621.rebane.activities;
public class LauncherActivity extends AppCompatActivity {
public static final String DATABASELASTUPDATE = "LastDayChecked4Updates";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_launcher);
| SQLiteDB db = new SQLiteDB(this);
|
rebane621/e621-android | src/main/java/de/e621/rebane/activities/DMailsActivity.java | // Path: src/main/java/de/e621/rebane/components/listadapter/DMailListAdapter.java
// public class DMailListAdapter extends XMLListAdapter {
//
// public int getLastPage(int pagesize) {
// return 100;
// } //can't be computed
//
// public DMailListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList) {
// super(context, textViewResourceId, rowDataList);
// svNumPosts = Integer.MAX_VALUE; //can't be computed
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// DMailViewHolder holder = new DMailViewHolder(Integer.parseInt(list.get(position).getFirstChildContent("id").orElse("")));
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.twolined_listentry, parent, false);
//
// SQLiteDB db = new SQLiteDB(getContext().getApplicationContext());
// db.open();
// LoginManager lm = LoginManager.getInstance(getContext().getApplicationContext(), db);
// XMLNode tmp = list.get(position);
// //Logger.getLogger("a621").info(tmp.toString());
//
// holder.populate(position, convertView, tmp, lm);
//
// return convertView;
// }
// }
| import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.itwookie.XMLreader.XMLNode;
import java.net.HttpURLConnection;
import java.net.URL;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.DMailListAdapter;
|
return super.onOptionsItemSelected(item);
}
@Override void setPagesize() {
pagesize = 30; //given by API
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt(FORUMQUERYPAGE, page);
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
page = intent.getIntExtra(FORUMQUERYPAGE,1);
if (results==null) searchPosts("", page);
}
@Override void searchPosts(String escapedQuery, int page) {
API_URI = "dmail/inbox.xml?page="+page;
API_LOGIN = true;
super.searchPosts(escapedQuery, page);
}
@Override void onSearchResult(XMLNode result, String query, int page) {
| // Path: src/main/java/de/e621/rebane/components/listadapter/DMailListAdapter.java
// public class DMailListAdapter extends XMLListAdapter {
//
// public int getLastPage(int pagesize) {
// return 100;
// } //can't be computed
//
// public DMailListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList) {
// super(context, textViewResourceId, rowDataList);
// svNumPosts = Integer.MAX_VALUE; //can't be computed
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// DMailViewHolder holder = new DMailViewHolder(Integer.parseInt(list.get(position).getFirstChildContent("id").orElse("")));
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.twolined_listentry, parent, false);
//
// SQLiteDB db = new SQLiteDB(getContext().getApplicationContext());
// db.open();
// LoginManager lm = LoginManager.getInstance(getContext().getApplicationContext(), db);
// XMLNode tmp = list.get(position);
// //Logger.getLogger("a621").info(tmp.toString());
//
// holder.populate(position, convertView, tmp, lm);
//
// return convertView;
// }
// }
// Path: src/main/java/de/e621/rebane/activities/DMailsActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.itwookie.XMLreader.XMLNode;
import java.net.HttpURLConnection;
import java.net.URL;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.DMailListAdapter;
return super.onOptionsItemSelected(item);
}
@Override void setPagesize() {
pagesize = 30; //given by API
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt(FORUMQUERYPAGE, page);
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
page = intent.getIntExtra(FORUMQUERYPAGE,1);
if (results==null) searchPosts("", page);
}
@Override void searchPosts(String escapedQuery, int page) {
API_URI = "dmail/inbox.xml?page="+page;
API_LOGIN = true;
super.searchPosts(escapedQuery, page);
}
@Override void onSearchResult(XMLNode result, String query, int page) {
| results = new DMailListAdapter(getApplicationContext(), R.id.lblTitle, result.getChildren());
|
rebane621/e621-android | src/main/java/de/e621/rebane/activities/ForumsActivity.java | // Path: src/main/java/de/e621/rebane/components/listadapter/ForumListAdapter.java
// public class ForumListAdapter extends XMLListAdapter {
//
// public int getLastPage(int pagesize) {
// return 100;
// } //can't be retrieved
//
// public ForumListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList) {
// super(context, textViewResourceId, rowDataList);
// svNumPosts = Integer.MAX_VALUE; //can't be computed
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// ForumViewHolder holder = new ForumViewHolder();
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.twolined_listentry, parent, false);
//
// holder.populate(position, convertView, list.get(position));
//
// return convertView;
// }
// }
| import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.view.View;
import com.itwookie.XMLreader.XMLNode;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.ForumListAdapter;
| package de.e621.rebane.activities;
/** with what little information is returned by the forum API I won't continue that for now */
public class ForumsActivity extends PaginatedListActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
final static String FORUMQUERYPAGE = "a621 SearchManager Forum Page";
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paginated_list);
postLayoutInflated(this.getClass());
}*/
@Override
@SuppressLint("MissingSuperCall")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(R.layout.content_paginated_list, savedInstanceState);
//setContentView(R.layout.activity_posts);
postLayoutInflated(this.getClass());
}
@Override void setPagesize() {
pagesize = 30; //given by API
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt(FORUMQUERYPAGE, page);
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
page = intent.getIntExtra(FORUMQUERYPAGE,1);
if (results==null) searchPosts("", page);
}
@Override void searchPosts(String escapedQuery, int page) {
API_URI = "forum/index.xml?page="+page;
API_LOGIN = false;
super.searchPosts(escapedQuery, page);
}
@Override void onSearchResult(XMLNode result, String query, int page) {
| // Path: src/main/java/de/e621/rebane/components/listadapter/ForumListAdapter.java
// public class ForumListAdapter extends XMLListAdapter {
//
// public int getLastPage(int pagesize) {
// return 100;
// } //can't be retrieved
//
// public ForumListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList) {
// super(context, textViewResourceId, rowDataList);
// svNumPosts = Integer.MAX_VALUE; //can't be computed
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// ForumViewHolder holder = new ForumViewHolder();
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.twolined_listentry, parent, false);
//
// holder.populate(position, convertView, list.get(position));
//
// return convertView;
// }
// }
// Path: src/main/java/de/e621/rebane/activities/ForumsActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.view.View;
import com.itwookie.XMLreader.XMLNode;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.ForumListAdapter;
package de.e621.rebane.activities;
/** with what little information is returned by the forum API I won't continue that for now */
public class ForumsActivity extends PaginatedListActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
final static String FORUMQUERYPAGE = "a621 SearchManager Forum Page";
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paginated_list);
postLayoutInflated(this.getClass());
}*/
@Override
@SuppressLint("MissingSuperCall")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(R.layout.content_paginated_list, savedInstanceState);
//setContentView(R.layout.activity_posts);
postLayoutInflated(this.getClass());
}
@Override void setPagesize() {
pagesize = 30; //given by API
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt(FORUMQUERYPAGE, page);
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
page = intent.getIntExtra(FORUMQUERYPAGE,1);
if (results==null) searchPosts("", page);
}
@Override void searchPosts(String escapedQuery, int page) {
API_URI = "forum/index.xml?page="+page;
API_LOGIN = false;
super.searchPosts(escapedQuery, page);
}
@Override void onSearchResult(XMLNode result, String query, int page) {
| results = new ForumListAdapter(getApplicationContext(), R.id.lblTitle, result.getChildren());
|
rebane621/e621-android | src/main/java/de/e621/rebane/service/DMailService.java | // Path: src/main/java/de/e621/rebane/activities/DMailsActivity.java
// public class DMailsActivity extends PaginatedListActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
//
// final static String FORUMQUERYPAGE = "a621 SearchManager DMail Page";
//
// @Override
// @SuppressLint("MissingSuperCall")
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(R.layout.content_paginated_list, savedInstanceState);
// //setContentView(R.layout.activity_paginated_list);
// postLayoutInflated(this.getClass());
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.dmails, menu);
// this.menu = menu;
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_mark_all_read) {
// new AsyncTask<String, Void, Void>() {
// @Override protected Void doInBackground(String... args) {
// try {
// HttpURLConnection urlc = (HttpURLConnection) new URL(args[0]).openConnection();
// urlc.addRequestProperty("User-Agent", args[1]);
// urlc.getContentLength();
// } catch (Exception e) {
// }
// return null;
// }
// }.execute(database.getValue(SettingsActivity.SETTINGBASEURL) + "dmail/mark_all_read", getApplicationContext().getString(R.string.requestUserAgent));
// Toast.makeText(getApplicationContext(), getString(R.string.dmail_response_markedall), Toast.LENGTH_LONG).show();
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// @Override void setPagesize() {
// pagesize = 30; //given by API
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState){
// super.onSaveInstanceState(outState);
// outState.putInt(FORUMQUERYPAGE, page);
// }
//
// @Override
// void handleIntent(Intent intent) {
// super.handleIntent(intent);
// page = intent.getIntExtra(FORUMQUERYPAGE,1);
//
// if (results==null) searchPosts("", page);
// }
//
// @Override void searchPosts(String escapedQuery, int page) {
// API_URI = "dmail/inbox.xml?page="+page;
// API_LOGIN = true;
//
// super.searchPosts(escapedQuery, page);
// }
//
// @Override void onSearchResult(XMLNode result, String query, int page) {
// results = new DMailListAdapter(getApplicationContext(), R.id.lblTitle, result.getChildren());
// //results.svNumPosts = (result.attributes().contains("count") ? Integer.valueOf(result.getAttribute("count")) : 0); //this value is not provided
// DMailsActivity.this.page = page;
//
// ActionBar ab = getSupportActionBar();
// ab.setTitle(getResources().getString(R.string.title_dmail) + " | " + page);
// //setTitle(getResources().getString(R.string.title_posts) + " " + _page + (_query.equals("")?" | *":" | "+XMLUtils.unescapeXML(_query)));
// }
//
// }
| import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.itwookie.XMLreader.XMLNode;
import com.itwookie.XMLreader.XMLReader;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import de.e621.rebane.a621.R;
import de.e621.rebane.activities.DMailsActivity;
| urlc.setRequestMethod("GET");
urlc.setChunkedStreamingMode(256);
urlc.setConnectTimeout(15000);
urlc.setReadTimeout(15000);
urlc.setUseCaches(false);
InputStream bis = urlc.getInputStream();
Logger.getLogger("a621").info("Background - Connected with response code " + urlc.getResponseCode() + ": " + urlc.getResponseMessage());
result = (new XMLReader()).parse(bis);
} catch (Exception e) {
e.printStackTrace();
}
if (result != null) {
int cnt = 0;
StringBuilder cont = new StringBuilder();
for (XMLNode msg : result.getChildren()) {
if (!msg.getType().equals("dmail")) {
cnt = 0;
break;
}
//Logger.getLogger("a621").info ("DMail: " + msg.toString());
Boolean seen = Boolean.parseBoolean(msg.getFirstChildContent("has-seen").orElse(""));
if (!seen) {
cnt++;
cont.append(msg.getFirstChildContent("title").orElse("") + " \n");
}
}
if (cnt > 0) {
NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
| // Path: src/main/java/de/e621/rebane/activities/DMailsActivity.java
// public class DMailsActivity extends PaginatedListActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
//
// final static String FORUMQUERYPAGE = "a621 SearchManager DMail Page";
//
// @Override
// @SuppressLint("MissingSuperCall")
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(R.layout.content_paginated_list, savedInstanceState);
// //setContentView(R.layout.activity_paginated_list);
// postLayoutInflated(this.getClass());
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.dmails, menu);
// this.menu = menu;
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_mark_all_read) {
// new AsyncTask<String, Void, Void>() {
// @Override protected Void doInBackground(String... args) {
// try {
// HttpURLConnection urlc = (HttpURLConnection) new URL(args[0]).openConnection();
// urlc.addRequestProperty("User-Agent", args[1]);
// urlc.getContentLength();
// } catch (Exception e) {
// }
// return null;
// }
// }.execute(database.getValue(SettingsActivity.SETTINGBASEURL) + "dmail/mark_all_read", getApplicationContext().getString(R.string.requestUserAgent));
// Toast.makeText(getApplicationContext(), getString(R.string.dmail_response_markedall), Toast.LENGTH_LONG).show();
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// @Override void setPagesize() {
// pagesize = 30; //given by API
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState){
// super.onSaveInstanceState(outState);
// outState.putInt(FORUMQUERYPAGE, page);
// }
//
// @Override
// void handleIntent(Intent intent) {
// super.handleIntent(intent);
// page = intent.getIntExtra(FORUMQUERYPAGE,1);
//
// if (results==null) searchPosts("", page);
// }
//
// @Override void searchPosts(String escapedQuery, int page) {
// API_URI = "dmail/inbox.xml?page="+page;
// API_LOGIN = true;
//
// super.searchPosts(escapedQuery, page);
// }
//
// @Override void onSearchResult(XMLNode result, String query, int page) {
// results = new DMailListAdapter(getApplicationContext(), R.id.lblTitle, result.getChildren());
// //results.svNumPosts = (result.attributes().contains("count") ? Integer.valueOf(result.getAttribute("count")) : 0); //this value is not provided
// DMailsActivity.this.page = page;
//
// ActionBar ab = getSupportActionBar();
// ab.setTitle(getResources().getString(R.string.title_dmail) + " | " + page);
// //setTitle(getResources().getString(R.string.title_posts) + " " + _page + (_query.equals("")?" | *":" | "+XMLUtils.unescapeXML(_query)));
// }
//
// }
// Path: src/main/java/de/e621/rebane/service/DMailService.java
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.itwookie.XMLreader.XMLNode;
import com.itwookie.XMLreader.XMLReader;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import de.e621.rebane.a621.R;
import de.e621.rebane.activities.DMailsActivity;
urlc.setRequestMethod("GET");
urlc.setChunkedStreamingMode(256);
urlc.setConnectTimeout(15000);
urlc.setReadTimeout(15000);
urlc.setUseCaches(false);
InputStream bis = urlc.getInputStream();
Logger.getLogger("a621").info("Background - Connected with response code " + urlc.getResponseCode() + ": " + urlc.getResponseMessage());
result = (new XMLReader()).parse(bis);
} catch (Exception e) {
e.printStackTrace();
}
if (result != null) {
int cnt = 0;
StringBuilder cont = new StringBuilder();
for (XMLNode msg : result.getChildren()) {
if (!msg.getType().equals("dmail")) {
cnt = 0;
break;
}
//Logger.getLogger("a621").info ("DMail: " + msg.toString());
Boolean seen = Boolean.parseBoolean(msg.getFirstChildContent("has-seen").orElse(""));
if (!seen) {
cnt++;
cont.append(msg.getFirstChildContent("title").orElse("") + " \n");
}
}
if (cnt > 0) {
NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
| Intent dmail = new Intent(getApplicationContext(), DMailsActivity.class);
|
rebane621/e621-android | src/main/java/de/e621/rebane/activities/PoolsActivity.java | // Path: src/main/java/de/e621/rebane/components/listadapter/CoverListAdapter.java
// public class CoverListAdapter extends XMLListAdapter {
//
// public int getLastPage(int pagesize) {
// return Integer.MAX_VALUE;
// } //can't be retrieved
// String listType;
//
// public CoverListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList, String quality, String type) {
// super(context, textViewResourceId, rowDataList);
// listType = type;
// svNumPosts = Integer.MAX_VALUE; //can't be computed
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// CoverViewHolder holder = new CoverViewHolder();
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.cover_layout, parent, false);
//
// holder.populate(position, convertView, list.get(position), listType);
//
// return convertView;
// }
// }
| import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.itwookie.XMLreader.XMLNode;
import java.net.URLDecoder;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.CoverListAdapter;
| package de.e621.rebane.activities;
public class PoolsActivity extends PaginatedListActivity
implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
Menu menu = null;
@Override
@SuppressLint("MissingSuperCall")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(R.layout.content_cover_list, savedInstanceState);
//setContentView(R.layout.activity_posts);
postLayoutInflated(this.getClass());
}
void setPagesize() {
pagesize=20; //hardcoded
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
//page = intent.getIntExtra(SEARCHQUERYPAGE,1); //done by super
if (!Intent.ACTION_SEARCH.equals(intent.getAction())) { //true case handled by super
query = "";
}
if (results==null) searchPosts(query, page);
}
@Override
void searchPosts(String escapedQuery, int page) {
API_URI = "pool/index.xml?query="+escapedQuery+"&page="+ page;
API_LOGIN = false; //for vote meta search
super.searchPosts(escapedQuery, page);
}
void onSearchResult(XMLNode result, String query, int page) {
openDB();
String quality = database.getValue(SettingsActivity.SETTINGPREVIEWQUALITY); //i would really like to display thumbnails, a bit like a bookshelf
| // Path: src/main/java/de/e621/rebane/components/listadapter/CoverListAdapter.java
// public class CoverListAdapter extends XMLListAdapter {
//
// public int getLastPage(int pagesize) {
// return Integer.MAX_VALUE;
// } //can't be retrieved
// String listType;
//
// public CoverListAdapter(Context context, int textViewResourceId, List<XMLNode> rowDataList, String quality, String type) {
// super(context, textViewResourceId, rowDataList);
// listType = type;
// svNumPosts = Integer.MAX_VALUE; //can't be computed
// }
//
// public View getView(final int position, View convertView, ViewGroup parent) {
// CoverViewHolder holder = new CoverViewHolder();
//
// LayoutInflater inflator = LayoutInflater.from(parent.getContext());
// convertView = inflator.inflate(R.layout.cover_layout, parent, false);
//
// holder.populate(position, convertView, list.get(position), listType);
//
// return convertView;
// }
// }
// Path: src/main/java/de/e621/rebane/activities/PoolsActivity.java
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.itwookie.XMLreader.XMLNode;
import java.net.URLDecoder;
import de.e621.rebane.a621.R;
import de.e621.rebane.components.listadapter.CoverListAdapter;
package de.e621.rebane.activities;
public class PoolsActivity extends PaginatedListActivity
implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
Menu menu = null;
@Override
@SuppressLint("MissingSuperCall")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(R.layout.content_cover_list, savedInstanceState);
//setContentView(R.layout.activity_posts);
postLayoutInflated(this.getClass());
}
void setPagesize() {
pagesize=20; //hardcoded
}
@Override
void handleIntent(Intent intent) {
super.handleIntent(intent);
//page = intent.getIntExtra(SEARCHQUERYPAGE,1); //done by super
if (!Intent.ACTION_SEARCH.equals(intent.getAction())) { //true case handled by super
query = "";
}
if (results==null) searchPosts(query, page);
}
@Override
void searchPosts(String escapedQuery, int page) {
API_URI = "pool/index.xml?query="+escapedQuery+"&page="+ page;
API_LOGIN = false; //for vote meta search
super.searchPosts(escapedQuery, page);
}
void onSearchResult(XMLNode result, String query, int page) {
openDB();
String quality = database.getValue(SettingsActivity.SETTINGPREVIEWQUALITY); //i would really like to display thumbnails, a bit like a bookshelf
| results = new CoverListAdapter(this, R.id.txtMid, result.getChildren(), quality, "pool");
|
rbrick/Mojo | Core/src/test/java/me/rbrickis/test/Server.java | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/DispatchException.java
// public class DispatchException extends Exception {
//
// public DispatchException(String msg) {
// super(msg);
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/Dispatcher.java
// public interface Dispatcher<S> {
//
// boolean dispatch(String commandName, S sender, Arguments arguments) throws DispatchException;
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
// public class CommandGraph {
//
// private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>();
// private ParametricRegistry registry = new ParametricRegistry();
// private Class<? extends Annotation> b = null;
//
// public CommandGraph useSender(Class<?> clazz) {
// senderMap.put(Command.class, clazz);
// return this;
// }
//
// public CommandGraph unlessMarkedWith(Class<? extends Annotation> clazz) {
// this.b = clazz;
// return this;
// }
//
// public CommandGraph thenUseSender(Class<?> clazz) {
// if (b == null) {
// throw new IllegalArgumentException("b is null!");
// }
// senderMap.put(b, clazz);
// b = null;
// return this;
// }
//
// public CommandGraph withParametricRegistry(ParametricRegistry registry) {
// this.registry = registry;
// return this;
// }
//
//
// public ParametricRegistry getRegistry() {
// return registry;
// }
//
// public Class<?> getSender(Class<? extends Annotation> annotation) {
// Class<?> found = null;
// for (Class<? extends Annotation> a : senderMap.keySet()) {
// if (a == annotation) {
// found = senderMap.get(a);
// }
// }
// return found;
// }
//
// public Class<?> getSenderForMethod(Method method, Class<?> defaultType) {
// Class<?> found = null;
// if (method.isAnnotationPresent(Command.class)) {
// for (Annotation annotation : method.getAnnotations()) {
// if (annotation.annotationType() != Command.class && senderMap
// .containsKey(annotation.annotationType())) {
// found = senderMap.get(annotation.annotationType());
// }
// }
// }
// if (found == null) {
// return defaultType;
// }
// return found;
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
| import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.dispatcher.DispatchException;
import me.rbrickis.mojo.dispatcher.Dispatcher;
import me.rbrickis.mojo.parametric.graph.CommandGraph;
import me.rbrickis.mojo.registry.CommandRegistry;
import java.util.Arrays;
import java.util.Collections; | package me.rbrickis.test;
public class Server {
public static void main(String... args) throws DispatchException { | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/DispatchException.java
// public class DispatchException extends Exception {
//
// public DispatchException(String msg) {
// super(msg);
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/Dispatcher.java
// public interface Dispatcher<S> {
//
// boolean dispatch(String commandName, S sender, Arguments arguments) throws DispatchException;
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
// public class CommandGraph {
//
// private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>();
// private ParametricRegistry registry = new ParametricRegistry();
// private Class<? extends Annotation> b = null;
//
// public CommandGraph useSender(Class<?> clazz) {
// senderMap.put(Command.class, clazz);
// return this;
// }
//
// public CommandGraph unlessMarkedWith(Class<? extends Annotation> clazz) {
// this.b = clazz;
// return this;
// }
//
// public CommandGraph thenUseSender(Class<?> clazz) {
// if (b == null) {
// throw new IllegalArgumentException("b is null!");
// }
// senderMap.put(b, clazz);
// b = null;
// return this;
// }
//
// public CommandGraph withParametricRegistry(ParametricRegistry registry) {
// this.registry = registry;
// return this;
// }
//
//
// public ParametricRegistry getRegistry() {
// return registry;
// }
//
// public Class<?> getSender(Class<? extends Annotation> annotation) {
// Class<?> found = null;
// for (Class<? extends Annotation> a : senderMap.keySet()) {
// if (a == annotation) {
// found = senderMap.get(a);
// }
// }
// return found;
// }
//
// public Class<?> getSenderForMethod(Method method, Class<?> defaultType) {
// Class<?> found = null;
// if (method.isAnnotationPresent(Command.class)) {
// for (Annotation annotation : method.getAnnotations()) {
// if (annotation.annotationType() != Command.class && senderMap
// .containsKey(annotation.annotationType())) {
// found = senderMap.get(annotation.annotationType());
// }
// }
// }
// if (found == null) {
// return defaultType;
// }
// return found;
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
// Path: Core/src/test/java/me/rbrickis/test/Server.java
import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.dispatcher.DispatchException;
import me.rbrickis.mojo.dispatcher.Dispatcher;
import me.rbrickis.mojo.parametric.graph.CommandGraph;
import me.rbrickis.mojo.registry.CommandRegistry;
import java.util.Arrays;
import java.util.Collections;
package me.rbrickis.test;
public class Server {
public static void main(String... args) throws DispatchException { | CommandGraph graph = new CommandGraph() |
rbrick/Mojo | Core/src/test/java/me/rbrickis/test/Server.java | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/DispatchException.java
// public class DispatchException extends Exception {
//
// public DispatchException(String msg) {
// super(msg);
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/Dispatcher.java
// public interface Dispatcher<S> {
//
// boolean dispatch(String commandName, S sender, Arguments arguments) throws DispatchException;
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
// public class CommandGraph {
//
// private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>();
// private ParametricRegistry registry = new ParametricRegistry();
// private Class<? extends Annotation> b = null;
//
// public CommandGraph useSender(Class<?> clazz) {
// senderMap.put(Command.class, clazz);
// return this;
// }
//
// public CommandGraph unlessMarkedWith(Class<? extends Annotation> clazz) {
// this.b = clazz;
// return this;
// }
//
// public CommandGraph thenUseSender(Class<?> clazz) {
// if (b == null) {
// throw new IllegalArgumentException("b is null!");
// }
// senderMap.put(b, clazz);
// b = null;
// return this;
// }
//
// public CommandGraph withParametricRegistry(ParametricRegistry registry) {
// this.registry = registry;
// return this;
// }
//
//
// public ParametricRegistry getRegistry() {
// return registry;
// }
//
// public Class<?> getSender(Class<? extends Annotation> annotation) {
// Class<?> found = null;
// for (Class<? extends Annotation> a : senderMap.keySet()) {
// if (a == annotation) {
// found = senderMap.get(a);
// }
// }
// return found;
// }
//
// public Class<?> getSenderForMethod(Method method, Class<?> defaultType) {
// Class<?> found = null;
// if (method.isAnnotationPresent(Command.class)) {
// for (Annotation annotation : method.getAnnotations()) {
// if (annotation.annotationType() != Command.class && senderMap
// .containsKey(annotation.annotationType())) {
// found = senderMap.get(annotation.annotationType());
// }
// }
// }
// if (found == null) {
// return defaultType;
// }
// return found;
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
| import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.dispatcher.DispatchException;
import me.rbrickis.mojo.dispatcher.Dispatcher;
import me.rbrickis.mojo.parametric.graph.CommandGraph;
import me.rbrickis.mojo.registry.CommandRegistry;
import java.util.Arrays;
import java.util.Collections; | package me.rbrickis.test;
public class Server {
public static void main(String... args) throws DispatchException {
CommandGraph graph = new CommandGraph()
.useSender(Actor.class);
Actor sender = new Actor("System", 18);
| // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/DispatchException.java
// public class DispatchException extends Exception {
//
// public DispatchException(String msg) {
// super(msg);
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/Dispatcher.java
// public interface Dispatcher<S> {
//
// boolean dispatch(String commandName, S sender, Arguments arguments) throws DispatchException;
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
// public class CommandGraph {
//
// private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>();
// private ParametricRegistry registry = new ParametricRegistry();
// private Class<? extends Annotation> b = null;
//
// public CommandGraph useSender(Class<?> clazz) {
// senderMap.put(Command.class, clazz);
// return this;
// }
//
// public CommandGraph unlessMarkedWith(Class<? extends Annotation> clazz) {
// this.b = clazz;
// return this;
// }
//
// public CommandGraph thenUseSender(Class<?> clazz) {
// if (b == null) {
// throw new IllegalArgumentException("b is null!");
// }
// senderMap.put(b, clazz);
// b = null;
// return this;
// }
//
// public CommandGraph withParametricRegistry(ParametricRegistry registry) {
// this.registry = registry;
// return this;
// }
//
//
// public ParametricRegistry getRegistry() {
// return registry;
// }
//
// public Class<?> getSender(Class<? extends Annotation> annotation) {
// Class<?> found = null;
// for (Class<? extends Annotation> a : senderMap.keySet()) {
// if (a == annotation) {
// found = senderMap.get(a);
// }
// }
// return found;
// }
//
// public Class<?> getSenderForMethod(Method method, Class<?> defaultType) {
// Class<?> found = null;
// if (method.isAnnotationPresent(Command.class)) {
// for (Annotation annotation : method.getAnnotations()) {
// if (annotation.annotationType() != Command.class && senderMap
// .containsKey(annotation.annotationType())) {
// found = senderMap.get(annotation.annotationType());
// }
// }
// }
// if (found == null) {
// return defaultType;
// }
// return found;
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
// Path: Core/src/test/java/me/rbrickis/test/Server.java
import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.dispatcher.DispatchException;
import me.rbrickis.mojo.dispatcher.Dispatcher;
import me.rbrickis.mojo.parametric.graph.CommandGraph;
import me.rbrickis.mojo.registry.CommandRegistry;
import java.util.Arrays;
import java.util.Collections;
package me.rbrickis.test;
public class Server {
public static void main(String... args) throws DispatchException {
CommandGraph graph = new CommandGraph()
.useSender(Actor.class);
Actor sender = new Actor("System", 18);
| CommandRegistry registry = new TestCommandRegistry(graph); |
rbrick/Mojo | Core/src/test/java/me/rbrickis/test/Server.java | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/DispatchException.java
// public class DispatchException extends Exception {
//
// public DispatchException(String msg) {
// super(msg);
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/Dispatcher.java
// public interface Dispatcher<S> {
//
// boolean dispatch(String commandName, S sender, Arguments arguments) throws DispatchException;
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
// public class CommandGraph {
//
// private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>();
// private ParametricRegistry registry = new ParametricRegistry();
// private Class<? extends Annotation> b = null;
//
// public CommandGraph useSender(Class<?> clazz) {
// senderMap.put(Command.class, clazz);
// return this;
// }
//
// public CommandGraph unlessMarkedWith(Class<? extends Annotation> clazz) {
// this.b = clazz;
// return this;
// }
//
// public CommandGraph thenUseSender(Class<?> clazz) {
// if (b == null) {
// throw new IllegalArgumentException("b is null!");
// }
// senderMap.put(b, clazz);
// b = null;
// return this;
// }
//
// public CommandGraph withParametricRegistry(ParametricRegistry registry) {
// this.registry = registry;
// return this;
// }
//
//
// public ParametricRegistry getRegistry() {
// return registry;
// }
//
// public Class<?> getSender(Class<? extends Annotation> annotation) {
// Class<?> found = null;
// for (Class<? extends Annotation> a : senderMap.keySet()) {
// if (a == annotation) {
// found = senderMap.get(a);
// }
// }
// return found;
// }
//
// public Class<?> getSenderForMethod(Method method, Class<?> defaultType) {
// Class<?> found = null;
// if (method.isAnnotationPresent(Command.class)) {
// for (Annotation annotation : method.getAnnotations()) {
// if (annotation.annotationType() != Command.class && senderMap
// .containsKey(annotation.annotationType())) {
// found = senderMap.get(annotation.annotationType());
// }
// }
// }
// if (found == null) {
// return defaultType;
// }
// return found;
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
| import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.dispatcher.DispatchException;
import me.rbrickis.mojo.dispatcher.Dispatcher;
import me.rbrickis.mojo.parametric.graph.CommandGraph;
import me.rbrickis.mojo.registry.CommandRegistry;
import java.util.Arrays;
import java.util.Collections; | package me.rbrickis.test;
public class Server {
public static void main(String... args) throws DispatchException {
CommandGraph graph = new CommandGraph()
.useSender(Actor.class);
Actor sender = new Actor("System", 18);
CommandRegistry registry = new TestCommandRegistry(graph);
registry.registerClass(TestCommands.class);
| // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/DispatchException.java
// public class DispatchException extends Exception {
//
// public DispatchException(String msg) {
// super(msg);
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/Dispatcher.java
// public interface Dispatcher<S> {
//
// boolean dispatch(String commandName, S sender, Arguments arguments) throws DispatchException;
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
// public class CommandGraph {
//
// private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>();
// private ParametricRegistry registry = new ParametricRegistry();
// private Class<? extends Annotation> b = null;
//
// public CommandGraph useSender(Class<?> clazz) {
// senderMap.put(Command.class, clazz);
// return this;
// }
//
// public CommandGraph unlessMarkedWith(Class<? extends Annotation> clazz) {
// this.b = clazz;
// return this;
// }
//
// public CommandGraph thenUseSender(Class<?> clazz) {
// if (b == null) {
// throw new IllegalArgumentException("b is null!");
// }
// senderMap.put(b, clazz);
// b = null;
// return this;
// }
//
// public CommandGraph withParametricRegistry(ParametricRegistry registry) {
// this.registry = registry;
// return this;
// }
//
//
// public ParametricRegistry getRegistry() {
// return registry;
// }
//
// public Class<?> getSender(Class<? extends Annotation> annotation) {
// Class<?> found = null;
// for (Class<? extends Annotation> a : senderMap.keySet()) {
// if (a == annotation) {
// found = senderMap.get(a);
// }
// }
// return found;
// }
//
// public Class<?> getSenderForMethod(Method method, Class<?> defaultType) {
// Class<?> found = null;
// if (method.isAnnotationPresent(Command.class)) {
// for (Annotation annotation : method.getAnnotations()) {
// if (annotation.annotationType() != Command.class && senderMap
// .containsKey(annotation.annotationType())) {
// found = senderMap.get(annotation.annotationType());
// }
// }
// }
// if (found == null) {
// return defaultType;
// }
// return found;
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
// Path: Core/src/test/java/me/rbrickis/test/Server.java
import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.dispatcher.DispatchException;
import me.rbrickis.mojo.dispatcher.Dispatcher;
import me.rbrickis.mojo.parametric.graph.CommandGraph;
import me.rbrickis.mojo.registry.CommandRegistry;
import java.util.Arrays;
import java.util.Collections;
package me.rbrickis.test;
public class Server {
public static void main(String... args) throws DispatchException {
CommandGraph graph = new CommandGraph()
.useSender(Actor.class);
Actor sender = new Actor("System", 18);
CommandRegistry registry = new TestCommandRegistry(graph);
registry.registerClass(TestCommands.class);
| Dispatcher<Actor> dispatcher = new TestDispatcher(registry); |
rbrick/Mojo | Core/src/test/java/me/rbrickis/test/Server.java | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/DispatchException.java
// public class DispatchException extends Exception {
//
// public DispatchException(String msg) {
// super(msg);
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/Dispatcher.java
// public interface Dispatcher<S> {
//
// boolean dispatch(String commandName, S sender, Arguments arguments) throws DispatchException;
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
// public class CommandGraph {
//
// private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>();
// private ParametricRegistry registry = new ParametricRegistry();
// private Class<? extends Annotation> b = null;
//
// public CommandGraph useSender(Class<?> clazz) {
// senderMap.put(Command.class, clazz);
// return this;
// }
//
// public CommandGraph unlessMarkedWith(Class<? extends Annotation> clazz) {
// this.b = clazz;
// return this;
// }
//
// public CommandGraph thenUseSender(Class<?> clazz) {
// if (b == null) {
// throw new IllegalArgumentException("b is null!");
// }
// senderMap.put(b, clazz);
// b = null;
// return this;
// }
//
// public CommandGraph withParametricRegistry(ParametricRegistry registry) {
// this.registry = registry;
// return this;
// }
//
//
// public ParametricRegistry getRegistry() {
// return registry;
// }
//
// public Class<?> getSender(Class<? extends Annotation> annotation) {
// Class<?> found = null;
// for (Class<? extends Annotation> a : senderMap.keySet()) {
// if (a == annotation) {
// found = senderMap.get(a);
// }
// }
// return found;
// }
//
// public Class<?> getSenderForMethod(Method method, Class<?> defaultType) {
// Class<?> found = null;
// if (method.isAnnotationPresent(Command.class)) {
// for (Annotation annotation : method.getAnnotations()) {
// if (annotation.annotationType() != Command.class && senderMap
// .containsKey(annotation.annotationType())) {
// found = senderMap.get(annotation.annotationType());
// }
// }
// }
// if (found == null) {
// return defaultType;
// }
// return found;
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
| import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.dispatcher.DispatchException;
import me.rbrickis.mojo.dispatcher.Dispatcher;
import me.rbrickis.mojo.parametric.graph.CommandGraph;
import me.rbrickis.mojo.registry.CommandRegistry;
import java.util.Arrays;
import java.util.Collections; | package me.rbrickis.test;
public class Server {
public static void main(String... args) throws DispatchException {
CommandGraph graph = new CommandGraph()
.useSender(Actor.class);
Actor sender = new Actor("System", 18);
CommandRegistry registry = new TestCommandRegistry(graph);
registry.registerClass(TestCommands.class);
Dispatcher<Actor> dispatcher = new TestDispatcher(registry);
// no args in method (doesn't matter what is provided, it will always execute the code) | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/DispatchException.java
// public class DispatchException extends Exception {
//
// public DispatchException(String msg) {
// super(msg);
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/dispatcher/Dispatcher.java
// public interface Dispatcher<S> {
//
// boolean dispatch(String commandName, S sender, Arguments arguments) throws DispatchException;
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
// public class CommandGraph {
//
// private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>();
// private ParametricRegistry registry = new ParametricRegistry();
// private Class<? extends Annotation> b = null;
//
// public CommandGraph useSender(Class<?> clazz) {
// senderMap.put(Command.class, clazz);
// return this;
// }
//
// public CommandGraph unlessMarkedWith(Class<? extends Annotation> clazz) {
// this.b = clazz;
// return this;
// }
//
// public CommandGraph thenUseSender(Class<?> clazz) {
// if (b == null) {
// throw new IllegalArgumentException("b is null!");
// }
// senderMap.put(b, clazz);
// b = null;
// return this;
// }
//
// public CommandGraph withParametricRegistry(ParametricRegistry registry) {
// this.registry = registry;
// return this;
// }
//
//
// public ParametricRegistry getRegistry() {
// return registry;
// }
//
// public Class<?> getSender(Class<? extends Annotation> annotation) {
// Class<?> found = null;
// for (Class<? extends Annotation> a : senderMap.keySet()) {
// if (a == annotation) {
// found = senderMap.get(a);
// }
// }
// return found;
// }
//
// public Class<?> getSenderForMethod(Method method, Class<?> defaultType) {
// Class<?> found = null;
// if (method.isAnnotationPresent(Command.class)) {
// for (Annotation annotation : method.getAnnotations()) {
// if (annotation.annotationType() != Command.class && senderMap
// .containsKey(annotation.annotationType())) {
// found = senderMap.get(annotation.annotationType());
// }
// }
// }
// if (found == null) {
// return defaultType;
// }
// return found;
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
// Path: Core/src/test/java/me/rbrickis/test/Server.java
import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.dispatcher.DispatchException;
import me.rbrickis.mojo.dispatcher.Dispatcher;
import me.rbrickis.mojo.parametric.graph.CommandGraph;
import me.rbrickis.mojo.registry.CommandRegistry;
import java.util.Arrays;
import java.util.Collections;
package me.rbrickis.test;
public class Server {
public static void main(String... args) throws DispatchException {
CommandGraph graph = new CommandGraph()
.useSender(Actor.class);
Actor sender = new Actor("System", 18);
CommandRegistry registry = new TestCommandRegistry(graph);
registry.registerClass(TestCommands.class);
Dispatcher<Actor> dispatcher = new TestDispatcher(registry);
// no args in method (doesn't matter what is provided, it will always execute the code) | dispatcher.dispatch("help", sender, new Arguments(Arrays.asList("Blah", "blah", "bal"))); |
rbrick/Mojo | Bukkit/src/main/java/me/rbrickis/mojo/bukkit/ExamplePlugin.java | // Path: Bukkit/src/main/java/me/rbrickis/mojo/bukkit/command/BukkitCommandRegistry.java
// public class BukkitCommandRegistry implements CommandRegistry {
//
// // Commands that we have registered ourselves.
// private Map<String, CommandHolder> ourCommands = new HashMap<>();
//
// private CommandGraph commandGraph;
//
// private SimpleCommandMap commandMap = Reflection.getSafeClass(Bukkit.getServer().getPluginManager())
// .<SimpleCommandMap>getField("commandMap").get();
//
// private HashMap<String, org.bukkit.command.Command> knownCommands = Reflection.getSafeClass(commandMap).
// <HashMap<String, org.bukkit.command.Command>>getField("knownCommands").get();
//
//
// private JavaPlugin parent;
//
// public BukkitCommandRegistry(JavaPlugin plugin) {
// this(new CommandGraph()
// .useSender(CommandSender.class)
// .unlessMarkedWith(Player.class)
// .thenUseSender(org.bukkit.entity.Player.class)
// .withParametricRegistry(new BukkitParametricRegistry()), plugin);
// }
//
// public BukkitCommandRegistry(CommandGraph graph, JavaPlugin plugin) {
// this.commandGraph = graph;
// this.parent = plugin;
// }
//
// public void registerCommand(CommandHolder command) {
// ourCommands.put(command.getName(), command);
// for (String alias : command.getAliases()) {
// ourCommands.put(alias, command);
// }
//
// if (knownCommands.containsKey(command.getName().toLowerCase())) {
// knownCommands.remove(command.getName());
// Reflection.getSafeClass(commandMap).getField("knownCommands").set(knownCommands);
// }
// commandMap.register(parent.getName(), new WrappedCommand(command));
//
// for (String alias : command.getAliases()) {
// if (knownCommands.containsKey(alias.toLowerCase())) {
// knownCommands.remove(alias.toLowerCase());
// Reflection.getSafeClass(commandMap).getField("knownCommands").set(knownCommands);
// }
// commandMap.register(parent.getName(), new WrappedCommand(command));
// }
//
// }
//
// @Override
// public void registerObject(Object object) {
// for (Method method : object.getClass().getMethods()) {
// if (method.isAnnotationPresent(Command.class)) {
// registerCommand(new CommandHolder(method, commandGraph.getRegistry(), commandGraph.getSenderForMethod(method, commandGraph.getSender(Command.class))));
// }
// }
// }
//
// @Override
// public void registerClass(Class<?> clazz) {
// try {
// Object object = clazz.newInstance();
// registerObject(object);
// } catch (InstantiationException | IllegalAccessException e) {
// throw new IllegalArgumentException("Unable to instantiate the class!");
// }
// }
//
// @Override
// public CommandHolder get(String alias) {
// CommandHolder h = null;
// for (String a : ourCommands.keySet()) {
// if (a.equalsIgnoreCase(alias)) {
// h = ourCommands.get(a);
// }
// }
// return h;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
| import me.rbrickis.mojo.bukkit.command.BukkitCommandRegistry;
import me.rbrickis.mojo.registry.CommandRegistry;
import org.bukkit.plugin.java.JavaPlugin; | package me.rbrickis.mojo.bukkit;
public class ExamplePlugin extends JavaPlugin {
@Override
public void onEnable() { | // Path: Bukkit/src/main/java/me/rbrickis/mojo/bukkit/command/BukkitCommandRegistry.java
// public class BukkitCommandRegistry implements CommandRegistry {
//
// // Commands that we have registered ourselves.
// private Map<String, CommandHolder> ourCommands = new HashMap<>();
//
// private CommandGraph commandGraph;
//
// private SimpleCommandMap commandMap = Reflection.getSafeClass(Bukkit.getServer().getPluginManager())
// .<SimpleCommandMap>getField("commandMap").get();
//
// private HashMap<String, org.bukkit.command.Command> knownCommands = Reflection.getSafeClass(commandMap).
// <HashMap<String, org.bukkit.command.Command>>getField("knownCommands").get();
//
//
// private JavaPlugin parent;
//
// public BukkitCommandRegistry(JavaPlugin plugin) {
// this(new CommandGraph()
// .useSender(CommandSender.class)
// .unlessMarkedWith(Player.class)
// .thenUseSender(org.bukkit.entity.Player.class)
// .withParametricRegistry(new BukkitParametricRegistry()), plugin);
// }
//
// public BukkitCommandRegistry(CommandGraph graph, JavaPlugin plugin) {
// this.commandGraph = graph;
// this.parent = plugin;
// }
//
// public void registerCommand(CommandHolder command) {
// ourCommands.put(command.getName(), command);
// for (String alias : command.getAliases()) {
// ourCommands.put(alias, command);
// }
//
// if (knownCommands.containsKey(command.getName().toLowerCase())) {
// knownCommands.remove(command.getName());
// Reflection.getSafeClass(commandMap).getField("knownCommands").set(knownCommands);
// }
// commandMap.register(parent.getName(), new WrappedCommand(command));
//
// for (String alias : command.getAliases()) {
// if (knownCommands.containsKey(alias.toLowerCase())) {
// knownCommands.remove(alias.toLowerCase());
// Reflection.getSafeClass(commandMap).getField("knownCommands").set(knownCommands);
// }
// commandMap.register(parent.getName(), new WrappedCommand(command));
// }
//
// }
//
// @Override
// public void registerObject(Object object) {
// for (Method method : object.getClass().getMethods()) {
// if (method.isAnnotationPresent(Command.class)) {
// registerCommand(new CommandHolder(method, commandGraph.getRegistry(), commandGraph.getSenderForMethod(method, commandGraph.getSender(Command.class))));
// }
// }
// }
//
// @Override
// public void registerClass(Class<?> clazz) {
// try {
// Object object = clazz.newInstance();
// registerObject(object);
// } catch (InstantiationException | IllegalAccessException e) {
// throw new IllegalArgumentException("Unable to instantiate the class!");
// }
// }
//
// @Override
// public CommandHolder get(String alias) {
// CommandHolder h = null;
// for (String a : ourCommands.keySet()) {
// if (a.equalsIgnoreCase(alias)) {
// h = ourCommands.get(a);
// }
// }
// return h;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
// Path: Bukkit/src/main/java/me/rbrickis/mojo/bukkit/ExamplePlugin.java
import me.rbrickis.mojo.bukkit.command.BukkitCommandRegistry;
import me.rbrickis.mojo.registry.CommandRegistry;
import org.bukkit.plugin.java.JavaPlugin;
package me.rbrickis.mojo.bukkit;
public class ExamplePlugin extends JavaPlugin {
@Override
public void onEnable() { | CommandRegistry registry = new BukkitCommandRegistry(this); |
rbrick/Mojo | Bukkit/src/main/java/me/rbrickis/mojo/bukkit/ExamplePlugin.java | // Path: Bukkit/src/main/java/me/rbrickis/mojo/bukkit/command/BukkitCommandRegistry.java
// public class BukkitCommandRegistry implements CommandRegistry {
//
// // Commands that we have registered ourselves.
// private Map<String, CommandHolder> ourCommands = new HashMap<>();
//
// private CommandGraph commandGraph;
//
// private SimpleCommandMap commandMap = Reflection.getSafeClass(Bukkit.getServer().getPluginManager())
// .<SimpleCommandMap>getField("commandMap").get();
//
// private HashMap<String, org.bukkit.command.Command> knownCommands = Reflection.getSafeClass(commandMap).
// <HashMap<String, org.bukkit.command.Command>>getField("knownCommands").get();
//
//
// private JavaPlugin parent;
//
// public BukkitCommandRegistry(JavaPlugin plugin) {
// this(new CommandGraph()
// .useSender(CommandSender.class)
// .unlessMarkedWith(Player.class)
// .thenUseSender(org.bukkit.entity.Player.class)
// .withParametricRegistry(new BukkitParametricRegistry()), plugin);
// }
//
// public BukkitCommandRegistry(CommandGraph graph, JavaPlugin plugin) {
// this.commandGraph = graph;
// this.parent = plugin;
// }
//
// public void registerCommand(CommandHolder command) {
// ourCommands.put(command.getName(), command);
// for (String alias : command.getAliases()) {
// ourCommands.put(alias, command);
// }
//
// if (knownCommands.containsKey(command.getName().toLowerCase())) {
// knownCommands.remove(command.getName());
// Reflection.getSafeClass(commandMap).getField("knownCommands").set(knownCommands);
// }
// commandMap.register(parent.getName(), new WrappedCommand(command));
//
// for (String alias : command.getAliases()) {
// if (knownCommands.containsKey(alias.toLowerCase())) {
// knownCommands.remove(alias.toLowerCase());
// Reflection.getSafeClass(commandMap).getField("knownCommands").set(knownCommands);
// }
// commandMap.register(parent.getName(), new WrappedCommand(command));
// }
//
// }
//
// @Override
// public void registerObject(Object object) {
// for (Method method : object.getClass().getMethods()) {
// if (method.isAnnotationPresent(Command.class)) {
// registerCommand(new CommandHolder(method, commandGraph.getRegistry(), commandGraph.getSenderForMethod(method, commandGraph.getSender(Command.class))));
// }
// }
// }
//
// @Override
// public void registerClass(Class<?> clazz) {
// try {
// Object object = clazz.newInstance();
// registerObject(object);
// } catch (InstantiationException | IllegalAccessException e) {
// throw new IllegalArgumentException("Unable to instantiate the class!");
// }
// }
//
// @Override
// public CommandHolder get(String alias) {
// CommandHolder h = null;
// for (String a : ourCommands.keySet()) {
// if (a.equalsIgnoreCase(alias)) {
// h = ourCommands.get(a);
// }
// }
// return h;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
| import me.rbrickis.mojo.bukkit.command.BukkitCommandRegistry;
import me.rbrickis.mojo.registry.CommandRegistry;
import org.bukkit.plugin.java.JavaPlugin; | package me.rbrickis.mojo.bukkit;
public class ExamplePlugin extends JavaPlugin {
@Override
public void onEnable() { | // Path: Bukkit/src/main/java/me/rbrickis/mojo/bukkit/command/BukkitCommandRegistry.java
// public class BukkitCommandRegistry implements CommandRegistry {
//
// // Commands that we have registered ourselves.
// private Map<String, CommandHolder> ourCommands = new HashMap<>();
//
// private CommandGraph commandGraph;
//
// private SimpleCommandMap commandMap = Reflection.getSafeClass(Bukkit.getServer().getPluginManager())
// .<SimpleCommandMap>getField("commandMap").get();
//
// private HashMap<String, org.bukkit.command.Command> knownCommands = Reflection.getSafeClass(commandMap).
// <HashMap<String, org.bukkit.command.Command>>getField("knownCommands").get();
//
//
// private JavaPlugin parent;
//
// public BukkitCommandRegistry(JavaPlugin plugin) {
// this(new CommandGraph()
// .useSender(CommandSender.class)
// .unlessMarkedWith(Player.class)
// .thenUseSender(org.bukkit.entity.Player.class)
// .withParametricRegistry(new BukkitParametricRegistry()), plugin);
// }
//
// public BukkitCommandRegistry(CommandGraph graph, JavaPlugin plugin) {
// this.commandGraph = graph;
// this.parent = plugin;
// }
//
// public void registerCommand(CommandHolder command) {
// ourCommands.put(command.getName(), command);
// for (String alias : command.getAliases()) {
// ourCommands.put(alias, command);
// }
//
// if (knownCommands.containsKey(command.getName().toLowerCase())) {
// knownCommands.remove(command.getName());
// Reflection.getSafeClass(commandMap).getField("knownCommands").set(knownCommands);
// }
// commandMap.register(parent.getName(), new WrappedCommand(command));
//
// for (String alias : command.getAliases()) {
// if (knownCommands.containsKey(alias.toLowerCase())) {
// knownCommands.remove(alias.toLowerCase());
// Reflection.getSafeClass(commandMap).getField("knownCommands").set(knownCommands);
// }
// commandMap.register(parent.getName(), new WrappedCommand(command));
// }
//
// }
//
// @Override
// public void registerObject(Object object) {
// for (Method method : object.getClass().getMethods()) {
// if (method.isAnnotationPresent(Command.class)) {
// registerCommand(new CommandHolder(method, commandGraph.getRegistry(), commandGraph.getSenderForMethod(method, commandGraph.getSender(Command.class))));
// }
// }
// }
//
// @Override
// public void registerClass(Class<?> clazz) {
// try {
// Object object = clazz.newInstance();
// registerObject(object);
// } catch (InstantiationException | IllegalAccessException e) {
// throw new IllegalArgumentException("Unable to instantiate the class!");
// }
// }
//
// @Override
// public CommandHolder get(String alias) {
// CommandHolder h = null;
// for (String a : ourCommands.keySet()) {
// if (a.equalsIgnoreCase(alias)) {
// h = ourCommands.get(a);
// }
// }
// return h;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/registry/CommandRegistry.java
// public interface CommandRegistry {
//
// void registerCommand(CommandHolder holder);
//
// void registerObject(Object object);
//
// void registerClass(Class<?> clazz);
//
// CommandHolder get(String alias);
//
// }
// Path: Bukkit/src/main/java/me/rbrickis/mojo/bukkit/ExamplePlugin.java
import me.rbrickis.mojo.bukkit.command.BukkitCommandRegistry;
import me.rbrickis.mojo.registry.CommandRegistry;
import org.bukkit.plugin.java.JavaPlugin;
package me.rbrickis.mojo.bukkit;
public class ExamplePlugin extends JavaPlugin {
@Override
public void onEnable() { | CommandRegistry registry = new BukkitCommandRegistry(this); |
rbrick/Mojo | Core/src/test/java/me/rbrickis/test/WrappedCommand.java | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/command/CommandHolder.java
// public class CommandHolder {
//
// private String name;
// private String[] aliases;
// private String permission = "";
// private String permissionMessage = "";
// private ParametricRegistry registry;
// private Method method;
// private Class<?> senderType;
// private List<Parameter> parameters;
// private String usage;
// private String description;
//
// public CommandHolder(Method method, ParametricRegistry registry, Class<?> senderType) {
//
// Command command = method.getDeclaredAnnotation(Command.class);
// if (command.aliases().length == 0) {
// throw new IllegalArgumentException("Must have at least one alias!");
// } else {
// name = command.aliases()[0];
// List<String> laliases = new ArrayList<>();
// for (int i = 1; i < command.aliases().length; i++) {
// laliases.add(command.aliases()[i]);
// }
// this.aliases = laliases.toArray(new String[] {});
// }
// if (method.isAnnotationPresent(Require.class)) {
// this.permission = method.getAnnotation(Require.class).value();
// this.permissionMessage = method.getAnnotation(Require.class).message();
// }
//
// this.registry = registry;
// this.method = method;
// this.senderType = senderType;
// this.method.setAccessible(true);
// MethodParser parser = new MethodParser(method, registry);
// this.parameters = parser.parse();
// this.description = command.desc();
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getAliases() {
// return aliases;
// }
//
// public String getPermission() {
// return permission;
// }
//
// public String getPermissionMessage() {
// return permissionMessage;
// }
//
// public boolean isAnnotationPresent(Class<? extends Annotation> annotation) {
// boolean found = false;
// for (Annotation anno : method.getAnnotations()) {
// if (anno.annotationType() == annotation) {
// found = true;
// }
// }
// return found;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getUsage() {
// if (usage == null)
// usage = getName() + " " + new UsageBuilder(parameters).build();
// return usage;
// }
//
// public boolean call(Object sender, Arguments arguments) throws CommandInvocationException {
// if (senderType == null) {
// throw new IllegalArgumentException("Sender type is null!");
// }
// if (!senderType.isAssignableFrom(sender.getClass())) {
// throw new IllegalArgumentException(
// "Object provided is not assignable from the sender provided");
// }
//
// ParametricParser pParser = new ParametricParser(parameters);
// ParametricParser.ParsedResult parsedObj = pParser.parse(senderType.cast(sender), arguments);
// boolean isStatic = Modifier.isStatic(method.getModifiers());
//
// if (!parsedObj.isSuccessful()) {
// return false;
// }
//
// if (isStatic) {
// try {
// method.invoke(null, parsedObj.getObjects());
// return true;
// } catch (IllegalAccessException | InvocationTargetException e) {
// e.printStackTrace();
// throw new CommandInvocationException(e.getMessage());
// }
// } else {
// try {
// Object instance = method.getDeclaringClass().newInstance();
// method.invoke(instance, parsedObj.getObjects());
// return true;
// } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
// throw new CommandInvocationException(e.getMessage());
// }
// }
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/command/CommandInvocationException.java
// public class CommandInvocationException extends Exception {
//
// public CommandInvocationException(String s) {
// super(s);
// }
//
// }
| import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.command.CommandHolder;
import me.rbrickis.mojo.command.CommandInvocationException; | package me.rbrickis.test;
public class WrappedCommand extends TestCommand {
private CommandHolder holder;
public WrappedCommand(CommandHolder holder) {
super(holder.getName(), holder.getAliases(), holder.getDescription());
this.holder = holder;
}
@Override | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/command/CommandHolder.java
// public class CommandHolder {
//
// private String name;
// private String[] aliases;
// private String permission = "";
// private String permissionMessage = "";
// private ParametricRegistry registry;
// private Method method;
// private Class<?> senderType;
// private List<Parameter> parameters;
// private String usage;
// private String description;
//
// public CommandHolder(Method method, ParametricRegistry registry, Class<?> senderType) {
//
// Command command = method.getDeclaredAnnotation(Command.class);
// if (command.aliases().length == 0) {
// throw new IllegalArgumentException("Must have at least one alias!");
// } else {
// name = command.aliases()[0];
// List<String> laliases = new ArrayList<>();
// for (int i = 1; i < command.aliases().length; i++) {
// laliases.add(command.aliases()[i]);
// }
// this.aliases = laliases.toArray(new String[] {});
// }
// if (method.isAnnotationPresent(Require.class)) {
// this.permission = method.getAnnotation(Require.class).value();
// this.permissionMessage = method.getAnnotation(Require.class).message();
// }
//
// this.registry = registry;
// this.method = method;
// this.senderType = senderType;
// this.method.setAccessible(true);
// MethodParser parser = new MethodParser(method, registry);
// this.parameters = parser.parse();
// this.description = command.desc();
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getAliases() {
// return aliases;
// }
//
// public String getPermission() {
// return permission;
// }
//
// public String getPermissionMessage() {
// return permissionMessage;
// }
//
// public boolean isAnnotationPresent(Class<? extends Annotation> annotation) {
// boolean found = false;
// for (Annotation anno : method.getAnnotations()) {
// if (anno.annotationType() == annotation) {
// found = true;
// }
// }
// return found;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getUsage() {
// if (usage == null)
// usage = getName() + " " + new UsageBuilder(parameters).build();
// return usage;
// }
//
// public boolean call(Object sender, Arguments arguments) throws CommandInvocationException {
// if (senderType == null) {
// throw new IllegalArgumentException("Sender type is null!");
// }
// if (!senderType.isAssignableFrom(sender.getClass())) {
// throw new IllegalArgumentException(
// "Object provided is not assignable from the sender provided");
// }
//
// ParametricParser pParser = new ParametricParser(parameters);
// ParametricParser.ParsedResult parsedObj = pParser.parse(senderType.cast(sender), arguments);
// boolean isStatic = Modifier.isStatic(method.getModifiers());
//
// if (!parsedObj.isSuccessful()) {
// return false;
// }
//
// if (isStatic) {
// try {
// method.invoke(null, parsedObj.getObjects());
// return true;
// } catch (IllegalAccessException | InvocationTargetException e) {
// e.printStackTrace();
// throw new CommandInvocationException(e.getMessage());
// }
// } else {
// try {
// Object instance = method.getDeclaringClass().newInstance();
// method.invoke(instance, parsedObj.getObjects());
// return true;
// } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
// throw new CommandInvocationException(e.getMessage());
// }
// }
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/command/CommandInvocationException.java
// public class CommandInvocationException extends Exception {
//
// public CommandInvocationException(String s) {
// super(s);
// }
//
// }
// Path: Core/src/test/java/me/rbrickis/test/WrappedCommand.java
import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.command.CommandHolder;
import me.rbrickis.mojo.command.CommandInvocationException;
package me.rbrickis.test;
public class WrappedCommand extends TestCommand {
private CommandHolder holder;
public WrappedCommand(CommandHolder holder) {
super(holder.getName(), holder.getAliases(), holder.getDescription());
this.holder = holder;
}
@Override | public void execute(Actor sender, Arguments arguments) { |
rbrick/Mojo | Core/src/test/java/me/rbrickis/test/WrappedCommand.java | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/command/CommandHolder.java
// public class CommandHolder {
//
// private String name;
// private String[] aliases;
// private String permission = "";
// private String permissionMessage = "";
// private ParametricRegistry registry;
// private Method method;
// private Class<?> senderType;
// private List<Parameter> parameters;
// private String usage;
// private String description;
//
// public CommandHolder(Method method, ParametricRegistry registry, Class<?> senderType) {
//
// Command command = method.getDeclaredAnnotation(Command.class);
// if (command.aliases().length == 0) {
// throw new IllegalArgumentException("Must have at least one alias!");
// } else {
// name = command.aliases()[0];
// List<String> laliases = new ArrayList<>();
// for (int i = 1; i < command.aliases().length; i++) {
// laliases.add(command.aliases()[i]);
// }
// this.aliases = laliases.toArray(new String[] {});
// }
// if (method.isAnnotationPresent(Require.class)) {
// this.permission = method.getAnnotation(Require.class).value();
// this.permissionMessage = method.getAnnotation(Require.class).message();
// }
//
// this.registry = registry;
// this.method = method;
// this.senderType = senderType;
// this.method.setAccessible(true);
// MethodParser parser = new MethodParser(method, registry);
// this.parameters = parser.parse();
// this.description = command.desc();
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getAliases() {
// return aliases;
// }
//
// public String getPermission() {
// return permission;
// }
//
// public String getPermissionMessage() {
// return permissionMessage;
// }
//
// public boolean isAnnotationPresent(Class<? extends Annotation> annotation) {
// boolean found = false;
// for (Annotation anno : method.getAnnotations()) {
// if (anno.annotationType() == annotation) {
// found = true;
// }
// }
// return found;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getUsage() {
// if (usage == null)
// usage = getName() + " " + new UsageBuilder(parameters).build();
// return usage;
// }
//
// public boolean call(Object sender, Arguments arguments) throws CommandInvocationException {
// if (senderType == null) {
// throw new IllegalArgumentException("Sender type is null!");
// }
// if (!senderType.isAssignableFrom(sender.getClass())) {
// throw new IllegalArgumentException(
// "Object provided is not assignable from the sender provided");
// }
//
// ParametricParser pParser = new ParametricParser(parameters);
// ParametricParser.ParsedResult parsedObj = pParser.parse(senderType.cast(sender), arguments);
// boolean isStatic = Modifier.isStatic(method.getModifiers());
//
// if (!parsedObj.isSuccessful()) {
// return false;
// }
//
// if (isStatic) {
// try {
// method.invoke(null, parsedObj.getObjects());
// return true;
// } catch (IllegalAccessException | InvocationTargetException e) {
// e.printStackTrace();
// throw new CommandInvocationException(e.getMessage());
// }
// } else {
// try {
// Object instance = method.getDeclaringClass().newInstance();
// method.invoke(instance, parsedObj.getObjects());
// return true;
// } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
// throw new CommandInvocationException(e.getMessage());
// }
// }
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/command/CommandInvocationException.java
// public class CommandInvocationException extends Exception {
//
// public CommandInvocationException(String s) {
// super(s);
// }
//
// }
| import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.command.CommandHolder;
import me.rbrickis.mojo.command.CommandInvocationException; | package me.rbrickis.test;
public class WrappedCommand extends TestCommand {
private CommandHolder holder;
public WrappedCommand(CommandHolder holder) {
super(holder.getName(), holder.getAliases(), holder.getDescription());
this.holder = holder;
}
@Override
public void execute(Actor sender, Arguments arguments) {
try {
holder.call(sender, arguments); | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/command/CommandHolder.java
// public class CommandHolder {
//
// private String name;
// private String[] aliases;
// private String permission = "";
// private String permissionMessage = "";
// private ParametricRegistry registry;
// private Method method;
// private Class<?> senderType;
// private List<Parameter> parameters;
// private String usage;
// private String description;
//
// public CommandHolder(Method method, ParametricRegistry registry, Class<?> senderType) {
//
// Command command = method.getDeclaredAnnotation(Command.class);
// if (command.aliases().length == 0) {
// throw new IllegalArgumentException("Must have at least one alias!");
// } else {
// name = command.aliases()[0];
// List<String> laliases = new ArrayList<>();
// for (int i = 1; i < command.aliases().length; i++) {
// laliases.add(command.aliases()[i]);
// }
// this.aliases = laliases.toArray(new String[] {});
// }
// if (method.isAnnotationPresent(Require.class)) {
// this.permission = method.getAnnotation(Require.class).value();
// this.permissionMessage = method.getAnnotation(Require.class).message();
// }
//
// this.registry = registry;
// this.method = method;
// this.senderType = senderType;
// this.method.setAccessible(true);
// MethodParser parser = new MethodParser(method, registry);
// this.parameters = parser.parse();
// this.description = command.desc();
// }
//
// public String getName() {
// return name;
// }
//
// public String[] getAliases() {
// return aliases;
// }
//
// public String getPermission() {
// return permission;
// }
//
// public String getPermissionMessage() {
// return permissionMessage;
// }
//
// public boolean isAnnotationPresent(Class<? extends Annotation> annotation) {
// boolean found = false;
// for (Annotation anno : method.getAnnotations()) {
// if (anno.annotationType() == annotation) {
// found = true;
// }
// }
// return found;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getUsage() {
// if (usage == null)
// usage = getName() + " " + new UsageBuilder(parameters).build();
// return usage;
// }
//
// public boolean call(Object sender, Arguments arguments) throws CommandInvocationException {
// if (senderType == null) {
// throw new IllegalArgumentException("Sender type is null!");
// }
// if (!senderType.isAssignableFrom(sender.getClass())) {
// throw new IllegalArgumentException(
// "Object provided is not assignable from the sender provided");
// }
//
// ParametricParser pParser = new ParametricParser(parameters);
// ParametricParser.ParsedResult parsedObj = pParser.parse(senderType.cast(sender), arguments);
// boolean isStatic = Modifier.isStatic(method.getModifiers());
//
// if (!parsedObj.isSuccessful()) {
// return false;
// }
//
// if (isStatic) {
// try {
// method.invoke(null, parsedObj.getObjects());
// return true;
// } catch (IllegalAccessException | InvocationTargetException e) {
// e.printStackTrace();
// throw new CommandInvocationException(e.getMessage());
// }
// } else {
// try {
// Object instance = method.getDeclaringClass().newInstance();
// method.invoke(instance, parsedObj.getObjects());
// return true;
// } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
// throw new CommandInvocationException(e.getMessage());
// }
// }
// }
//
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/command/CommandInvocationException.java
// public class CommandInvocationException extends Exception {
//
// public CommandInvocationException(String s) {
// super(s);
// }
//
// }
// Path: Core/src/test/java/me/rbrickis/test/WrappedCommand.java
import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.command.CommandHolder;
import me.rbrickis.mojo.command.CommandInvocationException;
package me.rbrickis.test;
public class WrappedCommand extends TestCommand {
private CommandHolder holder;
public WrappedCommand(CommandHolder holder) {
super(holder.getName(), holder.getAliases(), holder.getDescription());
this.holder = holder;
}
@Override
public void execute(Actor sender, Arguments arguments) {
try {
holder.call(sender, arguments); | } catch (CommandInvocationException e) { |
rbrick/Mojo | Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java | // Path: Core/src/main/java/me/rbrickis/mojo/parametric/ParametricRegistry.java
// public class ParametricRegistry implements Binder<Class<?>, ParameterResolver<?>> {
//
// private Map<Class<?>, ParameterResolver<?>> currentBindings = new HashMap<Class<?>, ParameterResolver<?>>();
//
// private Class<?> currentBind = null;
//
// public ParametricRegistry() {
// bind(String.class).to(argument -> argument);
//
// bind(Integer.TYPE).to(argument -> {
// int parsed = 0;
// try {
// parsed = Integer.parseInt(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Integer.class).to(currentBindings.get(Integer.TYPE));
//
// bind(Float.TYPE).to(argument -> {
// float parsed = 0;
// try {
// parsed = Float.parseFloat(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Float.class).to(currentBindings.get(Float.TYPE));
//
// bind(Double.TYPE).to(argument -> {
// Double parsed = 0d;
// try {
// parsed = Double.parseDouble(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Double.class).to(currentBindings.get(Double.TYPE));
//
// bind(Long.TYPE).to(argument -> {
// Long parsed = 0L;
// try {
// parsed = Long.parseLong(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Long.class).to(currentBindings.get(Long.TYPE));
//
//
//
// bind(Byte.TYPE).to(argument -> {
// Byte parsed = 0x0;
// try {
// parsed = Byte.parseByte(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Byte.class).to(currentBindings.get(Byte.TYPE));
//
// bind(Boolean.TYPE).to(argument -> {
// boolean parsed = false;
// if (argument.equalsIgnoreCase("true") || argument.equalsIgnoreCase("yes")) {
// parsed = true;
// } else if (argument.equalsIgnoreCase("false") || argument.equalsIgnoreCase("no")) {
// parsed = false;
// }
// return parsed;
// });
//
// bind(Boolean.class).to(currentBindings.get(Boolean.TYPE));
//
// }
//
// public Binder<Class<?>, ParameterResolver<?>> bind(Class<?> bind) {
// this.currentBind = bind;
// return this;
// }
//
// public void to(ParameterResolver<?> to) {
// if (currentBind == null) {
// throw new IllegalArgumentException("currentBind is null!");
// } else {
// currentBindings.put(currentBind, to);
// currentBind = null;
// }
// }
//
// public Map<Class<?>, ParameterResolver<?>> getBindings() {
// return currentBindings;
// }
//
// public ParameterResolver<?> get(Class<?> clazz) {
// if (!currentBindings.containsKey(clazz)) {
// throw new IllegalArgumentException("Could not find resolver for " + clazz.getSimpleName() + ".class");
// }
// return currentBindings.get(clazz);
// }
// }
| import me.rbrickis.mojo.annotations.Command;
import me.rbrickis.mojo.parametric.ParametricRegistry;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map; | package me.rbrickis.mojo.parametric.graph;
public class CommandGraph {
private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>(); | // Path: Core/src/main/java/me/rbrickis/mojo/parametric/ParametricRegistry.java
// public class ParametricRegistry implements Binder<Class<?>, ParameterResolver<?>> {
//
// private Map<Class<?>, ParameterResolver<?>> currentBindings = new HashMap<Class<?>, ParameterResolver<?>>();
//
// private Class<?> currentBind = null;
//
// public ParametricRegistry() {
// bind(String.class).to(argument -> argument);
//
// bind(Integer.TYPE).to(argument -> {
// int parsed = 0;
// try {
// parsed = Integer.parseInt(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Integer.class).to(currentBindings.get(Integer.TYPE));
//
// bind(Float.TYPE).to(argument -> {
// float parsed = 0;
// try {
// parsed = Float.parseFloat(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Float.class).to(currentBindings.get(Float.TYPE));
//
// bind(Double.TYPE).to(argument -> {
// Double parsed = 0d;
// try {
// parsed = Double.parseDouble(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Double.class).to(currentBindings.get(Double.TYPE));
//
// bind(Long.TYPE).to(argument -> {
// Long parsed = 0L;
// try {
// parsed = Long.parseLong(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Long.class).to(currentBindings.get(Long.TYPE));
//
//
//
// bind(Byte.TYPE).to(argument -> {
// Byte parsed = 0x0;
// try {
// parsed = Byte.parseByte(argument);
// } catch (NumberFormatException ex) {
// ex.printStackTrace();
// }
// return parsed;
// });
//
// bind(Byte.class).to(currentBindings.get(Byte.TYPE));
//
// bind(Boolean.TYPE).to(argument -> {
// boolean parsed = false;
// if (argument.equalsIgnoreCase("true") || argument.equalsIgnoreCase("yes")) {
// parsed = true;
// } else if (argument.equalsIgnoreCase("false") || argument.equalsIgnoreCase("no")) {
// parsed = false;
// }
// return parsed;
// });
//
// bind(Boolean.class).to(currentBindings.get(Boolean.TYPE));
//
// }
//
// public Binder<Class<?>, ParameterResolver<?>> bind(Class<?> bind) {
// this.currentBind = bind;
// return this;
// }
//
// public void to(ParameterResolver<?> to) {
// if (currentBind == null) {
// throw new IllegalArgumentException("currentBind is null!");
// } else {
// currentBindings.put(currentBind, to);
// currentBind = null;
// }
// }
//
// public Map<Class<?>, ParameterResolver<?>> getBindings() {
// return currentBindings;
// }
//
// public ParameterResolver<?> get(Class<?> clazz) {
// if (!currentBindings.containsKey(clazz)) {
// throw new IllegalArgumentException("Could not find resolver for " + clazz.getSimpleName() + ".class");
// }
// return currentBindings.get(clazz);
// }
// }
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/graph/CommandGraph.java
import me.rbrickis.mojo.annotations.Command;
import me.rbrickis.mojo.parametric.ParametricRegistry;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
package me.rbrickis.mojo.parametric.graph;
public class CommandGraph {
private Map<Class<? extends Annotation>, Class<?>> senderMap = new HashMap<>(); | private ParametricRegistry registry = new ParametricRegistry(); |
rbrick/Mojo | Core/src/main/java/me/rbrickis/mojo/parametric/ParametricParser.java | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// public static Object toPrimitiveNumber(Number number) {
// if (number instanceof Byte) {
// return number.byteValue();
// } else if (number instanceof Long) {
// return number.longValue();
// } else if (number instanceof Short) {
// return number.shortValue();
// } else if (number instanceof Integer) {
// return number.intValue();
// } else if (number instanceof Float) {
// return number.floatValue();
// } else if (number instanceof Double) {
// return number.doubleValue();
// }
// return 0;
// }
//
// public static Object toPrimitiveBoolean(Boolean booleans) {
// return booleans.booleanValue();
// }
// }
| import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.utils.PrimitiveUtils;
import java.util.ArrayList;
import java.util.List; | package me.rbrickis.mojo.parametric;
public class ParametricParser {
private List<Parameter> parameters;
public ParametricParser(List<Parameter> parameters) {
this.parameters = parameters;
}
| // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// public static Object toPrimitiveNumber(Number number) {
// if (number instanceof Byte) {
// return number.byteValue();
// } else if (number instanceof Long) {
// return number.longValue();
// } else if (number instanceof Short) {
// return number.shortValue();
// } else if (number instanceof Integer) {
// return number.intValue();
// } else if (number instanceof Float) {
// return number.floatValue();
// } else if (number instanceof Double) {
// return number.doubleValue();
// }
// return 0;
// }
//
// public static Object toPrimitiveBoolean(Boolean booleans) {
// return booleans.booleanValue();
// }
// }
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/ParametricParser.java
import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.utils.PrimitiveUtils;
import java.util.ArrayList;
import java.util.List;
package me.rbrickis.mojo.parametric;
public class ParametricParser {
private List<Parameter> parameters;
public ParametricParser(List<Parameter> parameters) {
this.parameters = parameters;
}
| public ParsedResult parse(Object sender, Arguments arguments) { |
rbrick/Mojo | Core/src/main/java/me/rbrickis/mojo/parametric/ParametricParser.java | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// public static Object toPrimitiveNumber(Number number) {
// if (number instanceof Byte) {
// return number.byteValue();
// } else if (number instanceof Long) {
// return number.longValue();
// } else if (number instanceof Short) {
// return number.shortValue();
// } else if (number instanceof Integer) {
// return number.intValue();
// } else if (number instanceof Float) {
// return number.floatValue();
// } else if (number instanceof Double) {
// return number.doubleValue();
// }
// return 0;
// }
//
// public static Object toPrimitiveBoolean(Boolean booleans) {
// return booleans.booleanValue();
// }
// }
| import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.utils.PrimitiveUtils;
import java.util.ArrayList;
import java.util.List; | package me.rbrickis.mojo.parametric;
public class ParametricParser {
private List<Parameter> parameters;
public ParametricParser(List<Parameter> parameters) {
this.parameters = parameters;
}
public ParsedResult parse(Object sender, Arguments arguments) {
boolean wasSuccess = true;
List<Object> objects = new ArrayList<>();
objects.add(sender);
for (Parameter parameter : parameters) {
Object obj = null;
if (arguments.get(parameter.getArgumentIndex()) == null) {
if (parameter.hasDefault()) {
obj = parameter.parse(parameter.getDefault());
} else {
wasSuccess = false;
}
} else {
obj = parameter.parse(arguments.get(parameter.getArgumentIndex()));
}
// is continuous
if (parameter.hasText()) {
if (arguments.get(parameter.getArgumentIndex()) != null) {
obj = arguments.join(parameter.getArgumentIndex());
}
objects.add(obj);
break;
} else if (parameter.getType().isPrimitive()) {
if (Number.class.isAssignableFrom(parameter.getType())) { | // Path: Core/src/main/java/me/rbrickis/mojo/Arguments.java
// public class Arguments {
//
// private List<String> arguments;
//
// public Arguments() {
// this.arguments = new ArrayList<>();
// }
//
// public Arguments(String... arguments) {
// this.arguments = Arrays.asList(arguments);
// }
//
// public Arguments(List<String> arguments) {
// this.arguments = arguments;
// }
//
//
// /**
// * @see Arguments#size()
// */
// public int length() {
// return size();
// }
//
// /**
// * @return The size of the arguments provide
// */
// public int size() {
// return arguments.size();
// }
//
// /**
// * @param index the index to pull from
// * @return 'null' if the index is out of bounds, or the String at the index.
// */
// public String get(int index) {
// try {
// return arguments.get(index);
// } catch (IndexOutOfBoundsException ex) {
// return null;
// }
// }
//
// public String join(int at, char delimiter) {
// StringBuilder builder = new StringBuilder();
// for (int x = at; x < arguments.size(); x++) {
// builder.append(get(x)).append(delimiter);
// }
// return builder.toString();
// }
//
// public String join(int at) {
// return join(at, ' ');
// }
//
//
// public List<String> getArguments() {
// return arguments;
// }
// }
//
// Path: Core/src/main/java/me/rbrickis/mojo/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// public static Object toPrimitiveNumber(Number number) {
// if (number instanceof Byte) {
// return number.byteValue();
// } else if (number instanceof Long) {
// return number.longValue();
// } else if (number instanceof Short) {
// return number.shortValue();
// } else if (number instanceof Integer) {
// return number.intValue();
// } else if (number instanceof Float) {
// return number.floatValue();
// } else if (number instanceof Double) {
// return number.doubleValue();
// }
// return 0;
// }
//
// public static Object toPrimitiveBoolean(Boolean booleans) {
// return booleans.booleanValue();
// }
// }
// Path: Core/src/main/java/me/rbrickis/mojo/parametric/ParametricParser.java
import me.rbrickis.mojo.Arguments;
import me.rbrickis.mojo.utils.PrimitiveUtils;
import java.util.ArrayList;
import java.util.List;
package me.rbrickis.mojo.parametric;
public class ParametricParser {
private List<Parameter> parameters;
public ParametricParser(List<Parameter> parameters) {
this.parameters = parameters;
}
public ParsedResult parse(Object sender, Arguments arguments) {
boolean wasSuccess = true;
List<Object> objects = new ArrayList<>();
objects.add(sender);
for (Parameter parameter : parameters) {
Object obj = null;
if (arguments.get(parameter.getArgumentIndex()) == null) {
if (parameter.hasDefault()) {
obj = parameter.parse(parameter.getDefault());
} else {
wasSuccess = false;
}
} else {
obj = parameter.parse(arguments.get(parameter.getArgumentIndex()));
}
// is continuous
if (parameter.hasText()) {
if (arguments.get(parameter.getArgumentIndex()) != null) {
obj = arguments.join(parameter.getArgumentIndex());
}
objects.add(obj);
break;
} else if (parameter.getType().isPrimitive()) {
if (Number.class.isAssignableFrom(parameter.getType())) { | obj = PrimitiveUtils.toPrimitiveNumber((Number) obj); |
wwfdoink/jolokia-web | src/main/java/prj/jolokiaweb/config/SecurityConfig.java | // Path: src/main/java/prj/jolokiaweb/jolokia/AgentInfo.java
// public class AgentInfo {
// public enum JolokiaPermission {
// NONE,READ,WRITE,EXECUTE
// }
//
// private String url;
// private boolean isLocalAgent = false;
// private boolean requireAuth = false;
// private String agentUsername;
// private String agentPassword;
//
// private String webUsername;
// private String webPassword;
// private SSLConfig SSLConfig = new SSLConfig();
//
// private Set<JolokiaPermission> beanPermissions = new HashSet<>();
//
// public AgentInfo() {
// }
//
// public String getUrl() {
// return (url != null) ? url.toString() : null;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getAgentUsername() {
// return agentUsername;
// }
//
// public void setAgentUsername(String agentUsername) {
// this.agentUsername = agentUsername;
// }
//
// public String getAgentPassword() {
// return agentPassword;
// }
//
// public void setAgentPassword(String agentPassword) {
// this.agentPassword = agentPassword;
// }
//
// public String getWebUsername() {
// return webUsername;
// }
//
// public void setWebUsername(String webUsername) {
// this.webUsername = webUsername;
// }
//
// public String getWebPassword() {
// return webPassword;
// }
//
// public void setWebPassword(String webPassword) {
// this.webPassword = webPassword;
// }
//
// public boolean isLocalAgent() {
// return isLocalAgent;
// }
//
// public boolean requiresLocalAuth() {
// return webUsername != null;
// }
//
// public void setLocalAgent(boolean localAgent) {
// isLocalAgent = localAgent;
// }
//
// public boolean isRequireAuth() {
// return requireAuth;
// }
//
// public void setRequireAuth(boolean requireAuth) {
// this.requireAuth = requireAuth;
// }
//
// public void addPermission(JolokiaPermission ... permission) {
// this.beanPermissions.addAll(Arrays.asList(permission));
// }
//
// public void clearPermission() {
// this.beanPermissions.clear();
// }
//
// public Set<JolokiaPermission> getBeanPermissions() {
// return beanPermissions;
// }
//
// public SSLConfig getSSLConfig() {
// return SSLConfig;
// }
//
// public void setSSLConfig(SSLConfig SSLConfig) {
// this.SSLConfig = SSLConfig;
// }
// }
//
// Path: src/main/java/prj/jolokiaweb/jolokia/JolokiaClient.java
// public class JolokiaClient {
// private static final int MAX_CONNECTIONS = 2;
// private static J4pClient instance;
// private static AgentInfo agentInfo;
//
//
// private JolokiaClient(){
// }
//
// public static J4pClient init(AgentInfo initialAgentInfo){
// if (instance != null) {
// return instance;
// }
// agentInfo = initialAgentInfo;
// return getInstance();
// }
//
// public static synchronized J4pClient getInstance() {
// if (instance == null) {
// String user = agentInfo.getAgentUsername();
// String password = agentInfo.getAgentPassword();
// if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {
// user = agentInfo.getWebUsername();
// password = agentInfo.getWebPassword();
// }
//
// J4pClientBuilder clientBuilder = J4pClientBuilderFactory
// .url(agentInfo.getUrl())
// .user(user)
// .password(password)
// .maxTotalConnections(MAX_CONNECTIONS);
//
// SSLConfig config = agentInfo.getSSLConfig();
// if (config.isSelfSignedCertAllowed()) {
// try {
// SSLContext sslContext = new SSLContextBuilder()
// .loadTrustMaterial(null, new TrustSelfSignedStrategy())
// .build();
//
// SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(
// sslContext,
// SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// );
//
// clientBuilder.sslConnectionSocketFactory(sslConnection);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// instance = clientBuilder.build();
// }
// return instance;
// }
//
// public static AgentInfo getAgentInfo() {
// return agentInfo;
// }
// }
| import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import prj.jolokiaweb.jolokia.AgentInfo;
import prj.jolokiaweb.jolokia.JolokiaClient; | package prj.jolokiaweb.config;
@EnableWebSecurity
public class SecurityConfig {
public static final String ROLE_USER = "user";
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { | // Path: src/main/java/prj/jolokiaweb/jolokia/AgentInfo.java
// public class AgentInfo {
// public enum JolokiaPermission {
// NONE,READ,WRITE,EXECUTE
// }
//
// private String url;
// private boolean isLocalAgent = false;
// private boolean requireAuth = false;
// private String agentUsername;
// private String agentPassword;
//
// private String webUsername;
// private String webPassword;
// private SSLConfig SSLConfig = new SSLConfig();
//
// private Set<JolokiaPermission> beanPermissions = new HashSet<>();
//
// public AgentInfo() {
// }
//
// public String getUrl() {
// return (url != null) ? url.toString() : null;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getAgentUsername() {
// return agentUsername;
// }
//
// public void setAgentUsername(String agentUsername) {
// this.agentUsername = agentUsername;
// }
//
// public String getAgentPassword() {
// return agentPassword;
// }
//
// public void setAgentPassword(String agentPassword) {
// this.agentPassword = agentPassword;
// }
//
// public String getWebUsername() {
// return webUsername;
// }
//
// public void setWebUsername(String webUsername) {
// this.webUsername = webUsername;
// }
//
// public String getWebPassword() {
// return webPassword;
// }
//
// public void setWebPassword(String webPassword) {
// this.webPassword = webPassword;
// }
//
// public boolean isLocalAgent() {
// return isLocalAgent;
// }
//
// public boolean requiresLocalAuth() {
// return webUsername != null;
// }
//
// public void setLocalAgent(boolean localAgent) {
// isLocalAgent = localAgent;
// }
//
// public boolean isRequireAuth() {
// return requireAuth;
// }
//
// public void setRequireAuth(boolean requireAuth) {
// this.requireAuth = requireAuth;
// }
//
// public void addPermission(JolokiaPermission ... permission) {
// this.beanPermissions.addAll(Arrays.asList(permission));
// }
//
// public void clearPermission() {
// this.beanPermissions.clear();
// }
//
// public Set<JolokiaPermission> getBeanPermissions() {
// return beanPermissions;
// }
//
// public SSLConfig getSSLConfig() {
// return SSLConfig;
// }
//
// public void setSSLConfig(SSLConfig SSLConfig) {
// this.SSLConfig = SSLConfig;
// }
// }
//
// Path: src/main/java/prj/jolokiaweb/jolokia/JolokiaClient.java
// public class JolokiaClient {
// private static final int MAX_CONNECTIONS = 2;
// private static J4pClient instance;
// private static AgentInfo agentInfo;
//
//
// private JolokiaClient(){
// }
//
// public static J4pClient init(AgentInfo initialAgentInfo){
// if (instance != null) {
// return instance;
// }
// agentInfo = initialAgentInfo;
// return getInstance();
// }
//
// public static synchronized J4pClient getInstance() {
// if (instance == null) {
// String user = agentInfo.getAgentUsername();
// String password = agentInfo.getAgentPassword();
// if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {
// user = agentInfo.getWebUsername();
// password = agentInfo.getWebPassword();
// }
//
// J4pClientBuilder clientBuilder = J4pClientBuilderFactory
// .url(agentInfo.getUrl())
// .user(user)
// .password(password)
// .maxTotalConnections(MAX_CONNECTIONS);
//
// SSLConfig config = agentInfo.getSSLConfig();
// if (config.isSelfSignedCertAllowed()) {
// try {
// SSLContext sslContext = new SSLContextBuilder()
// .loadTrustMaterial(null, new TrustSelfSignedStrategy())
// .build();
//
// SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(
// sslContext,
// SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// );
//
// clientBuilder.sslConnectionSocketFactory(sslConnection);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// instance = clientBuilder.build();
// }
// return instance;
// }
//
// public static AgentInfo getAgentInfo() {
// return agentInfo;
// }
// }
// Path: src/main/java/prj/jolokiaweb/config/SecurityConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import prj.jolokiaweb.jolokia.AgentInfo;
import prj.jolokiaweb.jolokia.JolokiaClient;
package prj.jolokiaweb.config;
@EnableWebSecurity
public class SecurityConfig {
public static final String ROLE_USER = "user";
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { | AgentInfo info = JolokiaClient.getAgentInfo(); |
wwfdoink/jolokia-web | src/main/java/prj/jolokiaweb/config/SecurityConfig.java | // Path: src/main/java/prj/jolokiaweb/jolokia/AgentInfo.java
// public class AgentInfo {
// public enum JolokiaPermission {
// NONE,READ,WRITE,EXECUTE
// }
//
// private String url;
// private boolean isLocalAgent = false;
// private boolean requireAuth = false;
// private String agentUsername;
// private String agentPassword;
//
// private String webUsername;
// private String webPassword;
// private SSLConfig SSLConfig = new SSLConfig();
//
// private Set<JolokiaPermission> beanPermissions = new HashSet<>();
//
// public AgentInfo() {
// }
//
// public String getUrl() {
// return (url != null) ? url.toString() : null;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getAgentUsername() {
// return agentUsername;
// }
//
// public void setAgentUsername(String agentUsername) {
// this.agentUsername = agentUsername;
// }
//
// public String getAgentPassword() {
// return agentPassword;
// }
//
// public void setAgentPassword(String agentPassword) {
// this.agentPassword = agentPassword;
// }
//
// public String getWebUsername() {
// return webUsername;
// }
//
// public void setWebUsername(String webUsername) {
// this.webUsername = webUsername;
// }
//
// public String getWebPassword() {
// return webPassword;
// }
//
// public void setWebPassword(String webPassword) {
// this.webPassword = webPassword;
// }
//
// public boolean isLocalAgent() {
// return isLocalAgent;
// }
//
// public boolean requiresLocalAuth() {
// return webUsername != null;
// }
//
// public void setLocalAgent(boolean localAgent) {
// isLocalAgent = localAgent;
// }
//
// public boolean isRequireAuth() {
// return requireAuth;
// }
//
// public void setRequireAuth(boolean requireAuth) {
// this.requireAuth = requireAuth;
// }
//
// public void addPermission(JolokiaPermission ... permission) {
// this.beanPermissions.addAll(Arrays.asList(permission));
// }
//
// public void clearPermission() {
// this.beanPermissions.clear();
// }
//
// public Set<JolokiaPermission> getBeanPermissions() {
// return beanPermissions;
// }
//
// public SSLConfig getSSLConfig() {
// return SSLConfig;
// }
//
// public void setSSLConfig(SSLConfig SSLConfig) {
// this.SSLConfig = SSLConfig;
// }
// }
//
// Path: src/main/java/prj/jolokiaweb/jolokia/JolokiaClient.java
// public class JolokiaClient {
// private static final int MAX_CONNECTIONS = 2;
// private static J4pClient instance;
// private static AgentInfo agentInfo;
//
//
// private JolokiaClient(){
// }
//
// public static J4pClient init(AgentInfo initialAgentInfo){
// if (instance != null) {
// return instance;
// }
// agentInfo = initialAgentInfo;
// return getInstance();
// }
//
// public static synchronized J4pClient getInstance() {
// if (instance == null) {
// String user = agentInfo.getAgentUsername();
// String password = agentInfo.getAgentPassword();
// if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {
// user = agentInfo.getWebUsername();
// password = agentInfo.getWebPassword();
// }
//
// J4pClientBuilder clientBuilder = J4pClientBuilderFactory
// .url(agentInfo.getUrl())
// .user(user)
// .password(password)
// .maxTotalConnections(MAX_CONNECTIONS);
//
// SSLConfig config = agentInfo.getSSLConfig();
// if (config.isSelfSignedCertAllowed()) {
// try {
// SSLContext sslContext = new SSLContextBuilder()
// .loadTrustMaterial(null, new TrustSelfSignedStrategy())
// .build();
//
// SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(
// sslContext,
// SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// );
//
// clientBuilder.sslConnectionSocketFactory(sslConnection);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// instance = clientBuilder.build();
// }
// return instance;
// }
//
// public static AgentInfo getAgentInfo() {
// return agentInfo;
// }
// }
| import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import prj.jolokiaweb.jolokia.AgentInfo;
import prj.jolokiaweb.jolokia.JolokiaClient; | package prj.jolokiaweb.config;
@EnableWebSecurity
public class SecurityConfig {
public static final String ROLE_USER = "user";
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { | // Path: src/main/java/prj/jolokiaweb/jolokia/AgentInfo.java
// public class AgentInfo {
// public enum JolokiaPermission {
// NONE,READ,WRITE,EXECUTE
// }
//
// private String url;
// private boolean isLocalAgent = false;
// private boolean requireAuth = false;
// private String agentUsername;
// private String agentPassword;
//
// private String webUsername;
// private String webPassword;
// private SSLConfig SSLConfig = new SSLConfig();
//
// private Set<JolokiaPermission> beanPermissions = new HashSet<>();
//
// public AgentInfo() {
// }
//
// public String getUrl() {
// return (url != null) ? url.toString() : null;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getAgentUsername() {
// return agentUsername;
// }
//
// public void setAgentUsername(String agentUsername) {
// this.agentUsername = agentUsername;
// }
//
// public String getAgentPassword() {
// return agentPassword;
// }
//
// public void setAgentPassword(String agentPassword) {
// this.agentPassword = agentPassword;
// }
//
// public String getWebUsername() {
// return webUsername;
// }
//
// public void setWebUsername(String webUsername) {
// this.webUsername = webUsername;
// }
//
// public String getWebPassword() {
// return webPassword;
// }
//
// public void setWebPassword(String webPassword) {
// this.webPassword = webPassword;
// }
//
// public boolean isLocalAgent() {
// return isLocalAgent;
// }
//
// public boolean requiresLocalAuth() {
// return webUsername != null;
// }
//
// public void setLocalAgent(boolean localAgent) {
// isLocalAgent = localAgent;
// }
//
// public boolean isRequireAuth() {
// return requireAuth;
// }
//
// public void setRequireAuth(boolean requireAuth) {
// this.requireAuth = requireAuth;
// }
//
// public void addPermission(JolokiaPermission ... permission) {
// this.beanPermissions.addAll(Arrays.asList(permission));
// }
//
// public void clearPermission() {
// this.beanPermissions.clear();
// }
//
// public Set<JolokiaPermission> getBeanPermissions() {
// return beanPermissions;
// }
//
// public SSLConfig getSSLConfig() {
// return SSLConfig;
// }
//
// public void setSSLConfig(SSLConfig SSLConfig) {
// this.SSLConfig = SSLConfig;
// }
// }
//
// Path: src/main/java/prj/jolokiaweb/jolokia/JolokiaClient.java
// public class JolokiaClient {
// private static final int MAX_CONNECTIONS = 2;
// private static J4pClient instance;
// private static AgentInfo agentInfo;
//
//
// private JolokiaClient(){
// }
//
// public static J4pClient init(AgentInfo initialAgentInfo){
// if (instance != null) {
// return instance;
// }
// agentInfo = initialAgentInfo;
// return getInstance();
// }
//
// public static synchronized J4pClient getInstance() {
// if (instance == null) {
// String user = agentInfo.getAgentUsername();
// String password = agentInfo.getAgentPassword();
// if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {
// user = agentInfo.getWebUsername();
// password = agentInfo.getWebPassword();
// }
//
// J4pClientBuilder clientBuilder = J4pClientBuilderFactory
// .url(agentInfo.getUrl())
// .user(user)
// .password(password)
// .maxTotalConnections(MAX_CONNECTIONS);
//
// SSLConfig config = agentInfo.getSSLConfig();
// if (config.isSelfSignedCertAllowed()) {
// try {
// SSLContext sslContext = new SSLContextBuilder()
// .loadTrustMaterial(null, new TrustSelfSignedStrategy())
// .build();
//
// SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(
// sslContext,
// SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// );
//
// clientBuilder.sslConnectionSocketFactory(sslConnection);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// instance = clientBuilder.build();
// }
// return instance;
// }
//
// public static AgentInfo getAgentInfo() {
// return agentInfo;
// }
// }
// Path: src/main/java/prj/jolokiaweb/config/SecurityConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import prj.jolokiaweb.jolokia.AgentInfo;
import prj.jolokiaweb.jolokia.JolokiaClient;
package prj.jolokiaweb.config;
@EnableWebSecurity
public class SecurityConfig {
public static final String ROLE_USER = "user";
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { | AgentInfo info = JolokiaClient.getAgentInfo(); |
wwfdoink/jolokia-web | src/main/java/prj/jolokiaweb/config/PermissionCheckInterceptor.java | // Path: src/main/java/prj/jolokiaweb/jolokia/AgentInfo.java
// public class AgentInfo {
// public enum JolokiaPermission {
// NONE,READ,WRITE,EXECUTE
// }
//
// private String url;
// private boolean isLocalAgent = false;
// private boolean requireAuth = false;
// private String agentUsername;
// private String agentPassword;
//
// private String webUsername;
// private String webPassword;
// private SSLConfig SSLConfig = new SSLConfig();
//
// private Set<JolokiaPermission> beanPermissions = new HashSet<>();
//
// public AgentInfo() {
// }
//
// public String getUrl() {
// return (url != null) ? url.toString() : null;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getAgentUsername() {
// return agentUsername;
// }
//
// public void setAgentUsername(String agentUsername) {
// this.agentUsername = agentUsername;
// }
//
// public String getAgentPassword() {
// return agentPassword;
// }
//
// public void setAgentPassword(String agentPassword) {
// this.agentPassword = agentPassword;
// }
//
// public String getWebUsername() {
// return webUsername;
// }
//
// public void setWebUsername(String webUsername) {
// this.webUsername = webUsername;
// }
//
// public String getWebPassword() {
// return webPassword;
// }
//
// public void setWebPassword(String webPassword) {
// this.webPassword = webPassword;
// }
//
// public boolean isLocalAgent() {
// return isLocalAgent;
// }
//
// public boolean requiresLocalAuth() {
// return webUsername != null;
// }
//
// public void setLocalAgent(boolean localAgent) {
// isLocalAgent = localAgent;
// }
//
// public boolean isRequireAuth() {
// return requireAuth;
// }
//
// public void setRequireAuth(boolean requireAuth) {
// this.requireAuth = requireAuth;
// }
//
// public void addPermission(JolokiaPermission ... permission) {
// this.beanPermissions.addAll(Arrays.asList(permission));
// }
//
// public void clearPermission() {
// this.beanPermissions.clear();
// }
//
// public Set<JolokiaPermission> getBeanPermissions() {
// return beanPermissions;
// }
//
// public SSLConfig getSSLConfig() {
// return SSLConfig;
// }
//
// public void setSSLConfig(SSLConfig SSLConfig) {
// this.SSLConfig = SSLConfig;
// }
// }
//
// Path: src/main/java/prj/jolokiaweb/jolokia/JolokiaClient.java
// public class JolokiaClient {
// private static final int MAX_CONNECTIONS = 2;
// private static J4pClient instance;
// private static AgentInfo agentInfo;
//
//
// private JolokiaClient(){
// }
//
// public static J4pClient init(AgentInfo initialAgentInfo){
// if (instance != null) {
// return instance;
// }
// agentInfo = initialAgentInfo;
// return getInstance();
// }
//
// public static synchronized J4pClient getInstance() {
// if (instance == null) {
// String user = agentInfo.getAgentUsername();
// String password = agentInfo.getAgentPassword();
// if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {
// user = agentInfo.getWebUsername();
// password = agentInfo.getWebPassword();
// }
//
// J4pClientBuilder clientBuilder = J4pClientBuilderFactory
// .url(agentInfo.getUrl())
// .user(user)
// .password(password)
// .maxTotalConnections(MAX_CONNECTIONS);
//
// SSLConfig config = agentInfo.getSSLConfig();
// if (config.isSelfSignedCertAllowed()) {
// try {
// SSLContext sslContext = new SSLContextBuilder()
// .loadTrustMaterial(null, new TrustSelfSignedStrategy())
// .build();
//
// SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(
// sslContext,
// SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// );
//
// clientBuilder.sslConnectionSocketFactory(sslConnection);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// instance = clientBuilder.build();
// }
// return instance;
// }
//
// public static AgentInfo getAgentInfo() {
// return agentInfo;
// }
// }
| import org.json.simple.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import prj.jolokiaweb.jolokia.AgentInfo;
import prj.jolokiaweb.jolokia.JolokiaClient;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | package prj.jolokiaweb.config;
public class PermissionCheckInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURI().startsWith("/api/beans")) { | // Path: src/main/java/prj/jolokiaweb/jolokia/AgentInfo.java
// public class AgentInfo {
// public enum JolokiaPermission {
// NONE,READ,WRITE,EXECUTE
// }
//
// private String url;
// private boolean isLocalAgent = false;
// private boolean requireAuth = false;
// private String agentUsername;
// private String agentPassword;
//
// private String webUsername;
// private String webPassword;
// private SSLConfig SSLConfig = new SSLConfig();
//
// private Set<JolokiaPermission> beanPermissions = new HashSet<>();
//
// public AgentInfo() {
// }
//
// public String getUrl() {
// return (url != null) ? url.toString() : null;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getAgentUsername() {
// return agentUsername;
// }
//
// public void setAgentUsername(String agentUsername) {
// this.agentUsername = agentUsername;
// }
//
// public String getAgentPassword() {
// return agentPassword;
// }
//
// public void setAgentPassword(String agentPassword) {
// this.agentPassword = agentPassword;
// }
//
// public String getWebUsername() {
// return webUsername;
// }
//
// public void setWebUsername(String webUsername) {
// this.webUsername = webUsername;
// }
//
// public String getWebPassword() {
// return webPassword;
// }
//
// public void setWebPassword(String webPassword) {
// this.webPassword = webPassword;
// }
//
// public boolean isLocalAgent() {
// return isLocalAgent;
// }
//
// public boolean requiresLocalAuth() {
// return webUsername != null;
// }
//
// public void setLocalAgent(boolean localAgent) {
// isLocalAgent = localAgent;
// }
//
// public boolean isRequireAuth() {
// return requireAuth;
// }
//
// public void setRequireAuth(boolean requireAuth) {
// this.requireAuth = requireAuth;
// }
//
// public void addPermission(JolokiaPermission ... permission) {
// this.beanPermissions.addAll(Arrays.asList(permission));
// }
//
// public void clearPermission() {
// this.beanPermissions.clear();
// }
//
// public Set<JolokiaPermission> getBeanPermissions() {
// return beanPermissions;
// }
//
// public SSLConfig getSSLConfig() {
// return SSLConfig;
// }
//
// public void setSSLConfig(SSLConfig SSLConfig) {
// this.SSLConfig = SSLConfig;
// }
// }
//
// Path: src/main/java/prj/jolokiaweb/jolokia/JolokiaClient.java
// public class JolokiaClient {
// private static final int MAX_CONNECTIONS = 2;
// private static J4pClient instance;
// private static AgentInfo agentInfo;
//
//
// private JolokiaClient(){
// }
//
// public static J4pClient init(AgentInfo initialAgentInfo){
// if (instance != null) {
// return instance;
// }
// agentInfo = initialAgentInfo;
// return getInstance();
// }
//
// public static synchronized J4pClient getInstance() {
// if (instance == null) {
// String user = agentInfo.getAgentUsername();
// String password = agentInfo.getAgentPassword();
// if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {
// user = agentInfo.getWebUsername();
// password = agentInfo.getWebPassword();
// }
//
// J4pClientBuilder clientBuilder = J4pClientBuilderFactory
// .url(agentInfo.getUrl())
// .user(user)
// .password(password)
// .maxTotalConnections(MAX_CONNECTIONS);
//
// SSLConfig config = agentInfo.getSSLConfig();
// if (config.isSelfSignedCertAllowed()) {
// try {
// SSLContext sslContext = new SSLContextBuilder()
// .loadTrustMaterial(null, new TrustSelfSignedStrategy())
// .build();
//
// SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(
// sslContext,
// SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// );
//
// clientBuilder.sslConnectionSocketFactory(sslConnection);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// instance = clientBuilder.build();
// }
// return instance;
// }
//
// public static AgentInfo getAgentInfo() {
// return agentInfo;
// }
// }
// Path: src/main/java/prj/jolokiaweb/config/PermissionCheckInterceptor.java
import org.json.simple.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import prj.jolokiaweb.jolokia.AgentInfo;
import prj.jolokiaweb.jolokia.JolokiaClient;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
package prj.jolokiaweb.config;
public class PermissionCheckInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURI().startsWith("/api/beans")) { | if (!JolokiaClient.getAgentInfo().getBeanPermissions().contains(AgentInfo.JolokiaPermission.READ)) { |
wwfdoink/jolokia-web | src/main/java/prj/jolokiaweb/config/PermissionCheckInterceptor.java | // Path: src/main/java/prj/jolokiaweb/jolokia/AgentInfo.java
// public class AgentInfo {
// public enum JolokiaPermission {
// NONE,READ,WRITE,EXECUTE
// }
//
// private String url;
// private boolean isLocalAgent = false;
// private boolean requireAuth = false;
// private String agentUsername;
// private String agentPassword;
//
// private String webUsername;
// private String webPassword;
// private SSLConfig SSLConfig = new SSLConfig();
//
// private Set<JolokiaPermission> beanPermissions = new HashSet<>();
//
// public AgentInfo() {
// }
//
// public String getUrl() {
// return (url != null) ? url.toString() : null;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getAgentUsername() {
// return agentUsername;
// }
//
// public void setAgentUsername(String agentUsername) {
// this.agentUsername = agentUsername;
// }
//
// public String getAgentPassword() {
// return agentPassword;
// }
//
// public void setAgentPassword(String agentPassword) {
// this.agentPassword = agentPassword;
// }
//
// public String getWebUsername() {
// return webUsername;
// }
//
// public void setWebUsername(String webUsername) {
// this.webUsername = webUsername;
// }
//
// public String getWebPassword() {
// return webPassword;
// }
//
// public void setWebPassword(String webPassword) {
// this.webPassword = webPassword;
// }
//
// public boolean isLocalAgent() {
// return isLocalAgent;
// }
//
// public boolean requiresLocalAuth() {
// return webUsername != null;
// }
//
// public void setLocalAgent(boolean localAgent) {
// isLocalAgent = localAgent;
// }
//
// public boolean isRequireAuth() {
// return requireAuth;
// }
//
// public void setRequireAuth(boolean requireAuth) {
// this.requireAuth = requireAuth;
// }
//
// public void addPermission(JolokiaPermission ... permission) {
// this.beanPermissions.addAll(Arrays.asList(permission));
// }
//
// public void clearPermission() {
// this.beanPermissions.clear();
// }
//
// public Set<JolokiaPermission> getBeanPermissions() {
// return beanPermissions;
// }
//
// public SSLConfig getSSLConfig() {
// return SSLConfig;
// }
//
// public void setSSLConfig(SSLConfig SSLConfig) {
// this.SSLConfig = SSLConfig;
// }
// }
//
// Path: src/main/java/prj/jolokiaweb/jolokia/JolokiaClient.java
// public class JolokiaClient {
// private static final int MAX_CONNECTIONS = 2;
// private static J4pClient instance;
// private static AgentInfo agentInfo;
//
//
// private JolokiaClient(){
// }
//
// public static J4pClient init(AgentInfo initialAgentInfo){
// if (instance != null) {
// return instance;
// }
// agentInfo = initialAgentInfo;
// return getInstance();
// }
//
// public static synchronized J4pClient getInstance() {
// if (instance == null) {
// String user = agentInfo.getAgentUsername();
// String password = agentInfo.getAgentPassword();
// if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {
// user = agentInfo.getWebUsername();
// password = agentInfo.getWebPassword();
// }
//
// J4pClientBuilder clientBuilder = J4pClientBuilderFactory
// .url(agentInfo.getUrl())
// .user(user)
// .password(password)
// .maxTotalConnections(MAX_CONNECTIONS);
//
// SSLConfig config = agentInfo.getSSLConfig();
// if (config.isSelfSignedCertAllowed()) {
// try {
// SSLContext sslContext = new SSLContextBuilder()
// .loadTrustMaterial(null, new TrustSelfSignedStrategy())
// .build();
//
// SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(
// sslContext,
// SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// );
//
// clientBuilder.sslConnectionSocketFactory(sslConnection);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// instance = clientBuilder.build();
// }
// return instance;
// }
//
// public static AgentInfo getAgentInfo() {
// return agentInfo;
// }
// }
| import org.json.simple.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import prj.jolokiaweb.jolokia.AgentInfo;
import prj.jolokiaweb.jolokia.JolokiaClient;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | package prj.jolokiaweb.config;
public class PermissionCheckInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURI().startsWith("/api/beans")) { | // Path: src/main/java/prj/jolokiaweb/jolokia/AgentInfo.java
// public class AgentInfo {
// public enum JolokiaPermission {
// NONE,READ,WRITE,EXECUTE
// }
//
// private String url;
// private boolean isLocalAgent = false;
// private boolean requireAuth = false;
// private String agentUsername;
// private String agentPassword;
//
// private String webUsername;
// private String webPassword;
// private SSLConfig SSLConfig = new SSLConfig();
//
// private Set<JolokiaPermission> beanPermissions = new HashSet<>();
//
// public AgentInfo() {
// }
//
// public String getUrl() {
// return (url != null) ? url.toString() : null;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getAgentUsername() {
// return agentUsername;
// }
//
// public void setAgentUsername(String agentUsername) {
// this.agentUsername = agentUsername;
// }
//
// public String getAgentPassword() {
// return agentPassword;
// }
//
// public void setAgentPassword(String agentPassword) {
// this.agentPassword = agentPassword;
// }
//
// public String getWebUsername() {
// return webUsername;
// }
//
// public void setWebUsername(String webUsername) {
// this.webUsername = webUsername;
// }
//
// public String getWebPassword() {
// return webPassword;
// }
//
// public void setWebPassword(String webPassword) {
// this.webPassword = webPassword;
// }
//
// public boolean isLocalAgent() {
// return isLocalAgent;
// }
//
// public boolean requiresLocalAuth() {
// return webUsername != null;
// }
//
// public void setLocalAgent(boolean localAgent) {
// isLocalAgent = localAgent;
// }
//
// public boolean isRequireAuth() {
// return requireAuth;
// }
//
// public void setRequireAuth(boolean requireAuth) {
// this.requireAuth = requireAuth;
// }
//
// public void addPermission(JolokiaPermission ... permission) {
// this.beanPermissions.addAll(Arrays.asList(permission));
// }
//
// public void clearPermission() {
// this.beanPermissions.clear();
// }
//
// public Set<JolokiaPermission> getBeanPermissions() {
// return beanPermissions;
// }
//
// public SSLConfig getSSLConfig() {
// return SSLConfig;
// }
//
// public void setSSLConfig(SSLConfig SSLConfig) {
// this.SSLConfig = SSLConfig;
// }
// }
//
// Path: src/main/java/prj/jolokiaweb/jolokia/JolokiaClient.java
// public class JolokiaClient {
// private static final int MAX_CONNECTIONS = 2;
// private static J4pClient instance;
// private static AgentInfo agentInfo;
//
//
// private JolokiaClient(){
// }
//
// public static J4pClient init(AgentInfo initialAgentInfo){
// if (instance != null) {
// return instance;
// }
// agentInfo = initialAgentInfo;
// return getInstance();
// }
//
// public static synchronized J4pClient getInstance() {
// if (instance == null) {
// String user = agentInfo.getAgentUsername();
// String password = agentInfo.getAgentPassword();
// if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {
// user = agentInfo.getWebUsername();
// password = agentInfo.getWebPassword();
// }
//
// J4pClientBuilder clientBuilder = J4pClientBuilderFactory
// .url(agentInfo.getUrl())
// .user(user)
// .password(password)
// .maxTotalConnections(MAX_CONNECTIONS);
//
// SSLConfig config = agentInfo.getSSLConfig();
// if (config.isSelfSignedCertAllowed()) {
// try {
// SSLContext sslContext = new SSLContextBuilder()
// .loadTrustMaterial(null, new TrustSelfSignedStrategy())
// .build();
//
// SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(
// sslContext,
// SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
// );
//
// clientBuilder.sslConnectionSocketFactory(sslConnection);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// instance = clientBuilder.build();
// }
// return instance;
// }
//
// public static AgentInfo getAgentInfo() {
// return agentInfo;
// }
// }
// Path: src/main/java/prj/jolokiaweb/config/PermissionCheckInterceptor.java
import org.json.simple.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import prj.jolokiaweb.jolokia.AgentInfo;
import prj.jolokiaweb.jolokia.JolokiaClient;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
package prj.jolokiaweb.config;
public class PermissionCheckInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURI().startsWith("/api/beans")) { | if (!JolokiaClient.getAgentInfo().getBeanPermissions().contains(AgentInfo.JolokiaPermission.READ)) { |
fabzo/kraken | src/main/java/fabzo/kraken/EnvironmentModule.java | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String IP_REF = "%s.ip";
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
| import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import io.vavr.collection.List;
import static fabzo.kraken.EnvironmentContext.IP_REF;
import static fabzo.kraken.EnvironmentContext.PORT_REF_FROM; | package fabzo.kraken;
/**
* Abstract environment module used to setup new test environments.
* Provides methods for registering infrastructure components and runners
* as well as setting configuration values.
*/
public abstract class EnvironmentModule {
private List<InfrastructureComponent> components = List.empty(); | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String IP_REF = "%s.ip";
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// Path: src/main/java/fabzo/kraken/EnvironmentModule.java
import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import io.vavr.collection.List;
import static fabzo.kraken.EnvironmentContext.IP_REF;
import static fabzo.kraken.EnvironmentContext.PORT_REF_FROM;
package fabzo.kraken;
/**
* Abstract environment module used to setup new test environments.
* Provides methods for registering infrastructure components and runners
* as well as setting configuration values.
*/
public abstract class EnvironmentModule {
private List<InfrastructureComponent> components = List.empty(); | private List<LifecycleHandler> handlers = List.empty(); |
fabzo/kraken | src/main/java/fabzo/kraken/EnvironmentModule.java | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String IP_REF = "%s.ip";
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
| import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import io.vavr.collection.List;
import static fabzo.kraken.EnvironmentContext.IP_REF;
import static fabzo.kraken.EnvironmentContext.PORT_REF_FROM; | package fabzo.kraken;
/**
* Abstract environment module used to setup new test environments.
* Provides methods for registering infrastructure components and runners
* as well as setting configuration values.
*/
public abstract class EnvironmentModule {
private List<InfrastructureComponent> components = List.empty();
private List<LifecycleHandler> handlers = List.empty();
public abstract void configure();
protected void register(final InfrastructureComponent component) {
this.components = components.append(component);
}
protected void register(final LifecycleHandler runner) {
this.handlers = handlers.append(runner);
}
List<InfrastructureComponent> components() {
return components;
}
List<LifecycleHandler> handlers() {
return handlers;
}
/**
* Builds a port reference that can be used to reference the port
* in component parameters.
*
* @param componentName Components name
* @param portName Ports name
* @return Port reference like ${:componentName:.ports.:portName:.from}
*/
protected String portRef(final String componentName, final String portName) { | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String IP_REF = "%s.ip";
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// Path: src/main/java/fabzo/kraken/EnvironmentModule.java
import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import io.vavr.collection.List;
import static fabzo.kraken.EnvironmentContext.IP_REF;
import static fabzo.kraken.EnvironmentContext.PORT_REF_FROM;
package fabzo.kraken;
/**
* Abstract environment module used to setup new test environments.
* Provides methods for registering infrastructure components and runners
* as well as setting configuration values.
*/
public abstract class EnvironmentModule {
private List<InfrastructureComponent> components = List.empty();
private List<LifecycleHandler> handlers = List.empty();
public abstract void configure();
protected void register(final InfrastructureComponent component) {
this.components = components.append(component);
}
protected void register(final LifecycleHandler runner) {
this.handlers = handlers.append(runner);
}
List<InfrastructureComponent> components() {
return components;
}
List<LifecycleHandler> handlers() {
return handlers;
}
/**
* Builds a port reference that can be used to reference the port
* in component parameters.
*
* @param componentName Components name
* @param portName Ports name
* @return Port reference like ${:componentName:.ports.:portName:.from}
*/
protected String portRef(final String componentName, final String portName) { | return String.format("${" + PORT_REF_FROM + "}", componentName, portName); |
fabzo/kraken | src/main/java/fabzo/kraken/EnvironmentModule.java | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String IP_REF = "%s.ip";
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
| import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import io.vavr.collection.List;
import static fabzo.kraken.EnvironmentContext.IP_REF;
import static fabzo.kraken.EnvironmentContext.PORT_REF_FROM; | package fabzo.kraken;
/**
* Abstract environment module used to setup new test environments.
* Provides methods for registering infrastructure components and runners
* as well as setting configuration values.
*/
public abstract class EnvironmentModule {
private List<InfrastructureComponent> components = List.empty();
private List<LifecycleHandler> handlers = List.empty();
public abstract void configure();
protected void register(final InfrastructureComponent component) {
this.components = components.append(component);
}
protected void register(final LifecycleHandler runner) {
this.handlers = handlers.append(runner);
}
List<InfrastructureComponent> components() {
return components;
}
List<LifecycleHandler> handlers() {
return handlers;
}
/**
* Builds a port reference that can be used to reference the port
* in component parameters.
*
* @param componentName Components name
* @param portName Ports name
* @return Port reference like ${:componentName:.ports.:portName:.from}
*/
protected String portRef(final String componentName, final String portName) {
return String.format("${" + PORT_REF_FROM + "}", componentName, portName);
}
/**
* Builds a ip reference that can be used to reference the IP
* in component parameters.
*
* @param componentName Components name
* @return IP reference like ${:componentName:.ip}
*/
protected String ipRef(final String componentName) { | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String IP_REF = "%s.ip";
//
// Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// Path: src/main/java/fabzo/kraken/EnvironmentModule.java
import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import io.vavr.collection.List;
import static fabzo.kraken.EnvironmentContext.IP_REF;
import static fabzo.kraken.EnvironmentContext.PORT_REF_FROM;
package fabzo.kraken;
/**
* Abstract environment module used to setup new test environments.
* Provides methods for registering infrastructure components and runners
* as well as setting configuration values.
*/
public abstract class EnvironmentModule {
private List<InfrastructureComponent> components = List.empty();
private List<LifecycleHandler> handlers = List.empty();
public abstract void configure();
protected void register(final InfrastructureComponent component) {
this.components = components.append(component);
}
protected void register(final LifecycleHandler runner) {
this.handlers = handlers.append(runner);
}
List<InfrastructureComponent> components() {
return components;
}
List<LifecycleHandler> handlers() {
return handlers;
}
/**
* Builds a port reference that can be used to reference the port
* in component parameters.
*
* @param componentName Components name
* @param portName Ports name
* @return Port reference like ${:componentName:.ports.:portName:.from}
*/
protected String portRef(final String componentName, final String portName) {
return String.format("${" + PORT_REF_FROM + "}", componentName, portName);
}
/**
* Builds a ip reference that can be used to reference the IP
* in component parameters.
*
* @param componentName Components name
* @return IP reference like ${:componentName:.ip}
*/
protected String ipRef(final String componentName) { | return String.format("${" + IP_REF + "}", componentName); |
fabzo/kraken | src/main/java/fabzo/kraken/handler/LifecycleHandler.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent; | package fabzo.kraken.handler;
public interface LifecycleHandler {
boolean canRun(final Class<? extends InfrastructureComponent> clazz);
| // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
package fabzo.kraken.handler;
public interface LifecycleHandler {
boolean canRun(final Class<? extends InfrastructureComponent> clazz);
| boolean run(final InfrastructureComponent component, final EnvironmentContext ctx); |
fabzo/kraken | src/main/java/fabzo/kraken/Kraken.java | // Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
| import lombok.extern.slf4j.Slf4j;
import static fabzo.kraken.utils.Utils.nameOf; | package fabzo.kraken;
@Slf4j
public class Kraken {
public static Environment createEnvironment(final EnvironmentModule module) { | // Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// Path: src/main/java/fabzo/kraken/Kraken.java
import lombok.extern.slf4j.Slf4j;
import static fabzo.kraken.utils.Utils.nameOf;
package fabzo.kraken;
@Slf4j
public class Kraken {
public static Environment createEnvironment(final EnvironmentModule module) { | log.info("Configuring module {}", nameOf(module)); |
fabzo/kraken | src/main/java/fabzo/kraken/wait/HTTPWait.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await; | package fabzo.kraken.wait;
@Slf4j
public class HTTPWait implements Wait {
private final String url;
private final String containsText;
private final Duration atMost;
public HTTPWait(final String url, final String containsText, final Duration atMost) {
this.url = url;
this.containsText = containsText;
this.atMost = atMost;
}
@Override | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/wait/HTTPWait.java
import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
package fabzo.kraken.wait;
@Slf4j
public class HTTPWait implements Wait {
private final String url;
private final String containsText;
private final Duration atMost;
public HTTPWait(final String url, final String containsText, final Duration atMost) {
this.url = url;
this.containsText = containsText;
this.atMost = atMost;
}
@Override | public boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component) { |
fabzo/kraken | src/main/java/fabzo/kraken/wait/HTTPWait.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await; | package fabzo.kraken.wait;
@Slf4j
public class HTTPWait implements Wait {
private final String url;
private final String containsText;
private final Duration atMost;
public HTTPWait(final String url, final String containsText, final Duration atMost) {
this.url = url;
this.containsText = containsText;
this.atMost = atMost;
}
@Override | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/wait/HTTPWait.java
import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
package fabzo.kraken.wait;
@Slf4j
public class HTTPWait implements Wait {
private final String url;
private final String containsText;
private final Duration atMost;
public HTTPWait(final String url, final String containsText, final Duration atMost) {
this.url = url;
this.containsText = containsText;
this.atMost = atMost;
}
@Override | public boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component) { |
fabzo/kraken | src/main/java/fabzo/kraken/wait/DatabaseWait.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import io.vavr.control.Option;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import java.sql.DriverManager;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static com.jayway.awaitility.Awaitility.await; | package fabzo.kraken.wait;
@Slf4j
public class DatabaseWait implements Wait {
private static final String DEFAULT_JDBC_URL = "jdbc:%s://%s:%s/%s?user=%s&password=%s&useUnicode=true&characterEncoding=utf8&useSSL=false&nullNamePatternMatchesAll=true&socketTimeout=5000";
private static final String TEST_SQL = "SELECT 1";
private String username = "root";
private String password = "";
private String driver;
private String database;
private String portName;
private final Duration atMost;
private Option<String> connectionUrl = Option.none();
public DatabaseWait(final String driver, final String database, final String username, final String password, final String portName, final Duration atMost) {
this.driver = driver;
this.database = database;
this.portName = portName;
this.username = username;
this.password = password;
this.atMost = atMost;
}
public DatabaseWait(final String connectionUrl, final Duration atMost) {
this.connectionUrl = Option.of(connectionUrl);
this.atMost = atMost;
}
| // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/wait/DatabaseWait.java
import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import io.vavr.control.Option;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import java.sql.DriverManager;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static com.jayway.awaitility.Awaitility.await;
package fabzo.kraken.wait;
@Slf4j
public class DatabaseWait implements Wait {
private static final String DEFAULT_JDBC_URL = "jdbc:%s://%s:%s/%s?user=%s&password=%s&useUnicode=true&characterEncoding=utf8&useSSL=false&nullNamePatternMatchesAll=true&socketTimeout=5000";
private static final String TEST_SQL = "SELECT 1";
private String username = "root";
private String password = "";
private String driver;
private String database;
private String portName;
private final Duration atMost;
private Option<String> connectionUrl = Option.none();
public DatabaseWait(final String driver, final String database, final String username, final String password, final String portName, final Duration atMost) {
this.driver = driver;
this.database = database;
this.portName = portName;
this.username = username;
this.password = password;
this.atMost = atMost;
}
public DatabaseWait(final String connectionUrl, final Duration atMost) {
this.connectionUrl = Option.of(connectionUrl);
this.atMost = atMost;
}
| private String createConnectionUrl(final InfrastructureComponent component, final EnvironmentContext ctx) { |
fabzo/kraken | src/main/java/fabzo/kraken/wait/DatabaseWait.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import io.vavr.control.Option;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import java.sql.DriverManager;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static com.jayway.awaitility.Awaitility.await; | package fabzo.kraken.wait;
@Slf4j
public class DatabaseWait implements Wait {
private static final String DEFAULT_JDBC_URL = "jdbc:%s://%s:%s/%s?user=%s&password=%s&useUnicode=true&characterEncoding=utf8&useSSL=false&nullNamePatternMatchesAll=true&socketTimeout=5000";
private static final String TEST_SQL = "SELECT 1";
private String username = "root";
private String password = "";
private String driver;
private String database;
private String portName;
private final Duration atMost;
private Option<String> connectionUrl = Option.none();
public DatabaseWait(final String driver, final String database, final String username, final String password, final String portName, final Duration atMost) {
this.driver = driver;
this.database = database;
this.portName = portName;
this.username = username;
this.password = password;
this.atMost = atMost;
}
public DatabaseWait(final String connectionUrl, final Duration atMost) {
this.connectionUrl = Option.of(connectionUrl);
this.atMost = atMost;
}
| // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/wait/DatabaseWait.java
import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import io.vavr.control.Option;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import java.sql.DriverManager;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static com.jayway.awaitility.Awaitility.await;
package fabzo.kraken.wait;
@Slf4j
public class DatabaseWait implements Wait {
private static final String DEFAULT_JDBC_URL = "jdbc:%s://%s:%s/%s?user=%s&password=%s&useUnicode=true&characterEncoding=utf8&useSSL=false&nullNamePatternMatchesAll=true&socketTimeout=5000";
private static final String TEST_SQL = "SELECT 1";
private String username = "root";
private String password = "";
private String driver;
private String database;
private String portName;
private final Duration atMost;
private Option<String> connectionUrl = Option.none();
public DatabaseWait(final String driver, final String database, final String username, final String password, final String portName, final Duration atMost) {
this.driver = driver;
this.database = database;
this.portName = portName;
this.username = username;
this.password = password;
this.atMost = atMost;
}
public DatabaseWait(final String connectionUrl, final Duration atMost) {
this.connectionUrl = Option.of(connectionUrl);
this.atMost = atMost;
}
| private String createConnectionUrl(final InfrastructureComponent component, final EnvironmentContext ctx) { |
fabzo/kraken | src/main/java/fabzo/kraken/wait/TimeWait.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.time.temporal.TemporalUnit; | package fabzo.kraken.wait;
@Slf4j
public class TimeWait implements Wait {
private final Duration duration;
public TimeWait(final int amount, final TemporalUnit unit) {
this(Duration.of(amount, unit));
}
public TimeWait(final Duration duration) {
this.duration = duration;
}
@Override | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/wait/TimeWait.java
import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.time.temporal.TemporalUnit;
package fabzo.kraken.wait;
@Slf4j
public class TimeWait implements Wait {
private final Duration duration;
public TimeWait(final int amount, final TemporalUnit unit) {
this(Duration.of(amount, unit));
}
public TimeWait(final Duration duration) {
this.duration = duration;
}
@Override | public boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component) { |
fabzo/kraken | src/main/java/fabzo/kraken/wait/TimeWait.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.time.temporal.TemporalUnit; | package fabzo.kraken.wait;
@Slf4j
public class TimeWait implements Wait {
private final Duration duration;
public TimeWait(final int amount, final TemporalUnit unit) {
this(Duration.of(amount, unit));
}
public TimeWait(final Duration duration) {
this.duration = duration;
}
@Override | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/wait/TimeWait.java
import com.google.common.base.MoreObjects;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.time.temporal.TemporalUnit;
package fabzo.kraken.wait;
@Slf4j
public class TimeWait implements Wait {
private final Duration duration;
public TimeWait(final int amount, final TemporalUnit unit) {
this(Duration.of(amount, unit));
}
public TimeWait(final Duration duration) {
this.duration = duration;
}
@Override | public boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component) { |
fabzo/kraken | src/main/java/fabzo/kraken/handler/AbstractLifecycleHandler.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/ComponentState.java
// public enum ComponentState {
// WAITING,
// CREATING,
// STARTING,
// STARTED,
// STOPPED,
// DESTROYED
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.ComponentState;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val; | package fabzo.kraken.handler;
@Slf4j
public abstract class AbstractLifecycleHandler implements LifecycleHandler {
private boolean isInitialized = false;
@Override | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/ComponentState.java
// public enum ComponentState {
// WAITING,
// CREATING,
// STARTING,
// STARTED,
// STOPPED,
// DESTROYED
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/handler/AbstractLifecycleHandler.java
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.ComponentState;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
package fabzo.kraken.handler;
@Slf4j
public abstract class AbstractLifecycleHandler implements LifecycleHandler {
private boolean isInitialized = false;
@Override | public boolean run(final InfrastructureComponent component, final EnvironmentContext ctx) { |
fabzo/kraken | src/main/java/fabzo/kraken/handler/AbstractLifecycleHandler.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/ComponentState.java
// public enum ComponentState {
// WAITING,
// CREATING,
// STARTING,
// STARTED,
// STOPPED,
// DESTROYED
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.ComponentState;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val; | package fabzo.kraken.handler;
@Slf4j
public abstract class AbstractLifecycleHandler implements LifecycleHandler {
private boolean isInitialized = false;
@Override | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/ComponentState.java
// public enum ComponentState {
// WAITING,
// CREATING,
// STARTING,
// STARTED,
// STOPPED,
// DESTROYED
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/handler/AbstractLifecycleHandler.java
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.ComponentState;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
package fabzo.kraken.handler;
@Slf4j
public abstract class AbstractLifecycleHandler implements LifecycleHandler {
private boolean isInitialized = false;
@Override | public boolean run(final InfrastructureComponent component, final EnvironmentContext ctx) { |
fabzo/kraken | src/main/java/fabzo/kraken/handler/AbstractLifecycleHandler.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/ComponentState.java
// public enum ComponentState {
// WAITING,
// CREATING,
// STARTING,
// STARTED,
// STOPPED,
// DESTROYED
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.ComponentState;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val; | package fabzo.kraken.handler;
@Slf4j
public abstract class AbstractLifecycleHandler implements LifecycleHandler {
private boolean isInitialized = false;
@Override
public boolean run(final InfrastructureComponent component, final EnvironmentContext ctx) {
final boolean runResult = doRun(component, ctx);
waitForComponent(component, ctx);
return runResult;
}
protected void waitForComponent(final InfrastructureComponent component, final EnvironmentContext ctx) {
component.waitFuncs().forEach(wait -> {
log.info("Waiting for {} using {}", component.name(), wait.toString());
if (!wait.execute(ctx, component)) {
throw new IllegalStateException("Wait function " + wait.getClass().getSimpleName() + " failed");
}
});
}
protected boolean isRunning(final InfrastructureComponent component) {
val state = component.state();
| // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/ComponentState.java
// public enum ComponentState {
// WAITING,
// CREATING,
// STARTING,
// STARTED,
// STOPPED,
// DESTROYED
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/handler/AbstractLifecycleHandler.java
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.ComponentState;
import fabzo.kraken.components.InfrastructureComponent;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
package fabzo.kraken.handler;
@Slf4j
public abstract class AbstractLifecycleHandler implements LifecycleHandler {
private boolean isInitialized = false;
@Override
public boolean run(final InfrastructureComponent component, final EnvironmentContext ctx) {
final boolean runResult = doRun(component, ctx);
waitForComponent(component, ctx);
return runResult;
}
protected void waitForComponent(final InfrastructureComponent component, final EnvironmentContext ctx) {
component.waitFuncs().forEach(wait -> {
log.info("Waiting for {} using {}", component.name(), wait.toString());
if (!wait.execute(ctx, component)) {
throw new IllegalStateException("Wait function " + wait.getClass().getSimpleName() + " failed");
}
});
}
protected boolean isRunning(final InfrastructureComponent component) {
val state = component.state();
| return state == ComponentState.CREATING |
fabzo/kraken | src/main/java/fabzo/kraken/components/InfrastructureComponent.java | // Path: src/main/java/fabzo/kraken/wait/Wait.java
// public interface Wait {
// boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component);
// }
| import fabzo.kraken.wait.Wait;
import io.vavr.collection.List; | package fabzo.kraken.components;
public abstract class InfrastructureComponent implements Named {
private ComponentState state = ComponentState.WAITING; | // Path: src/main/java/fabzo/kraken/wait/Wait.java
// public interface Wait {
// boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component);
// }
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
import fabzo.kraken.wait.Wait;
import io.vavr.collection.List;
package fabzo.kraken.components;
public abstract class InfrastructureComponent implements Named {
private ComponentState state = ComponentState.WAITING; | private List<Wait> waitFunctions = List.empty(); |
fabzo/kraken | src/main/java/fabzo/kraken/handler/docker/DockerCommands.java | // Path: src/main/java/fabzo/kraken/handler/docker/callbacks/LogContainerResultCallback.java
// @Slf4j
// public class LogContainerResultCallback extends ResultCallbackTemplate<LogContainerResultCallback, Frame> {
// private final String logPrefix;
//
// public LogContainerResultCallback(final String logPrefix) {
// this.logPrefix = logPrefix;
// }
//
// @Override
// public void onNext(final Frame item) {
// log.info("[{}] {}", logPrefix, item.toString());
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/docker/callbacks/NoLogPullImageResultCallback.java
// public class NoLogPullImageResultCallback extends NoLogResultCallbackTemplate<NoLogPullImageResultCallback, PullResponseItem> {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NoLogPullImageResultCallback.class);
//
// @CheckForNull
// private PullResponseItem latestItem = null;
//
// @Override
// public void onNext(PullResponseItem item) {
// this.latestItem = item;
// LOGGER.debug(item.toString());
// }
//
// /**
// * Awaits the image to be pulled successful.
// *
// * @throws DockerClientException
// * if the pull fails.
// */
// public void awaitSuccess() {
// try {
// awaitCompletion();
// } catch (InterruptedException e) {
// throw new DockerClientException("", e);
// }
//
// if (latestItem == null) {
// throw new DockerClientException("Could not pull image");
// } else if (!latestItem.isPullSuccessIndicated()) {
// String message = (latestItem.getError() != null) ? latestItem.getError() : latestItem.getStatus();
// throw new DockerClientException("Could not pull image: " + message);
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
| import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import fabzo.kraken.handler.docker.callbacks.LogContainerResultCallback;
import fabzo.kraken.handler.docker.callbacks.NoLogPullImageResultCallback;
import fabzo.kraken.utils.ShutdownHookManager;
import io.vavr.collection.List;
import io.vavr.control.Try;
import lombok.val; | package fabzo.kraken.handler.docker;
public class DockerCommands {
private static final String API_VERSION = "1.23";
private static final boolean VERIFY_TLS = false;
private final String dockerSocket;
private final DockerClient dockerClient;
private List<DockerClient> logDockerClients = List.empty();
public DockerCommands(final String dockerSocket, final String dockerRegistry) {
this.dockerSocket = dockerSocket;
this.dockerClient = newDockerClient(dockerSocket, dockerRegistry);
| // Path: src/main/java/fabzo/kraken/handler/docker/callbacks/LogContainerResultCallback.java
// @Slf4j
// public class LogContainerResultCallback extends ResultCallbackTemplate<LogContainerResultCallback, Frame> {
// private final String logPrefix;
//
// public LogContainerResultCallback(final String logPrefix) {
// this.logPrefix = logPrefix;
// }
//
// @Override
// public void onNext(final Frame item) {
// log.info("[{}] {}", logPrefix, item.toString());
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/docker/callbacks/NoLogPullImageResultCallback.java
// public class NoLogPullImageResultCallback extends NoLogResultCallbackTemplate<NoLogPullImageResultCallback, PullResponseItem> {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NoLogPullImageResultCallback.class);
//
// @CheckForNull
// private PullResponseItem latestItem = null;
//
// @Override
// public void onNext(PullResponseItem item) {
// this.latestItem = item;
// LOGGER.debug(item.toString());
// }
//
// /**
// * Awaits the image to be pulled successful.
// *
// * @throws DockerClientException
// * if the pull fails.
// */
// public void awaitSuccess() {
// try {
// awaitCompletion();
// } catch (InterruptedException e) {
// throw new DockerClientException("", e);
// }
//
// if (latestItem == null) {
// throw new DockerClientException("Could not pull image");
// } else if (!latestItem.isPullSuccessIndicated()) {
// String message = (latestItem.getError() != null) ? latestItem.getError() : latestItem.getStatus();
// throw new DockerClientException("Could not pull image: " + message);
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
// Path: src/main/java/fabzo/kraken/handler/docker/DockerCommands.java
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import fabzo.kraken.handler.docker.callbacks.LogContainerResultCallback;
import fabzo.kraken.handler.docker.callbacks.NoLogPullImageResultCallback;
import fabzo.kraken.utils.ShutdownHookManager;
import io.vavr.collection.List;
import io.vavr.control.Try;
import lombok.val;
package fabzo.kraken.handler.docker;
public class DockerCommands {
private static final String API_VERSION = "1.23";
private static final boolean VERIFY_TLS = false;
private final String dockerSocket;
private final DockerClient dockerClient;
private List<DockerClient> logDockerClients = List.empty();
public DockerCommands(final String dockerSocket, final String dockerRegistry) {
this.dockerSocket = dockerSocket;
this.dockerClient = newDockerClient(dockerSocket, dockerRegistry);
| ShutdownHookManager.addHook(1, this::cleanup); |
fabzo/kraken | src/main/java/fabzo/kraken/handler/docker/DockerCommands.java | // Path: src/main/java/fabzo/kraken/handler/docker/callbacks/LogContainerResultCallback.java
// @Slf4j
// public class LogContainerResultCallback extends ResultCallbackTemplate<LogContainerResultCallback, Frame> {
// private final String logPrefix;
//
// public LogContainerResultCallback(final String logPrefix) {
// this.logPrefix = logPrefix;
// }
//
// @Override
// public void onNext(final Frame item) {
// log.info("[{}] {}", logPrefix, item.toString());
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/docker/callbacks/NoLogPullImageResultCallback.java
// public class NoLogPullImageResultCallback extends NoLogResultCallbackTemplate<NoLogPullImageResultCallback, PullResponseItem> {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NoLogPullImageResultCallback.class);
//
// @CheckForNull
// private PullResponseItem latestItem = null;
//
// @Override
// public void onNext(PullResponseItem item) {
// this.latestItem = item;
// LOGGER.debug(item.toString());
// }
//
// /**
// * Awaits the image to be pulled successful.
// *
// * @throws DockerClientException
// * if the pull fails.
// */
// public void awaitSuccess() {
// try {
// awaitCompletion();
// } catch (InterruptedException e) {
// throw new DockerClientException("", e);
// }
//
// if (latestItem == null) {
// throw new DockerClientException("Could not pull image");
// } else if (!latestItem.isPullSuccessIndicated()) {
// String message = (latestItem.getError() != null) ? latestItem.getError() : latestItem.getStatus();
// throw new DockerClientException("Could not pull image: " + message);
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
| import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import fabzo.kraken.handler.docker.callbacks.LogContainerResultCallback;
import fabzo.kraken.handler.docker.callbacks.NoLogPullImageResultCallback;
import fabzo.kraken.utils.ShutdownHookManager;
import io.vavr.collection.List;
import io.vavr.control.Try;
import lombok.val; | package fabzo.kraken.handler.docker;
public class DockerCommands {
private static final String API_VERSION = "1.23";
private static final boolean VERIFY_TLS = false;
private final String dockerSocket;
private final DockerClient dockerClient;
private List<DockerClient> logDockerClients = List.empty();
public DockerCommands(final String dockerSocket, final String dockerRegistry) {
this.dockerSocket = dockerSocket;
this.dockerClient = newDockerClient(dockerSocket, dockerRegistry);
ShutdownHookManager.addHook(1, this::cleanup);
}
private void cleanup() {
Try.run(dockerClient::close);
logDockerClients.forEach(client -> Try.run(client::close));
}
private DockerClient newDockerClient(final String dockerSocket, final String dockerRegistry) {
val dockerConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost(dockerSocket)
.withDockerTlsVerify(VERIFY_TLS)
.withApiVersion(API_VERSION)
.withRegistryUrl(dockerRegistry)
.build();
return DockerClientBuilder.getInstance(dockerConfig).build();
}
public void pullImage(final String image, final String tag) {
dockerClient.pullImageCmd(image + ":" + tag) | // Path: src/main/java/fabzo/kraken/handler/docker/callbacks/LogContainerResultCallback.java
// @Slf4j
// public class LogContainerResultCallback extends ResultCallbackTemplate<LogContainerResultCallback, Frame> {
// private final String logPrefix;
//
// public LogContainerResultCallback(final String logPrefix) {
// this.logPrefix = logPrefix;
// }
//
// @Override
// public void onNext(final Frame item) {
// log.info("[{}] {}", logPrefix, item.toString());
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/docker/callbacks/NoLogPullImageResultCallback.java
// public class NoLogPullImageResultCallback extends NoLogResultCallbackTemplate<NoLogPullImageResultCallback, PullResponseItem> {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NoLogPullImageResultCallback.class);
//
// @CheckForNull
// private PullResponseItem latestItem = null;
//
// @Override
// public void onNext(PullResponseItem item) {
// this.latestItem = item;
// LOGGER.debug(item.toString());
// }
//
// /**
// * Awaits the image to be pulled successful.
// *
// * @throws DockerClientException
// * if the pull fails.
// */
// public void awaitSuccess() {
// try {
// awaitCompletion();
// } catch (InterruptedException e) {
// throw new DockerClientException("", e);
// }
//
// if (latestItem == null) {
// throw new DockerClientException("Could not pull image");
// } else if (!latestItem.isPullSuccessIndicated()) {
// String message = (latestItem.getError() != null) ? latestItem.getError() : latestItem.getStatus();
// throw new DockerClientException("Could not pull image: " + message);
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
// Path: src/main/java/fabzo/kraken/handler/docker/DockerCommands.java
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import fabzo.kraken.handler.docker.callbacks.LogContainerResultCallback;
import fabzo.kraken.handler.docker.callbacks.NoLogPullImageResultCallback;
import fabzo.kraken.utils.ShutdownHookManager;
import io.vavr.collection.List;
import io.vavr.control.Try;
import lombok.val;
package fabzo.kraken.handler.docker;
public class DockerCommands {
private static final String API_VERSION = "1.23";
private static final boolean VERIFY_TLS = false;
private final String dockerSocket;
private final DockerClient dockerClient;
private List<DockerClient> logDockerClients = List.empty();
public DockerCommands(final String dockerSocket, final String dockerRegistry) {
this.dockerSocket = dockerSocket;
this.dockerClient = newDockerClient(dockerSocket, dockerRegistry);
ShutdownHookManager.addHook(1, this::cleanup);
}
private void cleanup() {
Try.run(dockerClient::close);
logDockerClients.forEach(client -> Try.run(client::close));
}
private DockerClient newDockerClient(final String dockerSocket, final String dockerRegistry) {
val dockerConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost(dockerSocket)
.withDockerTlsVerify(VERIFY_TLS)
.withApiVersion(API_VERSION)
.withRegistryUrl(dockerRegistry)
.build();
return DockerClientBuilder.getInstance(dockerConfig).build();
}
public void pullImage(final String image, final String tag) {
dockerClient.pullImageCmd(image + ":" + tag) | .exec(new NoLogPullImageResultCallback()) |
fabzo/kraken | src/main/java/fabzo/kraken/handler/docker/DockerCommands.java | // Path: src/main/java/fabzo/kraken/handler/docker/callbacks/LogContainerResultCallback.java
// @Slf4j
// public class LogContainerResultCallback extends ResultCallbackTemplate<LogContainerResultCallback, Frame> {
// private final String logPrefix;
//
// public LogContainerResultCallback(final String logPrefix) {
// this.logPrefix = logPrefix;
// }
//
// @Override
// public void onNext(final Frame item) {
// log.info("[{}] {}", logPrefix, item.toString());
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/docker/callbacks/NoLogPullImageResultCallback.java
// public class NoLogPullImageResultCallback extends NoLogResultCallbackTemplate<NoLogPullImageResultCallback, PullResponseItem> {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NoLogPullImageResultCallback.class);
//
// @CheckForNull
// private PullResponseItem latestItem = null;
//
// @Override
// public void onNext(PullResponseItem item) {
// this.latestItem = item;
// LOGGER.debug(item.toString());
// }
//
// /**
// * Awaits the image to be pulled successful.
// *
// * @throws DockerClientException
// * if the pull fails.
// */
// public void awaitSuccess() {
// try {
// awaitCompletion();
// } catch (InterruptedException e) {
// throw new DockerClientException("", e);
// }
//
// if (latestItem == null) {
// throw new DockerClientException("Could not pull image");
// } else if (!latestItem.isPullSuccessIndicated()) {
// String message = (latestItem.getError() != null) ? latestItem.getError() : latestItem.getStatus();
// throw new DockerClientException("Could not pull image: " + message);
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
| import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import fabzo.kraken.handler.docker.callbacks.LogContainerResultCallback;
import fabzo.kraken.handler.docker.callbacks.NoLogPullImageResultCallback;
import fabzo.kraken.utils.ShutdownHookManager;
import io.vavr.collection.List;
import io.vavr.control.Try;
import lombok.val; |
public void removeContainer(final String id) {
dockerClient.removeContainerCmd(id).exec();
}
public void startContainer(final String id) {
dockerClient.startContainerCmd(id).exec();
}
public boolean isImageAvailable(final String image, final String tag) {
try {
dockerClient.inspectImageCmd(image + ":" + tag).exec();
return true;
} catch (final Exception e) {
return false;
}
}
public CreateContainerCmd createContainer(final String image) {
return dockerClient.createContainerCmd(image);
}
public void logContainer(final String id, final String logPrefix) {
val dockerClient = newDockerClient(dockerSocket, "");
logDockerClients = logDockerClients.append(dockerClient);
dockerClient.logContainerCmd(id)
.withFollowStream(true)
.withStdOut(true)
.withStdErr(true) | // Path: src/main/java/fabzo/kraken/handler/docker/callbacks/LogContainerResultCallback.java
// @Slf4j
// public class LogContainerResultCallback extends ResultCallbackTemplate<LogContainerResultCallback, Frame> {
// private final String logPrefix;
//
// public LogContainerResultCallback(final String logPrefix) {
// this.logPrefix = logPrefix;
// }
//
// @Override
// public void onNext(final Frame item) {
// log.info("[{}] {}", logPrefix, item.toString());
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/docker/callbacks/NoLogPullImageResultCallback.java
// public class NoLogPullImageResultCallback extends NoLogResultCallbackTemplate<NoLogPullImageResultCallback, PullResponseItem> {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NoLogPullImageResultCallback.class);
//
// @CheckForNull
// private PullResponseItem latestItem = null;
//
// @Override
// public void onNext(PullResponseItem item) {
// this.latestItem = item;
// LOGGER.debug(item.toString());
// }
//
// /**
// * Awaits the image to be pulled successful.
// *
// * @throws DockerClientException
// * if the pull fails.
// */
// public void awaitSuccess() {
// try {
// awaitCompletion();
// } catch (InterruptedException e) {
// throw new DockerClientException("", e);
// }
//
// if (latestItem == null) {
// throw new DockerClientException("Could not pull image");
// } else if (!latestItem.isPullSuccessIndicated()) {
// String message = (latestItem.getError() != null) ? latestItem.getError() : latestItem.getStatus();
// throw new DockerClientException("Could not pull image: " + message);
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
// Path: src/main/java/fabzo/kraken/handler/docker/DockerCommands.java
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import fabzo.kraken.handler.docker.callbacks.LogContainerResultCallback;
import fabzo.kraken.handler.docker.callbacks.NoLogPullImageResultCallback;
import fabzo.kraken.utils.ShutdownHookManager;
import io.vavr.collection.List;
import io.vavr.control.Try;
import lombok.val;
public void removeContainer(final String id) {
dockerClient.removeContainerCmd(id).exec();
}
public void startContainer(final String id) {
dockerClient.startContainerCmd(id).exec();
}
public boolean isImageAvailable(final String image, final String tag) {
try {
dockerClient.inspectImageCmd(image + ":" + tag).exec();
return true;
} catch (final Exception e) {
return false;
}
}
public CreateContainerCmd createContainer(final String image) {
return dockerClient.createContainerCmd(image);
}
public void logContainer(final String id, final String logPrefix) {
val dockerClient = newDockerClient(dockerSocket, "");
logDockerClients = logDockerClients.append(dockerClient);
dockerClient.logContainerCmd(id)
.withFollowStream(true)
.withStdOut(true)
.withStdErr(true) | .exec(new LogContainerResultCallback(logPrefix)); |
fabzo/kraken | src/main/java/fabzo/kraken/Environment.java | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public class Utils {
// private static final String RUNNING_IN_IDE = "RUNNING_IN_IDE";
// private static final Object ASSIGNED_PORTS_MONITOR = new Object();
// private static Set<Integer> assignedPorts = HashSet.empty();
//
// public static boolean isRunningInIDE() {
// final boolean foundIdeaRtJar = System.getProperty("java.class.path").contains("idea_rt.jar");
//
// String runningInIDE = System.getenv(RUNNING_IN_IDE);
// if (runningInIDE == null) {
// runningInIDE = System.getProperty(RUNNING_IN_IDE);
// }
//
// return foundIdeaRtJar || "true".equalsIgnoreCase(runningInIDE);
// }
//
// public static Try<Integer> getAvailablePort() {
// synchronized (ASSIGNED_PORTS_MONITOR) {
// return Try.of(() -> {
// int hostPort;
// do {
// final ServerSocket serverSocket = new ServerSocket(0);
// hostPort = serverSocket.getLocalPort();
// serverSocket.close();
// } while (assignedPorts.contains(hostPort));
//
// assignedPorts = assignedPorts.add(hostPort);
//
// return hostPort;
// });
// }
// }
//
// public static Try<String> getPublicFacingIP() {
// return Try.of(() -> {
// final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// final NetworkInterface iface = interfaces.nextElement();
// if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) {
// continue;
// }
//
// final Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// final InetAddress addr = addresses.nextElement();
//
// final String ip = addr.getHostAddress();
// if (Inet4Address.class == addr.getClass()) {
// return ip;
// }
// }
// }
//
// throw new Exception("Could not find public facing IP");
// });
// }
//
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
| import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import fabzo.kraken.utils.ShutdownHookManager;
import fabzo.kraken.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import static fabzo.kraken.utils.Utils.nameOf; | package fabzo.kraken;
@Slf4j
public class Environment {
private final EnvironmentModule module;
private final EnvironmentContext context;
public Environment(final EnvironmentModule module) {
this.module = module;
val salt = RandomStringUtils.randomAlphabetic(8).toLowerCase();
log.info("Using environment salt {}", salt);
this.context = new EnvironmentContext(salt);
setupEnvironment();
}
private void setupEnvironment() { | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public class Utils {
// private static final String RUNNING_IN_IDE = "RUNNING_IN_IDE";
// private static final Object ASSIGNED_PORTS_MONITOR = new Object();
// private static Set<Integer> assignedPorts = HashSet.empty();
//
// public static boolean isRunningInIDE() {
// final boolean foundIdeaRtJar = System.getProperty("java.class.path").contains("idea_rt.jar");
//
// String runningInIDE = System.getenv(RUNNING_IN_IDE);
// if (runningInIDE == null) {
// runningInIDE = System.getProperty(RUNNING_IN_IDE);
// }
//
// return foundIdeaRtJar || "true".equalsIgnoreCase(runningInIDE);
// }
//
// public static Try<Integer> getAvailablePort() {
// synchronized (ASSIGNED_PORTS_MONITOR) {
// return Try.of(() -> {
// int hostPort;
// do {
// final ServerSocket serverSocket = new ServerSocket(0);
// hostPort = serverSocket.getLocalPort();
// serverSocket.close();
// } while (assignedPorts.contains(hostPort));
//
// assignedPorts = assignedPorts.add(hostPort);
//
// return hostPort;
// });
// }
// }
//
// public static Try<String> getPublicFacingIP() {
// return Try.of(() -> {
// final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// final NetworkInterface iface = interfaces.nextElement();
// if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) {
// continue;
// }
//
// final Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// final InetAddress addr = addresses.nextElement();
//
// final String ip = addr.getHostAddress();
// if (Inet4Address.class == addr.getClass()) {
// return ip;
// }
// }
// }
//
// throw new Exception("Could not find public facing IP");
// });
// }
//
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// Path: src/main/java/fabzo/kraken/Environment.java
import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import fabzo.kraken.utils.ShutdownHookManager;
import fabzo.kraken.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import static fabzo.kraken.utils.Utils.nameOf;
package fabzo.kraken;
@Slf4j
public class Environment {
private final EnvironmentModule module;
private final EnvironmentContext context;
public Environment(final EnvironmentModule module) {
this.module = module;
val salt = RandomStringUtils.randomAlphabetic(8).toLowerCase();
log.info("Using environment salt {}", salt);
this.context = new EnvironmentContext(salt);
setupEnvironment();
}
private void setupEnvironment() { | Utils.getPublicFacingIP().forEach(context::setPublicFacingIP); |
fabzo/kraken | src/main/java/fabzo/kraken/Environment.java | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public class Utils {
// private static final String RUNNING_IN_IDE = "RUNNING_IN_IDE";
// private static final Object ASSIGNED_PORTS_MONITOR = new Object();
// private static Set<Integer> assignedPorts = HashSet.empty();
//
// public static boolean isRunningInIDE() {
// final boolean foundIdeaRtJar = System.getProperty("java.class.path").contains("idea_rt.jar");
//
// String runningInIDE = System.getenv(RUNNING_IN_IDE);
// if (runningInIDE == null) {
// runningInIDE = System.getProperty(RUNNING_IN_IDE);
// }
//
// return foundIdeaRtJar || "true".equalsIgnoreCase(runningInIDE);
// }
//
// public static Try<Integer> getAvailablePort() {
// synchronized (ASSIGNED_PORTS_MONITOR) {
// return Try.of(() -> {
// int hostPort;
// do {
// final ServerSocket serverSocket = new ServerSocket(0);
// hostPort = serverSocket.getLocalPort();
// serverSocket.close();
// } while (assignedPorts.contains(hostPort));
//
// assignedPorts = assignedPorts.add(hostPort);
//
// return hostPort;
// });
// }
// }
//
// public static Try<String> getPublicFacingIP() {
// return Try.of(() -> {
// final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// final NetworkInterface iface = interfaces.nextElement();
// if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) {
// continue;
// }
//
// final Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// final InetAddress addr = addresses.nextElement();
//
// final String ip = addr.getHostAddress();
// if (Inet4Address.class == addr.getClass()) {
// return ip;
// }
// }
// }
//
// throw new Exception("Could not find public facing IP");
// });
// }
//
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
| import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import fabzo.kraken.utils.ShutdownHookManager;
import fabzo.kraken.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import static fabzo.kraken.utils.Utils.nameOf; | package fabzo.kraken;
@Slf4j
public class Environment {
private final EnvironmentModule module;
private final EnvironmentContext context;
public Environment(final EnvironmentModule module) {
this.module = module;
val salt = RandomStringUtils.randomAlphabetic(8).toLowerCase();
log.info("Using environment salt {}", salt);
this.context = new EnvironmentContext(salt);
setupEnvironment();
}
private void setupEnvironment() {
Utils.getPublicFacingIP().forEach(context::setPublicFacingIP);
registerShutdownHook();
}
private void registerShutdownHook() { | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public class Utils {
// private static final String RUNNING_IN_IDE = "RUNNING_IN_IDE";
// private static final Object ASSIGNED_PORTS_MONITOR = new Object();
// private static Set<Integer> assignedPorts = HashSet.empty();
//
// public static boolean isRunningInIDE() {
// final boolean foundIdeaRtJar = System.getProperty("java.class.path").contains("idea_rt.jar");
//
// String runningInIDE = System.getenv(RUNNING_IN_IDE);
// if (runningInIDE == null) {
// runningInIDE = System.getProperty(RUNNING_IN_IDE);
// }
//
// return foundIdeaRtJar || "true".equalsIgnoreCase(runningInIDE);
// }
//
// public static Try<Integer> getAvailablePort() {
// synchronized (ASSIGNED_PORTS_MONITOR) {
// return Try.of(() -> {
// int hostPort;
// do {
// final ServerSocket serverSocket = new ServerSocket(0);
// hostPort = serverSocket.getLocalPort();
// serverSocket.close();
// } while (assignedPorts.contains(hostPort));
//
// assignedPorts = assignedPorts.add(hostPort);
//
// return hostPort;
// });
// }
// }
//
// public static Try<String> getPublicFacingIP() {
// return Try.of(() -> {
// final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// final NetworkInterface iface = interfaces.nextElement();
// if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) {
// continue;
// }
//
// final Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// final InetAddress addr = addresses.nextElement();
//
// final String ip = addr.getHostAddress();
// if (Inet4Address.class == addr.getClass()) {
// return ip;
// }
// }
// }
//
// throw new Exception("Could not find public facing IP");
// });
// }
//
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// Path: src/main/java/fabzo/kraken/Environment.java
import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import fabzo.kraken.utils.ShutdownHookManager;
import fabzo.kraken.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import static fabzo.kraken.utils.Utils.nameOf;
package fabzo.kraken;
@Slf4j
public class Environment {
private final EnvironmentModule module;
private final EnvironmentContext context;
public Environment(final EnvironmentModule module) {
this.module = module;
val salt = RandomStringUtils.randomAlphabetic(8).toLowerCase();
log.info("Using environment salt {}", salt);
this.context = new EnvironmentContext(salt);
setupEnvironment();
}
private void setupEnvironment() {
Utils.getPublicFacingIP().forEach(context::setPublicFacingIP);
registerShutdownHook();
}
private void registerShutdownHook() { | ShutdownHookManager.addHook(1000, () -> context.shutdownHooks().forEach(Runnable::run)); |
fabzo/kraken | src/main/java/fabzo/kraken/Environment.java | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public class Utils {
// private static final String RUNNING_IN_IDE = "RUNNING_IN_IDE";
// private static final Object ASSIGNED_PORTS_MONITOR = new Object();
// private static Set<Integer> assignedPorts = HashSet.empty();
//
// public static boolean isRunningInIDE() {
// final boolean foundIdeaRtJar = System.getProperty("java.class.path").contains("idea_rt.jar");
//
// String runningInIDE = System.getenv(RUNNING_IN_IDE);
// if (runningInIDE == null) {
// runningInIDE = System.getProperty(RUNNING_IN_IDE);
// }
//
// return foundIdeaRtJar || "true".equalsIgnoreCase(runningInIDE);
// }
//
// public static Try<Integer> getAvailablePort() {
// synchronized (ASSIGNED_PORTS_MONITOR) {
// return Try.of(() -> {
// int hostPort;
// do {
// final ServerSocket serverSocket = new ServerSocket(0);
// hostPort = serverSocket.getLocalPort();
// serverSocket.close();
// } while (assignedPorts.contains(hostPort));
//
// assignedPorts = assignedPorts.add(hostPort);
//
// return hostPort;
// });
// }
// }
//
// public static Try<String> getPublicFacingIP() {
// return Try.of(() -> {
// final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// final NetworkInterface iface = interfaces.nextElement();
// if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) {
// continue;
// }
//
// final Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// final InetAddress addr = addresses.nextElement();
//
// final String ip = addr.getHostAddress();
// if (Inet4Address.class == addr.getClass()) {
// return ip;
// }
// }
// }
//
// throw new Exception("Could not find public facing IP");
// });
// }
//
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
| import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import fabzo.kraken.utils.ShutdownHookManager;
import fabzo.kraken.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import static fabzo.kraken.utils.Utils.nameOf; | package fabzo.kraken;
@Slf4j
public class Environment {
private final EnvironmentModule module;
private final EnvironmentContext context;
public Environment(final EnvironmentModule module) {
this.module = module;
val salt = RandomStringUtils.randomAlphabetic(8).toLowerCase();
log.info("Using environment salt {}", salt);
this.context = new EnvironmentContext(salt);
setupEnvironment();
}
private void setupEnvironment() {
Utils.getPublicFacingIP().forEach(context::setPublicFacingIP);
registerShutdownHook();
}
private void registerShutdownHook() {
ShutdownHookManager.addHook(1000, () -> context.shutdownHooks().forEach(Runnable::run));
}
public void start() { | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public class Utils {
// private static final String RUNNING_IN_IDE = "RUNNING_IN_IDE";
// private static final Object ASSIGNED_PORTS_MONITOR = new Object();
// private static Set<Integer> assignedPorts = HashSet.empty();
//
// public static boolean isRunningInIDE() {
// final boolean foundIdeaRtJar = System.getProperty("java.class.path").contains("idea_rt.jar");
//
// String runningInIDE = System.getenv(RUNNING_IN_IDE);
// if (runningInIDE == null) {
// runningInIDE = System.getProperty(RUNNING_IN_IDE);
// }
//
// return foundIdeaRtJar || "true".equalsIgnoreCase(runningInIDE);
// }
//
// public static Try<Integer> getAvailablePort() {
// synchronized (ASSIGNED_PORTS_MONITOR) {
// return Try.of(() -> {
// int hostPort;
// do {
// final ServerSocket serverSocket = new ServerSocket(0);
// hostPort = serverSocket.getLocalPort();
// serverSocket.close();
// } while (assignedPorts.contains(hostPort));
//
// assignedPorts = assignedPorts.add(hostPort);
//
// return hostPort;
// });
// }
// }
//
// public static Try<String> getPublicFacingIP() {
// return Try.of(() -> {
// final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// final NetworkInterface iface = interfaces.nextElement();
// if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) {
// continue;
// }
//
// final Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// final InetAddress addr = addresses.nextElement();
//
// final String ip = addr.getHostAddress();
// if (Inet4Address.class == addr.getClass()) {
// return ip;
// }
// }
// }
//
// throw new Exception("Could not find public facing IP");
// });
// }
//
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// Path: src/main/java/fabzo/kraken/Environment.java
import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import fabzo.kraken.utils.ShutdownHookManager;
import fabzo.kraken.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import static fabzo.kraken.utils.Utils.nameOf;
package fabzo.kraken;
@Slf4j
public class Environment {
private final EnvironmentModule module;
private final EnvironmentContext context;
public Environment(final EnvironmentModule module) {
this.module = module;
val salt = RandomStringUtils.randomAlphabetic(8).toLowerCase();
log.info("Using environment salt {}", salt);
this.context = new EnvironmentContext(salt);
setupEnvironment();
}
private void setupEnvironment() {
Utils.getPublicFacingIP().forEach(context::setPublicFacingIP);
registerShutdownHook();
}
private void registerShutdownHook() {
ShutdownHookManager.addHook(1000, () -> context.shutdownHooks().forEach(Runnable::run));
}
public void start() { | log.info("Starting all components of {}", nameOf(module)); |
fabzo/kraken | src/main/java/fabzo/kraken/Environment.java | // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public class Utils {
// private static final String RUNNING_IN_IDE = "RUNNING_IN_IDE";
// private static final Object ASSIGNED_PORTS_MONITOR = new Object();
// private static Set<Integer> assignedPorts = HashSet.empty();
//
// public static boolean isRunningInIDE() {
// final boolean foundIdeaRtJar = System.getProperty("java.class.path").contains("idea_rt.jar");
//
// String runningInIDE = System.getenv(RUNNING_IN_IDE);
// if (runningInIDE == null) {
// runningInIDE = System.getProperty(RUNNING_IN_IDE);
// }
//
// return foundIdeaRtJar || "true".equalsIgnoreCase(runningInIDE);
// }
//
// public static Try<Integer> getAvailablePort() {
// synchronized (ASSIGNED_PORTS_MONITOR) {
// return Try.of(() -> {
// int hostPort;
// do {
// final ServerSocket serverSocket = new ServerSocket(0);
// hostPort = serverSocket.getLocalPort();
// serverSocket.close();
// } while (assignedPorts.contains(hostPort));
//
// assignedPorts = assignedPorts.add(hostPort);
//
// return hostPort;
// });
// }
// }
//
// public static Try<String> getPublicFacingIP() {
// return Try.of(() -> {
// final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// final NetworkInterface iface = interfaces.nextElement();
// if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) {
// continue;
// }
//
// final Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// final InetAddress addr = addresses.nextElement();
//
// final String ip = addr.getHostAddress();
// if (Inet4Address.class == addr.getClass()) {
// return ip;
// }
// }
// }
//
// throw new Exception("Could not find public facing IP");
// });
// }
//
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
| import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import fabzo.kraken.utils.ShutdownHookManager;
import fabzo.kraken.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import static fabzo.kraken.utils.Utils.nameOf; | package fabzo.kraken;
@Slf4j
public class Environment {
private final EnvironmentModule module;
private final EnvironmentContext context;
public Environment(final EnvironmentModule module) {
this.module = module;
val salt = RandomStringUtils.randomAlphabetic(8).toLowerCase();
log.info("Using environment salt {}", salt);
this.context = new EnvironmentContext(salt);
setupEnvironment();
}
private void setupEnvironment() {
Utils.getPublicFacingIP().forEach(context::setPublicFacingIP);
registerShutdownHook();
}
private void registerShutdownHook() {
ShutdownHookManager.addHook(1000, () -> context.shutdownHooks().forEach(Runnable::run));
}
public void start() {
log.info("Starting all components of {}", nameOf(module));
module.components().forEach(this::start);
}
| // Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
//
// Path: src/main/java/fabzo/kraken/handler/LifecycleHandler.java
// public interface LifecycleHandler {
//
// boolean canRun(final Class<? extends InfrastructureComponent> clazz);
//
// boolean run(final InfrastructureComponent component, final EnvironmentContext ctx);
//
// void stop(final InfrastructureComponent component, final EnvironmentContext ctx);
// }
//
// Path: src/main/java/fabzo/kraken/utils/ShutdownHookManager.java
// public class ShutdownHookManager {
// private static final PriorityQueue<ShutdownHookEntry> shutdownHooks = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.priority, o1.priority));
//
// static {
// Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookManager::executeShutdownHooks));
// }
//
// private static void executeShutdownHooks() {
// synchronized (shutdownHooks) {
// ShutdownHookEntry entry;
// while ((entry = shutdownHooks.poll()) != null) {
// entry.hook.run();
// }
// }
// }
//
// public static void addHook(final int priority, final Runnable shutdownHook) {
// ObjectUtil.checkNotNull(shutdownHook, "Shutdown hook should not be null");
// synchronized (shutdownHooks) {
// shutdownHooks.add(new ShutdownHookEntry(priority, shutdownHook));
// }
// }
//
// public static class ShutdownHookEntry {
// public int priority;
// public Runnable hook;
//
// public ShutdownHookEntry(final int priority, final Runnable hook) {
// this.priority = priority;
// this.hook = hook;
// }
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public class Utils {
// private static final String RUNNING_IN_IDE = "RUNNING_IN_IDE";
// private static final Object ASSIGNED_PORTS_MONITOR = new Object();
// private static Set<Integer> assignedPorts = HashSet.empty();
//
// public static boolean isRunningInIDE() {
// final boolean foundIdeaRtJar = System.getProperty("java.class.path").contains("idea_rt.jar");
//
// String runningInIDE = System.getenv(RUNNING_IN_IDE);
// if (runningInIDE == null) {
// runningInIDE = System.getProperty(RUNNING_IN_IDE);
// }
//
// return foundIdeaRtJar || "true".equalsIgnoreCase(runningInIDE);
// }
//
// public static Try<Integer> getAvailablePort() {
// synchronized (ASSIGNED_PORTS_MONITOR) {
// return Try.of(() -> {
// int hostPort;
// do {
// final ServerSocket serverSocket = new ServerSocket(0);
// hostPort = serverSocket.getLocalPort();
// serverSocket.close();
// } while (assignedPorts.contains(hostPort));
//
// assignedPorts = assignedPorts.add(hostPort);
//
// return hostPort;
// });
// }
// }
//
// public static Try<String> getPublicFacingIP() {
// return Try.of(() -> {
// final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// final NetworkInterface iface = interfaces.nextElement();
// if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) {
// continue;
// }
//
// final Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// final InetAddress addr = addresses.nextElement();
//
// final String ip = addr.getHostAddress();
// if (Inet4Address.class == addr.getClass()) {
// return ip;
// }
// }
// }
//
// throw new Exception("Could not find public facing IP");
// });
// }
//
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// }
//
// Path: src/main/java/fabzo/kraken/utils/Utils.java
// public static String nameOf(final Object obj) {
// val aClass = obj.getClass();
// if ("".equals(aClass.getSimpleName())) {
// return aClass.getName();
// }
// return aClass.getSimpleName();
// }
// Path: src/main/java/fabzo/kraken/Environment.java
import fabzo.kraken.components.InfrastructureComponent;
import fabzo.kraken.handler.LifecycleHandler;
import fabzo.kraken.utils.ShutdownHookManager;
import fabzo.kraken.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import static fabzo.kraken.utils.Utils.nameOf;
package fabzo.kraken;
@Slf4j
public class Environment {
private final EnvironmentModule module;
private final EnvironmentContext context;
public Environment(final EnvironmentModule module) {
this.module = module;
val salt = RandomStringUtils.randomAlphabetic(8).toLowerCase();
log.info("Using environment salt {}", salt);
this.context = new EnvironmentContext(salt);
setupEnvironment();
}
private void setupEnvironment() {
Utils.getPublicFacingIP().forEach(context::setPublicFacingIP);
registerShutdownHook();
}
private void registerShutdownHook() {
ShutdownHookManager.addHook(1000, () -> context.shutdownHooks().forEach(Runnable::run));
}
public void start() {
log.info("Starting all components of {}", nameOf(module));
module.components().forEach(this::start);
}
| private void start(final InfrastructureComponent component) { |
fabzo/kraken | src/main/java/fabzo/kraken/wait/TCPWait.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import com.google.common.base.MoreObjects;
import com.jayway.awaitility.Duration;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import static com.jayway.awaitility.Awaitility.await; | package fabzo.kraken.wait;
@Slf4j
public class TCPWait implements Wait {
private final String portName;
private final Duration atMost;
public static TCPWait on(final String portName, final Duration atMost) {
return new TCPWait(portName, atMost);
}
private TCPWait(final String portName, final Duration atMost) {
this.portName = portName;
this.atMost = atMost;
}
@Override | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/wait/TCPWait.java
import com.google.common.base.MoreObjects;
import com.jayway.awaitility.Duration;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import static com.jayway.awaitility.Awaitility.await;
package fabzo.kraken.wait;
@Slf4j
public class TCPWait implements Wait {
private final String portName;
private final Duration atMost;
public static TCPWait on(final String portName, final Duration atMost) {
return new TCPWait(portName, atMost);
}
private TCPWait(final String portName, final Duration atMost) {
this.portName = portName;
this.atMost = atMost;
}
@Override | public boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component) { |
fabzo/kraken | src/main/java/fabzo/kraken/wait/TCPWait.java | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
| import com.google.common.base.MoreObjects;
import com.jayway.awaitility.Duration;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import static com.jayway.awaitility.Awaitility.await; | package fabzo.kraken.wait;
@Slf4j
public class TCPWait implements Wait {
private final String portName;
private final Duration atMost;
public static TCPWait on(final String portName, final Duration atMost) {
return new TCPWait(portName, atMost);
}
private TCPWait(final String portName, final Duration atMost) {
this.portName = portName;
this.atMost = atMost;
}
@Override | // Path: src/main/java/fabzo/kraken/EnvironmentContext.java
// public class EnvironmentContext {
// public static final String PORT_REF_TO = "%s.ports.%s.to";
// public static final String PORT_REF_FROM = "%s.ports.%s.from";
// public static final String IP_REF = "%s.ip";
//
// private final String salt;
// private Option<String> publicFacingIP = Option.none();
// private Map<String, String> environmentVariables = HashMap.empty();
// private List<Runnable> shutdownHooks = List.empty();
//
// public EnvironmentContext(final String salt) {
// this.salt = salt;
// }
//
// public void putEnv(final String name, final String value) {
// this.environmentVariables = environmentVariables.put(name, value);
// }
//
// public void addPort(final String componentName, final String portName, final int fromPort, final int toPort) {
// putEnv(String.format(PORT_REF_FROM, componentName, portName), String.valueOf(fromPort));
// putEnv(String.format(PORT_REF_TO, componentName, portName), String.valueOf(toPort));
// }
//
// public void setIP(final String componentName, final String ip) {
// putEnv(String.format(IP_REF, componentName), String.valueOf(ip));
// }
//
// public String salt() {
// return salt;
// }
//
// public Option<String> publicFacingIP() {
// return publicFacingIP;
// }
//
// public String resolve(final String text) {
// return StrSubstitutor.replace(text, environmentVariables.toJavaMap());
// }
//
// public void setPublicFacingIP(final String ip) {
// publicFacingIP = Option.of(ip);
// }
//
// public Option<Integer> port(final String name, final String portName) {
// return environmentVariables
// .get(String.format(PORT_REF_FROM, name, portName))
// .map(this::toInt);
// }
//
// private Integer toInt(final String port) {
// return Try.of(() -> Integer.valueOf(port)).getOrNull();
// }
//
// /**
// * Returns the IP assigned to the service by its lifecycle handler. If no IP has been
// * assigned this function will fallback to the public facing IP or localhost.
// *
// * @param name Service name
// * @return Service IP, public facing host IP, or localhost
// */
// public String ip(final String name) {
// return environmentVariables
// .get(String.format(IP_REF, name))
// .getOrElse(() -> publicFacingIP().getOrElse("localhost"));
// }
//
// public void registerShutdownHook(final Runnable shutdownHook) {
// shutdownHooks = shutdownHooks.append(shutdownHook);
// }
//
// public List<Runnable> shutdownHooks() {
// return shutdownHooks;
// }
// }
//
// Path: src/main/java/fabzo/kraken/components/InfrastructureComponent.java
// public abstract class InfrastructureComponent implements Named {
// private ComponentState state = ComponentState.WAITING;
// private List<Wait> waitFunctions = List.empty();
//
// public InfrastructureComponent withWait(final Wait waitFunc) {
// this.waitFunctions = waitFunctions.append(waitFunc);
// return this;
// }
//
// public List<Wait> waitFuncs() {
// return waitFunctions;
// }
//
// public void setState(final ComponentState state) {
// this.state = state;
// }
//
// public ComponentState state() {
// return state;
// }
// }
// Path: src/main/java/fabzo/kraken/wait/TCPWait.java
import com.google.common.base.MoreObjects;
import com.jayway.awaitility.Duration;
import fabzo.kraken.EnvironmentContext;
import fabzo.kraken.components.InfrastructureComponent;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import static com.jayway.awaitility.Awaitility.await;
package fabzo.kraken.wait;
@Slf4j
public class TCPWait implements Wait {
private final String portName;
private final Duration atMost;
public static TCPWait on(final String portName, final Duration atMost) {
return new TCPWait(portName, atMost);
}
private TCPWait(final String portName, final Duration atMost) {
this.portName = portName;
this.atMost = atMost;
}
@Override | public boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component) { |
vertretungsplanme/substitution-schedule-parser | parser/src/test/java/me/vertretungsplan/parser/LoginHandlerTest.java | // Path: parser/src/main/java/me/vertretungsplan/objects/SubstitutionScheduleData.java
// public class SubstitutionScheduleData {
// private SubstitutionSchedule.Type type;
// private String api;
// private List<String> additionalInfos;
// private JSONObject data;
// private AuthenticationData authenticationData;
//
// public SubstitutionScheduleData() {
// additionalInfos = new ArrayList<>();
// }
//
// /**
// * Get the {@link SubstitutionSchedule.Type} of the substitution schedule this data represents
// * @return the type of this schedule
// */
// public SubstitutionSchedule.Type getType() {
// return type;
// }
//
// /**
// * Set the {@link SubstitutionSchedule.Type} of the substitution schedule this data represents
// * @param type the type of this schedule
// */
// @SuppressWarnings("SameParameterValue")
// public void setType(SubstitutionSchedule.Type type) {
// this.type = type;
// }
//
// /**
// * Get the type of parser to use for this schedule, as a string representation. This is used by
// * {@link me.vertretungsplan.parser.BaseParser#getInstance(SubstitutionScheduleData, CookieProvider)} to create a
// * suitable parser instance.
// *
// * @return the type of parser to use
// */
// public String getApi() {
// return api;
// }
//
// /**
// * Set the type of parser to use for this schedule, as a string representation. This information is used by
// * {@link me.vertretungsplan.parser.BaseParser#getInstance(SubstitutionScheduleData, CookieProvider)} to create a
// * suitable parser instance. Currently supported values are:
// * <ul>
// * <li>{@code "untis-monitor"}</li>
// * <li>{@code "untis-info"}</li>
// * <li>{@code "untis-info-headless"}</li>
// * <li>{@code "untis-subst"}</li>
// * <li>{@code "dsbmobile"}</li>
// * <li>{@code "svplan"}</li>
// * <li>{@code "davinci"}</li>
// * <li>{@code "turbovertretung"}</li>
// * <li>{@code "csv"}</li>
// * <li>{@code "legionboard"}</li>
// * </ul>
// *
// * @param api the type of parser to use
// */
// public void setApi(String api) {
// this.api = api;
// }
//
// /**
// * Get the types of {@link AdditionalInfo} this schedule should contain. Used by
// * {@link me.vertretungsplan.additionalinfo.BaseAdditionalInfoParser#getInstance(String)} to create a suitable
// * parser instance.
// *
// * @return the set of additional info types
// */
// public List<String> getAdditionalInfos() {
// return additionalInfos;
// }
//
// /**
// * Set the types of {@link AdditionalInfo} this schedule should contain. Used by
// * {@link me.vertretungsplan.additionalinfo.BaseAdditionalInfoParser#getInstance(String)} to create a suitable
// * parser instance. Currently supported values are:
// * <ul>
// * <li>{@code "winter-sh"}</li>
// * </ul>
// *
// * @param additionalInfos the additional info types to set
// */
// public void setAdditionalInfos(List<String> additionalInfos) {
// this.additionalInfos = additionalInfos;
// }
//
// /**
// * Get additional data about this substitution schedule in form of a JSON object. What data is needed here
// * depends on the parser type, see their own documentation in the <code>me.vertretungsplan.parser</code> package.
// *
// * @return additional data about this substitution schedule
// */
// public JSONObject getData() {
// return data;
// }
//
// /**
// * Set additional data about this substitution schedule in form of a JSON object. What data is needed here
// * depends on the parser type, see their own documentation in the <code>me.vertretungsplan.parser</code> package.
// *
// * @param data additional data about this substitution schedule
// */
// public void setData(JSONObject data) {
// this.data = data;
// }
//
// /**
// * Get information about what kind of {@link me.vertretungsplan.objects.credential.Credential} is needed to parse
// * this schedule and if there are additional parameters for authentication (such as a pre-set school number with
// * only the password needing to be filled in). If no credential is needed, this should return a
// * {@link me.vertretungsplan.objects.authentication.NoAuthenticationData} instance.
// *
// * @return the authentication data
// */
// public AuthenticationData getAuthenticationData() {
// return authenticationData;
// }
//
// /**
// * Set information about what kind of {@link me.vertretungsplan.objects.credential.Credential} is needed to parse
// * this schedule and if there are additional parameters for authentication (such as a pre-set school number with
// * only the password needing to be filled in). If no credential is needed, set this to a
// * {@link me.vertretungsplan.objects.authentication.NoAuthenticationData} instance.
// *
// * @param authenticationData the authentication data to set
// */
// public void setAuthenticationData(AuthenticationData authenticationData) {
// this.authenticationData = authenticationData;
// }
// }
| import com.github.tomakehurst.wiremock.core.Options;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import me.vertretungsplan.exception.CredentialInvalidException;
import me.vertretungsplan.objects.SubstitutionScheduleData;
import me.vertretungsplan.objects.credential.UserPasswordCredential;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.assertEquals; | package me.vertretungsplan.parser;
public class LoginHandlerTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT);
| // Path: parser/src/main/java/me/vertretungsplan/objects/SubstitutionScheduleData.java
// public class SubstitutionScheduleData {
// private SubstitutionSchedule.Type type;
// private String api;
// private List<String> additionalInfos;
// private JSONObject data;
// private AuthenticationData authenticationData;
//
// public SubstitutionScheduleData() {
// additionalInfos = new ArrayList<>();
// }
//
// /**
// * Get the {@link SubstitutionSchedule.Type} of the substitution schedule this data represents
// * @return the type of this schedule
// */
// public SubstitutionSchedule.Type getType() {
// return type;
// }
//
// /**
// * Set the {@link SubstitutionSchedule.Type} of the substitution schedule this data represents
// * @param type the type of this schedule
// */
// @SuppressWarnings("SameParameterValue")
// public void setType(SubstitutionSchedule.Type type) {
// this.type = type;
// }
//
// /**
// * Get the type of parser to use for this schedule, as a string representation. This is used by
// * {@link me.vertretungsplan.parser.BaseParser#getInstance(SubstitutionScheduleData, CookieProvider)} to create a
// * suitable parser instance.
// *
// * @return the type of parser to use
// */
// public String getApi() {
// return api;
// }
//
// /**
// * Set the type of parser to use for this schedule, as a string representation. This information is used by
// * {@link me.vertretungsplan.parser.BaseParser#getInstance(SubstitutionScheduleData, CookieProvider)} to create a
// * suitable parser instance. Currently supported values are:
// * <ul>
// * <li>{@code "untis-monitor"}</li>
// * <li>{@code "untis-info"}</li>
// * <li>{@code "untis-info-headless"}</li>
// * <li>{@code "untis-subst"}</li>
// * <li>{@code "dsbmobile"}</li>
// * <li>{@code "svplan"}</li>
// * <li>{@code "davinci"}</li>
// * <li>{@code "turbovertretung"}</li>
// * <li>{@code "csv"}</li>
// * <li>{@code "legionboard"}</li>
// * </ul>
// *
// * @param api the type of parser to use
// */
// public void setApi(String api) {
// this.api = api;
// }
//
// /**
// * Get the types of {@link AdditionalInfo} this schedule should contain. Used by
// * {@link me.vertretungsplan.additionalinfo.BaseAdditionalInfoParser#getInstance(String)} to create a suitable
// * parser instance.
// *
// * @return the set of additional info types
// */
// public List<String> getAdditionalInfos() {
// return additionalInfos;
// }
//
// /**
// * Set the types of {@link AdditionalInfo} this schedule should contain. Used by
// * {@link me.vertretungsplan.additionalinfo.BaseAdditionalInfoParser#getInstance(String)} to create a suitable
// * parser instance. Currently supported values are:
// * <ul>
// * <li>{@code "winter-sh"}</li>
// * </ul>
// *
// * @param additionalInfos the additional info types to set
// */
// public void setAdditionalInfos(List<String> additionalInfos) {
// this.additionalInfos = additionalInfos;
// }
//
// /**
// * Get additional data about this substitution schedule in form of a JSON object. What data is needed here
// * depends on the parser type, see their own documentation in the <code>me.vertretungsplan.parser</code> package.
// *
// * @return additional data about this substitution schedule
// */
// public JSONObject getData() {
// return data;
// }
//
// /**
// * Set additional data about this substitution schedule in form of a JSON object. What data is needed here
// * depends on the parser type, see their own documentation in the <code>me.vertretungsplan.parser</code> package.
// *
// * @param data additional data about this substitution schedule
// */
// public void setData(JSONObject data) {
// this.data = data;
// }
//
// /**
// * Get information about what kind of {@link me.vertretungsplan.objects.credential.Credential} is needed to parse
// * this schedule and if there are additional parameters for authentication (such as a pre-set school number with
// * only the password needing to be filled in). If no credential is needed, this should return a
// * {@link me.vertretungsplan.objects.authentication.NoAuthenticationData} instance.
// *
// * @return the authentication data
// */
// public AuthenticationData getAuthenticationData() {
// return authenticationData;
// }
//
// /**
// * Set information about what kind of {@link me.vertretungsplan.objects.credential.Credential} is needed to parse
// * this schedule and if there are additional parameters for authentication (such as a pre-set school number with
// * only the password needing to be filled in). If no credential is needed, set this to a
// * {@link me.vertretungsplan.objects.authentication.NoAuthenticationData} instance.
// *
// * @param authenticationData the authentication data to set
// */
// public void setAuthenticationData(AuthenticationData authenticationData) {
// this.authenticationData = authenticationData;
// }
// }
// Path: parser/src/test/java/me/vertretungsplan/parser/LoginHandlerTest.java
import com.github.tomakehurst.wiremock.core.Options;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import me.vertretungsplan.exception.CredentialInvalidException;
import me.vertretungsplan.objects.SubstitutionScheduleData;
import me.vertretungsplan.objects.credential.UserPasswordCredential;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.assertEquals;
package me.vertretungsplan.parser;
public class LoginHandlerTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(Options.DYNAMIC_PORT);
| private SubstitutionScheduleData dataBasic; |
vertretungsplanme/substitution-schedule-parser | parser/src/test/java/me/vertretungsplan/parser/ColorProviderTest.java | // Path: parser/src/main/java/me/vertretungsplan/objects/SubstitutionScheduleData.java
// public class SubstitutionScheduleData {
// private SubstitutionSchedule.Type type;
// private String api;
// private List<String> additionalInfos;
// private JSONObject data;
// private AuthenticationData authenticationData;
//
// public SubstitutionScheduleData() {
// additionalInfos = new ArrayList<>();
// }
//
// /**
// * Get the {@link SubstitutionSchedule.Type} of the substitution schedule this data represents
// * @return the type of this schedule
// */
// public SubstitutionSchedule.Type getType() {
// return type;
// }
//
// /**
// * Set the {@link SubstitutionSchedule.Type} of the substitution schedule this data represents
// * @param type the type of this schedule
// */
// @SuppressWarnings("SameParameterValue")
// public void setType(SubstitutionSchedule.Type type) {
// this.type = type;
// }
//
// /**
// * Get the type of parser to use for this schedule, as a string representation. This is used by
// * {@link me.vertretungsplan.parser.BaseParser#getInstance(SubstitutionScheduleData, CookieProvider)} to create a
// * suitable parser instance.
// *
// * @return the type of parser to use
// */
// public String getApi() {
// return api;
// }
//
// /**
// * Set the type of parser to use for this schedule, as a string representation. This information is used by
// * {@link me.vertretungsplan.parser.BaseParser#getInstance(SubstitutionScheduleData, CookieProvider)} to create a
// * suitable parser instance. Currently supported values are:
// * <ul>
// * <li>{@code "untis-monitor"}</li>
// * <li>{@code "untis-info"}</li>
// * <li>{@code "untis-info-headless"}</li>
// * <li>{@code "untis-subst"}</li>
// * <li>{@code "dsbmobile"}</li>
// * <li>{@code "svplan"}</li>
// * <li>{@code "davinci"}</li>
// * <li>{@code "turbovertretung"}</li>
// * <li>{@code "csv"}</li>
// * <li>{@code "legionboard"}</li>
// * </ul>
// *
// * @param api the type of parser to use
// */
// public void setApi(String api) {
// this.api = api;
// }
//
// /**
// * Get the types of {@link AdditionalInfo} this schedule should contain. Used by
// * {@link me.vertretungsplan.additionalinfo.BaseAdditionalInfoParser#getInstance(String)} to create a suitable
// * parser instance.
// *
// * @return the set of additional info types
// */
// public List<String> getAdditionalInfos() {
// return additionalInfos;
// }
//
// /**
// * Set the types of {@link AdditionalInfo} this schedule should contain. Used by
// * {@link me.vertretungsplan.additionalinfo.BaseAdditionalInfoParser#getInstance(String)} to create a suitable
// * parser instance. Currently supported values are:
// * <ul>
// * <li>{@code "winter-sh"}</li>
// * </ul>
// *
// * @param additionalInfos the additional info types to set
// */
// public void setAdditionalInfos(List<String> additionalInfos) {
// this.additionalInfos = additionalInfos;
// }
//
// /**
// * Get additional data about this substitution schedule in form of a JSON object. What data is needed here
// * depends on the parser type, see their own documentation in the <code>me.vertretungsplan.parser</code> package.
// *
// * @return additional data about this substitution schedule
// */
// public JSONObject getData() {
// return data;
// }
//
// /**
// * Set additional data about this substitution schedule in form of a JSON object. What data is needed here
// * depends on the parser type, see their own documentation in the <code>me.vertretungsplan.parser</code> package.
// *
// * @param data additional data about this substitution schedule
// */
// public void setData(JSONObject data) {
// this.data = data;
// }
//
// /**
// * Get information about what kind of {@link me.vertretungsplan.objects.credential.Credential} is needed to parse
// * this schedule and if there are additional parameters for authentication (such as a pre-set school number with
// * only the password needing to be filled in). If no credential is needed, this should return a
// * {@link me.vertretungsplan.objects.authentication.NoAuthenticationData} instance.
// *
// * @return the authentication data
// */
// public AuthenticationData getAuthenticationData() {
// return authenticationData;
// }
//
// /**
// * Set information about what kind of {@link me.vertretungsplan.objects.credential.Credential} is needed to parse
// * this schedule and if there are additional parameters for authentication (such as a pre-set school number with
// * only the password needing to be filled in). If no credential is needed, set this to a
// * {@link me.vertretungsplan.objects.authentication.NoAuthenticationData} instance.
// *
// * @param authenticationData the authentication data to set
// */
// public void setAuthenticationData(AuthenticationData authenticationData) {
// this.authenticationData = authenticationData;
// }
// }
| import me.vertretungsplan.objects.SubstitutionScheduleData;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals; | /*
* substitution-schedule-parser - Java library for parsing schools' substitution schedules
* Copyright (c) 2017 Johan v. Forstner
*
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package me.vertretungsplan.parser;
public class ColorProviderTest {
@Test
public void testPreconfigured() { | // Path: parser/src/main/java/me/vertretungsplan/objects/SubstitutionScheduleData.java
// public class SubstitutionScheduleData {
// private SubstitutionSchedule.Type type;
// private String api;
// private List<String> additionalInfos;
// private JSONObject data;
// private AuthenticationData authenticationData;
//
// public SubstitutionScheduleData() {
// additionalInfos = new ArrayList<>();
// }
//
// /**
// * Get the {@link SubstitutionSchedule.Type} of the substitution schedule this data represents
// * @return the type of this schedule
// */
// public SubstitutionSchedule.Type getType() {
// return type;
// }
//
// /**
// * Set the {@link SubstitutionSchedule.Type} of the substitution schedule this data represents
// * @param type the type of this schedule
// */
// @SuppressWarnings("SameParameterValue")
// public void setType(SubstitutionSchedule.Type type) {
// this.type = type;
// }
//
// /**
// * Get the type of parser to use for this schedule, as a string representation. This is used by
// * {@link me.vertretungsplan.parser.BaseParser#getInstance(SubstitutionScheduleData, CookieProvider)} to create a
// * suitable parser instance.
// *
// * @return the type of parser to use
// */
// public String getApi() {
// return api;
// }
//
// /**
// * Set the type of parser to use for this schedule, as a string representation. This information is used by
// * {@link me.vertretungsplan.parser.BaseParser#getInstance(SubstitutionScheduleData, CookieProvider)} to create a
// * suitable parser instance. Currently supported values are:
// * <ul>
// * <li>{@code "untis-monitor"}</li>
// * <li>{@code "untis-info"}</li>
// * <li>{@code "untis-info-headless"}</li>
// * <li>{@code "untis-subst"}</li>
// * <li>{@code "dsbmobile"}</li>
// * <li>{@code "svplan"}</li>
// * <li>{@code "davinci"}</li>
// * <li>{@code "turbovertretung"}</li>
// * <li>{@code "csv"}</li>
// * <li>{@code "legionboard"}</li>
// * </ul>
// *
// * @param api the type of parser to use
// */
// public void setApi(String api) {
// this.api = api;
// }
//
// /**
// * Get the types of {@link AdditionalInfo} this schedule should contain. Used by
// * {@link me.vertretungsplan.additionalinfo.BaseAdditionalInfoParser#getInstance(String)} to create a suitable
// * parser instance.
// *
// * @return the set of additional info types
// */
// public List<String> getAdditionalInfos() {
// return additionalInfos;
// }
//
// /**
// * Set the types of {@link AdditionalInfo} this schedule should contain. Used by
// * {@link me.vertretungsplan.additionalinfo.BaseAdditionalInfoParser#getInstance(String)} to create a suitable
// * parser instance. Currently supported values are:
// * <ul>
// * <li>{@code "winter-sh"}</li>
// * </ul>
// *
// * @param additionalInfos the additional info types to set
// */
// public void setAdditionalInfos(List<String> additionalInfos) {
// this.additionalInfos = additionalInfos;
// }
//
// /**
// * Get additional data about this substitution schedule in form of a JSON object. What data is needed here
// * depends on the parser type, see their own documentation in the <code>me.vertretungsplan.parser</code> package.
// *
// * @return additional data about this substitution schedule
// */
// public JSONObject getData() {
// return data;
// }
//
// /**
// * Set additional data about this substitution schedule in form of a JSON object. What data is needed here
// * depends on the parser type, see their own documentation in the <code>me.vertretungsplan.parser</code> package.
// *
// * @param data additional data about this substitution schedule
// */
// public void setData(JSONObject data) {
// this.data = data;
// }
//
// /**
// * Get information about what kind of {@link me.vertretungsplan.objects.credential.Credential} is needed to parse
// * this schedule and if there are additional parameters for authentication (such as a pre-set school number with
// * only the password needing to be filled in). If no credential is needed, this should return a
// * {@link me.vertretungsplan.objects.authentication.NoAuthenticationData} instance.
// *
// * @return the authentication data
// */
// public AuthenticationData getAuthenticationData() {
// return authenticationData;
// }
//
// /**
// * Set information about what kind of {@link me.vertretungsplan.objects.credential.Credential} is needed to parse
// * this schedule and if there are additional parameters for authentication (such as a pre-set school number with
// * only the password needing to be filled in). If no credential is needed, set this to a
// * {@link me.vertretungsplan.objects.authentication.NoAuthenticationData} instance.
// *
// * @param authenticationData the authentication data to set
// */
// public void setAuthenticationData(AuthenticationData authenticationData) {
// this.authenticationData = authenticationData;
// }
// }
// Path: parser/src/test/java/me/vertretungsplan/parser/ColorProviderTest.java
import me.vertretungsplan.objects.SubstitutionScheduleData;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/*
* substitution-schedule-parser - Java library for parsing schools' substitution schedules
* Copyright (c) 2017 Johan v. Forstner
*
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package me.vertretungsplan.parser;
public class ColorProviderTest {
@Test
public void testPreconfigured() { | final SubstitutionScheduleData scheduleData = new SubstitutionScheduleData(); |
jenkinsci/cloudbees-deployer-plugin | src/main/java/com/cloudbees/plugins/deployer/DeployFingerprintFacet.java | // Path: src/main/java/com/cloudbees/plugins/deployer/impl/run/RunDeployedApplicationLocation.java
// public class RunDeployedApplicationLocation extends DeployedApplicationLocation {
// private final String applicationId;
// private final String applicationEnvironment;
//
// public RunDeployedApplicationLocation(@NonNull String applicationId, @NonNull String applicationEnvironment,
// @NonNull String appURL) {
// super(appURL);
// applicationId.getClass(); // throw NPE if null
// applicationEnvironment.getClass(); // throw NPE if null
// this.applicationId = applicationId;
// this.applicationEnvironment = applicationEnvironment;
// }
//
// public String getApplicationId() {
// return applicationId;
// }
//
// public String getApplicationEnvironment() {
// return applicationEnvironment;
// }
//
// @Override
// public String getImageOf(@CheckForNull String size) {
// return "/plugin/cloudbees-deployer-plugin/images/" + (StringUtils.isBlank(size) ? "24x24" : size)
// + "/deployed-on-run.png";
// }
//
// @Override
// public String getDisplayName() {
// return Messages.RunHostImpl_DisplayName();
// }
//
// @Override
// public String getDescription() {
// return Messages.RunDeployedApplicationLocation_Description(applicationId, applicationEnvironment);
// }
// }
| import com.cloudbees.plugins.deployer.impl.run.RunDeployedApplicationLocation;
import com.cloudbees.plugins.deployer.records.DeployedApplicationFingerprintFacet;
import hudson.model.Fingerprint;
import jenkins.model.FingerprintFacet;
import java.io.ObjectStreamException; | /*
* The MIT License
*
* Copyright (c) 2011-2014, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cloudbees.plugins.deployer;
/**
* @author stephenc
* @since 21/02/2012 15:50
* @deprecated use {@link DeployedApplicationFingerprintFacet}
*/
@Deprecated
public class DeployFingerprintFacet extends FingerprintFacet {
private final String applicationId;
private final String applicationEnvironment;
private final String url;
/**
* @param fingerprint {@link hudson.model.Fingerprint} object to which this facet is going to be added
* to.
* @param timestamp Timestamp when the use happened.
* @param applicationId The application id that the file was deployed to.
* @param applicationEnvironment The application environment that the file was deployed with.
* @param url The url that the file was deployed on.
*/
public DeployFingerprintFacet(Fingerprint fingerprint, long timestamp, String applicationId,
String applicationEnvironment, String url) {
super(fingerprint, timestamp);
this.applicationId = applicationId;
this.applicationEnvironment = applicationEnvironment;
this.url = url;
}
public String getApplicationId() {
return applicationId;
}
public String getApplicationEnvironment() {
return applicationEnvironment;
}
public String getUrl() {
return url;
}
@SuppressWarnings("deprecation")
protected Object readResolve() throws ObjectStreamException { | // Path: src/main/java/com/cloudbees/plugins/deployer/impl/run/RunDeployedApplicationLocation.java
// public class RunDeployedApplicationLocation extends DeployedApplicationLocation {
// private final String applicationId;
// private final String applicationEnvironment;
//
// public RunDeployedApplicationLocation(@NonNull String applicationId, @NonNull String applicationEnvironment,
// @NonNull String appURL) {
// super(appURL);
// applicationId.getClass(); // throw NPE if null
// applicationEnvironment.getClass(); // throw NPE if null
// this.applicationId = applicationId;
// this.applicationEnvironment = applicationEnvironment;
// }
//
// public String getApplicationId() {
// return applicationId;
// }
//
// public String getApplicationEnvironment() {
// return applicationEnvironment;
// }
//
// @Override
// public String getImageOf(@CheckForNull String size) {
// return "/plugin/cloudbees-deployer-plugin/images/" + (StringUtils.isBlank(size) ? "24x24" : size)
// + "/deployed-on-run.png";
// }
//
// @Override
// public String getDisplayName() {
// return Messages.RunHostImpl_DisplayName();
// }
//
// @Override
// public String getDescription() {
// return Messages.RunDeployedApplicationLocation_Description(applicationId, applicationEnvironment);
// }
// }
// Path: src/main/java/com/cloudbees/plugins/deployer/DeployFingerprintFacet.java
import com.cloudbees.plugins.deployer.impl.run.RunDeployedApplicationLocation;
import com.cloudbees.plugins.deployer.records.DeployedApplicationFingerprintFacet;
import hudson.model.Fingerprint;
import jenkins.model.FingerprintFacet;
import java.io.ObjectStreamException;
/*
* The MIT License
*
* Copyright (c) 2011-2014, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cloudbees.plugins.deployer;
/**
* @author stephenc
* @since 21/02/2012 15:50
* @deprecated use {@link DeployedApplicationFingerprintFacet}
*/
@Deprecated
public class DeployFingerprintFacet extends FingerprintFacet {
private final String applicationId;
private final String applicationEnvironment;
private final String url;
/**
* @param fingerprint {@link hudson.model.Fingerprint} object to which this facet is going to be added
* to.
* @param timestamp Timestamp when the use happened.
* @param applicationId The application id that the file was deployed to.
* @param applicationEnvironment The application environment that the file was deployed with.
* @param url The url that the file was deployed on.
*/
public DeployFingerprintFacet(Fingerprint fingerprint, long timestamp, String applicationId,
String applicationEnvironment, String url) {
super(fingerprint, timestamp);
this.applicationId = applicationId;
this.applicationEnvironment = applicationEnvironment;
this.url = url;
}
public String getApplicationId() {
return applicationId;
}
public String getApplicationEnvironment() {
return applicationEnvironment;
}
public String getUrl() {
return url;
}
@SuppressWarnings("deprecation")
protected Object readResolve() throws ObjectStreamException { | return new DeployedApplicationFingerprintFacet<RunDeployedApplicationLocation>( |
Nanopublication/nanopub-java | src/main/java/org/nanopub/trusty/TrustyNanopubPattern.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
| import java.net.MalformedURLException;
import java.net.URL;
import net.trustyuri.TrustyUriUtils;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern; | package org.nanopub.trusty;
public class TrustyNanopubPattern implements NanopubPattern {
private static final long serialVersionUID = -678743536297253350L;
public TrustyNanopubPattern() {
}
@Override
public String getName() {
return "Trusty nanopublication";
}
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
// Path: src/main/java/org/nanopub/trusty/TrustyNanopubPattern.java
import java.net.MalformedURLException;
import java.net.URL;
import net.trustyuri.TrustyUriUtils;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern;
package org.nanopub.trusty;
public class TrustyNanopubPattern implements NanopubPattern {
private static final long serialVersionUID = -678743536297253350L;
public TrustyNanopubPattern() {
}
@Override
public String getName() {
return "Trusty nanopublication";
}
@Override | public boolean appliesTo(Nanopub nanopub) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/index/NanopubIndexImpl.java | // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubWithNs.java
// public interface NanopubWithNs extends Nanopub {
//
// public List<String> getNsPrefixes();
//
// public String getNamespace(String prefix);
//
// public void removeUnusedPrefixes();
//
// }
| import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.DC;
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.model.vocabulary.RDFS;
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubWithNs;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; | package org.nanopub.extra.index;
public class NanopubIndexImpl implements NanopubIndex, NanopubWithNs {
private final Nanopub np;
private final Set<IRI> elementSet;
private final Set<IRI> subIndexSet;
private final IRI appendedIndex;
private boolean isIncompleteIndex = false;
| // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubWithNs.java
// public interface NanopubWithNs extends Nanopub {
//
// public List<String> getNsPrefixes();
//
// public String getNamespace(String prefix);
//
// public void removeUnusedPrefixes();
//
// }
// Path: src/main/java/org/nanopub/extra/index/NanopubIndexImpl.java
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.DC;
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.model.vocabulary.RDFS;
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubWithNs;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
package org.nanopub.extra.index;
public class NanopubIndexImpl implements NanopubIndex, NanopubWithNs {
private final Nanopub np;
private final Set<IRI> elementSet;
private final Set<IRI> subIndexSet;
private final IRI appendedIndex;
private boolean isIncompleteIndex = false;
| protected NanopubIndexImpl(Nanopub npIndex) throws MalformedNanopubException { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/index/NanopubIndexPattern.java | // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
| import java.net.MalformedURLException;
import java.net.URL;
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern; | package org.nanopub.extra.index;
public class NanopubIndexPattern implements NanopubPattern {
private static final long serialVersionUID = -678743536297253350L;
public NanopubIndexPattern() {
}
@Override
public String getName() {
return "Nanopublication index";
}
@Override | // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
// Path: src/main/java/org/nanopub/extra/index/NanopubIndexPattern.java
import java.net.MalformedURLException;
import java.net.URL;
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern;
package org.nanopub.extra.index;
public class NanopubIndexPattern implements NanopubPattern {
private static final long serialVersionUID = -678743536297253350L;
public NanopubIndexPattern() {
}
@Override
public String getName() {
return "Nanopublication index";
}
@Override | public boolean appliesTo(Nanopub nanopub) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/index/NanopubIndexPattern.java | // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
| import java.net.MalformedURLException;
import java.net.URL;
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern; | package org.nanopub.extra.index;
public class NanopubIndexPattern implements NanopubPattern {
private static final long serialVersionUID = -678743536297253350L;
public NanopubIndexPattern() {
}
@Override
public String getName() {
return "Nanopublication index";
}
@Override
public boolean appliesTo(Nanopub nanopub) {
return IndexUtils.isIndex(nanopub);
}
@Override
public boolean isCorrectlyUsedBy(Nanopub nanopub) {
try {
new NanopubIndexImpl(nanopub); | // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
// Path: src/main/java/org/nanopub/extra/index/NanopubIndexPattern.java
import java.net.MalformedURLException;
import java.net.URL;
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern;
package org.nanopub.extra.index;
public class NanopubIndexPattern implements NanopubPattern {
private static final long serialVersionUID = -678743536297253350L;
public NanopubIndexPattern() {
}
@Override
public String getName() {
return "Nanopublication index";
}
@Override
public boolean appliesTo(Nanopub nanopub) {
return IndexUtils.isIndex(nanopub);
}
@Override
public boolean isCorrectlyUsedBy(Nanopub nanopub) {
try {
new NanopubIndexImpl(nanopub); | } catch (MalformedNanopubException ex) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/trusty/TempUriReplacer.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
| import java.util.Map;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.rio.RDFHandler;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.nanopub.Nanopub; | package org.nanopub.trusty;
/**
* You can use temporary URIs for your nanopublications that start with
* "http://purl.org/nanopub/temp/". These then become "http://purl.org/np/ARTIFACTCODE-PLACEHOLDER/"
* before being transformed to trusty nanopublications, and as final trusty nanopublications have
* the actual artifact code instead of the placeholder.
*
* @author Tobias Kuhn
*/
public class TempUriReplacer implements RDFHandler {
public static final String tempUri = "http://purl.org/nanopub/temp/";
public static final String normUri = "http://purl.org/np/ARTIFACTCODE-PLACEHOLDER/";
private String uriPrefix;
private RDFHandler nestedHandler;
private Map<Resource,IRI> transformMap;
| // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
// Path: src/main/java/org/nanopub/trusty/TempUriReplacer.java
import java.util.Map;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.rio.RDFHandler;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.nanopub.Nanopub;
package org.nanopub.trusty;
/**
* You can use temporary URIs for your nanopublications that start with
* "http://purl.org/nanopub/temp/". These then become "http://purl.org/np/ARTIFACTCODE-PLACEHOLDER/"
* before being transformed to trusty nanopublications, and as final trusty nanopublications have
* the actual artifact code instead of the placeholder.
*
* @author Tobias Kuhn
*/
public class TempUriReplacer implements RDFHandler {
public static final String tempUri = "http://purl.org/nanopub/temp/";
public static final String normUri = "http://purl.org/np/ARTIFACTCODE-PLACEHOLDER/";
private String uriPrefix;
private RDFHandler nestedHandler;
private Map<Resource,IRI> transformMap;
| public TempUriReplacer(Nanopub np, RDFHandler nestedHandler, Map<Resource,IRI> transformMap) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/security/TransformContext.java | // Path: src/main/java/org/nanopub/trusty/CrossRefResolver.java
// public class CrossRefResolver implements RDFHandler {
//
// private Map<Resource,IRI> tempRefMap;
// private Map<String,String> tempPrefixMap;
// private RDFHandler nestedHandler;
//
// public CrossRefResolver(Map<Resource,IRI> tempRefMap, Map<String,String> tempPrefixMap, RDFHandler nestedHandler) {
// this.tempRefMap = tempRefMap;
// this.tempPrefixMap = tempPrefixMap;
// this.nestedHandler = nestedHandler;
// }
//
// @Override
// public void handleStatement(Statement st) throws RDFHandlerException {
// nestedHandler.handleStatement(SimpleValueFactory.getInstance().createStatement(
// (Resource) replace(st.getSubject()),
// (IRI) replace(st.getPredicate()),
// replace(st.getObject()),
// (Resource) replace(st.getContext())));
// }
//
// @Override
// public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
// String transformedUri = replace(SimpleValueFactory.getInstance().createIRI(uri)).stringValue();
// nestedHandler.handleNamespace(prefix, transformedUri);
// }
//
// private Value replace(Value v) {
// if (!(v instanceof Resource)) return v;
// IRI i = tempRefMap.get(v);
// if (i != null) return i;
// if (v instanceof IRI && tempPrefixMap != null) {
// for (String prefix : tempPrefixMap.keySet()) {
// if (v.stringValue().startsWith(prefix)) {
// return vf.createIRI(v.stringValue().replace(prefix, tempPrefixMap.get(prefix)));
// }
// }
// }
// return v;
// }
//
// @Override
// public void startRDF() throws RDFHandlerException {
// nestedHandler.startRDF();
// }
//
// @Override
// public void endRDF() throws RDFHandlerException {
// nestedHandler.endRDF();
// }
//
// @Override
// public void handleComment(String comment) throws RDFHandlerException {
// nestedHandler.handleComment(comment);
// }
//
// private static ValueFactory vf = SimpleValueFactory.getInstance();
//
// }
| import java.security.KeyPair;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.nanopub.trusty.CrossRefResolver;
import net.trustyuri.TrustyUriUtils;
import net.trustyuri.rdf.RdfFileContent; | tempPrefixMap = new HashMap<>();
tempRefMap = new HashMap<>();
} else if (resolveCrossRefs) {
tempRefMap = new HashMap<>();
}
}
public SignatureAlgorithm getSignatureAlgorithm() {
return algorithm;
}
public KeyPair getKey() {
return key;
}
public IRI getSigner() {
return signer;
}
public Map<Resource,IRI> getTempRefMap() {
return tempRefMap;
}
public Map<String,String> getTempPrefixMap() {
return tempPrefixMap;
}
public RdfFileContent resolveCrossRefs(RdfFileContent input) {
if (tempRefMap == null) return input;
RdfFileContent output = new RdfFileContent(RDFFormat.TRIG); | // Path: src/main/java/org/nanopub/trusty/CrossRefResolver.java
// public class CrossRefResolver implements RDFHandler {
//
// private Map<Resource,IRI> tempRefMap;
// private Map<String,String> tempPrefixMap;
// private RDFHandler nestedHandler;
//
// public CrossRefResolver(Map<Resource,IRI> tempRefMap, Map<String,String> tempPrefixMap, RDFHandler nestedHandler) {
// this.tempRefMap = tempRefMap;
// this.tempPrefixMap = tempPrefixMap;
// this.nestedHandler = nestedHandler;
// }
//
// @Override
// public void handleStatement(Statement st) throws RDFHandlerException {
// nestedHandler.handleStatement(SimpleValueFactory.getInstance().createStatement(
// (Resource) replace(st.getSubject()),
// (IRI) replace(st.getPredicate()),
// replace(st.getObject()),
// (Resource) replace(st.getContext())));
// }
//
// @Override
// public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
// String transformedUri = replace(SimpleValueFactory.getInstance().createIRI(uri)).stringValue();
// nestedHandler.handleNamespace(prefix, transformedUri);
// }
//
// private Value replace(Value v) {
// if (!(v instanceof Resource)) return v;
// IRI i = tempRefMap.get(v);
// if (i != null) return i;
// if (v instanceof IRI && tempPrefixMap != null) {
// for (String prefix : tempPrefixMap.keySet()) {
// if (v.stringValue().startsWith(prefix)) {
// return vf.createIRI(v.stringValue().replace(prefix, tempPrefixMap.get(prefix)));
// }
// }
// }
// return v;
// }
//
// @Override
// public void startRDF() throws RDFHandlerException {
// nestedHandler.startRDF();
// }
//
// @Override
// public void endRDF() throws RDFHandlerException {
// nestedHandler.endRDF();
// }
//
// @Override
// public void handleComment(String comment) throws RDFHandlerException {
// nestedHandler.handleComment(comment);
// }
//
// private static ValueFactory vf = SimpleValueFactory.getInstance();
//
// }
// Path: src/main/java/org/nanopub/extra/security/TransformContext.java
import java.security.KeyPair;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.nanopub.trusty.CrossRefResolver;
import net.trustyuri.TrustyUriUtils;
import net.trustyuri.rdf.RdfFileContent;
tempPrefixMap = new HashMap<>();
tempRefMap = new HashMap<>();
} else if (resolveCrossRefs) {
tempRefMap = new HashMap<>();
}
}
public SignatureAlgorithm getSignatureAlgorithm() {
return algorithm;
}
public KeyPair getKey() {
return key;
}
public IRI getSigner() {
return signer;
}
public Map<Resource,IRI> getTempRefMap() {
return tempRefMap;
}
public Map<String,String> getTempPrefixMap() {
return tempPrefixMap;
}
public RdfFileContent resolveCrossRefs(RdfFileContent input) {
if (tempRefMap == null) return input;
RdfFileContent output = new RdfFileContent(RDFFormat.TRIG); | input.propagate(new CrossRefResolver(tempRefMap, tempPrefixMap, output)); |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/fingerprint/FingerprintHandler.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
| import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.nanopub.Nanopub; | package org.nanopub.op.fingerprint;
public interface FingerprintHandler {
public static final IRI nanopubUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/nanopuburi");
public static final IRI headUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/head");
public static final IRI assertionUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/assertion");
public static final IRI provUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/provenance");
public static final IRI pubinfoUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/pubinfo");
public static final IRI timestampPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/timestamp");
| // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
// Path: src/main/java/org/nanopub/op/fingerprint/FingerprintHandler.java
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.nanopub.Nanopub;
package org.nanopub.op.fingerprint;
public interface FingerprintHandler {
public static final IRI nanopubUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/nanopuburi");
public static final IRI headUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/head");
public static final IRI assertionUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/assertion");
public static final IRI provUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/provenance");
public static final IRI pubinfoUriPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/pubinfo");
public static final IRI timestampPlaceholder = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/placeholders/timestamp");
| public String getFingerprint(Nanopub np); |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/aida/AidaPattern.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
| import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern; | package org.nanopub.extra.aida;
public class AidaPattern implements NanopubPattern {
private static final long serialVersionUID = -164193908921728662L;
@Override
public String getName() {
return "AIDA nanopublication";
}
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
// Path: src/main/java/org/nanopub/extra/aida/AidaPattern.java
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern;
package org.nanopub.extra.aida;
public class AidaPattern implements NanopubPattern {
private static final long serialVersionUID = -164193908921728662L;
@Override
public String getName() {
return "AIDA nanopublication";
}
@Override | public boolean appliesTo(Nanopub nanopub) { |
Nanopublication/nanopub-java | src/test/java/org/nanopub/CheckInvalidNanopubsTest.java | // Path: src/main/java/org/nanopub/CheckNanopub.java
// public class Report {
//
// private int signed, legacySigned, trusty, notTrusty, invalidSignature, invalid, error;
//
// private Report() {
// }
//
// private void countSigned() {
// signed++;
// }
//
// public int getSignedCount() {
// return signed;
// }
//
// private void countLegacySigned() {
// legacySigned++;
// }
//
// public int getLegacySignedCount() {
// return legacySigned;
// }
//
// private void countTrusty() {
// trusty++;
// }
//
// public int getTrustyCount() {
// return trusty;
// }
//
// private void countNotTrusty() {
// notTrusty++;
// }
//
// public int getNotTrustyCount() {
// return notTrusty;
// }
//
// private void countInvalidSignature() {
// invalidSignature++;
// }
//
// public int getInvalidSignatureCount() {
// return invalidSignature;
// }
//
// private void countInvalid() {
// invalid++;
// }
//
// public int getInvalidCount() {
// return invalid;
// }
//
// private void countError() {
// error++;
// }
//
// public int getErrorCount() {
// return error;
// }
//
// public int getAllValidCount() {
// return signed + trusty + notTrusty;
// }
//
// public int getAllInvalidCount() {
// return invalidSignature + invalid + error;
// }
//
// public boolean areAllValid() {
// return getAllInvalidCount() == 0;
// }
//
//
// public String getSummary() {
// String s = "";
// if (signed > 0) s += " " + signed + " trusty with signature;";
// if (legacySigned > 0) s += " " + legacySigned + " trusty with legacy signature;";
// if (trusty > 0) s += " " + trusty + " trusty (without signature);";
// if (notTrusty > 0) s += " " + notTrusty + " valid (not trusty);";
// if (invalidSignature > 0) s += " " + invalidSignature + " invalid signature;";
// if (invalid > 0) s += " " + invalid + " invalid nanopubs;";
// if (error > 0) s += " " + error + " errors;";
// s = s.replaceFirst("^ ", "");
// return s;
// }
// }
| import java.io.File;
import org.junit.Test;
import org.nanopub.CheckNanopub.Report; | package org.nanopub;
public class CheckInvalidNanopubsTest {
@Test
public void runTest() throws Exception {
File testSuiteValidDir = new File("src/main/resources/testsuite/invalid/");
for (File testFile : testSuiteValidDir.listFiles()) {
testInvalid(testFile.getName());
}
}
public void testInvalid(String filename) throws Exception { | // Path: src/main/java/org/nanopub/CheckNanopub.java
// public class Report {
//
// private int signed, legacySigned, trusty, notTrusty, invalidSignature, invalid, error;
//
// private Report() {
// }
//
// private void countSigned() {
// signed++;
// }
//
// public int getSignedCount() {
// return signed;
// }
//
// private void countLegacySigned() {
// legacySigned++;
// }
//
// public int getLegacySignedCount() {
// return legacySigned;
// }
//
// private void countTrusty() {
// trusty++;
// }
//
// public int getTrustyCount() {
// return trusty;
// }
//
// private void countNotTrusty() {
// notTrusty++;
// }
//
// public int getNotTrustyCount() {
// return notTrusty;
// }
//
// private void countInvalidSignature() {
// invalidSignature++;
// }
//
// public int getInvalidSignatureCount() {
// return invalidSignature;
// }
//
// private void countInvalid() {
// invalid++;
// }
//
// public int getInvalidCount() {
// return invalid;
// }
//
// private void countError() {
// error++;
// }
//
// public int getErrorCount() {
// return error;
// }
//
// public int getAllValidCount() {
// return signed + trusty + notTrusty;
// }
//
// public int getAllInvalidCount() {
// return invalidSignature + invalid + error;
// }
//
// public boolean areAllValid() {
// return getAllInvalidCount() == 0;
// }
//
//
// public String getSummary() {
// String s = "";
// if (signed > 0) s += " " + signed + " trusty with signature;";
// if (legacySigned > 0) s += " " + legacySigned + " trusty with legacy signature;";
// if (trusty > 0) s += " " + trusty + " trusty (without signature);";
// if (notTrusty > 0) s += " " + notTrusty + " valid (not trusty);";
// if (invalidSignature > 0) s += " " + invalidSignature + " invalid signature;";
// if (invalid > 0) s += " " + invalid + " invalid nanopubs;";
// if (error > 0) s += " " + error + " errors;";
// s = s.replaceFirst("^ ", "");
// return s;
// }
// }
// Path: src/test/java/org/nanopub/CheckInvalidNanopubsTest.java
import java.io.File;
import org.junit.Test;
import org.nanopub.CheckNanopub.Report;
package org.nanopub;
public class CheckInvalidNanopubsTest {
@Test
public void runTest() throws Exception {
File testSuiteValidDir = new File("src/main/resources/testsuite/invalid/");
for (File testFile : testSuiteValidDir.listFiles()) {
testInvalid(testFile.getName());
}
}
public void testInvalid(String filename) throws Exception { | Report report = null; |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/topic/WikipathwaysTopics.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.RDF; | package org.nanopub.op.topic;
public class WikipathwaysTopics implements TopicHandler {
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
// Path: src/main/java/org/nanopub/op/topic/WikipathwaysTopics.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.RDF;
package org.nanopub.op.topic;
public class WikipathwaysTopics implements TopicHandler {
@Override | public String getTopic(Nanopub np) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/index/IndexUtils.java | // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
| import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.RDF; | package org.nanopub.extra.index;
public class IndexUtils {
private IndexUtils() {} // no instances allowed
| // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
// Path: src/main/java/org/nanopub/extra/index/IndexUtils.java
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.RDF;
package org.nanopub.extra.index;
public class IndexUtils {
private IndexUtils() {} // no instances allowed
| public static boolean isIndex(Nanopub np) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/index/IndexUtils.java | // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
| import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.RDF; | package org.nanopub.extra.index;
public class IndexUtils {
private IndexUtils() {} // no instances allowed
public static boolean isIndex(Nanopub np) {
for (Statement st : np.getPubinfo()) {
if (!st.getSubject().equals(np.getUri())) continue;
if (!st.getPredicate().equals(RDF.TYPE)) continue;
if (!st.getObject().equals(NanopubIndex.NANOPUB_INDEX_URI)) continue;
return true;
}
return false;
}
| // Path: src/main/java/org/nanopub/MalformedNanopubException.java
// public class MalformedNanopubException extends Exception {
//
// private static final long serialVersionUID = -1022546557206977739L;
//
// public MalformedNanopubException(String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
// Path: src/main/java/org/nanopub/extra/index/IndexUtils.java
import org.nanopub.MalformedNanopubException;
import org.nanopub.Nanopub;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.RDF;
package org.nanopub.extra.index;
public class IndexUtils {
private IndexUtils() {} // no instances allowed
public static boolean isIndex(Nanopub np) {
for (Statement st : np.getPubinfo()) {
if (!st.getSubject().equals(np.getUri())) continue;
if (!st.getPredicate().equals(RDF.TYPE)) continue;
if (!st.getObject().equals(NanopubIndex.NANOPUB_INDEX_URI)) continue;
return true;
}
return false;
}
| public static NanopubIndex castToIndex(Nanopub np) throws MalformedNanopubException { |
Nanopublication/nanopub-java | src/test/java/org/nanopub/CheckValidNanopubsTest.java | // Path: src/main/java/org/nanopub/CheckNanopub.java
// public class Report {
//
// private int signed, legacySigned, trusty, notTrusty, invalidSignature, invalid, error;
//
// private Report() {
// }
//
// private void countSigned() {
// signed++;
// }
//
// public int getSignedCount() {
// return signed;
// }
//
// private void countLegacySigned() {
// legacySigned++;
// }
//
// public int getLegacySignedCount() {
// return legacySigned;
// }
//
// private void countTrusty() {
// trusty++;
// }
//
// public int getTrustyCount() {
// return trusty;
// }
//
// private void countNotTrusty() {
// notTrusty++;
// }
//
// public int getNotTrustyCount() {
// return notTrusty;
// }
//
// private void countInvalidSignature() {
// invalidSignature++;
// }
//
// public int getInvalidSignatureCount() {
// return invalidSignature;
// }
//
// private void countInvalid() {
// invalid++;
// }
//
// public int getInvalidCount() {
// return invalid;
// }
//
// private void countError() {
// error++;
// }
//
// public int getErrorCount() {
// return error;
// }
//
// public int getAllValidCount() {
// return signed + trusty + notTrusty;
// }
//
// public int getAllInvalidCount() {
// return invalidSignature + invalid + error;
// }
//
// public boolean areAllValid() {
// return getAllInvalidCount() == 0;
// }
//
//
// public String getSummary() {
// String s = "";
// if (signed > 0) s += " " + signed + " trusty with signature;";
// if (legacySigned > 0) s += " " + legacySigned + " trusty with legacy signature;";
// if (trusty > 0) s += " " + trusty + " trusty (without signature);";
// if (notTrusty > 0) s += " " + notTrusty + " valid (not trusty);";
// if (invalidSignature > 0) s += " " + invalidSignature + " invalid signature;";
// if (invalid > 0) s += " " + invalid + " invalid nanopubs;";
// if (error > 0) s += " " + error + " errors;";
// s = s.replaceFirst("^ ", "");
// return s;
// }
// }
| import java.io.File;
import org.junit.Test;
import org.nanopub.CheckNanopub.Report; | package org.nanopub;
public class CheckValidNanopubsTest {
@Test
public void runTest() throws Exception {
File testSuiteValidDir = new File("src/main/resources/testsuite/valid/");
for (File testFile : testSuiteValidDir.listFiles()) {
testValid(testFile.getName());
}
}
public void testValid(String filename) throws Exception {
CheckNanopub c = new CheckNanopub("src/main/resources/testsuite/valid/" + filename); | // Path: src/main/java/org/nanopub/CheckNanopub.java
// public class Report {
//
// private int signed, legacySigned, trusty, notTrusty, invalidSignature, invalid, error;
//
// private Report() {
// }
//
// private void countSigned() {
// signed++;
// }
//
// public int getSignedCount() {
// return signed;
// }
//
// private void countLegacySigned() {
// legacySigned++;
// }
//
// public int getLegacySignedCount() {
// return legacySigned;
// }
//
// private void countTrusty() {
// trusty++;
// }
//
// public int getTrustyCount() {
// return trusty;
// }
//
// private void countNotTrusty() {
// notTrusty++;
// }
//
// public int getNotTrustyCount() {
// return notTrusty;
// }
//
// private void countInvalidSignature() {
// invalidSignature++;
// }
//
// public int getInvalidSignatureCount() {
// return invalidSignature;
// }
//
// private void countInvalid() {
// invalid++;
// }
//
// public int getInvalidCount() {
// return invalid;
// }
//
// private void countError() {
// error++;
// }
//
// public int getErrorCount() {
// return error;
// }
//
// public int getAllValidCount() {
// return signed + trusty + notTrusty;
// }
//
// public int getAllInvalidCount() {
// return invalidSignature + invalid + error;
// }
//
// public boolean areAllValid() {
// return getAllInvalidCount() == 0;
// }
//
//
// public String getSummary() {
// String s = "";
// if (signed > 0) s += " " + signed + " trusty with signature;";
// if (legacySigned > 0) s += " " + legacySigned + " trusty with legacy signature;";
// if (trusty > 0) s += " " + trusty + " trusty (without signature);";
// if (notTrusty > 0) s += " " + notTrusty + " valid (not trusty);";
// if (invalidSignature > 0) s += " " + invalidSignature + " invalid signature;";
// if (invalid > 0) s += " " + invalid + " invalid nanopubs;";
// if (error > 0) s += " " + error + " errors;";
// s = s.replaceFirst("^ ", "");
// return s;
// }
// }
// Path: src/test/java/org/nanopub/CheckValidNanopubsTest.java
import java.io.File;
import org.junit.Test;
import org.nanopub.CheckNanopub.Report;
package org.nanopub;
public class CheckValidNanopubsTest {
@Test
public void runTest() throws Exception {
File testSuiteValidDir = new File("src/main/resources/testsuite/valid/");
for (File testFile : testSuiteValidDir.listFiles()) {
testValid(testFile.getName());
}
}
public void testValid(String filename) throws Exception {
CheckNanopub c = new CheckNanopub("src/main/resources/testsuite/valid/" + filename); | Report report = c.check(); |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/server/NanopubServerUtils.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.nanopub.Nanopub; |
static {
// Hard-coded server instances:
bootstrapServerList.add("http://server.nanopubs.lod.labs.vu.nl/");
bootstrapServerList.add("http://130.60.24.146:7880/");
bootstrapServerList.add("https://server.nanopubs.knows.idlab.ugent.be/");
bootstrapServerList.add("https://openphacts.cs.man.ac.uk/nanopub/server/");
bootstrapServerList.add("http://server.np.scify.org/");
bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-1/");
bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-2/");
bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-3/");
bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-4/");
}
public static List<String> getBootstrapServerList() {
return bootstrapServerList;
}
public static int getVersionValue(String versionString) {
try {
int major = Integer.parseInt(versionString.split("\\.")[0]);
int minor = Integer.parseInt(versionString.split("\\.")[1]);
return (major * 1000) + minor;
} catch (Exception ex) {
return 0;
}
}
public static final IRI PROTECTED_NANOPUB = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/ProtectedNanopub");
| // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
// Path: src/main/java/org/nanopub/extra/server/NanopubServerUtils.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.nanopub.Nanopub;
static {
// Hard-coded server instances:
bootstrapServerList.add("http://server.nanopubs.lod.labs.vu.nl/");
bootstrapServerList.add("http://130.60.24.146:7880/");
bootstrapServerList.add("https://server.nanopubs.knows.idlab.ugent.be/");
bootstrapServerList.add("https://openphacts.cs.man.ac.uk/nanopub/server/");
bootstrapServerList.add("http://server.np.scify.org/");
bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-1/");
bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-2/");
bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-3/");
bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-4/");
}
public static List<String> getBootstrapServerList() {
return bootstrapServerList;
}
public static int getVersionValue(String versionString) {
try {
int major = Integer.parseInt(versionString.split("\\.")[0]);
int minor = Integer.parseInt(versionString.split("\\.")[1]);
return (major * 1000) + minor;
} catch (Exception ex) {
return 0;
}
}
public static final IRI PROTECTED_NANOPUB = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/ProtectedNanopub");
| public static boolean isProtectedNanopub(Nanopub np) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/topic/UriTailTopics.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
| import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler; | package org.nanopub.op.topic;
public class UriTailTopics implements TopicHandler {
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
// Path: src/main/java/org/nanopub/op/topic/UriTailTopics.java
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler;
package org.nanopub.op.topic;
public class UriTailTopics implements TopicHandler {
@Override | public String getTopic(Nanopub np) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/topic/NoTopics.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
| import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler; | package org.nanopub.op.topic;
public class NoTopics implements TopicHandler {
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
// Path: src/main/java/org/nanopub/op/topic/NoTopics.java
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler;
package org.nanopub.op.topic;
public class NoTopics implements TopicHandler {
@Override | public String getTopic(Nanopub np) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/topic/UriBaseTopics.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
| import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler; | package org.nanopub.op.topic;
public class UriBaseTopics implements TopicHandler {
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
// Path: src/main/java/org/nanopub/op/topic/UriBaseTopics.java
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler;
package org.nanopub.op.topic;
public class UriBaseTopics implements TopicHandler {
@Override | public String getTopic(Nanopub np) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/server/ServerIterator.java | // Path: src/main/java/org/nanopub/extra/server/ServerInfo.java
// public static class ServerInfoException extends Exception {
//
// private static final long serialVersionUID = 3903673740899289181L;
//
// public ServerInfoException(String serverUrl) {
// super(serverUrl);
// }
//
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.nanopub.extra.server.ServerInfo.ServerInfoException; | String url = serversToGetPeers.remove(0);
if (serversPeersGot.containsKey(url)) continue;
serversPeersGot.put(url, true);
try {
for (String peerUrl : NanopubServerUtils.loadPeerList(url)) {
if (serverBlackList.containsKey(peerUrl)) continue;
if (!serversContacted.containsKey(peerUrl)) {
serversToContact.add(peerUrl);
}
if (!serversPeersGot.containsKey(peerUrl)) {
serversToGetPeers.add(peerUrl);
}
}
} catch (IOException ex) {
// ignore
}
}
}
}
return null;
}
private ServerInfo getServerInfo(String url) {
if (System.currentTimeMillis() - serverInfoRefreshed > serverInfoRefreshInterval) {
serverInfos.clear();
serverInfoRefreshed = System.currentTimeMillis();
}
if (!serverInfos.containsKey(url)) {
try {
serverInfos.put(url, ServerInfo.load(url)); | // Path: src/main/java/org/nanopub/extra/server/ServerInfo.java
// public static class ServerInfoException extends Exception {
//
// private static final long serialVersionUID = 3903673740899289181L;
//
// public ServerInfoException(String serverUrl) {
// super(serverUrl);
// }
//
// }
// Path: src/main/java/org/nanopub/extra/server/ServerIterator.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.nanopub.extra.server.ServerInfo.ServerInfoException;
String url = serversToGetPeers.remove(0);
if (serversPeersGot.containsKey(url)) continue;
serversPeersGot.put(url, true);
try {
for (String peerUrl : NanopubServerUtils.loadPeerList(url)) {
if (serverBlackList.containsKey(peerUrl)) continue;
if (!serversContacted.containsKey(peerUrl)) {
serversToContact.add(peerUrl);
}
if (!serversPeersGot.containsKey(peerUrl)) {
serversToGetPeers.add(peerUrl);
}
}
} catch (IOException ex) {
// ignore
}
}
}
}
return null;
}
private ServerInfo getServerInfo(String url) {
if (System.currentTimeMillis() - serverInfoRefreshed > serverInfoRefreshInterval) {
serverInfos.clear();
serverInfoRefreshed = System.currentTimeMillis();
}
if (!serverInfos.containsKey(url)) {
try {
serverInfos.put(url, ServerInfo.load(url)); | } catch (ServerInfoException ex) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/topic/DisgenetTopics.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
| import org.nanopub.Nanopub; | package org.nanopub.op.topic;
public class DisgenetTopics extends DefaultTopics {
public DisgenetTopics() {
super("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
}
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
// Path: src/main/java/org/nanopub/op/topic/DisgenetTopics.java
import org.nanopub.Nanopub;
package org.nanopub.op.topic;
public class DisgenetTopics extends DefaultTopics {
public DisgenetTopics() {
super("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
}
@Override | public String getTopic(Nanopub np) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/NanopubUtils.java | // Path: src/main/java/org/nanopub/trusty/TrustyNanopubUtils.java
// public class TrustyNanopubUtils {
//
// public static RDFFormat STNP_FORMAT = new RDFFormat("Serialized Trusty Nanopub", "text/plain", Charset.forName("UTF8"), "stnp", false, true);
//
// private TrustyNanopubUtils() {} // no instances allowed
//
// public static void writeNanopub(Nanopub nanopub, OutputStream out, RDFFormat format)
// throws RDFHandlerException {
// RDFWriter writer = Rio.createWriter(format, new OutputStreamWriter(out, Charset.forName("UTF-8")));
// writer.startRDF();
// String s = nanopub.getUri().toString();
// writer.handleNamespace("this", s);
// writer.handleNamespace("sub", s + RdfUtils.postAcChar);
// if (!(RdfUtils.bnodeChar + "").matches("[A-Za-z0-9\\-_]")) {
// writer.handleNamespace("node", s + RdfUtils.postAcChar + RdfUtils.bnodeChar);
// }
// writer.handleNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
// writer.handleNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
// writer.handleNamespace("rdfg", "http://www.w3.org/2004/03/trix/rdfg-1/");
// writer.handleNamespace("xsd", "http://www.w3.org/2001/XMLSchema#");
// writer.handleNamespace("owl", "http://www.w3.org/2002/07/owl#");
// writer.handleNamespace("dct", "http://purl.org/dc/terms/");
// writer.handleNamespace("dce", "http://purl.org/dc/elements/1.1/");
// writer.handleNamespace("pav", "http://swan.mindinformatics.org/ontologies/1.2/pav/");
// writer.handleNamespace("np", "http://www.nanopub.org/nschema#");
// for (Statement st : NanopubUtils.getStatements(nanopub)) {
// writer.handleStatement(st);
// }
// writer.endRDF();
// }
//
// public static boolean isValidTrustyNanopub(Nanopub nanopub) {
// String artifactCode = TrustyUriUtils.getArtifactCode(nanopub.getUri().toString());
// if (artifactCode == null) return false;
// List<Statement> statements = NanopubUtils.getStatements(nanopub);
// statements = RdfPreprocessor.run(statements, artifactCode);
//
// // System.err.println("TRUSTY INPUT: ---");
// // System.err.print(RdfHasher.getDigestString(statements));
// // System.err.println("---");
//
// String ac = RdfHasher.makeArtifactCode(statements);
// return ac.equals(artifactCode);
// }
//
// public static String getTrustyDigestString(Nanopub nanopub) {
// String artifactCode = TrustyUriUtils.getArtifactCode(nanopub.getUri().toString());
// if (artifactCode == null) return null;
// List<Statement> statements = NanopubUtils.getStatements(nanopub);
// statements = RdfPreprocessor.run(statements, artifactCode);
// return RdfHasher.getDigestString(statements);
// }
//
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
import org.eclipse.rdf4j.model.Namespace;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandler;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.RDFWriter;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.BasicParserSettings;
import org.nanopub.trusty.TrustyNanopubUtils; | return s;
}
private static List<Statement> getSortedList(Set<Statement> s) {
List<Statement> l = new ArrayList<Statement>(s);
Collections.sort(l, new Comparator<Statement>() {
@Override
public int compare(Statement st1, Statement st2) {
// TODO better sorting
return st1.toString().compareTo(st2.toString());
}
});
return l;
}
public static void writeToStream(Nanopub nanopub, OutputStream out, RDFFormat format)
throws RDFHandlerException {
writeNanopub(nanopub, format, new OutputStreamWriter(out, Charset.forName("UTF-8")));
}
public static String writeToString(Nanopub nanopub, RDFFormat format) throws RDFHandlerException {
StringWriter sw = new StringWriter();
writeNanopub(nanopub, format, sw);
return sw.toString();
}
private static void writeNanopub(Nanopub nanopub, RDFFormat format, Writer writer)
throws RDFHandlerException { | // Path: src/main/java/org/nanopub/trusty/TrustyNanopubUtils.java
// public class TrustyNanopubUtils {
//
// public static RDFFormat STNP_FORMAT = new RDFFormat("Serialized Trusty Nanopub", "text/plain", Charset.forName("UTF8"), "stnp", false, true);
//
// private TrustyNanopubUtils() {} // no instances allowed
//
// public static void writeNanopub(Nanopub nanopub, OutputStream out, RDFFormat format)
// throws RDFHandlerException {
// RDFWriter writer = Rio.createWriter(format, new OutputStreamWriter(out, Charset.forName("UTF-8")));
// writer.startRDF();
// String s = nanopub.getUri().toString();
// writer.handleNamespace("this", s);
// writer.handleNamespace("sub", s + RdfUtils.postAcChar);
// if (!(RdfUtils.bnodeChar + "").matches("[A-Za-z0-9\\-_]")) {
// writer.handleNamespace("node", s + RdfUtils.postAcChar + RdfUtils.bnodeChar);
// }
// writer.handleNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
// writer.handleNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
// writer.handleNamespace("rdfg", "http://www.w3.org/2004/03/trix/rdfg-1/");
// writer.handleNamespace("xsd", "http://www.w3.org/2001/XMLSchema#");
// writer.handleNamespace("owl", "http://www.w3.org/2002/07/owl#");
// writer.handleNamespace("dct", "http://purl.org/dc/terms/");
// writer.handleNamespace("dce", "http://purl.org/dc/elements/1.1/");
// writer.handleNamespace("pav", "http://swan.mindinformatics.org/ontologies/1.2/pav/");
// writer.handleNamespace("np", "http://www.nanopub.org/nschema#");
// for (Statement st : NanopubUtils.getStatements(nanopub)) {
// writer.handleStatement(st);
// }
// writer.endRDF();
// }
//
// public static boolean isValidTrustyNanopub(Nanopub nanopub) {
// String artifactCode = TrustyUriUtils.getArtifactCode(nanopub.getUri().toString());
// if (artifactCode == null) return false;
// List<Statement> statements = NanopubUtils.getStatements(nanopub);
// statements = RdfPreprocessor.run(statements, artifactCode);
//
// // System.err.println("TRUSTY INPUT: ---");
// // System.err.print(RdfHasher.getDigestString(statements));
// // System.err.println("---");
//
// String ac = RdfHasher.makeArtifactCode(statements);
// return ac.equals(artifactCode);
// }
//
// public static String getTrustyDigestString(Nanopub nanopub) {
// String artifactCode = TrustyUriUtils.getArtifactCode(nanopub.getUri().toString());
// if (artifactCode == null) return null;
// List<Statement> statements = NanopubUtils.getStatements(nanopub);
// statements = RdfPreprocessor.run(statements, artifactCode);
// return RdfHasher.getDigestString(statements);
// }
//
// }
// Path: src/main/java/org/nanopub/NanopubUtils.java
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
import org.eclipse.rdf4j.model.Namespace;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandler;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.RDFWriter;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.BasicParserSettings;
import org.nanopub.trusty.TrustyNanopubUtils;
return s;
}
private static List<Statement> getSortedList(Set<Statement> s) {
List<Statement> l = new ArrayList<Statement>(s);
Collections.sort(l, new Comparator<Statement>() {
@Override
public int compare(Statement st1, Statement st2) {
// TODO better sorting
return st1.toString().compareTo(st2.toString());
}
});
return l;
}
public static void writeToStream(Nanopub nanopub, OutputStream out, RDFFormat format)
throws RDFHandlerException {
writeNanopub(nanopub, format, new OutputStreamWriter(out, Charset.forName("UTF-8")));
}
public static String writeToString(Nanopub nanopub, RDFFormat format) throws RDFHandlerException {
StringWriter sw = new StringWriter();
writeNanopub(nanopub, format, sw);
return sw.toString();
}
private static void writeNanopub(Nanopub nanopub, RDFFormat format, Writer writer)
throws RDFHandlerException { | if (format.equals(TrustyNanopubUtils.STNP_FORMAT)) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/Nanopub2Html.java | // Path: src/main/java/org/nanopub/MultiNanopubRdfHandler.java
// public interface NanopubHandler {
//
// public void handleNanopub(Nanopub np);
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.rdf4j.RDF4JException;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.nanopub.MultiNanopubRdfHandler.NanopubHandler;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException; | jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
try {
obj.run();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
private Nanopub2Html() {
}
private Nanopub2Html(OutputStream outputStream, boolean standalone, boolean indentContext) {
this.outputStream = outputStream;
this.standalone = standalone;
this.indentContextDisabled = !indentContext;
}
private void run() throws IOException {
if (outputFile != null) {
outputStream = new FileOutputStream(outputFile);
}
for (String s : inputNanopubs) {
try { | // Path: src/main/java/org/nanopub/MultiNanopubRdfHandler.java
// public interface NanopubHandler {
//
// public void handleNanopub(Nanopub np);
//
// }
// Path: src/main/java/org/nanopub/Nanopub2Html.java
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.rdf4j.RDF4JException;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.nanopub.MultiNanopubRdfHandler.NanopubHandler;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
try {
obj.run();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
private Nanopub2Html() {
}
private Nanopub2Html(OutputStream outputStream, boolean standalone, boolean indentContext) {
this.outputStream = outputStream;
this.standalone = standalone;
this.indentContextDisabled = !indentContext;
}
private void run() throws IOException {
if (outputFile != null) {
outputStream = new FileOutputStream(outputFile);
}
for (String s : inputNanopubs) {
try { | MultiNanopubRdfHandler.process(new File(s), new NanopubHandler() { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/topic/MetaboliteSpeciesTopics.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
| import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Statement;
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler; | package org.nanopub.op.topic;
public class MetaboliteSpeciesTopics implements TopicHandler {
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
// Path: src/main/java/org/nanopub/op/topic/MetaboliteSpeciesTopics.java
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Statement;
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler;
package org.nanopub.op.topic;
public class MetaboliteSpeciesTopics implements TopicHandler {
@Override | public String getTopic(Nanopub np) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/extra/security/DigitalSignaturePattern.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
| import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern; | package org.nanopub.extra.security;
public class DigitalSignaturePattern implements NanopubPattern {
private static final long serialVersionUID = 669651544354988407L;
@Override
public String getName() {
return "Digitally signed nanopublication";
}
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/NanopubPattern.java
// public interface NanopubPattern extends Serializable {
//
// /**
// * This method should return the name of the pattern, as to be shown to the
// * user.
// *
// * @return The name of the pattern
// */
// public String getName();
//
// /**
// * This method should return true if this pattern applies to the given
// * nanopublication. This can be because the creators of the pattern think
// * that the given nanopublication should use it, or because the
// * nanopublication seems to be using the pattern, but not necessarily in a
// * correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if the pattern applies to the nanopublication
// */
// public boolean appliesTo(Nanopub nanopub);
//
// /**
// * This method should return true if the given nanopublication uses this
// * pattern in a correct and valid manner.
// *
// * @param nanopub The nanopublication
// * @return true if this pattern is used in a valid manner
// */
// public boolean isCorrectlyUsedBy(Nanopub nanopub);
//
// /**
// * This method can optionally return a short description of the given
// * nanopublication, such as information about the relevant elements of
// * this pattern (if valid) or the errors (if invalid).
// *
// * @param nanopub The nanopublication
// * @return A short description of the nanopublication with respect to
// * the pattern
// */
// public String getDescriptionFor(Nanopub nanopub);
//
// /**
// * This method should return a URL with additional information about the
// * given pattern.
// *
// * @return A URL with additional information
// */
// public URL getPatternInfoUrl() throws MalformedURLException;
//
// }
// Path: src/main/java/org/nanopub/extra/security/DigitalSignaturePattern.java
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import org.nanopub.Nanopub;
import org.nanopub.NanopubPattern;
package org.nanopub.extra.security;
public class DigitalSignaturePattern implements NanopubPattern {
private static final long serialVersionUID = 669651544354988407L;
@Override
public String getName() {
return "Digitally signed nanopublication";
}
@Override | public boolean appliesTo(Nanopub nanopub) { |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/topic/DefaultTopics.java | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
| import java.util.HashMap;
import java.util.Map;
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement; | package org.nanopub.op.topic;
public class DefaultTopics implements TopicHandler {
private Map<String,Boolean> ignore = new HashMap<>();
public DefaultTopics(String ignoreProperties) {
if (ignoreProperties != null) {
for (String s : ignoreProperties.trim().split("\\|")) {
if (!s.isEmpty()) ignore.put(s, true);
}
}
}
@Override | // Path: src/main/java/org/nanopub/Nanopub.java
// public interface Nanopub {
//
// // URIs in the nanopub namespace:
// public static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#Nanopublication");
// public static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasAssertion");
// public static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasProvenance");
// public static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI("http://www.nanopub.org/nschema#hasPublicationInfo");
//
// // URIs that link nanopublications:
// public static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI("http://purl.org/nanopub/x/supersedes");
//
// public IRI getUri();
//
// public IRI getHeadUri();
//
// public Set<Statement> getHead();
//
// public IRI getAssertionUri();
//
// public Set<Statement> getAssertion();
//
// public IRI getProvenanceUri();
//
// public Set<Statement> getProvenance();
//
// public IRI getPubinfoUri();
//
// public Set<Statement> getPubinfo();
//
// public Set<IRI> getGraphUris();
//
// // TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,
// // we might not need the following three methods anymore...
//
// public Calendar getCreationTime();
//
// public Set<IRI> getAuthors();
//
// public Set<IRI> getCreators();
//
// public int getTripleCount();
//
// public long getByteCount();
//
// }
//
// Path: src/main/java/org/nanopub/op/Topic.java
// public interface TopicHandler {
//
// public String getTopic(Nanopub np);
//
// }
// Path: src/main/java/org/nanopub/op/topic/DefaultTopics.java
import java.util.HashMap;
import java.util.Map;
import org.nanopub.Nanopub;
import org.nanopub.op.Topic.TopicHandler;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
package org.nanopub.op.topic;
public class DefaultTopics implements TopicHandler {
private Map<String,Boolean> ignore = new HashMap<>();
public DefaultTopics(String ignoreProperties) {
if (ignoreProperties != null) {
for (String s : ignoreProperties.trim().split("\\|")) {
if (!s.isEmpty()) ignore.put(s, true);
}
}
}
@Override | public String getTopic(Nanopub np) { |
AURIN/online-whatif | src/test/java/au/org/aurin/wif/controller/FactorsControllerTest.java | // Path: src/main/java/au/org/aurin/wif/svc/suitability/FactorService.java
// public interface FactorService {
//
// /**
// * Adds the factor.
// *
// * @param factor
// * the factor
// * @param projectId
// * the project id
// * @return the wif factor
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// * @throws InvalidLabelException
// */
// Factor createFactor(Factor factor, String projectId)
// throws WifInvalidInputException, WifInvalidConfigException,
// InvalidLabelException;
//
// /**
// * Gets the factor.
// *
// * @param id
// * the id
// * @return the factor
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// Factor getFactor(String id) throws WifInvalidInputException,
// WifInvalidConfigException;
//
// /**
// * Gets the factor.
// *
// * @param id
// * the id
// * @param projectId
// * the project id
// * @return the factor
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// Factor getFactor(String id, String projectId)
// throws WifInvalidInputException, WifInvalidConfigException;
//
// /**
// * Update factor.
// *
// * @param factor
// * the factor
// * @param projectId
// * the project id
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// void updateFactor(Factor factor, String projectId)
// throws WifInvalidInputException, WifInvalidConfigException;
//
// /**
// * Delete factor.
// *
// * @param id
// * the id
// * @param projectId
// * the project id
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// void deleteFactor(String id, String projectId)
// throws WifInvalidInputException, WifInvalidConfigException;
//
// /**
// * Gets the factors for a given project.
// *
// * @param projectId
// * the project id
// * @return the factors
// * @throws WifInvalidInputException
// * the wif invalid input exception
// */
// List<Factor> getFactors(String projectId) throws WifInvalidInputException;
//
//
// /**
// * Gets the factorTypes for a given factor.
// *
// * @param factorId
// * the factor id
// * @return the factorTypes
// * @throws WifInvalidInputException
// * the wif invalid input exception
// */
// List<FactorType> getFactorTypes(String factorId) throws WifInvalidInputException;
//
//
// /**
// * Gets the factorType.
// *
// * @param projectId
// * the project id
// * @param factorId
// * the factor id
// * @param id
// * the id
// * @return the factorType
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// FactorType getFactorType(String projectId, String factorId, String id )
// throws WifInvalidInputException, WifInvalidConfigException;
//
//
// /**
// * Delete factorType.
// *
// *
// * @param projectId
// * the project id
// * @param factorid
// * the factorid
// * @param id
// * the id
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// void deleteFactorType(String projectId, String factorId, String id)
// throws WifInvalidInputException, WifInvalidConfigException;
//
//
// /**
// * Gets the factorTypeByLabel.
// *
// * @param projectId
// * the project id
// * @param factorId
// * the factor id
// * @param label
// * the label
// * @return the factorType
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// List<FactorType> getFactorTypeByLable(String projectId, String factorId, String lable )
// throws WifInvalidInputException, WifInvalidConfigException;
//
// /**
// * Delete factorTypeExtra.
// *
// *
// * @param projectId
// * the project id
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// void deleteFactorTypesExtra(String projectId)
// throws WifInvalidInputException, WifInvalidConfigException;
//
//
// }
| import static java.util.Arrays.asList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import au.org.aurin.wif.exception.validate.WifInvalidInputException;
import au.org.aurin.wif.model.suitability.Factor;
import au.org.aurin.wif.svc.suitability.FactorService; | package au.org.aurin.wif.controller;
/**
* The Class FactorsControllerTest.
*/
public class FactorsControllerTest {
/** The factors controller. */
private FactorsController factorsController;
/**
* Setup.
*/
@BeforeClass (enabled = false)
public void setup() {
factorsController = new FactorsController();
}
/**
* Creates the factor.
*
* @throws Exception the exception
*/
@Test (enabled = false)
public void createFactor() throws Exception { | // Path: src/main/java/au/org/aurin/wif/svc/suitability/FactorService.java
// public interface FactorService {
//
// /**
// * Adds the factor.
// *
// * @param factor
// * the factor
// * @param projectId
// * the project id
// * @return the wif factor
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// * @throws InvalidLabelException
// */
// Factor createFactor(Factor factor, String projectId)
// throws WifInvalidInputException, WifInvalidConfigException,
// InvalidLabelException;
//
// /**
// * Gets the factor.
// *
// * @param id
// * the id
// * @return the factor
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// Factor getFactor(String id) throws WifInvalidInputException,
// WifInvalidConfigException;
//
// /**
// * Gets the factor.
// *
// * @param id
// * the id
// * @param projectId
// * the project id
// * @return the factor
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// Factor getFactor(String id, String projectId)
// throws WifInvalidInputException, WifInvalidConfigException;
//
// /**
// * Update factor.
// *
// * @param factor
// * the factor
// * @param projectId
// * the project id
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// void updateFactor(Factor factor, String projectId)
// throws WifInvalidInputException, WifInvalidConfigException;
//
// /**
// * Delete factor.
// *
// * @param id
// * the id
// * @param projectId
// * the project id
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// void deleteFactor(String id, String projectId)
// throws WifInvalidInputException, WifInvalidConfigException;
//
// /**
// * Gets the factors for a given project.
// *
// * @param projectId
// * the project id
// * @return the factors
// * @throws WifInvalidInputException
// * the wif invalid input exception
// */
// List<Factor> getFactors(String projectId) throws WifInvalidInputException;
//
//
// /**
// * Gets the factorTypes for a given factor.
// *
// * @param factorId
// * the factor id
// * @return the factorTypes
// * @throws WifInvalidInputException
// * the wif invalid input exception
// */
// List<FactorType> getFactorTypes(String factorId) throws WifInvalidInputException;
//
//
// /**
// * Gets the factorType.
// *
// * @param projectId
// * the project id
// * @param factorId
// * the factor id
// * @param id
// * the id
// * @return the factorType
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// FactorType getFactorType(String projectId, String factorId, String id )
// throws WifInvalidInputException, WifInvalidConfigException;
//
//
// /**
// * Delete factorType.
// *
// *
// * @param projectId
// * the project id
// * @param factorid
// * the factorid
// * @param id
// * the id
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// void deleteFactorType(String projectId, String factorId, String id)
// throws WifInvalidInputException, WifInvalidConfigException;
//
//
// /**
// * Gets the factorTypeByLabel.
// *
// * @param projectId
// * the project id
// * @param factorId
// * the factor id
// * @param label
// * the label
// * @return the factorType
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// List<FactorType> getFactorTypeByLable(String projectId, String factorId, String lable )
// throws WifInvalidInputException, WifInvalidConfigException;
//
// /**
// * Delete factorTypeExtra.
// *
// *
// * @param projectId
// * the project id
// * @throws WifInvalidInputException
// * the wif invalid input exception
// * @throws WifInvalidConfigException
// * the wif invalid config exception
// */
// void deleteFactorTypesExtra(String projectId)
// throws WifInvalidInputException, WifInvalidConfigException;
//
//
// }
// Path: src/test/java/au/org/aurin/wif/controller/FactorsControllerTest.java
import static java.util.Arrays.asList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import au.org.aurin.wif.exception.validate.WifInvalidInputException;
import au.org.aurin.wif.model.suitability.Factor;
import au.org.aurin.wif.svc.suitability.FactorService;
package au.org.aurin.wif.controller;
/**
* The Class FactorsControllerTest.
*/
public class FactorsControllerTest {
/** The factors controller. */
private FactorsController factorsController;
/**
* Setup.
*/
@BeforeClass (enabled = false)
public void setup() {
factorsController = new FactorsController();
}
/**
* Creates the factor.
*
* @throws Exception the exception
*/
@Test (enabled = false)
public void createFactor() throws Exception { | FactorService factorService = mock(FactorService.class); |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/search/LevenshteinSearch.java | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
| import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel; | package com.learningmodule.association.conceptdrug.search;
/*
* Class that implements method to get the Approximate String matches using Levenshtien Distance
* for a string and to make the Dictionary
* link of the algorithm explanation http://stevehanov.ca/blog/index.php?id=114
*/
public class LevenshteinSearch {
// root node of the Trie
private TrieNode trie;
private Logger log = Logger.getLogger(LevenshteinSearch.class);
// database interface to get dictionary for concept words | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/search/LevenshteinSearch.java
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
package com.learningmodule.association.conceptdrug.search;
/*
* Class that implements method to get the Approximate String matches using Levenshtien Distance
* for a string and to make the Dictionary
* link of the algorithm explanation http://stevehanov.ca/blog/index.php?id=114
*/
public class LevenshteinSearch {
// root node of the Trie
private TrieNode trie;
private Logger log = Logger.getLogger(LevenshteinSearch.class);
// database interface to get dictionary for concept words | private ConceptDrugDatabaseInterface learningInterface; |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/search/LevenshteinSearch.java | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
| import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel; | package com.learningmodule.association.conceptdrug.search;
/*
* Class that implements method to get the Approximate String matches using Levenshtien Distance
* for a string and to make the Dictionary
* link of the algorithm explanation http://stevehanov.ca/blog/index.php?id=114
*/
public class LevenshteinSearch {
// root node of the Trie
private TrieNode trie;
private Logger log = Logger.getLogger(LevenshteinSearch.class);
// database interface to get dictionary for concept words
private ConceptDrugDatabaseInterface learningInterface;
// constructor for this class
public LevenshteinSearch(ConceptDrugDatabaseInterface learningInterface) {
this.learningInterface = learningInterface;
// make the dictionary when Object is created
makeDictionary();
}
/*
* Method that will construct the dictionary by getting all the
* concept_words from database
*/
public void makeDictionary() {
// get the list of words from database | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/search/LevenshteinSearch.java
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
package com.learningmodule.association.conceptdrug.search;
/*
* Class that implements method to get the Approximate String matches using Levenshtien Distance
* for a string and to make the Dictionary
* link of the algorithm explanation http://stevehanov.ca/blog/index.php?id=114
*/
public class LevenshteinSearch {
// root node of the Trie
private TrieNode trie;
private Logger log = Logger.getLogger(LevenshteinSearch.class);
// database interface to get dictionary for concept words
private ConceptDrugDatabaseInterface learningInterface;
// constructor for this class
public LevenshteinSearch(ConceptDrugDatabaseInterface learningInterface) {
this.learningInterface = learningInterface;
// make the dictionary when Object is created
makeDictionary();
}
/*
* Method that will construct the dictionary by getting all the
* concept_words from database
*/
public void makeDictionary() {
// get the list of words from database | LinkedList<ConceptWordModel> names = learningInterface.getConceptWords(); |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java | // Path: src/com/learningmodule/association/conceptdrug/model/ConceptRow.java
// public class Cell implements Serializable {
// private static final long serialVersionUID = 1L;
//
// // each cell contains drug Id and confidence level
// private String drug;
// private double confidence;
//
// public Cell(String drug, double confidence) {
// this.drug = drug;
// this.confidence = confidence;
// }
//
// public String getDrug() {
// return drug;
// }
//
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// @Override
// public String toString() {
// return "Cell [drug=" + drug + ", confidence=" + confidence + "]";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Cell other = (Cell) obj;
// if (drug.equals(other.drug))
// return false;
// return true;
// }
//
// }
| import java.io.Serializable;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.model.ConceptRow.Cell; | package com.learningmodule.association.conceptdrug.model;
/*
* Class that represent he resultant matrix that will be used to predict the drug for a concept
*/
public class PredictionMatrix implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
// Prediction matrix is a hastable with key as concept_id and value as
// ConceptRow
Hashtable<String, ConceptRow> rows;
public PredictionMatrix(int noOfConcepts) {
rows = new Hashtable<String, ConceptRow>();
}
/*
* method to get the list of drugs that are associated with a drugId
*/ | // Path: src/com/learningmodule/association/conceptdrug/model/ConceptRow.java
// public class Cell implements Serializable {
// private static final long serialVersionUID = 1L;
//
// // each cell contains drug Id and confidence level
// private String drug;
// private double confidence;
//
// public Cell(String drug, double confidence) {
// this.drug = drug;
// this.confidence = confidence;
// }
//
// public String getDrug() {
// return drug;
// }
//
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// @Override
// public String toString() {
// return "Cell [drug=" + drug + ", confidence=" + confidence + "]";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Cell other = (Cell) obj;
// if (drug.equals(other.drug))
// return false;
// return true;
// }
//
// }
// Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.model.ConceptRow.Cell;
package com.learningmodule.association.conceptdrug.model;
/*
* Class that represent he resultant matrix that will be used to predict the drug for a concept
*/
public class PredictionMatrix implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
// Prediction matrix is a hastable with key as concept_id and value as
// ConceptRow
Hashtable<String, ConceptRow> rows;
public PredictionMatrix(int noOfConcepts) {
rows = new Hashtable<String, ConceptRow>();
}
/*
* method to get the list of drugs that are associated with a drugId
*/ | public LinkedList<Cell> getDrugs(String conceptId) { |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/search/DatabaseConceptDictionaryCollector.java | // Path: src/com/database/DatabaseConnector.java
// public class DatabaseConnector {
// private static Connection connection = null;
// private static Logger log = Logger.getLogger(DatabaseConnector.class);
// /*
// * make connection as soon as the class is loaded
// */
// static {
// makeConnection();
// }
//
// /*
// * method to make the connection with the database
// */
// public static void makeConnection() {
//
// try {
// PropertiesReader.load();
// // get the connection with the database
// Class.forName("com.mysql.jdbc.Driver");
// connection = DriverManager.getConnection(PropertiesReader.getUrl(),
// PropertiesReader.getUser(), PropertiesReader.getPassword());
// System.out.println("MySQL JDBC Driver Registered!");
// log.debug("MySQL JDBC Driver Registered!");
// } catch (SQLException e) {
// System.out.println("Connection Failed! Check output console");
// e.printStackTrace();
// log.fatal(e);
// return;
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// log.fatal(e);
// }
// }
//
// /*
// * method to check if database is connected
// */
// public static boolean isConnected() {
// if (connection != null) {
// try {
// return !connection.isClosed();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// return true;
// }
// return false;
// }
//
// /*
// * method the close the connection with database.
// */
// public static void closeConnection() {
// try {
// connection.close();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// log.error(e);
// }
// }
//
// public static Connection getConnection() {
// if(connection == null) {
// makeConnection();
// }
// return connection;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
| import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import com.database.DatabaseConnector;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel; | package com.learningmodule.association.conceptdrug.search;
/*
* Class that implements the method to get the all the concept words and respective conceptId's from database
*/
public class DatabaseConceptDictionaryCollector {
public static LinkedList<ConceptWordModel> getConceptWords() { | // Path: src/com/database/DatabaseConnector.java
// public class DatabaseConnector {
// private static Connection connection = null;
// private static Logger log = Logger.getLogger(DatabaseConnector.class);
// /*
// * make connection as soon as the class is loaded
// */
// static {
// makeConnection();
// }
//
// /*
// * method to make the connection with the database
// */
// public static void makeConnection() {
//
// try {
// PropertiesReader.load();
// // get the connection with the database
// Class.forName("com.mysql.jdbc.Driver");
// connection = DriverManager.getConnection(PropertiesReader.getUrl(),
// PropertiesReader.getUser(), PropertiesReader.getPassword());
// System.out.println("MySQL JDBC Driver Registered!");
// log.debug("MySQL JDBC Driver Registered!");
// } catch (SQLException e) {
// System.out.println("Connection Failed! Check output console");
// e.printStackTrace();
// log.fatal(e);
// return;
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// log.fatal(e);
// }
// }
//
// /*
// * method to check if database is connected
// */
// public static boolean isConnected() {
// if (connection != null) {
// try {
// return !connection.isClosed();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// return true;
// }
// return false;
// }
//
// /*
// * method the close the connection with database.
// */
// public static void closeConnection() {
// try {
// connection.close();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// log.error(e);
// }
// }
//
// public static Connection getConnection() {
// if(connection == null) {
// makeConnection();
// }
// return connection;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/search/DatabaseConceptDictionaryCollector.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import com.database.DatabaseConnector;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
package com.learningmodule.association.conceptdrug.search;
/*
* Class that implements the method to get the all the concept words and respective conceptId's from database
*/
public class DatabaseConceptDictionaryCollector {
public static LinkedList<ConceptWordModel> getConceptWords() { | if (DatabaseConnector.getConnection() != null) { |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/learning/LearningMethod.java | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
// public class PredictionMatrix implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// // Prediction matrix is a hastable with key as concept_id and value as
// // ConceptRow
// Hashtable<String, ConceptRow> rows;
//
// public PredictionMatrix(int noOfConcepts) {
// rows = new Hashtable<String, ConceptRow>();
// }
//
// /*
// * method to get the list of drugs that are associated with a drugId
// */
// public LinkedList<Cell> getDrugs(String conceptId) {
// // if conceptId is present in the hash table then get the list of drugs
// // related to it
// if (rows.containsKey(conceptId)) {
// return rows.get(conceptId).getDrugs();
// }
// return null;
// }
//
// /*
// * method to get all the concepts which are related to some drug
// */
// public LinkedList<String> getNonEmptyConcepts() {
// Enumeration<String> temp = rows.keys();
// LinkedList<String> result = new LinkedList<String>();
// while (temp.hasMoreElements()) {
// String key = temp.nextElement();
// if (!getDrugs(key).isEmpty()) {
// result.add(key);
// }
// }
// return result;
// }
//
// /*
// * method to add a new cell to Prediction matrix
// */
// public void addCell(String concept, String drug, double conf) {
// // if concept is already present in hast table put a new key value pair
// // with key as this concept
// if (!rows.containsKey(concept)) {
// rows.put(concept, new ConceptRow(concept));
// }
// // add the drug in conceptRow
// rows.get(concept).addCell(drug, conf);
// }
//
// @Override
// public String toString() {
// String result = "";
// int count = 0;
// Enumeration<String> keys = rows.keys();
// while (keys.hasMoreElements()) {
// result = result + rows.get(keys.nextElement()).toString() + "\n";
// count++;
// }
// return result + count;
// }
//
// }
| import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.model.PredictionMatrix; | package com.learningmodule.association.conceptdrug.learning;
/*
* Class used for finding association rules between the observations and drugs.
*/
//import weka.associations.Apriori;
//import weka.core.Instances;
public class LearningMethod {
// parameters of association rule finding
private double lowerMinSupport = 0.0001;
// private double upperMinSupport = 1.0;
private double minConfidence = 0.3;
// private double rulesToInstancesRatio = 0.4;
private static Logger log = Logger.getLogger(LearningMethod.class); | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
// public class PredictionMatrix implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// // Prediction matrix is a hastable with key as concept_id and value as
// // ConceptRow
// Hashtable<String, ConceptRow> rows;
//
// public PredictionMatrix(int noOfConcepts) {
// rows = new Hashtable<String, ConceptRow>();
// }
//
// /*
// * method to get the list of drugs that are associated with a drugId
// */
// public LinkedList<Cell> getDrugs(String conceptId) {
// // if conceptId is present in the hash table then get the list of drugs
// // related to it
// if (rows.containsKey(conceptId)) {
// return rows.get(conceptId).getDrugs();
// }
// return null;
// }
//
// /*
// * method to get all the concepts which are related to some drug
// */
// public LinkedList<String> getNonEmptyConcepts() {
// Enumeration<String> temp = rows.keys();
// LinkedList<String> result = new LinkedList<String>();
// while (temp.hasMoreElements()) {
// String key = temp.nextElement();
// if (!getDrugs(key).isEmpty()) {
// result.add(key);
// }
// }
// return result;
// }
//
// /*
// * method to add a new cell to Prediction matrix
// */
// public void addCell(String concept, String drug, double conf) {
// // if concept is already present in hast table put a new key value pair
// // with key as this concept
// if (!rows.containsKey(concept)) {
// rows.put(concept, new ConceptRow(concept));
// }
// // add the drug in conceptRow
// rows.get(concept).addCell(drug, conf);
// }
//
// @Override
// public String toString() {
// String result = "";
// int count = 0;
// Enumeration<String> keys = rows.keys();
// while (keys.hasMoreElements()) {
// result = result + rows.get(keys.nextElement()).toString() + "\n";
// count++;
// }
// return result + count;
// }
//
// }
// Path: src/com/learningmodule/association/conceptdrug/learning/LearningMethod.java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.model.PredictionMatrix;
package com.learningmodule.association.conceptdrug.learning;
/*
* Class used for finding association rules between the observations and drugs.
*/
//import weka.associations.Apriori;
//import weka.core.Instances;
public class LearningMethod {
// parameters of association rule finding
private double lowerMinSupport = 0.0001;
// private double upperMinSupport = 1.0;
private double minConfidence = 0.3;
// private double rulesToInstancesRatio = 0.4;
private static Logger log = Logger.getLogger(LearningMethod.class); | private PredictionMatrix resultMatrix; |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/learning/LearningMethod.java | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
// public class PredictionMatrix implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// // Prediction matrix is a hastable with key as concept_id and value as
// // ConceptRow
// Hashtable<String, ConceptRow> rows;
//
// public PredictionMatrix(int noOfConcepts) {
// rows = new Hashtable<String, ConceptRow>();
// }
//
// /*
// * method to get the list of drugs that are associated with a drugId
// */
// public LinkedList<Cell> getDrugs(String conceptId) {
// // if conceptId is present in the hash table then get the list of drugs
// // related to it
// if (rows.containsKey(conceptId)) {
// return rows.get(conceptId).getDrugs();
// }
// return null;
// }
//
// /*
// * method to get all the concepts which are related to some drug
// */
// public LinkedList<String> getNonEmptyConcepts() {
// Enumeration<String> temp = rows.keys();
// LinkedList<String> result = new LinkedList<String>();
// while (temp.hasMoreElements()) {
// String key = temp.nextElement();
// if (!getDrugs(key).isEmpty()) {
// result.add(key);
// }
// }
// return result;
// }
//
// /*
// * method to add a new cell to Prediction matrix
// */
// public void addCell(String concept, String drug, double conf) {
// // if concept is already present in hast table put a new key value pair
// // with key as this concept
// if (!rows.containsKey(concept)) {
// rows.put(concept, new ConceptRow(concept));
// }
// // add the drug in conceptRow
// rows.get(concept).addCell(drug, conf);
// }
//
// @Override
// public String toString() {
// String result = "";
// int count = 0;
// Enumeration<String> keys = rows.keys();
// while (keys.hasMoreElements()) {
// result = result + rows.get(keys.nextElement()).toString() + "\n";
// count++;
// }
// return result + count;
// }
//
// }
| import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.model.PredictionMatrix; | public PredictionMatrix getMatrix() throws IOException {
if (resultMatrix == null) {
return readResults();
}
return resultMatrix;
}
/*
* method to save the results of association rules in a file
*/
public PredictionMatrix readResults() throws IOException {
try {
String path = PostProcessing.class.getResource("/").getFile();
InputStream saveFile = new FileInputStream(path + "files/" + matrixFileName);
ObjectInputStream restore = new ObjectInputStream(saveFile);
resultMatrix = (PredictionMatrix) restore.readObject();
restore.close();
System.out.print("xxx");
return resultMatrix;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e);
}
return null;
}
/*
* method for learning from database
*/ | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
// public class PredictionMatrix implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// // Prediction matrix is a hastable with key as concept_id and value as
// // ConceptRow
// Hashtable<String, ConceptRow> rows;
//
// public PredictionMatrix(int noOfConcepts) {
// rows = new Hashtable<String, ConceptRow>();
// }
//
// /*
// * method to get the list of drugs that are associated with a drugId
// */
// public LinkedList<Cell> getDrugs(String conceptId) {
// // if conceptId is present in the hash table then get the list of drugs
// // related to it
// if (rows.containsKey(conceptId)) {
// return rows.get(conceptId).getDrugs();
// }
// return null;
// }
//
// /*
// * method to get all the concepts which are related to some drug
// */
// public LinkedList<String> getNonEmptyConcepts() {
// Enumeration<String> temp = rows.keys();
// LinkedList<String> result = new LinkedList<String>();
// while (temp.hasMoreElements()) {
// String key = temp.nextElement();
// if (!getDrugs(key).isEmpty()) {
// result.add(key);
// }
// }
// return result;
// }
//
// /*
// * method to add a new cell to Prediction matrix
// */
// public void addCell(String concept, String drug, double conf) {
// // if concept is already present in hast table put a new key value pair
// // with key as this concept
// if (!rows.containsKey(concept)) {
// rows.put(concept, new ConceptRow(concept));
// }
// // add the drug in conceptRow
// rows.get(concept).addCell(drug, conf);
// }
//
// @Override
// public String toString() {
// String result = "";
// int count = 0;
// Enumeration<String> keys = rows.keys();
// while (keys.hasMoreElements()) {
// result = result + rows.get(keys.nextElement()).toString() + "\n";
// count++;
// }
// return result + count;
// }
//
// }
// Path: src/com/learningmodule/association/conceptdrug/learning/LearningMethod.java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.model.PredictionMatrix;
public PredictionMatrix getMatrix() throws IOException {
if (resultMatrix == null) {
return readResults();
}
return resultMatrix;
}
/*
* method to save the results of association rules in a file
*/
public PredictionMatrix readResults() throws IOException {
try {
String path = PostProcessing.class.getResource("/").getFile();
InputStream saveFile = new FileInputStream(path + "files/" + matrixFileName);
ObjectInputStream restore = new ObjectInputStream(saveFile);
resultMatrix = (PredictionMatrix) restore.readObject();
restore.close();
System.out.print("xxx");
return resultMatrix;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e);
}
return null;
}
/*
* method for learning from database
*/ | public void learn(ConceptDrugDatabaseInterface learningInterface) { |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/learning/LearningMethod.java | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
// public class PredictionMatrix implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// // Prediction matrix is a hastable with key as concept_id and value as
// // ConceptRow
// Hashtable<String, ConceptRow> rows;
//
// public PredictionMatrix(int noOfConcepts) {
// rows = new Hashtable<String, ConceptRow>();
// }
//
// /*
// * method to get the list of drugs that are associated with a drugId
// */
// public LinkedList<Cell> getDrugs(String conceptId) {
// // if conceptId is present in the hash table then get the list of drugs
// // related to it
// if (rows.containsKey(conceptId)) {
// return rows.get(conceptId).getDrugs();
// }
// return null;
// }
//
// /*
// * method to get all the concepts which are related to some drug
// */
// public LinkedList<String> getNonEmptyConcepts() {
// Enumeration<String> temp = rows.keys();
// LinkedList<String> result = new LinkedList<String>();
// while (temp.hasMoreElements()) {
// String key = temp.nextElement();
// if (!getDrugs(key).isEmpty()) {
// result.add(key);
// }
// }
// return result;
// }
//
// /*
// * method to add a new cell to Prediction matrix
// */
// public void addCell(String concept, String drug, double conf) {
// // if concept is already present in hast table put a new key value pair
// // with key as this concept
// if (!rows.containsKey(concept)) {
// rows.put(concept, new ConceptRow(concept));
// }
// // add the drug in conceptRow
// rows.get(concept).addCell(drug, conf);
// }
//
// @Override
// public String toString() {
// String result = "";
// int count = 0;
// Enumeration<String> keys = rows.keys();
// while (keys.hasMoreElements()) {
// result = result + rows.get(keys.nextElement()).toString() + "\n";
// count++;
// }
// return result + count;
// }
//
// }
| import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.model.PredictionMatrix; | }
/*
* method to save the results of association rules in a file
*/
public PredictionMatrix readResults() throws IOException {
try {
String path = PostProcessing.class.getResource("/").getFile();
InputStream saveFile = new FileInputStream(path + "files/" + matrixFileName);
ObjectInputStream restore = new ObjectInputStream(saveFile);
resultMatrix = (PredictionMatrix) restore.readObject();
restore.close();
System.out.print("xxx");
return resultMatrix;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e);
}
return null;
}
/*
* method for learning from database
*/
public void learn(ConceptDrugDatabaseInterface learningInterface) {
// get the pre-processed data
// Instances instances =
// PreProcessing.process(learningInterface.getData()); | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
// public class PredictionMatrix implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// // Prediction matrix is a hastable with key as concept_id and value as
// // ConceptRow
// Hashtable<String, ConceptRow> rows;
//
// public PredictionMatrix(int noOfConcepts) {
// rows = new Hashtable<String, ConceptRow>();
// }
//
// /*
// * method to get the list of drugs that are associated with a drugId
// */
// public LinkedList<Cell> getDrugs(String conceptId) {
// // if conceptId is present in the hash table then get the list of drugs
// // related to it
// if (rows.containsKey(conceptId)) {
// return rows.get(conceptId).getDrugs();
// }
// return null;
// }
//
// /*
// * method to get all the concepts which are related to some drug
// */
// public LinkedList<String> getNonEmptyConcepts() {
// Enumeration<String> temp = rows.keys();
// LinkedList<String> result = new LinkedList<String>();
// while (temp.hasMoreElements()) {
// String key = temp.nextElement();
// if (!getDrugs(key).isEmpty()) {
// result.add(key);
// }
// }
// return result;
// }
//
// /*
// * method to add a new cell to Prediction matrix
// */
// public void addCell(String concept, String drug, double conf) {
// // if concept is already present in hast table put a new key value pair
// // with key as this concept
// if (!rows.containsKey(concept)) {
// rows.put(concept, new ConceptRow(concept));
// }
// // add the drug in conceptRow
// rows.get(concept).addCell(drug, conf);
// }
//
// @Override
// public String toString() {
// String result = "";
// int count = 0;
// Enumeration<String> keys = rows.keys();
// while (keys.hasMoreElements()) {
// result = result + rows.get(keys.nextElement()).toString() + "\n";
// count++;
// }
// return result + count;
// }
//
// }
// Path: src/com/learningmodule/association/conceptdrug/learning/LearningMethod.java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.model.PredictionMatrix;
}
/*
* method to save the results of association rules in a file
*/
public PredictionMatrix readResults() throws IOException {
try {
String path = PostProcessing.class.getResource("/").getFile();
InputStream saveFile = new FileInputStream(path + "files/" + matrixFileName);
ObjectInputStream restore = new ObjectInputStream(saveFile);
resultMatrix = (PredictionMatrix) restore.readObject();
restore.close();
System.out.print("xxx");
return resultMatrix;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e);
}
return null;
}
/*
* method for learning from database
*/
public void learn(ConceptDrugDatabaseInterface learningInterface) {
// get the pre-processed data
// Instances instances =
// PreProcessing.process(learningInterface.getData()); | LinkedList<EncounterIdConceptDrug> data = learningInterface.getData(); |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/learning/PreProcessing.java | // Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
| import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instances;
import weka.core.SparseInstance;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug; | package com.learningmodule.association.conceptdrug.learning;
/*
* class for preprocessing the data and converting it into form of Instances for Weka.
*/
public class PreProcessing {
private static Logger log = Logger.getLogger(PreProcessing.class);
| // Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/learning/PreProcessing.java
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instances;
import weka.core.SparseInstance;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
package com.learningmodule.association.conceptdrug.learning;
/*
* class for preprocessing the data and converting it into form of Instances for Weka.
*/
public class PreProcessing {
private static Logger log = Logger.getLogger(PreProcessing.class);
| public static Instances process(LinkedList<EncounterIdConceptDrug> data) { |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/predictionmodule/ConceptNameDatabaseOperation.java | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptDrugPredictionResult.java
// public class ConceptDrugPredictionResult implements PredictionResult {
// // contains drug info
// private AbstractDrugModel drug;
//
// // confidence related to the drug and query
// private double confidence;
//
// // concepts names for the concepts, drug related to
// private LinkedList<String> tags;
//
// // conceptsId of concepts drug realted to
// private HashSet<String> conceptIds;
//
// public ConceptDrugPredictionResult(String drug, double confidence) {
// this.drug = new DrugModel(drug);
// this.confidence = confidence;
// this.conceptIds = new HashSet<String>();
// this.tags = new LinkedList<String>();
// }
//
// public AbstractDrugModel getDrug() {
// return drug;
// }
//
// @Override
// public Object getValue() {
// return drug;
// }
//
// public void setDrug(AbstractDrugModel drug) {
// this.drug = drug;
// }
//
// @Override
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// public LinkedList<String> getTags() {
// return tags;
// }
//
// /*
// * method to add a tag for drug result
// */
// public void addTags(String tag) {
// this.tags.add(tag);
// }
//
// public HashSet<String> getConceptIds() {
// return conceptIds;
// }
//
// /*
// * method to add concept Ids related to the drug result
// */
// public void addConceptId(String conceptId) {
// this.conceptIds.add(conceptId);
// }
//
// public boolean hasConcept(String conceptId) {
// return conceptIds.contains(conceptId);
// }
//
// @Override
// public String toString() {
// return "PredictionResults [drug=" + drug.toString() + ", confidence=" + confidence + "]";
// }
// }
| import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptDrugPredictionResult; | package com.learningmodule.association.conceptdrug.predictionmodule;
/*
* class that fetch the concept name from database interface and add names to tag in results
*/
public class ConceptNameDatabaseOperation {
// method to get the list of tags for each drug result
public static LinkedList<ConceptDrugPredictionResult> getTags(
LinkedList<ConceptDrugPredictionResult> results, | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptDrugPredictionResult.java
// public class ConceptDrugPredictionResult implements PredictionResult {
// // contains drug info
// private AbstractDrugModel drug;
//
// // confidence related to the drug and query
// private double confidence;
//
// // concepts names for the concepts, drug related to
// private LinkedList<String> tags;
//
// // conceptsId of concepts drug realted to
// private HashSet<String> conceptIds;
//
// public ConceptDrugPredictionResult(String drug, double confidence) {
// this.drug = new DrugModel(drug);
// this.confidence = confidence;
// this.conceptIds = new HashSet<String>();
// this.tags = new LinkedList<String>();
// }
//
// public AbstractDrugModel getDrug() {
// return drug;
// }
//
// @Override
// public Object getValue() {
// return drug;
// }
//
// public void setDrug(AbstractDrugModel drug) {
// this.drug = drug;
// }
//
// @Override
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// public LinkedList<String> getTags() {
// return tags;
// }
//
// /*
// * method to add a tag for drug result
// */
// public void addTags(String tag) {
// this.tags.add(tag);
// }
//
// public HashSet<String> getConceptIds() {
// return conceptIds;
// }
//
// /*
// * method to add concept Ids related to the drug result
// */
// public void addConceptId(String conceptId) {
// this.conceptIds.add(conceptId);
// }
//
// public boolean hasConcept(String conceptId) {
// return conceptIds.contains(conceptId);
// }
//
// @Override
// public String toString() {
// return "PredictionResults [drug=" + drug.toString() + ", confidence=" + confidence + "]";
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/predictionmodule/ConceptNameDatabaseOperation.java
import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptDrugPredictionResult;
package com.learningmodule.association.conceptdrug.predictionmodule;
/*
* class that fetch the concept name from database interface and add names to tag in results
*/
public class ConceptNameDatabaseOperation {
// method to get the list of tags for each drug result
public static LinkedList<ConceptDrugPredictionResult> getTags(
LinkedList<ConceptDrugPredictionResult> results, | ConceptDrugDatabaseInterface learningDataInterface) { |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/predictionmodule/ConceptNameDatabaseOperation.java | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptDrugPredictionResult.java
// public class ConceptDrugPredictionResult implements PredictionResult {
// // contains drug info
// private AbstractDrugModel drug;
//
// // confidence related to the drug and query
// private double confidence;
//
// // concepts names for the concepts, drug related to
// private LinkedList<String> tags;
//
// // conceptsId of concepts drug realted to
// private HashSet<String> conceptIds;
//
// public ConceptDrugPredictionResult(String drug, double confidence) {
// this.drug = new DrugModel(drug);
// this.confidence = confidence;
// this.conceptIds = new HashSet<String>();
// this.tags = new LinkedList<String>();
// }
//
// public AbstractDrugModel getDrug() {
// return drug;
// }
//
// @Override
// public Object getValue() {
// return drug;
// }
//
// public void setDrug(AbstractDrugModel drug) {
// this.drug = drug;
// }
//
// @Override
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// public LinkedList<String> getTags() {
// return tags;
// }
//
// /*
// * method to add a tag for drug result
// */
// public void addTags(String tag) {
// this.tags.add(tag);
// }
//
// public HashSet<String> getConceptIds() {
// return conceptIds;
// }
//
// /*
// * method to add concept Ids related to the drug result
// */
// public void addConceptId(String conceptId) {
// this.conceptIds.add(conceptId);
// }
//
// public boolean hasConcept(String conceptId) {
// return conceptIds.contains(conceptId);
// }
//
// @Override
// public String toString() {
// return "PredictionResults [drug=" + drug.toString() + ", confidence=" + confidence + "]";
// }
// }
| import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptDrugPredictionResult; | package com.learningmodule.association.conceptdrug.predictionmodule;
/*
* class that fetch the concept name from database interface and add names to tag in results
*/
public class ConceptNameDatabaseOperation {
// method to get the list of tags for each drug result
public static LinkedList<ConceptDrugPredictionResult> getTags(
LinkedList<ConceptDrugPredictionResult> results,
ConceptDrugDatabaseInterface learningDataInterface) {
// get the list of conceptId and conceptNames from database Interface | // Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptDrugPredictionResult.java
// public class ConceptDrugPredictionResult implements PredictionResult {
// // contains drug info
// private AbstractDrugModel drug;
//
// // confidence related to the drug and query
// private double confidence;
//
// // concepts names for the concepts, drug related to
// private LinkedList<String> tags;
//
// // conceptsId of concepts drug realted to
// private HashSet<String> conceptIds;
//
// public ConceptDrugPredictionResult(String drug, double confidence) {
// this.drug = new DrugModel(drug);
// this.confidence = confidence;
// this.conceptIds = new HashSet<String>();
// this.tags = new LinkedList<String>();
// }
//
// public AbstractDrugModel getDrug() {
// return drug;
// }
//
// @Override
// public Object getValue() {
// return drug;
// }
//
// public void setDrug(AbstractDrugModel drug) {
// this.drug = drug;
// }
//
// @Override
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// public LinkedList<String> getTags() {
// return tags;
// }
//
// /*
// * method to add a tag for drug result
// */
// public void addTags(String tag) {
// this.tags.add(tag);
// }
//
// public HashSet<String> getConceptIds() {
// return conceptIds;
// }
//
// /*
// * method to add concept Ids related to the drug result
// */
// public void addConceptId(String conceptId) {
// this.conceptIds.add(conceptId);
// }
//
// public boolean hasConcept(String conceptId) {
// return conceptIds.contains(conceptId);
// }
//
// @Override
// public String toString() {
// return "PredictionResults [drug=" + drug.toString() + ", confidence=" + confidence + "]";
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/predictionmodule/ConceptNameDatabaseOperation.java
import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptDrugPredictionResult;
package com.learningmodule.association.conceptdrug.predictionmodule;
/*
* class that fetch the concept name from database interface and add names to tag in results
*/
public class ConceptNameDatabaseOperation {
// method to get the list of tags for each drug result
public static LinkedList<ConceptDrugPredictionResult> getTags(
LinkedList<ConceptDrugPredictionResult> results,
ConceptDrugDatabaseInterface learningDataInterface) {
// get the list of conceptId and conceptNames from database Interface | LinkedList<ConceptNameModel> concepts = learningDataInterface |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/learning/PostProcessing.java | // Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
// public class PredictionMatrix implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// // Prediction matrix is a hastable with key as concept_id and value as
// // ConceptRow
// Hashtable<String, ConceptRow> rows;
//
// public PredictionMatrix(int noOfConcepts) {
// rows = new Hashtable<String, ConceptRow>();
// }
//
// /*
// * method to get the list of drugs that are associated with a drugId
// */
// public LinkedList<Cell> getDrugs(String conceptId) {
// // if conceptId is present in the hash table then get the list of drugs
// // related to it
// if (rows.containsKey(conceptId)) {
// return rows.get(conceptId).getDrugs();
// }
// return null;
// }
//
// /*
// * method to get all the concepts which are related to some drug
// */
// public LinkedList<String> getNonEmptyConcepts() {
// Enumeration<String> temp = rows.keys();
// LinkedList<String> result = new LinkedList<String>();
// while (temp.hasMoreElements()) {
// String key = temp.nextElement();
// if (!getDrugs(key).isEmpty()) {
// result.add(key);
// }
// }
// return result;
// }
//
// /*
// * method to add a new cell to Prediction matrix
// */
// public void addCell(String concept, String drug, double conf) {
// // if concept is already present in hast table put a new key value pair
// // with key as this concept
// if (!rows.containsKey(concept)) {
// rows.put(concept, new ConceptRow(concept));
// }
// // add the drug in conceptRow
// rows.get(concept).addCell(drug, conf);
// }
//
// @Override
// public String toString() {
// String result = "";
// int count = 0;
// Enumeration<String> keys = rows.keys();
// while (keys.hasMoreElements()) {
// result = result + rows.get(keys.nextElement()).toString() + "\n";
// count++;
// }
// return result + count;
// }
//
// }
| import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.model.PredictionMatrix;
import weka.associations.ItemSet;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instances; | package com.learningmodule.association.conceptdrug.learning;
/*
* Class for Post Processing of the results from aproiri algorithm
*/
public class PostProcessing {
private static Logger log = Logger.getLogger(PostProcessing.class);
/*
* method to save the rules and instances in files "rules" and "instances"
*/
public static void save(FastVector[] allRules, Instances instances) {
try {
String path = PostProcessing.class.getResource("/").getFile();
System.out.println(path);
FileOutputStream saveFile = new FileOutputStream(path + "files/rules");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(allRules);
save.close();
saveFile = new FileOutputStream(path + "files/instances");
save = new ObjectOutputStream(saveFile);
save.writeObject(instances);
save.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e);
} catch (IOException e) {
e.printStackTrace();
log.error(e);
}
}
/*
* Method to save the final Prediction matrix
*/ | // Path: src/com/learningmodule/association/conceptdrug/model/PredictionMatrix.java
// public class PredictionMatrix implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// // Prediction matrix is a hastable with key as concept_id and value as
// // ConceptRow
// Hashtable<String, ConceptRow> rows;
//
// public PredictionMatrix(int noOfConcepts) {
// rows = new Hashtable<String, ConceptRow>();
// }
//
// /*
// * method to get the list of drugs that are associated with a drugId
// */
// public LinkedList<Cell> getDrugs(String conceptId) {
// // if conceptId is present in the hash table then get the list of drugs
// // related to it
// if (rows.containsKey(conceptId)) {
// return rows.get(conceptId).getDrugs();
// }
// return null;
// }
//
// /*
// * method to get all the concepts which are related to some drug
// */
// public LinkedList<String> getNonEmptyConcepts() {
// Enumeration<String> temp = rows.keys();
// LinkedList<String> result = new LinkedList<String>();
// while (temp.hasMoreElements()) {
// String key = temp.nextElement();
// if (!getDrugs(key).isEmpty()) {
// result.add(key);
// }
// }
// return result;
// }
//
// /*
// * method to add a new cell to Prediction matrix
// */
// public void addCell(String concept, String drug, double conf) {
// // if concept is already present in hast table put a new key value pair
// // with key as this concept
// if (!rows.containsKey(concept)) {
// rows.put(concept, new ConceptRow(concept));
// }
// // add the drug in conceptRow
// rows.get(concept).addCell(drug, conf);
// }
//
// @Override
// public String toString() {
// String result = "";
// int count = 0;
// Enumeration<String> keys = rows.keys();
// while (keys.hasMoreElements()) {
// result = result + rows.get(keys.nextElement()).toString() + "\n";
// count++;
// }
// return result + count;
// }
//
// }
// Path: src/com/learningmodule/association/conceptdrug/learning/PostProcessing.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.model.PredictionMatrix;
import weka.associations.ItemSet;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instances;
package com.learningmodule.association.conceptdrug.learning;
/*
* Class for Post Processing of the results from aproiri algorithm
*/
public class PostProcessing {
private static Logger log = Logger.getLogger(PostProcessing.class);
/*
* method to save the rules and instances in files "rules" and "instances"
*/
public static void save(FastVector[] allRules, Instances instances) {
try {
String path = PostProcessing.class.getResource("/").getFile();
System.out.println(path);
FileOutputStream saveFile = new FileOutputStream(path + "files/rules");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(allRules);
save.close();
saveFile = new FileOutputStream(path + "files/instances");
save = new ObjectOutputStream(saveFile);
save.writeObject(instances);
save.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e);
} catch (IOException e) {
e.printStackTrace();
log.error(e);
}
}
/*
* Method to save the final Prediction matrix
*/ | public static void saveResults(PredictionMatrix matrix, String matrixFileName) { |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java | // Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/multifeature/EncounterIdConceptFeaturesDrugModel.java
// public class EncounterIdConceptFeaturesDrugModel {
//
// // encounter id of medical record
// private int id;
//
// // conceptId(disease/diagnosis)
// private String conceptId;
//
// // drug prescribed
// private String drugId;
//
// // other feature related to record like age, location of patient etc.
// private FeatureValue[] featuresValues;
//
// // number of feature;
// private int noOfFeatures;
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// FeatureValue[] featuresValues) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.featuresValues = featuresValues;
// noOfFeatures = featuresValues.length;
// }
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// int noOfFeatures) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.noOfFeatures = noOfFeatures;
// featuresValues = new FeatureValue[noOfFeatures];
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getDrugId() {
// return drugId;
// }
//
// public void setDrugId(String drugId) {
// this.drugId = drugId;
// }
//
// public FeatureValue[] getFeatures() {
// return featuresValues;
// }
//
// public void setFeatures(FeatureValue[] featuresValues) {
// this.featuresValues = featuresValues;
// }
//
// public int getNoOfFeatures() {
// return noOfFeatures;
// }
//
// @Override
// public String toString() {
// return "EncounterIdConceptFeaturesDrugModel [id=" + id + ", conceptId=" + conceptId
// + ", drugId=" + drugId + ", featuresValues=" + Arrays.toString(featuresValues)
// + ", noOfFeatures=" + noOfFeatures + "]";
// }
// }
| import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.multifeature.EncounterIdConceptFeaturesDrugModel; | package com.learningmodule.association.conceptdrug;
public interface ConceptDrugDatabaseInterface {
/*
* get name of file that will contain the prediction matrix generated by
* algorithm
*/
public String getMatrixFileName();
/*
* Method to get all the medical records containing encounterId(integer that
* represent an id for prescriptions written for a patient),
* ConceptId(integer that represent a diagnosis/diseases/observation for
* patient has been treated), DrugId(integer representing a drug that was
* written in the prescription)
*/ | // Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/multifeature/EncounterIdConceptFeaturesDrugModel.java
// public class EncounterIdConceptFeaturesDrugModel {
//
// // encounter id of medical record
// private int id;
//
// // conceptId(disease/diagnosis)
// private String conceptId;
//
// // drug prescribed
// private String drugId;
//
// // other feature related to record like age, location of patient etc.
// private FeatureValue[] featuresValues;
//
// // number of feature;
// private int noOfFeatures;
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// FeatureValue[] featuresValues) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.featuresValues = featuresValues;
// noOfFeatures = featuresValues.length;
// }
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// int noOfFeatures) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.noOfFeatures = noOfFeatures;
// featuresValues = new FeatureValue[noOfFeatures];
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getDrugId() {
// return drugId;
// }
//
// public void setDrugId(String drugId) {
// this.drugId = drugId;
// }
//
// public FeatureValue[] getFeatures() {
// return featuresValues;
// }
//
// public void setFeatures(FeatureValue[] featuresValues) {
// this.featuresValues = featuresValues;
// }
//
// public int getNoOfFeatures() {
// return noOfFeatures;
// }
//
// @Override
// public String toString() {
// return "EncounterIdConceptFeaturesDrugModel [id=" + id + ", conceptId=" + conceptId
// + ", drugId=" + drugId + ", featuresValues=" + Arrays.toString(featuresValues)
// + ", noOfFeatures=" + noOfFeatures + "]";
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.multifeature.EncounterIdConceptFeaturesDrugModel;
package com.learningmodule.association.conceptdrug;
public interface ConceptDrugDatabaseInterface {
/*
* get name of file that will contain the prediction matrix generated by
* algorithm
*/
public String getMatrixFileName();
/*
* Method to get all the medical records containing encounterId(integer that
* represent an id for prescriptions written for a patient),
* ConceptId(integer that represent a diagnosis/diseases/observation for
* patient has been treated), DrugId(integer representing a drug that was
* written in the prescription)
*/ | public LinkedList<EncounterIdConceptDrug> getData(); |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java | // Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/multifeature/EncounterIdConceptFeaturesDrugModel.java
// public class EncounterIdConceptFeaturesDrugModel {
//
// // encounter id of medical record
// private int id;
//
// // conceptId(disease/diagnosis)
// private String conceptId;
//
// // drug prescribed
// private String drugId;
//
// // other feature related to record like age, location of patient etc.
// private FeatureValue[] featuresValues;
//
// // number of feature;
// private int noOfFeatures;
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// FeatureValue[] featuresValues) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.featuresValues = featuresValues;
// noOfFeatures = featuresValues.length;
// }
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// int noOfFeatures) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.noOfFeatures = noOfFeatures;
// featuresValues = new FeatureValue[noOfFeatures];
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getDrugId() {
// return drugId;
// }
//
// public void setDrugId(String drugId) {
// this.drugId = drugId;
// }
//
// public FeatureValue[] getFeatures() {
// return featuresValues;
// }
//
// public void setFeatures(FeatureValue[] featuresValues) {
// this.featuresValues = featuresValues;
// }
//
// public int getNoOfFeatures() {
// return noOfFeatures;
// }
//
// @Override
// public String toString() {
// return "EncounterIdConceptFeaturesDrugModel [id=" + id + ", conceptId=" + conceptId
// + ", drugId=" + drugId + ", featuresValues=" + Arrays.toString(featuresValues)
// + ", noOfFeatures=" + noOfFeatures + "]";
// }
// }
| import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.multifeature.EncounterIdConceptFeaturesDrugModel; | package com.learningmodule.association.conceptdrug;
public interface ConceptDrugDatabaseInterface {
/*
* get name of file that will contain the prediction matrix generated by
* algorithm
*/
public String getMatrixFileName();
/*
* Method to get all the medical records containing encounterId(integer that
* represent an id for prescriptions written for a patient),
* ConceptId(integer that represent a diagnosis/diseases/observation for
* patient has been treated), DrugId(integer representing a drug that was
* written in the prescription)
*/
public LinkedList<EncounterIdConceptDrug> getData();
/*
* Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
* and feature related to medical records like age of patient, location of doctor/patient etc.
*/
| // Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/multifeature/EncounterIdConceptFeaturesDrugModel.java
// public class EncounterIdConceptFeaturesDrugModel {
//
// // encounter id of medical record
// private int id;
//
// // conceptId(disease/diagnosis)
// private String conceptId;
//
// // drug prescribed
// private String drugId;
//
// // other feature related to record like age, location of patient etc.
// private FeatureValue[] featuresValues;
//
// // number of feature;
// private int noOfFeatures;
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// FeatureValue[] featuresValues) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.featuresValues = featuresValues;
// noOfFeatures = featuresValues.length;
// }
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// int noOfFeatures) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.noOfFeatures = noOfFeatures;
// featuresValues = new FeatureValue[noOfFeatures];
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getDrugId() {
// return drugId;
// }
//
// public void setDrugId(String drugId) {
// this.drugId = drugId;
// }
//
// public FeatureValue[] getFeatures() {
// return featuresValues;
// }
//
// public void setFeatures(FeatureValue[] featuresValues) {
// this.featuresValues = featuresValues;
// }
//
// public int getNoOfFeatures() {
// return noOfFeatures;
// }
//
// @Override
// public String toString() {
// return "EncounterIdConceptFeaturesDrugModel [id=" + id + ", conceptId=" + conceptId
// + ", drugId=" + drugId + ", featuresValues=" + Arrays.toString(featuresValues)
// + ", noOfFeatures=" + noOfFeatures + "]";
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.multifeature.EncounterIdConceptFeaturesDrugModel;
package com.learningmodule.association.conceptdrug;
public interface ConceptDrugDatabaseInterface {
/*
* get name of file that will contain the prediction matrix generated by
* algorithm
*/
public String getMatrixFileName();
/*
* Method to get all the medical records containing encounterId(integer that
* represent an id for prescriptions written for a patient),
* ConceptId(integer that represent a diagnosis/diseases/observation for
* patient has been treated), DrugId(integer representing a drug that was
* written in the prescription)
*/
public LinkedList<EncounterIdConceptDrug> getData();
/*
* Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
* and feature related to medical records like age of patient, location of doctor/patient etc.
*/
| public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids); |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java | // Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/multifeature/EncounterIdConceptFeaturesDrugModel.java
// public class EncounterIdConceptFeaturesDrugModel {
//
// // encounter id of medical record
// private int id;
//
// // conceptId(disease/diagnosis)
// private String conceptId;
//
// // drug prescribed
// private String drugId;
//
// // other feature related to record like age, location of patient etc.
// private FeatureValue[] featuresValues;
//
// // number of feature;
// private int noOfFeatures;
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// FeatureValue[] featuresValues) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.featuresValues = featuresValues;
// noOfFeatures = featuresValues.length;
// }
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// int noOfFeatures) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.noOfFeatures = noOfFeatures;
// featuresValues = new FeatureValue[noOfFeatures];
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getDrugId() {
// return drugId;
// }
//
// public void setDrugId(String drugId) {
// this.drugId = drugId;
// }
//
// public FeatureValue[] getFeatures() {
// return featuresValues;
// }
//
// public void setFeatures(FeatureValue[] featuresValues) {
// this.featuresValues = featuresValues;
// }
//
// public int getNoOfFeatures() {
// return noOfFeatures;
// }
//
// @Override
// public String toString() {
// return "EncounterIdConceptFeaturesDrugModel [id=" + id + ", conceptId=" + conceptId
// + ", drugId=" + drugId + ", featuresValues=" + Arrays.toString(featuresValues)
// + ", noOfFeatures=" + noOfFeatures + "]";
// }
// }
| import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.multifeature.EncounterIdConceptFeaturesDrugModel; | package com.learningmodule.association.conceptdrug;
public interface ConceptDrugDatabaseInterface {
/*
* get name of file that will contain the prediction matrix generated by
* algorithm
*/
public String getMatrixFileName();
/*
* Method to get all the medical records containing encounterId(integer that
* represent an id for prescriptions written for a patient),
* ConceptId(integer that represent a diagnosis/diseases/observation for
* patient has been treated), DrugId(integer representing a drug that was
* written in the prescription)
*/
public LinkedList<EncounterIdConceptDrug> getData();
/*
* Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
* and feature related to medical records like age of patient, location of doctor/patient etc.
*/
public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
/*
* Method to get the list of conceptId and concept_name for given list of conceptId(integer)
*/
| // Path: src/com/learningmodule/association/conceptdrug/model/ConceptNameModel.java
// public class ConceptNameModel {
//
// private String conceptId;
// private String conceptName;
//
// public ConceptNameModel(String conceptId, String conceptName) {
// super();
// this.conceptId = conceptId;
// this.conceptName = conceptName;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getConceptName() {
// return conceptName;
// }
//
// public void setConceptName(String conceptName) {
// this.conceptName = conceptName;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptWordModel.java
// public class ConceptWordModel {
// private String conceptId;
// private String conceptWord;
//
// public ConceptWordModel(String conceptId, String conceptWord) {
// super();
// this.conceptId = conceptId;
// this.conceptWord = conceptWord;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public String getConceptWord() {
// return conceptWord;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/EncounterIdConceptDrug.java
// public class EncounterIdConceptDrug {
// private int id;
// private String drug, conceptId;
//
// public EncounterIdConceptDrug(int id, String drug, String conceptId) {
// super();
// this.id = id;
// this.drug = drug;
// this.conceptId = conceptId;
// }
//
// public int getEncounterId() {
// return id;
// }
// public void setEncounterId(int id) {
// this.id = id;
// }
//
// public String getDrug() {
// return drug;
// }
// public void setDrug(String drug) {
// this.drug = drug;
// }
// public String getConceptId() {
// return conceptId;
// }
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
// }
//
// Path: src/com/learningmodule/association/conceptdrug/multifeature/EncounterIdConceptFeaturesDrugModel.java
// public class EncounterIdConceptFeaturesDrugModel {
//
// // encounter id of medical record
// private int id;
//
// // conceptId(disease/diagnosis)
// private String conceptId;
//
// // drug prescribed
// private String drugId;
//
// // other feature related to record like age, location of patient etc.
// private FeatureValue[] featuresValues;
//
// // number of feature;
// private int noOfFeatures;
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// FeatureValue[] featuresValues) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.featuresValues = featuresValues;
// noOfFeatures = featuresValues.length;
// }
//
// public EncounterIdConceptFeaturesDrugModel(int id, String conceptId, String drugId,
// int noOfFeatures) {
// super();
// this.id = id;
// this.conceptId = conceptId;
// this.drugId = drugId;
// this.noOfFeatures = noOfFeatures;
// featuresValues = new FeatureValue[noOfFeatures];
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getConceptId() {
// return conceptId;
// }
//
// public void setConceptId(String conceptId) {
// this.conceptId = conceptId;
// }
//
// public String getDrugId() {
// return drugId;
// }
//
// public void setDrugId(String drugId) {
// this.drugId = drugId;
// }
//
// public FeatureValue[] getFeatures() {
// return featuresValues;
// }
//
// public void setFeatures(FeatureValue[] featuresValues) {
// this.featuresValues = featuresValues;
// }
//
// public int getNoOfFeatures() {
// return noOfFeatures;
// }
//
// @Override
// public String toString() {
// return "EncounterIdConceptFeaturesDrugModel [id=" + id + ", conceptId=" + conceptId
// + ", drugId=" + drugId + ", featuresValues=" + Arrays.toString(featuresValues)
// + ", noOfFeatures=" + noOfFeatures + "]";
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
import java.util.LinkedList;
import com.learningmodule.association.conceptdrug.model.ConceptNameModel;
import com.learningmodule.association.conceptdrug.model.ConceptWordModel;
import com.learningmodule.association.conceptdrug.model.EncounterIdConceptDrug;
import com.learningmodule.association.conceptdrug.multifeature.EncounterIdConceptFeaturesDrugModel;
package com.learningmodule.association.conceptdrug;
public interface ConceptDrugDatabaseInterface {
/*
* get name of file that will contain the prediction matrix generated by
* algorithm
*/
public String getMatrixFileName();
/*
* Method to get all the medical records containing encounterId(integer that
* represent an id for prescriptions written for a patient),
* ConceptId(integer that represent a diagnosis/diseases/observation for
* patient has been treated), DrugId(integer representing a drug that was
* written in the prescription)
*/
public LinkedList<EncounterIdConceptDrug> getData();
/*
* Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
* and feature related to medical records like age of patient, location of doctor/patient etc.
*/
public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
/*
* Method to get the list of conceptId and concept_name for given list of conceptId(integer)
*/
| public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds); |
Raxa/RaxaMachineLearning | src/com/umls/database/MRXWTableOperation.java | // Path: src/com/umls/models/ConceptWordModel.java
// public class ConceptWordModel {
//
// // ConceptId(CUI)
// private String concept;
//
// // word for concept
// private String word;
//
// public ConceptWordModel(String concept, String word) {
// super();
// this.concept = concept;
// this.word = word;
// }
//
// public String getConcept() {
// return concept;
// }
//
// public void setConcept(String concept) {
// this.concept = concept;
// }
//
// public String getWord() {
// return word;
// }
//
// public void setWord(String word) {
// this.word = word;
// }
// }
| import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import com.umls.models.ConceptWordModel; | package com.umls.database;
/*
* Class that implements the method for Operation on table MRXW_ENG(table with English word and CUI's)
*/
public class MRXWTableOperation {
/*
* method to get the list of CUI's for given query
*/
public static LinkedList<String> searchCUI(String query) {
if (UmlsDatabaseConnector.getConnection() != null) {
try {
Statement stat = UmlsDatabaseConnector.getConnection().createStatement();
// execute the SQL query
ResultSet rs = stat.executeQuery("SELECT MRXW_ENG.CUI FROM umls.MRXW_ENG WHERE"
+ " MRXW_ENG.WD In (" + getWords(query) + ") group by MRXW_ENG.CUI;");
// create a linked list of objects with EncounterId, drugId,
// ConceptId(observation)
LinkedList<String> data = new LinkedList<String>();
while (rs.next()) {
data.add(rs.getString(1));
}
return data;
} catch (SQLException e1) {
e1.printStackTrace();
}
} else
System.out.println("connection lost!");
return null;
}
| // Path: src/com/umls/models/ConceptWordModel.java
// public class ConceptWordModel {
//
// // ConceptId(CUI)
// private String concept;
//
// // word for concept
// private String word;
//
// public ConceptWordModel(String concept, String word) {
// super();
// this.concept = concept;
// this.word = word;
// }
//
// public String getConcept() {
// return concept;
// }
//
// public void setConcept(String concept) {
// this.concept = concept;
// }
//
// public String getWord() {
// return word;
// }
//
// public void setWord(String word) {
// this.word = word;
// }
// }
// Path: src/com/umls/database/MRXWTableOperation.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import com.umls.models.ConceptWordModel;
package com.umls.database;
/*
* Class that implements the method for Operation on table MRXW_ENG(table with English word and CUI's)
*/
public class MRXWTableOperation {
/*
* method to get the list of CUI's for given query
*/
public static LinkedList<String> searchCUI(String query) {
if (UmlsDatabaseConnector.getConnection() != null) {
try {
Statement stat = UmlsDatabaseConnector.getConnection().createStatement();
// execute the SQL query
ResultSet rs = stat.executeQuery("SELECT MRXW_ENG.CUI FROM umls.MRXW_ENG WHERE"
+ " MRXW_ENG.WD In (" + getWords(query) + ") group by MRXW_ENG.CUI;");
// create a linked list of objects with EncounterId, drugId,
// ConceptId(observation)
LinkedList<String> data = new LinkedList<String>();
while (rs.next()) {
data.add(rs.getString(1));
}
return data;
} catch (SQLException e1) {
e1.printStackTrace();
}
} else
System.out.println("connection lost!");
return null;
}
| public static LinkedList<ConceptWordModel> getWordsByLimit(int start, int size) { |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/predictionmodule/DrugTableOperation.java | // Path: src/com/learningmodule/association/conceptdrug/AbstractDrugModel.java
// public interface AbstractDrugModel {
//
// /*
// * set the Drug Id for this drug
// */
// public void setDrugId(String id);
//
// /*
// * get the drug Id for this drug
// */
// public String getDrugId();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/PredictionResult.java
// public interface PredictionResult {
// public double getConfidence();
// public Object getValue();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptDrugPredictionResult.java
// public class ConceptDrugPredictionResult implements PredictionResult {
// // contains drug info
// private AbstractDrugModel drug;
//
// // confidence related to the drug and query
// private double confidence;
//
// // concepts names for the concepts, drug related to
// private LinkedList<String> tags;
//
// // conceptsId of concepts drug realted to
// private HashSet<String> conceptIds;
//
// public ConceptDrugPredictionResult(String drug, double confidence) {
// this.drug = new DrugModel(drug);
// this.confidence = confidence;
// this.conceptIds = new HashSet<String>();
// this.tags = new LinkedList<String>();
// }
//
// public AbstractDrugModel getDrug() {
// return drug;
// }
//
// @Override
// public Object getValue() {
// return drug;
// }
//
// public void setDrug(AbstractDrugModel drug) {
// this.drug = drug;
// }
//
// @Override
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// public LinkedList<String> getTags() {
// return tags;
// }
//
// /*
// * method to add a tag for drug result
// */
// public void addTags(String tag) {
// this.tags.add(tag);
// }
//
// public HashSet<String> getConceptIds() {
// return conceptIds;
// }
//
// /*
// * method to add concept Ids related to the drug result
// */
// public void addConceptId(String conceptId) {
// this.conceptIds.add(conceptId);
// }
//
// public boolean hasConcept(String conceptId) {
// return conceptIds.contains(conceptId);
// }
//
// @Override
// public String toString() {
// return "PredictionResults [drug=" + drug.toString() + ", confidence=" + confidence + "]";
// }
// }
| import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.AbstractDrugModel;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.PredictionResult;
import com.learningmodule.association.conceptdrug.model.ConceptDrugPredictionResult; | package com.learningmodule.association.conceptdrug.predictionmodule;
/*
* class to fetch the drug data from database and add drug info in results
*/
public class DrugTableOperation {
private static Logger log = Logger.getLogger(DrugTableOperation.class);
// method to get the list of Drugs details from database of given drugIDs | // Path: src/com/learningmodule/association/conceptdrug/AbstractDrugModel.java
// public interface AbstractDrugModel {
//
// /*
// * set the Drug Id for this drug
// */
// public void setDrugId(String id);
//
// /*
// * get the drug Id for this drug
// */
// public String getDrugId();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/PredictionResult.java
// public interface PredictionResult {
// public double getConfidence();
// public Object getValue();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptDrugPredictionResult.java
// public class ConceptDrugPredictionResult implements PredictionResult {
// // contains drug info
// private AbstractDrugModel drug;
//
// // confidence related to the drug and query
// private double confidence;
//
// // concepts names for the concepts, drug related to
// private LinkedList<String> tags;
//
// // conceptsId of concepts drug realted to
// private HashSet<String> conceptIds;
//
// public ConceptDrugPredictionResult(String drug, double confidence) {
// this.drug = new DrugModel(drug);
// this.confidence = confidence;
// this.conceptIds = new HashSet<String>();
// this.tags = new LinkedList<String>();
// }
//
// public AbstractDrugModel getDrug() {
// return drug;
// }
//
// @Override
// public Object getValue() {
// return drug;
// }
//
// public void setDrug(AbstractDrugModel drug) {
// this.drug = drug;
// }
//
// @Override
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// public LinkedList<String> getTags() {
// return tags;
// }
//
// /*
// * method to add a tag for drug result
// */
// public void addTags(String tag) {
// this.tags.add(tag);
// }
//
// public HashSet<String> getConceptIds() {
// return conceptIds;
// }
//
// /*
// * method to add concept Ids related to the drug result
// */
// public void addConceptId(String conceptId) {
// this.conceptIds.add(conceptId);
// }
//
// public boolean hasConcept(String conceptId) {
// return conceptIds.contains(conceptId);
// }
//
// @Override
// public String toString() {
// return "PredictionResults [drug=" + drug.toString() + ", confidence=" + confidence + "]";
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/predictionmodule/DrugTableOperation.java
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.AbstractDrugModel;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.PredictionResult;
import com.learningmodule.association.conceptdrug.model.ConceptDrugPredictionResult;
package com.learningmodule.association.conceptdrug.predictionmodule;
/*
* class to fetch the drug data from database and add drug info in results
*/
public class DrugTableOperation {
private static Logger log = Logger.getLogger(DrugTableOperation.class);
// method to get the list of Drugs details from database of given drugIDs | public static LinkedList<PredictionResult> addDrugInfo( |
Raxa/RaxaMachineLearning | src/com/learningmodule/association/conceptdrug/predictionmodule/DrugTableOperation.java | // Path: src/com/learningmodule/association/conceptdrug/AbstractDrugModel.java
// public interface AbstractDrugModel {
//
// /*
// * set the Drug Id for this drug
// */
// public void setDrugId(String id);
//
// /*
// * get the drug Id for this drug
// */
// public String getDrugId();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/PredictionResult.java
// public interface PredictionResult {
// public double getConfidence();
// public Object getValue();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptDrugPredictionResult.java
// public class ConceptDrugPredictionResult implements PredictionResult {
// // contains drug info
// private AbstractDrugModel drug;
//
// // confidence related to the drug and query
// private double confidence;
//
// // concepts names for the concepts, drug related to
// private LinkedList<String> tags;
//
// // conceptsId of concepts drug realted to
// private HashSet<String> conceptIds;
//
// public ConceptDrugPredictionResult(String drug, double confidence) {
// this.drug = new DrugModel(drug);
// this.confidence = confidence;
// this.conceptIds = new HashSet<String>();
// this.tags = new LinkedList<String>();
// }
//
// public AbstractDrugModel getDrug() {
// return drug;
// }
//
// @Override
// public Object getValue() {
// return drug;
// }
//
// public void setDrug(AbstractDrugModel drug) {
// this.drug = drug;
// }
//
// @Override
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// public LinkedList<String> getTags() {
// return tags;
// }
//
// /*
// * method to add a tag for drug result
// */
// public void addTags(String tag) {
// this.tags.add(tag);
// }
//
// public HashSet<String> getConceptIds() {
// return conceptIds;
// }
//
// /*
// * method to add concept Ids related to the drug result
// */
// public void addConceptId(String conceptId) {
// this.conceptIds.add(conceptId);
// }
//
// public boolean hasConcept(String conceptId) {
// return conceptIds.contains(conceptId);
// }
//
// @Override
// public String toString() {
// return "PredictionResults [drug=" + drug.toString() + ", confidence=" + confidence + "]";
// }
// }
| import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.AbstractDrugModel;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.PredictionResult;
import com.learningmodule.association.conceptdrug.model.ConceptDrugPredictionResult; | package com.learningmodule.association.conceptdrug.predictionmodule;
/*
* class to fetch the drug data from database and add drug info in results
*/
public class DrugTableOperation {
private static Logger log = Logger.getLogger(DrugTableOperation.class);
// method to get the list of Drugs details from database of given drugIDs
public static LinkedList<PredictionResult> addDrugInfo( | // Path: src/com/learningmodule/association/conceptdrug/AbstractDrugModel.java
// public interface AbstractDrugModel {
//
// /*
// * set the Drug Id for this drug
// */
// public void setDrugId(String id);
//
// /*
// * get the drug Id for this drug
// */
// public String getDrugId();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/ConceptDrugDatabaseInterface.java
// public interface ConceptDrugDatabaseInterface {
//
// /*
// * get name of file that will contain the prediction matrix generated by
// * algorithm
// */
// public String getMatrixFileName();
//
// /*
// * Method to get all the medical records containing encounterId(integer that
// * represent an id for prescriptions written for a patient),
// * ConceptId(integer that represent a diagnosis/diseases/observation for
// * patient has been treated), DrugId(integer representing a drug that was
// * written in the prescription)
// */
// public LinkedList<EncounterIdConceptDrug> getData();
//
// /*
// * Method to get the medical records with given list of concepts Ids contaning encounterId, conceptId, DrugId,
// * and feature related to medical records like age of patient, location of doctor/patient etc.
// */
//
// public LinkedList<EncounterIdConceptFeaturesDrugModel> getDataByConceptIds(LinkedList<String> ids);
//
// /*
// * Method to get the list of conceptId and concept_name for given list of conceptId(integer)
// */
//
// public LinkedList<ConceptNameModel> getConceptIdNameByConceptIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of Drugs for given drugIds(integers)
// */
// public LinkedList<AbstractDrugModel> getDrugInfoByDrugIds(LinkedList<String> conceptIds);
//
// /*
// * Method to get the list of all conceptId and concept_words
// */
// public LinkedList<ConceptWordModel> getConceptWords();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/PredictionResult.java
// public interface PredictionResult {
// public double getConfidence();
// public Object getValue();
// }
//
// Path: src/com/learningmodule/association/conceptdrug/model/ConceptDrugPredictionResult.java
// public class ConceptDrugPredictionResult implements PredictionResult {
// // contains drug info
// private AbstractDrugModel drug;
//
// // confidence related to the drug and query
// private double confidence;
//
// // concepts names for the concepts, drug related to
// private LinkedList<String> tags;
//
// // conceptsId of concepts drug realted to
// private HashSet<String> conceptIds;
//
// public ConceptDrugPredictionResult(String drug, double confidence) {
// this.drug = new DrugModel(drug);
// this.confidence = confidence;
// this.conceptIds = new HashSet<String>();
// this.tags = new LinkedList<String>();
// }
//
// public AbstractDrugModel getDrug() {
// return drug;
// }
//
// @Override
// public Object getValue() {
// return drug;
// }
//
// public void setDrug(AbstractDrugModel drug) {
// this.drug = drug;
// }
//
// @Override
// public double getConfidence() {
// return confidence;
// }
//
// public void setConfidence(double confidence) {
// this.confidence = confidence;
// }
//
// public LinkedList<String> getTags() {
// return tags;
// }
//
// /*
// * method to add a tag for drug result
// */
// public void addTags(String tag) {
// this.tags.add(tag);
// }
//
// public HashSet<String> getConceptIds() {
// return conceptIds;
// }
//
// /*
// * method to add concept Ids related to the drug result
// */
// public void addConceptId(String conceptId) {
// this.conceptIds.add(conceptId);
// }
//
// public boolean hasConcept(String conceptId) {
// return conceptIds.contains(conceptId);
// }
//
// @Override
// public String toString() {
// return "PredictionResults [drug=" + drug.toString() + ", confidence=" + confidence + "]";
// }
// }
// Path: src/com/learningmodule/association/conceptdrug/predictionmodule/DrugTableOperation.java
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.learningmodule.association.conceptdrug.AbstractDrugModel;
import com.learningmodule.association.conceptdrug.ConceptDrugDatabaseInterface;
import com.learningmodule.association.conceptdrug.PredictionResult;
import com.learningmodule.association.conceptdrug.model.ConceptDrugPredictionResult;
package com.learningmodule.association.conceptdrug.predictionmodule;
/*
* class to fetch the drug data from database and add drug info in results
*/
public class DrugTableOperation {
private static Logger log = Logger.getLogger(DrugTableOperation.class);
// method to get the list of Drugs details from database of given drugIDs
public static LinkedList<PredictionResult> addDrugInfo( | LinkedList<ConceptDrugPredictionResult> drugs, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.