answer
stringlengths 17
10.2M
|
|---|
package com.jetbrains.python.inspections;
import com.intellij.codeInspection.LocalInspectionToolSession;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.SuppressIntentionAction;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.inspections.quickfix.DocstringQuickFix;
import com.jetbrains.python.inspections.quickfix.PySuppressInspectionFix;
import com.jetbrains.python.documentation.EpydocString;
import com.jetbrains.python.documentation.PyDocumentationSettings;
import com.jetbrains.python.documentation.SphinxDocString;
import com.jetbrains.python.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Alexey.Ivanov
*/
public class PyDocstringInspection extends PyInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return PyBundle.message("INSP.NAME.docstring");
}
@Override
public boolean isEnabledByDefault() {
return false;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder,
boolean isOnTheFly,
@NotNull LocalInspectionToolSession session) {
return new Visitor(holder, session);
}
public static class Visitor extends PyInspectionVisitor {
public Visitor(@Nullable ProblemsHolder holder, @NotNull LocalInspectionToolSession session) {
super(holder, session);
}
@Override
public void visitPyFile(PyFile node) {
checkDocString(node);
}
@Override
public void visitPyFunction(PyFunction node) {
final String name = node.getName();
if (name != null && !name.startsWith("_")) checkDocString(node);
}
@Override
public void visitPyClass(PyClass node) {
final String name = node.getName();
if (name != null && !name.startsWith("_")) checkDocString(node);
}
private void checkDocString(PyDocStringOwner node) {
final PyStringLiteralExpression docStringExpression = node.getDocStringExpression();
if (docStringExpression == null) {
PsiElement marker = null;
if (node instanceof PyClass) {
final ASTNode n = ((PyClass)node).getNameNode();
if (n != null) marker = n.getPsi();
}
else if (node instanceof PyFunction) {
final ASTNode n = ((PyFunction)node).getNameNode();
if (n != null) marker = n.getPsi();
}
else if (node instanceof PyFile) {
TextRange tr = new TextRange(0, 0);
ProblemsHolder holder = getHolder();
if (holder != null) {
holder.registerProblem(node, tr, PyBundle.message("INSP.no.docstring"));
}
return;
}
if (marker == null) marker = node;
if (node instanceof PyFunction || (node instanceof PyClass && ((PyClass)node).findInitOrNew(false) != null)) {
registerProblem(marker, PyBundle.message("INSP.no.docstring"), new DocstringQuickFix(null, null));
}
else {
registerProblem(marker, PyBundle.message("INSP.no.docstring"));
}
}
else {
boolean registered = checkParameters(node, docStringExpression);
if (!registered && StringUtil.isEmptyOrSpaces(docStringExpression.getStringValue())) {
registerProblem(docStringExpression, PyBundle.message("INSP.empty.docstring"));
}
}
}
private boolean checkParameters(PyDocStringOwner pyDocStringOwner, PyStringLiteralExpression node) {
final String text = node.getText();
if (text == null) {
return false;
}
List<String> docstringParams = getDocstringParams(node, text);
if (docstringParams == null) {
return false;
}
if (pyDocStringOwner instanceof PyFunction) {
PyDecoratorList decoratorList = ((PyFunction)pyDocStringOwner).getDecoratorList();
boolean isClassMethod = false;
if (decoratorList != null) {
isClassMethod = decoratorList.findDecorator(PyNames.CLASSMETHOD) != null;
}
PyParameter[] realParams = ((PyFunction)pyDocStringOwner).getParameterList().getParameters();
List<PyParameter> missingParams = getMissingParams(realParams, docstringParams, isClassMethod);
boolean registered = false;
if (!missingParams.isEmpty()) {
for (PyParameter param : missingParams) {
registerProblem(param, "Missing parameter " + param.getName() + " in docstring",
new DocstringQuickFix(param, null));
}
registered = true;
}
List<String> unexpectedParams = getUnexpectedParams(docstringParams, realParams, node);
if (!unexpectedParams.isEmpty()) {
for (String param : unexpectedParams) {
ProblemsHolder holder = getHolder();
int index = text.indexOf("param " + param + ":") + 6;
if (holder != null) {
holder.registerProblem(node, TextRange.create(index, index + param.length()),
"Unexpected parameter " + param + " in docstring",
new DocstringQuickFix(null, param));
}
}
registered = true;
}
return registered;
}
return false;
}
private List<String> getUnexpectedParams(List<String> docstringParams, PyParameter[] realParams, PyStringLiteralExpression node) {
for (PyParameter p : realParams) {
if (docstringParams.contains(p.getName())) {
docstringParams.remove(p.getName());
}
}
return docstringParams;
}
private List<PyParameter> getMissingParams(PyParameter[] realParams, List<String> docstringParams, boolean isClassMethod) {
List<PyParameter> missing = new ArrayList<PyParameter>();
boolean hasMissing = false;
for (PyParameter p : realParams) {
if ((!isClassMethod && !p.getText().equals(PyNames.CANONICAL_SELF)) ||
(isClassMethod && !p.getText().equals("cls"))) {
if (!docstringParams.contains(p.getName())) {
hasMissing = true;
missing.add(p);
}
}
}
return hasMissing ? missing : Collections.<PyParameter>emptyList();
}
}
private static List<String> getDocstringParams(PyStringLiteralExpression node,
String text) {
PyDocumentationSettings documentationSettings = PyDocumentationSettings.getInstance(node.getProject());
List<String> docstringParams = null;
if (documentationSettings.isEpydocFormat(node.getContainingFile())) {
docstringParams = new EpydocString(text).getParameters();
}
else if (documentationSettings.isReSTFormat(node.getContainingFile())) {
docstringParams = new SphinxDocString(text).getParameters();
}
return docstringParams;
}
@Override
public SuppressIntentionAction[] getSuppressActions(@Nullable PsiElement element) {
List<SuppressIntentionAction> result = new ArrayList<SuppressIntentionAction>();
if (element != null) {
if (PsiTreeUtil.getParentOfType(element, PyFunction.class) != null) {
result.add(new PySuppressInspectionFix(getShortName().replace("Inspection", ""), "Suppress for function", PyFunction.class));
}
if (PsiTreeUtil.getParentOfType(element, PyClass.class) != null) {
result.add(new PySuppressInspectionFix(getShortName().replace("Inspection", ""), "Suppress for class", PyClass.class));
}
}
return result.toArray(new SuppressIntentionAction[result.size()]);
}
}
|
package org.rakam.analysis.webhook;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClient;
import com.amazonaws.services.cloudwatch.model.MetricDatum;
import com.amazonaws.services.cloudwatch.model.PutMetricDataRequest;
import com.fasterxml.jackson.core.JsonGenerator;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.airlift.log.Logger;
import io.airlift.slice.DynamicSliceOutput;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.cookie.Cookie;
import okhttp3.*;
import org.rakam.aws.AWSConfig;
import org.rakam.collection.Event;
import org.rakam.collection.EventList;
import org.rakam.collection.FieldType;
import org.rakam.collection.SchemaField;
import org.rakam.plugin.EventMapper;
import org.rakam.util.JsonHelper;
import javax.inject.Inject;
import java.io.DataOutput;
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.SECONDS;
public class WebhookEventMapper implements EventMapper {
private final static Logger LOGGER = Logger.get(WebhookEventMapper.class);
private final OkHttpClient asyncHttpClient;
private final static int TIMEOUT_IN_MILLIS = 10000;
private final Queue<Event> queue = new ConcurrentLinkedQueue<>();
private final DynamicSliceOutput slice;
private final AtomicInteger counter;
private final AmazonCloudWatchAsyncClient cloudWatchClient;
@Inject
public WebhookEventMapper(WebhookConfig config, AWSConfig awsConfig) {
this.asyncHttpClient = new OkHttpClient.Builder()
.connectTimeout(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS)
.readTimeout(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS)
.writeTimeout(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS)
.build();
slice = new DynamicSliceOutput(100);
counter = new AtomicInteger();
cloudWatchClient = new AmazonCloudWatchAsyncClient(awsConfig.getCredentials());
cloudWatchClient.setRegion(awsConfig.getAWSRegion());
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder().setNameFormat("collection-webhook").build());
service.scheduleAtFixedRate(() -> {
try {
int size = counter.get();
if (size == 0) {
return;
}
JsonGenerator generator = JsonHelper.getMapper().getFactory().createGenerator((DataOutput) slice);
generator.writeStartObject();
generator.writeFieldName("activities");
generator.writeStartArray();
int i = 0;
for (; i < size; i++) {
Event event = queue.poll();
if (event == null) {
break;
}
generator.writeStartObject();
generator.writeFieldName("collection");
generator.writeString(event.collection());
List<SchemaField> fields = event.schema();
for (SchemaField field : fields) {
generator.writeFieldName("properties." + field.getName());
Object value = event.getAttribute(field.getName());
if (value == null) {
generator.writeNull();
} else {
write(field.getType(), generator, value);
}
}
generator.writeEndObject();
}
generator.writeEndArray();
generator.writeEndObject();
generator.flush();
MediaType mediaType = MediaType.parse("application/json");
Request.Builder builder = new Request.Builder().url(config.getUrl());
if (config.getHeaders() != null) {
for (Map.Entry<String, String> entry : config.getHeaders().entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
byte[] base = (byte[]) slice.getUnderlyingSlice().getBase();
RequestBody body = RequestBody.create(mediaType, base, 0, slice.size());
Request build = builder.post(body).build();
tryOperation(build, 2, i);
counter.addAndGet(-i);
} catch (Throwable e) {
LOGGER.error(e, "Error while sending request to webhook");
slice.reset();
}
}, 5, 5, SECONDS);
}
private void write(FieldType type, JsonGenerator generator, Object value) throws IOException {
switch (type) {
case STRING:
case BOOLEAN:
case LONG:
case INTEGER:
case DECIMAL:
case DOUBLE:
case TIMESTAMP:
case TIME:
case DATE:
generator.writeString(value.toString());
break;
default:
if (type.isMap()) {
generator.writeNull();
} else if (type.isArray()) {
generator.writeStartArray();
for (Object item : ((List) value)) {
generator.writeString(item.toString());
}
generator.writeEndArray();
} else {
throw new IllegalStateException(format("type %s is not supported.", type));
}
}
}
private void tryOperation(Request build, int retryCount, int numberOfRecords) throws IOException {
Response execute = null;
try {
execute = asyncHttpClient.newCall(build).execute();
if (execute.code() != 200) {
if (retryCount > 0) {
tryOperation(build, retryCount - 1, numberOfRecords);
return;
}
cloudWatchClient.putMetricDataAsync(new PutMetricDataRequest()
.withNamespace("rakam-webhook")
.withMetricData(new MetricDatum()
.withMetricName("request-error")
.withValue(Double.valueOf(numberOfRecords))));
LOGGER.error(new RuntimeException(execute.body().string()), "Unable to execute Webhook request");
} else {
cloudWatchClient.putMetricDataAsync(new PutMetricDataRequest()
.withNamespace("rakam-webhook")
.withMetricData(new MetricDatum()
.withMetricName("request-success")
.withValue(Double.valueOf(numberOfRecords))));
cloudWatchClient.putMetricDataAsync(new PutMetricDataRequest()
.withNamespace("rakam-webhook")
.withMetricData(new MetricDatum()
.withMetricName("request-latency")
.withValue(Double.valueOf(execute.receivedResponseAtMillis() - execute.sentRequestAtMillis()))));
}
} catch (Throwable e) {
if (retryCount > 0) {
tryOperation(build, retryCount - 1, numberOfRecords);
} else {
cloudWatchClient.putMetricDataAsync(new PutMetricDataRequest()
.withNamespace("rakam-webhook")
.withMetricData(new MetricDatum()
.withMetricName("request-error")
.withValue(Double.valueOf(numberOfRecords))));
LOGGER.error(e, "Unable to execute Webhook request");
}
} finally {
if (execute != null) {
execute.close();
}
slice.reset();
}
}
@Override
public CompletableFuture<List<Cookie>> mapAsync(Event event, RequestParams requestParams, InetAddress sourceAddress, HttpHeaders responseHeaders) {
queue.add(event);
counter.incrementAndGet();
return COMPLETED_EMPTY_FUTURE;
}
@Override
public CompletableFuture<List<Cookie>> mapAsync(EventList events, RequestParams requestParams, InetAddress sourceAddress, HttpHeaders responseHeaders) {
queue.addAll(events.events);
counter.addAndGet(events.events.size());
return COMPLETED_EMPTY_FUTURE;
}
}
|
package com.sandflow.smpte.regxml;
import com.sandflow.smpte.klv.Group;
import com.sandflow.smpte.klv.KLVInputStream.ByteOrder;
import com.sandflow.smpte.klv.Triplet;
import com.sandflow.smpte.klv.exceptions.KLVException;
import com.sandflow.smpte.mxf.MXFInputStream;
import com.sandflow.smpte.mxf.Set;
import com.sandflow.smpte.regxml.dict.DefinitionResolver;
import com.sandflow.smpte.regxml.dict.definitions.CharacterTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.ClassDefinition;
import com.sandflow.smpte.regxml.dict.definitions.Definition;
import com.sandflow.smpte.regxml.dict.definitions.EnumerationTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.ExtendibleEnumerationTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.FixedArrayTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.FloatTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.IndirectTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.IntegerTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.LensSerialFloatTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.OpaqueTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.PropertyAliasDefinition;
import com.sandflow.smpte.regxml.dict.definitions.PropertyDefinition;
import com.sandflow.smpte.regxml.dict.definitions.RecordTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.RenameTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.SetTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.StreamTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.StringTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.StrongReferenceTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.VariableArrayTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.WeakReferenceTypeDefinition;
import com.sandflow.smpte.util.AUID;
import com.sandflow.smpte.util.HalfFloat;
import com.sandflow.smpte.util.IDAU;
import com.sandflow.smpte.util.UL;
import com.sandflow.smpte.util.UMID;
import com.sandflow.smpte.util.UUID;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Builds a RegXML Fragment of a single KLV Group, typically a Header Metadata
* MXF Set, using a collection of MetaDictionary definitions
*/
public class FragmentBuilder {
private final static Logger LOG = Logger.getLogger(FragmentBuilder.class.getName());
private static final UL INSTANCE_UID_ITEM_UL = UL.fromURN("urn:smpte:ul:060e2b34.01010101.01011502.00000000");
private static final UL AUID_UL = UL.fromDotValue("06.0E.2B.34.01.04.01.01.01.03.01.00.00.00.00.00");
private static final UL UUID_UL = UL.fromDotValue("06.0E.2B.34.01.04.01.01.01.03.03.00.00.00.00.00");
private static final UL DateStruct_UL = UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.05.00.00.00.00.00");
private static final UL PackageID_UL = UL.fromDotValue("06.0E.2B.34.01.04.01.01.01.03.02.00.00.00.00.00");
private static final UL Rational_UL = UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.01.00.00.00.00.00");
private static final UL TimeStruct_UL = UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.06.00.00.00.00.00");
private static final UL TimeStamp_UL = UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.07.00.00.00.00.00");
private static final UL VersionType_UL = UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.03.00.00.00.00.00");
private static final UL ByteOrder_UL = UL.fromDotValue("06.0E.2B.34.01.01.01.01.03.01.02.01.02.00.00.00");
private static final UL Character_UL = UL.fromURN("urn:smpte:ul:060e2b34.01040101.01100100.00000000");
private static final UL Char_UL = UL.fromURN("urn:smpte:ul:060e2b34.01040101.01100300.00000000");
private static final UL UTF8Character_UL = UL.fromURN("urn:smpte:ul:060e2b34.01040101.01100500.00000000");
private static final UL ProductReleaseType_UL = UL.fromURN("urn:smpte:ul:060e2b34.01040101.02010101.00000000");
private static final UL Boolean_UL = UL.fromURN("urn:smpte:ul:060e2b34.01040101.01040100.00000000");
private static final UL PrimaryPackage_UL = UL.fromURN("urn:smpte:ul:060e2b34.01010104.06010104.01080000");
private static final UL LinkedGenerationID_UL = UL.fromURN("urn:smpte:ul:060e2b34.01010102.05200701.08000000");
private static final UL GenerationID_UL = UL.fromURN("urn:smpte:ul:060e2b34.01010102.05200701.01000000");
private static final UL ApplicationProductID_UL = UL.fromURN("urn:smpte:ul:060e2b34.01010102.05200701.07000000");
private static final String REGXML_NS = "http://sandflow.com/ns/SMPTEST2001-1/baseline";
private final static String XMLNS_NS = "http:
private static final String BYTEORDER_BE = "BigEndian";
private static final String BYTEORDER_LE = "LittleEndian";
private static final String UID_ATTR = "uid";
private static final String ACTUALTYPE_ATTR = "actualType";
private final DefinitionResolver defresolver;
private final Map<UUID, Set> setresolver;
private final HashMap<URI, String> nsprefixes = new HashMap<>();
/**
* Instantiates a FragmentBuilder
*
* @param defresolver Map between Group Keys and MetaDictionary definitions
* @param setresolver Allows Strong References to be resolved
*/
public FragmentBuilder(DefinitionResolver defresolver, Map<UUID, Set> setresolver) {
this.defresolver = defresolver;
this.setresolver = setresolver;
}
/**
* Creates a RegXML Fragment, represented an XML DOM Document Fragment
*
* @param group KLV Group for which the Fragment will be generated.
* @param document Document from which the XML DOM Document Fragment will be
* created.
* @return XML DOM Document Fragment containing a single RegXML Fragment
* @throws ParserConfigurationException
* @throws KLVException
* @throws com.sandflow.smpte.regxml.FragmentBuilder.RuleException
*/
public DocumentFragment fromTriplet(Group group, Document document) throws ParserConfigurationException, KLVException, RuleException {
DocumentFragment df = document.createDocumentFragment();
applyRule3(df, group);
/* NOTE: Hack to clean-up namespace prefixes */
for (Map.Entry<URI, String> entry : nsprefixes.entrySet()) {
((Element) df.getFirstChild()).setAttributeNS(XMLNS_NS, "xmlns:" + entry.getValue(), entry.getKey().toString());
}
return df;
}
private String getPrefix(URI ns) {
String prefix = this.nsprefixes.get(ns);
/* if prefix does not exist, create one */
if (prefix == null) {
prefix = "r" + this.nsprefixes.size();
this.nsprefixes.put(ns, prefix);
}
return prefix;
}
private String getPrefix(String ns) {
try {
return getPrefix(new URI(ns));
} catch (URISyntaxException ex) {
throw new RuntimeException(ex);
}
}
void applyRule3(Node node, Group group) throws RuleException {
Definition definition = defresolver.getDefinition(new AUID(group.getKey()));
if (definition == null) {
LOG.info(
String.format(
"Unknown Group UL = %s",
group.getKey().toString()
)
);
return;
}
if (definition.getIdentification().asUL().getVersion() != group.getKey().getVersion()) {
LOG.warning(
String.format(
"Group UL %s in file does not have the same version as in the register (0x%02x)",
group.getKey(),
definition.getIdentification().asUL().getVersion()
)
);
}
Element objelem = node.getOwnerDocument().createElementNS(definition.getNamespace().toString(), definition.getSymbol());
node.appendChild(objelem);
objelem.setPrefix(getPrefix(definition.getNamespace()));
for (Triplet item : group.getItems()) {
/* skip if the property is not defined in the registers */
Definition itemdef = defresolver.getDefinition(new AUID(item.getKey()));
if (itemdef == null) {
LOG.info(
String.format(
"Unknown property UL = %s at group %s",
item.getKey().toString(),
definition.getSymbol()
)
);
objelem.appendChild(
objelem.getOwnerDocument().createComment(
String.format(
"Unknown property\nKey: %s\nData: %s",
item.getKey().toString(),
bytesToString(item.getValue())
)
)
);
continue;
}
/* make sure this is a property definition */
if (!(itemdef instanceof PropertyDefinition)) {
LOG.warning(
String.format(
"Item UL = %s at group %s is not a property",
item.getKey().toString(),
definition.getSymbol()
)
);
objelem.appendChild(
objelem.getOwnerDocument().createComment(
String.format(
"Item UL = %s is not a property",
item.getKey().toString()
)
)
);
continue;
}
/* warn if version byte of the property does not match the register version byte */
if (itemdef.getIdentification().asUL().getVersion() != item.getKey().getVersion()) {
LOG.warning(
String.format(
"Property UL %s in file does not have the same version as in the register (0x%02x)",
item.getKey().toString(),
itemdef.getIdentification().asUL().getVersion()
)
);
}
Element elem = node.getOwnerDocument().createElementNS(itemdef.getNamespace().toString(), itemdef.getSymbol());
objelem.appendChild(elem);
elem.setPrefix(getPrefix(itemdef.getNamespace()));
/* write the property */
applyRule4(elem, new MXFInputStream(item.getValueAsStream()), itemdef);
/* detect cyclic references */
if (item.getKey().equals(INSTANCE_UID_ITEM_UL)) {
String iidns = objelem.getLastChild().getNamespaceURI();
String iidname = objelem.getLastChild().getLocalName();
String iid = objelem.getLastChild().getTextContent();
/* look for identical instanceID in parent elements */
Node parent = node;
while (parent.getNodeType() == Node.ELEMENT_NODE) {
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeType() == Node.ELEMENT_NODE
&& iidname.equals(n.getLocalName())
&& iidns.equals(n.getNamespaceURI())
&& iid.equals(n.getTextContent())) {
LOG.warning(
String.format(
"Self-referencing Strong Reference at Group %s with UID %s",
definition.getSymbol(),
iid
)
);
Comment comment = node.getOwnerDocument().createComment(
String.format(
"Strong Reference %s not found",
iid
)
);
node.appendChild(comment);
return;
}
}
parent = parent.getParentNode();
}
}
/* add reg:uid if property is a unique ID */
if (((PropertyDefinition) itemdef).isUniqueIdentifier()) {
Attr attr = node.getOwnerDocument().createAttributeNS(REGXML_NS, UID_ATTR);
attr.setPrefix(getPrefix(REGXML_NS));
attr.setTextContent(objelem.getLastChild().getTextContent());
objelem.setAttributeNodeNS(attr);
}
}
}
void applyRule4(Element element, MXFInputStream value, Definition propdef) throws RuleException {
try {
if (propdef.getIdentification().equals(ByteOrder_UL)) {
int byteorder;
byteorder = value.readUnsignedShort();
/* ISSUE: ST 2001-1 inverses these constants */
if (byteorder == 0x4D4D) {
element.setTextContent(BYTEORDER_BE);
} else if (byteorder == 0x4949) {
element.setTextContent(BYTEORDER_LE);
LOG.warning("ByteOrder property set to little-endian: either the property is set incorrectly"
+ "or the file does not conform to MXF. Processing assumes a big-endian byte order.");
element.appendChild(
element.getOwnerDocument().createComment(
String.format("ByteOrder property set to little-endian: either the property is set incorrectly"
+ "or the file does not conform to MXF. Processing assumes a big-endian byte order.")
)
);
} else {
throw new RuleException("Unknown ByteOrder value.");
}
} else {
if (propdef instanceof PropertyAliasDefinition) {
propdef = defresolver.getDefinition(((PropertyAliasDefinition) propdef).getOriginalProperty());
}
Definition typedef = findBaseDefinition(defresolver.getDefinition(((PropertyDefinition) propdef).getType()));
if (typedef == null) {
throw new RuleException(
String.format(
"Type %s not found at %s.",
((PropertyDefinition) propdef).getType().toString(),
propdef.getSymbol()
)
);
}
if (propdef.getIdentification().equals(PrimaryPackage_UL)) {
/* EXCEPTION: PrimaryPackage is encoded as the Instance UUID of the target set
but needs to be the UMID contained in the unique ID of the target set */
UUID uuid = value.readUUID();
/* is this a local reference through Instance ID? */
Group g = setresolver.get(uuid);
if (g != null) {
boolean foundUniqueID = false;
/* find the unique identifier in the group */
for (Triplet item : g.getItems()) {
Definition itemdef = defresolver.getDefinition(new AUID(item.getKey()));
if (itemdef != null
&& itemdef instanceof PropertyDefinition
&& ((PropertyDefinition) itemdef).isUniqueIdentifier()) {
applyRule4(element, new MXFInputStream(item.getValueAsStream()), itemdef);
foundUniqueID = true;
break;
}
}
if (foundUniqueID != true) {
LOG.warning(
String.format(
"Target Primary Package with Instance UID %s has no IsUnique element.",
uuid.toString()
)
);
element.appendChild(
element.getOwnerDocument().createComment(
String.format(
"Target Primary Package with Instance UID %s has no IsUnique element.",
uuid.toString()
)
)
);
}
} else {
LOG.warning(
String.format(
"Target Primary Package with Instance UID %s not found.",
uuid.toString()
)
);
element.appendChild(
element.getOwnerDocument().createComment(
String.format(
"Target Primary Package with Instance UID %s not found.",
uuid.toString()
)
)
);
}
} else {
if (propdef.getIdentification().equals(LinkedGenerationID_UL)
|| propdef.getIdentification().equals(GenerationID_UL)
|| propdef.getIdentification().equals(ApplicationProductID_UL)) {
/* EXCEPTION: LinkedGenerationID, GenerationID and ApplicationProductID
are encoded using UUID */
typedef = defresolver.getDefinition(new AUID(UUID_UL));
}
applyRule5(element, value, typedef);
}
}
} catch (EOFException eof) {
LOG.warning(
String.format(
"Value too short for element %s",
propdef.getSymbol()
)
);
Comment comment = element.getOwnerDocument().createComment(
String.format(
"Value too short for element %s",
propdef.getSymbol()
)
);
element.appendChild(comment);
} catch (IOException ioe) {
throw new RuleException(ioe);
}
}
void applyRule5(Element element, MXFInputStream value, Definition definition) throws RuleException, IOException {
if (definition instanceof CharacterTypeDefinition) {
applyRule5_1(element, value, (CharacterTypeDefinition) definition);
} else if (definition instanceof EnumerationTypeDefinition) {
applyRule5_2(element, value, (EnumerationTypeDefinition) definition);
} else if (definition instanceof ExtendibleEnumerationTypeDefinition) {
applyRule5_3(element, value, (ExtendibleEnumerationTypeDefinition) definition);
} else if (definition instanceof FixedArrayTypeDefinition) {
applyRule5_4(element, value, (FixedArrayTypeDefinition) definition);
} else if (definition instanceof IndirectTypeDefinition) {
applyRule5_5(element, value, (IndirectTypeDefinition) definition);
} else if (definition instanceof IntegerTypeDefinition) {
applyRule5_6(element, value, (IntegerTypeDefinition) definition);
} else if (definition instanceof OpaqueTypeDefinition) {
applyRule5_7(element, value, (OpaqueTypeDefinition) definition);
} else if (definition instanceof RecordTypeDefinition) {
applyRule5_8(element, value, (RecordTypeDefinition) definition);
} else if (definition instanceof RenameTypeDefinition) {
applyRule5_9(element, value, (RenameTypeDefinition) definition);
} else if (definition instanceof SetTypeDefinition) {
applyRule5_10(element, value, (SetTypeDefinition) definition);
} else if (definition instanceof StreamTypeDefinition) {
applyRule5_11(element, value, (StreamTypeDefinition) definition);
} else if (definition instanceof StringTypeDefinition) {
applyRule5_12(element, value, (StringTypeDefinition) definition);
} else if (definition instanceof StrongReferenceTypeDefinition) {
applyRule5_13(element, value, (StrongReferenceTypeDefinition) definition);
} else if (definition instanceof VariableArrayTypeDefinition) {
applyRule5_14(element, value, (VariableArrayTypeDefinition) definition);
} else if (definition instanceof WeakReferenceTypeDefinition) {
applyRule5_15(element, value, (WeakReferenceTypeDefinition) definition);
} else if (definition instanceof FloatTypeDefinition) {
applyRule5_alpha(element, value, (FloatTypeDefinition) definition);
} else if (definition instanceof LensSerialFloatTypeDefinition) {
applyRule5_beta(element, value, (LensSerialFloatTypeDefinition) definition);
} else {
throw new RuleException(
String.format(
"Illegal Definition %s in Rule 5.",
definition.getClass().toString()
)
);
}
}
private void readCharacters(InputStream value, CharacterTypeDefinition definition, StringBuilder sb) throws RuleException, IOException {
Reader in = null;
if (definition.getIdentification().equals(Character_UL)) {
in = new InputStreamReader(value, "UTF-16BE");
} else if (definition.getIdentification().equals(Char_UL)) {
in = new InputStreamReader(value, "US-ASCII");
} else if (definition.getIdentification().equals(UTF8Character_UL)) {
/* NOTE: Use of UTF-8 character encoding is specified in RP 2057 */
in = new InputStreamReader(value, "UTF-8");
} else {
throw new RuleException(
String.format("Character type %s not supported",
definition.getIdentification().toString()
)
);
}
char[] chars = new char[32];
for (int c; (c = in.read(chars)) != -1;) {
sb.append(chars, 0, c);
}
}
void applyRule5_1(Element element, MXFInputStream value, CharacterTypeDefinition definition) throws RuleException, IOException {
StringBuilder sb = new StringBuilder();
readCharacters(value, definition, sb);
element.setTextContent(sb.toString());
}
void applyRule5_2(Element element, MXFInputStream value, EnumerationTypeDefinition definition) throws RuleException, IOException {
try {
Definition bdef = findBaseDefinition(defresolver.getDefinition(definition.getElementType()));
if (!(bdef instanceof IntegerTypeDefinition)) {
throw new RuleException(
String.format("Enum %s does not have an Integer base type.",
definition.getIdentification().toString()
));
}
IntegerTypeDefinition idef = (IntegerTypeDefinition) bdef;
int len = 0;
if (definition.getIdentification().equals(ProductReleaseType_UL)) {
/* EXCEPTION: ProductReleaseType_UL is listed as
a UInt8 enum but encoded as a UInt16 */
len = 2;
} else {
switch (idef.getSize()) {
case ONE:
len = 1;
break;
case TWO:
len = 2;
break;
case FOUR:
len = 4;
break;
case EIGHT:
len = 8;
break;
}
}
byte[] val = new byte[len];
int br = value.read(val);
String str = null;
if (br == 0) {
str = "ERROR";
LOG.warning(
String.format(
"No data at Enumeration %s.",
definition.getIdentification()
)
);
} else {
if (br != len) {
LOG.warning(
String.format(
"Incorrect field legnth for Enumeration %s: expected %d and parsed %d.",
definition.getIdentification(),
len,
br
)
);
}
/* still try to read the value even if the length is not as expected */
BigInteger bi = idef.isSigned() ? new BigInteger(val) : new BigInteger(1, val);
if (definition.getElementType().equals(Boolean_UL)) {
/* find the "true" enum element */
/* MXF can encode "true" as any value other than 0 */
for (EnumerationTypeDefinition.Element e : definition.getElements()) {
if ((bi.intValue() == 0 && e.getValue() == 0) || (bi.intValue() != 0 && e.getValue() == 1)) {
str = e.getName();
}
}
} else {
for (EnumerationTypeDefinition.Element e : definition.getElements()) {
if (e.getValue() == bi.intValue()) {
str = e.getName();
}
}
}
if (str == null) {
str = "UNDEFINED";
LOG.warning(
String.format(
"Undefined value %d for Enumeration %s.",
bi.intValue(),
definition.getIdentification()
)
);
}
}
element.setTextContent(str);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
void applyRule5_3(Element element, MXFInputStream value, ExtendibleEnumerationTypeDefinition definition) throws RuleException, IOException {
try {
UL ul = value.readUL();
/* NOTE: ST 2001-1 XML Schema does not allow ULs as values for Extendible Enumerations, which
defeats the purpose of the type. This issue could be addressed at the next revision opportunity. */
element.setTextContent(ul.toString());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
void applyRule5_4(Element element, MXFInputStream value, FixedArrayTypeDefinition definition) throws RuleException, IOException {
if (definition.getIdentification().equals(UUID_UL)) {
UUID uuid = value.readUUID();
element.setTextContent(uuid.toString());
} else {
Definition typedef = findBaseDefinition(defresolver.getDefinition(definition.getElementType()));
applyCoreRule5_4(element, value, typedef, definition.getElementCount());
}
}
void applyCoreRule5_4(Element element, MXFInputStream value, Definition typedef, int elementcount) throws RuleException, IOException {
for (int i = 0; i < elementcount; i++) {
if (typedef instanceof StrongReferenceTypeDefinition) {
/* Rule 5.4.1 */
applyRule5_13(element, value, (StrongReferenceTypeDefinition) typedef);
} else {
/* Rule 5.4.2 */
Element elem = element.getOwnerDocument().createElementNS(typedef.getNamespace().toString(), typedef.getSymbol());
elem.setPrefix(getPrefix(typedef.getNamespace()));
applyRule5(elem, value, typedef);
element.appendChild(elem);
}
}
}
void applyRule5_5(Element element, MXFInputStream value, IndirectTypeDefinition definition) throws RuleException, IOException {
ByteOrder bo;
switch (value.readUnsignedByte()) {
case 0x4c /* little endian */:
bo = ByteOrder.LITTLE_ENDIAN;
break;
case 0x42 /* big endian */:
bo = ByteOrder.BIG_ENDIAN;
break;
default:
throw new RuleException("Unknown Indirect Byte Order value.");
}
IDAU idau = value.readIDAU();
if (idau == null) {
throw new RuleException("Invalid IDAU");
}
AUID auid = idau.asAUID();
Definition def = (Definition) defresolver.getDefinition(auid);
if (def == null) {
LOG.warning(
String.format(
"No definition found for indirect type with AUID %s.",
idau.toString()
)
);
element.appendChild(
element.getOwnerDocument().createComment(
String.format(
"No definition found for indirect type with AUID %s.",
idau.toString()
))
);
return;
}
// create reg:actualType attribute
Attr attr = element.getOwnerDocument().createAttributeNS(REGXML_NS, ACTUALTYPE_ATTR);
attr.setPrefix(getPrefix(REGXML_NS));
attr.setTextContent(def.getSymbol());
element.setAttributeNodeNS(attr);
MXFInputStream orderedval = new MXFInputStream(value, bo);
applyRule5(element, orderedval, def);
}
void applyRule5_6(Element element, MXFInputStream value, IntegerTypeDefinition definition) throws RuleException, IOException {
try {
int len = 0;
switch (definition.getSize()) {
case ONE:
len = 1;
break;
case TWO:
len = 2;
break;
case FOUR:
len = 4;
break;
case EIGHT:
len = 8;
break;
}
byte[] val = new byte[len];
int br = value.read(val);
if (br == 0) {
LOG.warning(
String.format(
"No data at Integer %s.",
definition.getIdentification()
)
);
element.setTextContent("NaN");
} else {
if (br != len) {
LOG.warning(
String.format(
"Incorrect field legnth for Integer %s: expected %d and parsed %d.",
definition.getIdentification(),
len,
br
)
);
}
BigInteger bi = definition.isSigned() ? new BigInteger(val) : new BigInteger(1, val);
element.setTextContent(bi.toString());
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
void applyRule5_7(Element element, MXFInputStream value, OpaqueTypeDefinition definition) throws RuleException {
/* NOTE: Opaque Types are not used in MXF */
throw new RuleException("Opaque types are not supported.");
}
String generateISO8601Time(int hour, int minutes, int seconds, int millis) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%02d:%02d:%02d", hour, minutes, seconds));
if (millis != 0) {
sb.append(String.format(".%03d", millis));
}
sb.append("Z");
return sb.toString();
}
String generateISO8601Date(int year, int month, int day) {
return String.format("%04d-%02d-%02d", year, month, day);
}
void applyRule5_8(Element element, MXFInputStream value, RecordTypeDefinition definition) throws RuleException, IOException {
if (definition.getIdentification().equals(AUID_UL)) {
AUID auid = value.readAUID();
element.setTextContent(auid.toString());
} else if (definition.getIdentification().equals(DateStruct_UL)) {
int year = value.readUnsignedShort();
int month = value.readUnsignedByte();
int day = value.readUnsignedByte();
element.setTextContent(generateISO8601Date(year, month, day));
} else if (definition.getIdentification().equals(PackageID_UL)) {
UMID umid = value.readUMID();
element.setTextContent(umid.toString());
} else if (definition.getIdentification().equals(Rational_UL)) {
int numerator = value.readInt();
int denominator = value.readInt();
element.setTextContent(String.format("%d/%d", numerator, denominator));
} else if (definition.getIdentification().equals(TimeStruct_UL)) {
/*INFO: ST 2001-1 and ST 377-1 diverge on the meaning of 'fraction'.
fraction is msec/4 according to 377-1 */
int hour = value.readUnsignedByte();
int minute = value.readUnsignedByte();
int second = value.readUnsignedByte();
int fraction = value.readUnsignedByte();
element.setTextContent(generateISO8601Time(hour, minute, second, 4 * fraction));
} else if (definition.getIdentification().equals(TimeStamp_UL)) {
int year = value.readUnsignedShort();
int month = value.readUnsignedByte();
int day = value.readUnsignedByte();
int hour = value.readUnsignedByte();
int minute = value.readUnsignedByte();
int second = value.readUnsignedByte();
int fraction = value.readUnsignedByte();
element.setTextContent(generateISO8601Date(year, month, day) + "T" + generateISO8601Time(hour, minute, second, 4 * fraction));
} else if (definition.getIdentification().equals(VersionType_UL)) {
/* EXCEPTION: registers used Int8 but MXF specifies UInt8 */
int major = value.readUnsignedByte();
int minor = value.readUnsignedByte();
element.setTextContent(String.format("%d.%d", major, minor));
} else {
for (RecordTypeDefinition.Member member : definition.getMembers()) {
Definition itemdef = findBaseDefinition(defresolver.getDefinition(member.getType()));
Element elem = element.getOwnerDocument().createElementNS(definition.getNamespace().toString(), member.getName());
elem.setPrefix(getPrefix(definition.getNamespace()));
applyRule5(elem, value, itemdef);
element.appendChild(elem);
}
}
}
void applyRule5_9(Element element, MXFInputStream value, RenameTypeDefinition definition) throws RuleException, IOException {
Definition rdef = defresolver.getDefinition(definition.getRenamedType());
applyRule5(element, value, rdef);
}
void applyRule5_10(Element element, MXFInputStream value, SetTypeDefinition definition) throws RuleException, IOException {
Definition typedef = findBaseDefinition(defresolver.getDefinition(definition.getElementType()));
try {
DataInputStream dis = new DataInputStream(value);
long itemcount = dis.readInt() & 0xfffffffL;
long itemlength = dis.readInt() & 0xfffffffL;
applyCoreRule5_4(element, value, typedef, (int) itemcount);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
void applyRule5_11(Element element, MXFInputStream value, StreamTypeDefinition definition) throws RuleException {
throw new RuleException("Rule 5.11 is not supported yet.");
}
void applyRule5_12(Element element, MXFInputStream value, StringTypeDefinition definition) throws RuleException, IOException {
/* Rule 5.12 */
Definition chrdef = findBaseDefinition(defresolver.getDefinition(definition.getElementType()));
/* NOTE: ST 2001-1 implies that integer-based strings are supported, but
does not described semantics.
*/
if (!(chrdef instanceof CharacterTypeDefinition)) {
throw new RuleException(
String.format(
"String type %s does not have a Character Type as element.",
definition.getIdentification().toString()
)
);
}
StringBuilder sb = new StringBuilder();
readCharacters(value, (CharacterTypeDefinition) chrdef, sb);
/* remove trailing zeroes if any */
int nullpos = sb.indexOf("\0");
if (nullpos > -1) {
sb.setLength(nullpos);
}
element.setTextContent(sb.toString());
}
void applyRule5_13(Element element, MXFInputStream value, StrongReferenceTypeDefinition definition) throws RuleException, IOException {
Definition typedef = findBaseDefinition(defresolver.getDefinition(definition.getReferenceType()));
if (!(typedef instanceof ClassDefinition)) {
throw new RuleException("Rule 5.13 applied to non class.");
}
UUID uuid = value.readUUID();
Group g = setresolver.get(uuid);
if (g != null) {
applyRule3(element, g);
} else {
LOG.warning(
String.format(
"Strong Reference %s not found at %s",
uuid.toString(),
definition.getSymbol()
)
);
Comment comment = element.getOwnerDocument().createComment(
String.format(
"Strong Reference %s not found",
uuid.toString()
)
);
element.appendChild(comment);
}
}
void applyRule5_alpha(Element element, MXFInputStream value, FloatTypeDefinition definition) throws RuleException, IOException {
try {
DataInputStream dis = new DataInputStream(value);
double val = 0;
switch (definition.getSize()) {
case HALF:
val = HalfFloat.toDouble(dis.readUnsignedShort());
break;
case SINGLE:
val = dis.readFloat();
break;
case DOUBLE:
val = dis.readDouble();
break;
}
element.setTextContent(Double.toString(val));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
void applyRule5_beta(Element element, MXFInputStream value, LensSerialFloatTypeDefinition definition) throws RuleException {
throw new RuleException("Lens serial floats not supported.");
}
Definition findBaseDefinition(Definition definition) {
while (definition instanceof RenameTypeDefinition) {
definition = defresolver.getDefinition(((RenameTypeDefinition) definition).getRenamedType());
}
return definition;
}
public Collection<PropertyDefinition> getAllMembersOf(ClassDefinition definition) {
ClassDefinition cdef = definition;
ArrayList<PropertyDefinition> props = new ArrayList<>();
while (cdef != null) {
for (AUID auid : defresolver.getMembersOf(cdef)) {
props.add((PropertyDefinition) defresolver.getDefinition(auid));
}
if (cdef.getParentClass() != null) {
cdef = (ClassDefinition) defresolver.getDefinition(cdef.getParentClass());
} else {
cdef = null;
}
}
return props;
}
final static char[] HEXMAP = "0123456789abcdef".toCharArray();
private String bytesToString(byte[] buffer) {
char[] out = new char[2 * buffer.length];
for (int j = 0; j < buffer.length; j++) {
int v = buffer[j] & 0xFF;
out[j * 2] = HEXMAP[v >>> 4];
out[j * 2 + 1] = HEXMAP[v & 0x0F];
}
return new String(out);
}
void applyRule5_14(Element element, MXFInputStream value, VariableArrayTypeDefinition definition) throws RuleException, IOException {
Definition typedef = findBaseDefinition(defresolver.getDefinition(definition.getElementType()));
try {
DataInputStream dis = new DataInputStream(value);
if (definition.getSymbol().equals("DataValue")) {
/* RULE 5.14.2 */
/* DataValue is string of octets, without number of elements or size of elements */
byte[] buffer = new byte[32];
StringBuilder sb = new StringBuilder();
for (int sz = 0; (sz = dis.read(buffer)) > -1;) {
for (int j = 0; j < sz; j++) {
int v = buffer[j] & 0xFF;
sb.append(HEXMAP[v >>> 4]);
sb.append(HEXMAP[v & 0x0F]);
}
}
element.setTextContent(sb.toString());
} else {
Definition base = findBaseDefinition(typedef);
if (base instanceof CharacterTypeDefinition || base.getName().contains("StringArray")) {
/* RULE 5.14.1 */
/* INFO: StringArray is not used in MXF (ST 377-1) */
throw new RuleException("StringArray not supported.");
} else {
long itemcount = dis.readInt() & 0xfffffffL;
long itemlength = dis.readInt() & 0xfffffffL;
applyCoreRule5_4(element, value, typedef, (int) itemcount);
}
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (EOFException eof) {
Comment comment = element.getOwnerDocument().createComment(
String.format(
"Value too short for Type %s",
typedef.getSymbol()
)
);
element.appendChild(comment);
}
}
void applyRule5_15(Element element, MXFInputStream value, WeakReferenceTypeDefinition typedefinition) throws RuleException {
ClassDefinition classdef = (ClassDefinition) defresolver.getDefinition(typedefinition.getReferencedType());
PropertyDefinition uniquepropdef = null;
for (PropertyDefinition propdef : getAllMembersOf(classdef)) {
if (propdef.isUniqueIdentifier()) {
uniquepropdef = propdef;
break;
}
}
if (uniquepropdef == null) {
throw new RuleException(
String.format("Underlying class of weak reference type %s does not have a unique identifier.",
typedefinition.getIdentification().toString())
);
}
applyRule4(element, value, uniquepropdef);
}
public static class RuleException extends Exception {
public RuleException(Throwable t) {
super(t);
}
public RuleException(String msg) {
super(msg);
}
public RuleException(String msg, Throwable t) {
super(msg, t);
}
}
}
|
package ai.subut.kurjun.repo;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.ws.rs.core.Response;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.http.HTTPConduit;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import ai.subut.kurjun.common.service.KurjunConstants;
import ai.subut.kurjun.common.service.KurjunContext;
import ai.subut.kurjun.common.utils.InetUtils;
import ai.subut.kurjun.metadata.common.raw.RawMetadata;
import ai.subut.kurjun.metadata.common.utils.MetadataUtils;
import ai.subut.kurjun.model.annotation.Nullable;
import ai.subut.kurjun.model.identity.User;
import ai.subut.kurjun.model.index.ReleaseFile;
import ai.subut.kurjun.model.metadata.Metadata;
import ai.subut.kurjun.model.metadata.SerializableMetadata;
import ai.subut.kurjun.repo.cache.PackageCache;
import ai.subut.kurjun.repo.util.http.WebClientFactory;
public class RemoteRawRepository extends RemoteRepositoryBase
{
private static final Logger LOGGER = LoggerFactory.getLogger( RemoteRawRepository.class );
static final String INFO_PATH = "info";
static final String GET_PATH = "get";
static final String LIST_PATH = "list";
private final String MD5_PATH = "md5";
private final String FILE_PATH = "/file/";
private WebClientFactory webClientFactory;
@Inject
private Gson gson;
private PackageCache cache;
private final URL url;
private final User identity;
private String md5Sum = "";
private List<SerializableMetadata> remoteIndexChache;
private static final int CONN_TIMEOUT = 3000;
private static final int READ_TIMEOUT = 3000;
private static final int CONN_TIMEOUT_FOR_URL_CHECK = 200;
@Inject
public RemoteRawRepository( PackageCache cache, WebClientFactory webClientFactory, @Assisted( "url" ) String url,
@Assisted @Nullable User identity )
{
this.webClientFactory = webClientFactory;
this.cache = cache;
this.identity = identity;
try
{
this.url = new URL( url );
}
catch ( MalformedURLException ex )
{
throw new IllegalArgumentException( "Invalid url", ex );
}
_initCache();
}
private void _initCache()
{
this.remoteIndexChache = listPackages();
this.md5Sum = getMd5();
}
@Override
public SerializableMetadata getPackageInfo( Metadata metadata )
{
WebClient webClient =
webClientFactory.make( this, FILE_PATH + INFO_PATH, MetadataUtils.makeParamsMap( metadata ) );
if ( identity != null )
{
webClient.header( KurjunConstants.HTTP_HEADER_FINGERPRINT, identity.getKeyFingerprint() );
}
Response resp = doGet( webClient );
if ( resp != null && resp.getStatus() == Response.Status.OK.getStatusCode() )
{
if ( resp.getEntity() instanceof InputStream )
{
try
{
String json = IOUtils.toString( ( InputStream ) resp.getEntity() );
return gson.fromJson( json, RawMetadata.class );
}
catch ( IOException ex )
{
LOGGER.error( "Failed to read response data", ex );
}
}
}
return null;
}
@Override
public InputStream getPackageStream( Metadata metadata )
{
InputStream cachedStream = checkCache( metadata );
if ( cachedStream != null )
{
return cachedStream;
}
WebClient webClient =
webClientFactory.make( this, FILE_PATH + GET_PATH, MetadataUtils.makeParamsMap( metadata ) );
if ( identity != null )
{
webClient.header( KurjunConstants.HTTP_HEADER_FINGERPRINT, identity.getKeyFingerprint() );
}
Response resp = doGet( webClient );
if ( resp != null && resp.getStatus() == Response.Status.OK.getStatusCode() )
{
if ( resp.getEntity() instanceof InputStream )
{
InputStream inputStream = ( InputStream ) resp.getEntity();
byte[] md5Calculated = cacheStream( inputStream );
// compare the requested and received md5 checksums
if ( Arrays.equals( metadata.getMd5Sum(), md5Calculated ) )
{
return cache.get( md5Calculated );
}
else
{
deleteCache( md5Calculated );
LOGGER.error( "Md5 checksum mismatch after getting the package from remote host. "
+ "Requested with md5={}, name={}", Hex.toHexString( metadata.getMd5Sum() ),
metadata.getName() );
}
}
}
return null;
}
@Override
public List<SerializableMetadata> listPackages()
{
if ( this.md5Sum.equalsIgnoreCase( getMd5() ) )
{
return this.remoteIndexChache;
}
WebClient webClient = webClientFactory.make( this, FILE_PATH + LIST_PATH, null );
if ( identity != null )
{
webClient.header( KurjunConstants.HTTP_HEADER_FINGERPRINT, identity.getKeyFingerprint() );
}
Response resp = doGet( webClient );
if ( resp != null && resp.getStatus() == Response.Status.OK.getStatusCode() )
{
if ( resp.getEntity() instanceof InputStream )
{
try
{
List<String> items = IOUtils.readLines( ( InputStream ) resp.getEntity() );
return toObjectList( items.get( 0 ) );
}
catch ( IOException ex )
{
LOGGER.error( "Failed to read packages list", ex );
}
}
}
return Collections.emptyList();
}
@Override
protected Logger getLogger()
{
return LOGGER;
}
@Override
public String getMd5()
{
WebClient webClient = webClientFactory.make( this, FILE_PATH + MD5_PATH, null );
Response resp = doGet( webClient );
if ( resp != null && resp.getStatus() == Response.Status.OK.getStatusCode() )
{
if ( resp.getEntity() instanceof InputStream )
{
try
{
List<String> items = IOUtils.readLines( ( InputStream ) resp.getEntity() );
if ( items.size() > 0 )
{
return items.get( 0 );
}
}
catch ( IOException ex )
{
LOGGER.error( "Failed to read packages list", ex );
}
}
}
return "";
}
@Override
public List<SerializableMetadata> getCachedData()
{
return this.remoteIndexChache;
}
@Override
public User getIdentity()
{
return identity;
}
@Override
public URL getUrl()
{
return url;
}
@Override
public boolean isKurjun()
{
return true;
}
@Override
public Set<ReleaseFile> getDistributions()
{
throw new UnsupportedOperationException( "Not supported in raw repositories." );
}
private List<SerializableMetadata> parseItems( String items )
{
Type collectionType = new TypeToken<LinkedList<RawMetadata>>()
{
}.getType();
return gson.fromJson( items, collectionType );
}
private Response doGet( WebClient webClient )
{
try
{
URI remote = webClient.getCurrentURI();
if ( InetUtils.isHostReachable( remote.getHost(), remote.getPort(), CONN_TIMEOUT_FOR_URL_CHECK ) )
{
HTTPConduit httpConduit = ( HTTPConduit ) WebClient.getConfig( webClient ).getConduit();
httpConduit.getClient().setConnectionTimeout( CONN_TIMEOUT );
httpConduit.getClient().setReceiveTimeout( READ_TIMEOUT );
return webClient.get();
}
else
{
LOGGER.warn( "Remote host is not reachable {}:{}", remote.getHost(), remote.getPort() );
}
}
catch ( Exception e )
{
LOGGER.warn( "Failed to do GET.", e );
}
return null;
}
private SerializableMetadata toObject( String items )
{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
try
{
return objectMapper.readValue( items, RawMetadata.class );
}
catch ( IOException e )
{
e.printStackTrace();
}
return null;
}
private List<SerializableMetadata> toObjectList( String items )
{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
try
{
return objectMapper.readValue( items, new TypeReference<List<RawMetadata>>()
{
} );
}
catch ( IOException e )
{
e.printStackTrace();
}
return null;
}
@Override
public KurjunContext getContext()
{
return null;
}
}
|
package sampler.supervised.regression;
import cc.mallet.util.Randoms;
import core.AbstractExperiment;
import core.AbstractSampler;
import data.ResponseTextDataset;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import optimization.GurobiMLRL2Norm;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import regression.Regressor;
import sampler.RLDA;
import sampler.RecursiveLDA;
import sampling.likelihood.CascadeDirMult.PathAssumption;
import sampling.likelihood.DirMult;
import sampling.util.FullTable;
import sampling.util.Restaurant;
import sampling.util.SparseCount;
import sampling.util.TopicTreeNode;
import util.CLIUtils;
import util.IOUtils;
import util.MiscUtils;
import util.PredictionUtils;
import util.RankingItem;
import util.SamplerUtils;
import util.StatisticsUtils;
import util.evaluation.Measurement;
import util.evaluation.MimnoTopicCoherence;
import util.evaluation.RegressionEvaluation;
/**
*
* @author vietan
*/
public class SHLDA extends AbstractSampler
implements Regressor<ResponseTextDataset> {
public static Randoms randoms = new Randoms(1123581321);
public static final String LEXICAL_REG_OVERTIME = "lexical-weights-overtime.txt";
private static final STable NULL_TABLE = null;
public static final int STAY = 0;
public static final int PASS = 1;
public static final Double WEIGHT_THRESHOLD = 10e-2;
public static final int PSEUDO_TABLE_INDEX = -1;
public static final int PSEUDO_NODE_INDEX = -1;
// hyperparameter indices
public static final int ALPHA = 0;
public static final int RHO = 1; // response variable variance
public static final int TAU_MEAN = 2; // lexical regression parameter mean
public static final int TAU_SIGMA = 3; // lexical regression parameter variance
// hyperparameters
protected double[] betas; // topics concentration parameter
protected double[] gammas;
protected double[] mus; // regression parameter means
protected double[] sigmas; // regression parameter variances
protected double[] pis; // level distribution parameter
// input data
protected String[][] rawSentences;
protected int[][][] words; // [D] x [S_d] x [N_ds]: words
protected int[][] docWords;
protected double[] responses; // [D]: response variables of each author
protected int L; // level of hierarchies
protected int V; // vocabulary size
protected int D; // number of documents
// input statistics
protected int sentCount;
protected int tokenCount;
// pre-computed hyperparameters
protected double logAlpha;
protected double sqrtRho;
protected double[] sqrtSigmas;
protected double[] logGammas;
protected PathAssumption pathAssumption;
// latent variables
private DirMult[] docLevelDist;
private STable[][] c; // path assigned to sentences
private int[][][] z; // level assigned to tokens
private double[] lexParams;
private double[][] lexDesignMatrix;
// state structure
private SNode globalTreeRoot; // tree
private Restaurant<STable, Integer, SNode>[] localRestaurants; // franchise
// for regression
protected double[] docValues;
protected int[][][] sentLevelCounts;
// auxiliary
protected double[] uniform;
protected int numSentAsntsChange;
protected int numTableAsgnsChange;
protected ArrayList<String> authorVocab;
protected int[] initBranchFactor = new int[]{16, 3};
private int numAccepts;
private int numProposes;
private String seededAssignmentFile;
public void setInitialBranchingFactor(int[] bf) {
this.initBranchFactor = bf;
}
public void setResponses(double[] responses) {
this.responses = responses;
}
public void setRawSentences(String[][] rawSents) {
this.rawSentences = rawSents;
}
public void setAuthorVocab(ArrayList<String> authorVoc) {
this.authorVocab = authorVoc;
}
public File getIterationPredictionFolder() {
return new File(getSamplerFolderPath(), IterPredictionFolder);
}
public void configure(SHLDA sampler) {
this.configure(sampler.folder, sampler.V, sampler.L,
sampler.hyperparams.get(ALPHA),
sampler.hyperparams.get(RHO),
sampler.hyperparams.get(TAU_MEAN),
sampler.hyperparams.get(TAU_SIGMA),
sampler.betas,
sampler.gammas,
sampler.mus,
sampler.sigmas,
sampler.pis,
sampler.initBranchFactor,
sampler.initState,
sampler.pathAssumption,
sampler.paramOptimized,
sampler.BURN_IN,
sampler.MAX_ITER,
sampler.LAG,
sampler.REP_INTERVAL);
}
public void configure(String folder,
int V, int L,
double alpha,
double rho,
double tau_mean,
double tau_scale,
double[] betas,
double[] gammas,
double[] mus,
double[] sigmas,
double[] pis,
int[] initBranchFactor,
InitialState initState,
PathAssumption pathAssumption,
boolean paramOpt,
int burnin, int maxiter, int samplelag, int repInt) {
if (verbose) {
logln("Configuring ...");
}
this.folder = folder;
this.V = V;
this.L = L;
this.betas = betas;
this.gammas = gammas;
this.mus = mus;
this.sigmas = sigmas;
this.pis = pis;
this.hyperparams = new ArrayList<Double>();
this.hyperparams.add(alpha);
this.hyperparams.add(rho);
this.hyperparams.add(tau_mean);
this.hyperparams.add(tau_scale);
for (double beta : betas) {
this.hyperparams.add(beta);
}
for (double gamma : gammas) {
this.hyperparams.add(gamma);
}
for (double mu : mus) {
this.hyperparams.add(mu);
}
for (double sigma : sigmas) {
this.hyperparams.add(sigma);
}
for (double pi : pis) {
this.hyperparams.add(pi);
}
if (initBranchFactor != null) {
this.initBranchFactor = initBranchFactor;
}
this.updatePrecomputedHyperparameters();
this.sampledParams = new ArrayList<ArrayList<Double>>();
this.sampledParams.add(cloneHyperparameters());
this.BURN_IN = burnin;
this.MAX_ITER = maxiter;
this.LAG = samplelag;
this.REP_INTERVAL = repInt;
this.pathAssumption = pathAssumption;
this.initState = initState;
this.paramOptimized = paramOpt;
this.prefix += initState.toString();
this.setName();
// assert dimensions
if (this.betas.length != this.L) {
throw new RuntimeException("Vector betas must have length " + this.L
+ ". Current length = " + this.betas.length);
}
if (this.gammas.length != this.L - 1) {
throw new RuntimeException("Vector gammas must have length " + (this.L - 1)
+ ". Current length = " + this.gammas.length);
}
if (this.mus.length != this.L) {
throw new RuntimeException("Vector mus must have length " + this.L
+ ". Current length = " + this.mus.length);
}
if (this.sigmas.length != this.L) {
throw new RuntimeException("Vector sigmas must have length " + this.L
+ ". Current length = " + this.sigmas.length);
}
if (this.pis.length != this.L) {
throw new RuntimeException("Vector pis must have length " + this.L
+ ". Current length = " + this.pis.length);
}
this.uniform = new double[V];
for (int v = 0; v < V; v++) {
this.uniform[v] = 1.0 / V;
}
if (!debug) {
System.err.close();
}
if (verbose) {
logln("--- V = " + V);
logln("--- L = " + L);
logln("--- folder\t" + folder);
logln("--- max level:\t" + L);
logln("--- alpha:\t" + hyperparams.get(ALPHA));
logln("--- rho:\t" + hyperparams.get(RHO));
logln("--- tau mean:\t" + hyperparams.get(TAU_MEAN));
logln("--- tau scale:\t" + hyperparams.get(TAU_SIGMA));
logln("--- betas:\t" + MiscUtils.arrayToString(betas));
logln("--- gammas:\t" + MiscUtils.arrayToString(gammas));
logln("--- reg mus:\t" + MiscUtils.arrayToString(mus));
logln("--- reg sigmas:\t" + MiscUtils.arrayToString(sigmas));
logln("--- pis:\t" + MiscUtils.arrayToString(pis));
logln("--- burn-in:\t" + BURN_IN);
logln("--- max iter:\t" + MAX_ITER);
logln("--- sample lag:\t" + LAG);
logln("--- paramopt:\t" + paramOptimized);
logln("--- initialize:\t" + this.initState);
logln("--- path assumption:\t" + this.pathAssumption);
}
}
private void updatePrecomputedHyperparameters() {
logAlpha = Math.log(hyperparams.get(ALPHA));
sqrtRho = Math.sqrt(hyperparams.get(RHO));
sqrtSigmas = new double[sigmas.length];
for (int i = 0; i < sqrtSigmas.length; i++) {
sqrtSigmas[i] = Math.sqrt(sigmas[i]);
}
logGammas = new double[gammas.length];
for (int i = 0; i < logGammas.length; i++) {
logGammas[i] = Math.log(gammas[i]);
}
}
@Override
public String getName() {
return this.name;
}
protected void setName() {
StringBuilder str = new StringBuilder();
str.append(this.prefix)
.append("_SHLDA")
.append("_B-").append(BURN_IN)
.append("_M-").append(MAX_ITER)
.append("_L-").append(LAG);
for (double h : hyperparams) {
str.append("-").append(MiscUtils.formatDouble(h));
}
str.append("_opt-").append(this.paramOptimized);
str.append("_").append(this.paramOptimized);
for (int ii = 0; ii < initBranchFactor.length; ii++) {
str.append("-").append(initBranchFactor[ii]);
}
this.name = str.toString();
}
private void prepareDataStatistics() {
// statistics
sentCount = 0;
tokenCount = 0;
for (int d = 0; d < D; d++) {
sentCount += words[d].length;
for (int s = 0; s < words[d].length; s++) {
tokenCount += words[d][s].length;
}
}
// document words
docWords = new int[D][];
for (int d = 0; d < D; d++) {
int docLength = 0;
for (int s = 0; s < words[d].length; s++) {
docLength += words[d][s].length;
}
docWords[d] = new int[docLength];
int count = 0;
for (int s = 0; s < words[d].length; s++) {
for (int n = 0; n < words[d][s].length; n++) {
docWords[d][count++] = words[d][s][n];
}
}
}
}
@Override
public void train(ResponseTextDataset trainData) {
train(trainData.getSentenceWords(),
trainData.getResponses());
}
public void train(int[][][] ws, double[] rs) {
this.words = ws;
this.responses = rs;
this.D = this.words.length;
this.prepareDataStatistics();
if (verbose) {
logln("--- # documents:\t" + D);
logln("--- # tokens:\t" + tokenCount);
logln("--- # sentences:\t" + sentCount);
logln("--- response distributions:");
logln("
logln("
int[] histogram = StatisticsUtils.bin(responses, 10);
for (int ii = 0; ii < histogram.length; ii++) {
logln("
}
}
}
@Override
public void test(ResponseTextDataset testData) {
test(testData.getSentenceWords(),
new File(getSamplerFolderPath(), IterPredictionFolder));
}
public void test(int[][][] newWords, File iterPredFolder) {
if (verbose) {
logln("Test sampling ...");
}
// start testing
File reportFolder = new File(getSamplerFolderPath(), ReportFolder);
if (!reportFolder.exists()) {
throw new RuntimeException("Report folder does not exist");
}
String[] filenames = reportFolder.list();
try {
IOUtils.createFolder(iterPredFolder);
for (int i = 0; i < filenames.length; i++) {
String filename = filenames[i];
if (!filename.contains("zip")) {
continue;
}
File partialResultFile = new File(iterPredFolder,
IOUtils.removeExtension(filename) + ".txt");
sampleNewDocuments(
new File(reportFolder, filename), newWords,
partialResultFile.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while sampling during test time.");
}
}
/**
* Compute the regression sum from the topic tree for a set of tokens with
* known level assignments given the path
*
* @param pathNode The leaf node of the given path
* @param levelAssignments Array containing level assignments
*
* @return The regression sum
*/
private double computeTopicWeightFullPath(SNode pathNode, int[] levelAssignments) {
int[] levelCounts = new int[L];
for (int n = 0; n < levelAssignments.length; n++) {
int level = levelAssignments[n];
levelCounts[level]++;
}
double regSum = 0.0;
SNode[] path = getPathFromNode(pathNode);
for (int lvl = 0; lvl < path.length; lvl++) {
regSum += levelCounts[lvl] * path[lvl].getRegressionParameter();
}
return regSum;
}
/**
* Return a path from the root to a given node
*
* @param node The given node
* @return An array containing the path
*/
SNode[] getPathFromNode(SNode node) {
SNode[] path = new SNode[node.getLevel() + 1];
SNode curNode = node;
int l = node.getLevel();
while (curNode != null) {
path[l--] = curNode;
curNode = curNode.getParent();
}
return path;
}
private void updateAuthorValues() {
docValues = new double[D];
for (int d = 0; d < D; d++) {
// topic
double docTopicVal = 0.0;
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
docTopicVal += computeTopicWeightFullPath(c[d][s].getContent(), z[d][s]);
}
double tVal = docTopicVal / docWords[d].length;
docValues[d] += tVal;
// lexical
double docLexicalVal = 0.0;
for (int s = 0; s < words[d].length; s++) {
for (int n = 0; n < words[d][s].length; n++) {
docLexicalVal += lexParams[words[d][s][n]];
}
}
double lVal = docLexicalVal / docWords[d].length;
docValues[d] += lVal;
}
}
private boolean isValidSentence(int d, int s) {
return this.words[d][s].length > 0;
}
private void evaluateRegressPrediction(double[] trueVals, double[] predVals) {
RegressionEvaluation eval = new RegressionEvaluation(trueVals, predVals);
eval.computeCorrelationCoefficient();
eval.computeMeanSquareError();
eval.computeMeanAbsoluteError();
eval.computeRSquared();
eval.computePredictiveRSquared();
ArrayList<Measurement> measurements = eval.getMeasurements();
for (Measurement measurement : measurements) {
logln("
}
}
public double[] getRegressionValues() {
double[] predVals = new double[D];
for (int d = 0; d < D; d++) {
predVals[d] = getPredictedAuthorResponse(d);
}
return predVals;
}
public double getPredictedAuthorResponse(int d) {
return docValues[d];
}
@Override
public void initialize() {
if (verbose) {
logln("Initializing ...");
}
iter = INIT;
initializeModelStructure();
initializeDataStructure();
initializeAssignments();
// sampleTopics();
updateParameters();
if (verbose) {
logln("
logln(printGlobalTree());
logln(printGlobalTreeSummary());
logln(printLocalRestaurantSummary());
getLogLikelihood();
}
if (debug) {
validate("Initialized");
evaluateRegressPrediction(responses, getRegressionValues());
}
}
/**
* Initialize model structure.
*/
protected void initializeModelStructure() {
DirMult dmModel = new DirMult(V, betas[0] * V, uniform);
double regParam = 0.0;
this.globalTreeRoot = new SNode(iter, 0, 0, dmModel, regParam, null);
this.lexParams = new double[V];
}
/**
* Initialize data-specific structures.
*/
protected void initializeDataStructure() {
this.docLevelDist = new DirMult[D];
for (int d = 0; d < D; d++) {
this.docLevelDist[d] = new DirMult(pis);
}
this.localRestaurants = new Restaurant[D];
for (int d = 0; d < D; d++) {
this.localRestaurants[d] = new Restaurant<STable, Integer, SNode>();
}
this.sentLevelCounts = new int[D][][];
for (int d = 0; d < D; d++) {
this.sentLevelCounts[d] = new int[words[d].length][L];
}
this.c = new STable[D][];
this.z = new int[D][][];
for (int d = 0; d < D; d++) {
c[d] = new STable[words[d].length];
z[d] = new int[words[d].length][];
for (int s = 0; s < words[d].length; s++) {
z[d][s] = new int[words[d][s].length];
}
}
// partial design matrix
this.lexDesignMatrix = new double[D][V];
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
for (int n = 0; n < words[d][s].length; n++) {
int w = words[d][s][n];
lexDesignMatrix[d][w]++;
}
}
for (int v = 0; v < V; v++) {
lexDesignMatrix[d][v] /= docWords[d].length;
}
}
this.docValues = new double[D];
}
/**
* Initialize assignments.
*/
protected void initializeAssignments() {
switch (initState) {
case PRESET:
initializeRecursiveLDAAssignments();
break;
case SEEDED:
if (this.seededAssignmentFile == null) {
throw new RuntimeException("Seeded assignment file is not "
+ "initialized.");
}
initializeRecursiveLDAAssignmentsSeeded(seededAssignmentFile);
break;
default:
throw new RuntimeException("Initialization not supported");
}
}
public void setSeededAssignmentFile(String f) {
this.seededAssignmentFile = f;
}
protected void initializeRecursiveLDAAssignments() {
int[][] seededAssignments = null;
initializeRecursiveLDAAssignmentsSeeded(seededAssignments);
}
protected void initializeRecursiveLDAAssignmentsSeeded(String seededFile) {
int[][] seededAssignments = null;
try {
BufferedReader reader = IOUtils.getBufferedReader(seededFile);
int numDocs = Integer.parseInt(reader.readLine());
if (numDocs != D) {
throw new RuntimeException("Number of documents is incorrect. "
+ numDocs + " vs. " + D);
}
seededAssignments = new int[D][];
for (int d = 0; d < D; d++) {
String[] sline = reader.readLine().split(" ");
seededAssignments[d] = new int[sline.length];
for (int n = 0; n < sline.length; n++) {
seededAssignments[d][n] = Integer.parseInt(sline[n]);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
logln(">>> Seeded assignments cannot be loaded from " + seededFile);
}
initializeRecursiveLDAAssignmentsSeeded(seededAssignments);
}
private void initializeRecursiveLDAAssignmentsSeeded(int[][] seededAssignments) {
if (verbose) {
logln("--- Initializing assignments using recursive LDA ...");
}
RecursiveLDA rLDA = new RecursiveLDA();
rLDA.setVerbose(verbose);
rLDA.setDebug(debug);
rLDA.setLog(false);
rLDA.setReport(false);
double[] empBackgroundTopic = new double[V];
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
for (int n = 0; n < words[d][s].length; n++) {
empBackgroundTopic[words[d][s][n]]++;
}
}
}
for (int v = 0; v < V; v++) {
empBackgroundTopic[v] /= tokenCount;
}
int init_burnin = 25;
int init_maxiter = 50;
int init_samplelag = 5;
double[] init_alphas = {0.1, 0.1};
double[] init_betas = {0.1, 0.1};
double ratio = 1000;
rLDA.configure(folder, docWords,
V, initBranchFactor, ratio, init_alphas, init_betas, initState,
paramOptimized, init_burnin, init_maxiter, init_samplelag, 1);
try {
File lldaZFile = new File(rLDA.getSamplerFolderPath(), "model.zip");
if (lldaZFile.exists()) {
rLDA.inputState(lldaZFile);
} else {
rLDA.initialize();
rLDA.iterate(seededAssignments);
IOUtils.createFolder(rLDA.getSamplerFolderPath());
rLDA.outputState(lldaZFile);
}
rLDA.setWordVocab(wordVocab);
rLDA.outputTopicTopWords(new File(rLDA.getSamplerFolderPath(), TopWordFile), 20);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while initializing");
}
setLog(true);
this.globalTreeRoot.setTopic(empBackgroundTopic);
HashMap<RLDA, SNode> nodeMap = new HashMap<RLDA, SNode>();
nodeMap.put(rLDA.getRoot(), globalTreeRoot);
Queue<RLDA> queue = new LinkedList<RLDA>();
queue.add(rLDA.getRoot());
while (!queue.isEmpty()) {
RLDA rldaNode = queue.poll();
for (RLDA rldaChild : rldaNode.getChildren()) {
queue.add(rldaChild);
}
if (rldaNode.getParent() == null) {
continue;
}
int rLDAIndex = rldaNode.getIndex();
int level = rldaNode.getLevel();
if (rLDA.hasBackground() && level == 1
&& rLDAIndex == RecursiveLDA.BACKGROUND) {
continue; // skip background node
}
DirMult topic = new DirMult(V, betas[level] * V, 1.0 / V);
double regParam = SamplerUtils.getGaussian(mus[level], sigmas[level]);
SNode parent = nodeMap.get(rldaNode.getParent());
int sNodeIndex = parent.getNextChildIndex();
SNode node = new SNode(iter, sNodeIndex, level, topic, regParam, parent);
node.setTopic(rldaNode.getParent().getTopics()[rLDAIndex].getDistribution());
parent.addChild(sNodeIndex, node);
nodeMap.put(rldaNode, node);
level++;
if (level == rLDA.getNumLevels()) {
for (int ii = 0; ii < rldaNode.getTopics().length; ii++) {
DirMult subtopic = new DirMult(V, betas[level] * V, 1.0 / V);
double subregParam = SamplerUtils.getGaussian(mus[level], sigmas[level]);
SNode leaf = new SNode(iter, ii, level, subtopic, subregParam, node);
leaf.setTopic(rldaNode.getTopics()[ii].getDistribution());
node.addChild(ii, leaf);
}
}
}
if (verbose) {
logln(printGlobalTree());
outputTopicTopWords(new File(getSamplerFolderPath(), "init-" + TopWordFile), 15);
}
// initialize assignments
for (int d = 0; d < D; d++) {
HashMap<SNode, STable> nodeTableMap = new HashMap<SNode, STable>();
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
SparseCount obs = new SparseCount();
for (int n = 0; n < words[d][s].length; n++) {
obs.increment(words[d][s][n]);
}
// recursively sample a node for this sentence
SNode leafNode = recurseNode(globalTreeRoot, obs);
STable table = nodeTableMap.get(leafNode);
if (table == null) {
int tabIdx = localRestaurants[d].getNextTableIndex();
table = new STable(iter, tabIdx, leafNode, d);
localRestaurants[d].addTable(table);
addTableToPath(leafNode);
nodeTableMap.put(leafNode, table);
}
localRestaurants[d].addCustomerToTable(s, table.getIndex());
c[d][s] = table;
// sample level for each token
SNode[] path = getPathFromNode(c[d][s].getContent());
for (int n = 0; n < words[d][s].length; n++) {
double[] logprobs = new double[L];
for (int ll = 0; ll < L; ll++) {
logprobs[ll] = docLevelDist[d].getLogLikelihood(ll)
+ path[ll].getLogProbability(words[d][s][n]);
// if (d == 1) {
// System.out.println("s = " + s
// + ". n = " + n
// + ". ll = " + ll
// + ". " + MiscUtils.formatDouble(docLevelDist[d].getLogLikelihood(ll))
// + ". " + MiscUtils.formatDouble(path[ll].getLogProbability(words[d][s][n]))
// + ". " + MiscUtils.formatDouble(logprobs[ll]));
}
int lvl = SamplerUtils.logMaxRescaleSample(logprobs);
// debug
// if (d == 1) {
// System.out.println(">>> " + lvl);
z[d][s][n] = lvl;
sentLevelCounts[d][s][z[d][s][n]]++;
docLevelDist[d].increment(z[d][s][n]);
path[z[d][s][n]].getContent().increment(words[d][s][n]);
}
}
}
if (verbose && debug) {
validate("After initializing assignments");
outputTopicTopWords(new File(getSamplerFolderPath(), "init-assigned-" + TopWordFile), 15);
}
}
private SNode recurseNode(SNode node, SparseCount obs) {
if (node.getLevel() == L - 1) {
return node;
}
ArrayList<SNode> children = new ArrayList<SNode>();
ArrayList<Double> logprobs = new ArrayList<Double>();
for (SNode child : node.getChildren()) {
children.add(child);
logprobs.add(node.getLogProbability(obs));
}
int sampledIdx = SamplerUtils.logMaxRescaleSample(logprobs);
SNode sampledNode = children.get(sampledIdx);
return recurseNode(sampledNode, obs);
}
protected void inspectRestaurant(int d) {
int docTokenCount = 0;
int docNonEmptySentCount = 0;
for (int s = 0; s < words[d].length; s++) {
if (words[d][s].length != 0) {
docNonEmptySentCount++;
docTokenCount += words[d][s].length;
}
}
System.out.println("\n\n>>>d: " + d
+ ". # sentences:" + words[d].length
+ ". # non-empty sentences: " + docNonEmptySentCount
+ ". # tokens: " + docTokenCount
+ "\t # tables: " + localRestaurants[d].getNumTables());
for (int ll = 0; ll < L; ll++) {
System.out.println(">>> >>> level: " + ll + "\t" + docLevelDist[d].getCount(ll));
}
for (STable table : localRestaurants[d].getTables()) {
SNode node = table.getContent();
System.out.print("Table " + table.getTableId()
+ "\t#c: " + table.getNumCustomers()
+ "\t" + node.toString()
+ ":::");
double[] nodeTopic = node.getTopic();
String[] topWords = getTopWords(nodeTopic, 10);
System.out.print("\t");
for (String word : topWords) {
System.out.print(word + "\t");
}
System.out.println();
for (int s : table.getCustomers()) {
System.out.print(">>>s=" + s);
for (int n = 0; n < words[d][s].length; n++) {
System.out.print("; " + wordVocab.get(words[d][s][n])
+ " (" + z[d][s][n] + ")");
}
System.out.println();
System.out.println("\t" + rawSentences[d][s]);
System.out.println();
}
System.out.println();
}
}
@Override
public void iterate() {
if (verbose) {
logln("Iterating ...");
}
this.logLikelihoods = new ArrayList<Double>();
File repFolderPath = new File(getSamplerFolderPath(), ReportFolder);
try {
if (report && !repFolderPath.exists()) {
IOUtils.createFolder(repFolderPath);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
if (log && !isLogging()) {
openLogger();
}
logln(getClass().toString());
startTime = System.currentTimeMillis();
for (iter = 0; iter < MAX_ITER; iter++) {
double loglikelihood = this.getLogLikelihood();
logLikelihoods.add(loglikelihood);
double[] storeWeights = new double[V];
System.arraycopy(lexParams, 0, storeWeights, 0, V);
if (verbose) {
String str = "Iter " + iter + "/" + MAX_ITER
+ "\t llh = " + MiscUtils.formatDouble(loglikelihood)
+ "\n*** *** # sents change: " + numSentAsntsChange
+ " / " + sentCount
+ " (" + (double) numSentAsntsChange / sentCount + ")"
+ "\n*** *** # tables change: " + numTableAsgnsChange
+ " / " + globalTreeRoot.getNumTables()
+ " (" + (double) numTableAsgnsChange / globalTreeRoot.getNumTables() + ")"
+ "\n*** *** # accept: " + numAccepts
+ " / " + numProposes
+ " (" + (double) numAccepts / numProposes + ")"
+ "\n" + getCurrentState()
+ "\n";
if (iter <= BURN_IN) {
logln("--- Burning in. " + str);
} else {
logln("--- Sampling. " + str);
}
}
numTableAsgnsChange = 0;
numSentAsntsChange = 0;
numProposes = 0;
numAccepts = 0;
long tabSent = 0;
long pathTab = 0;
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
tabSent += sampleSentenceAssignmentsApprox(d, s, REMOVE, ADD,
REMOVE, ADD, OBSERVED, EXTEND);
}
for (STable table : this.localRestaurants[d].getTables()) {
pathTab += samplePathForTable(d, table,
REMOVE, ADD, REMOVE, ADD,
OBSERVED, EXTEND);
}
}
long updateParam = updateParameters();
long sampleTopics = sampleTopics();
logln("Time spent. Iter = " + iter
+ ". tab->sen: " + tabSent
+ ". pat->tab: " + pathTab
+ ". upd->par: " + updateParam
+ ". sam->top: " + sampleTopics);
if (verbose) {
evaluateRegressPrediction(responses, getRegressionValues());
}
if (iter > BURN_IN && iter % LAG == 0) {
if (paramOptimized) {
if (verbose) {
logln("
}
sliceSample();
this.sampledParams.add(this.cloneHyperparameters());
if (verbose) {
logln("
}
}
}
if (debug) {
this.validate("Iteration " + iter);
}
float elapsedSeconds = (System.currentTimeMillis() - startTime) / (1000);
logln("Elapsed time iterating: " + elapsedSeconds + " seconds");
System.out.println();
// store model
if (report && iter > BURN_IN && iter % LAG == 0) {
outputState(new File(repFolderPath, "iter-" + iter + ".zip"));
outputTopicTopWords(new File(repFolderPath,
"iter-" + iter + "-top-words.txt"), 15);
}
}
// output final model
if (report) {
outputState(new File(repFolderPath, "iter-" + iter + ".zip"));
outputTopicTopWords(new File(repFolderPath,
"iter-" + iter + "-top-words.txt"), 15);
}
if (verbose) {
logln(printGlobalTreeSummary());
logln(printLocalRestaurantSummary());
}
float elapsedSeconds = (System.currentTimeMillis() - startTime) / (1000);
logln("Total runtime iterating: " + elapsedSeconds + " seconds");
if (log && isLogging()) {
closeLogger();
}
}
private double getPathResponseLogLikelihood(int d, SNode[] path, int[] levelCounts) {
double denom = docWords[d].length;
double addReg = 0.0;
int level;
for (level = 0; level < path.length; level++) {
addReg += path[level].getRegressionParameter() * levelCounts[level] / denom;
}
double mean = docValues[d] + addReg;
double resLlh = StatisticsUtils.logNormalProbability(
responses[d], mean, sqrtRho);
return resLlh;
}
/**
* Sample a path on the global tree for a table.
*
* @param d The restaurant index
* @param table The table
* @param removeFromModel Whether the current assignment should be removed
* @param addToModel Whether the new assignment should be added
* @param observed Whether the response variable is observed
* @param extend Whether the global tree is extendable
*/
private long samplePathForTable(int d, STable table,
boolean removeFromModel, boolean addToModel,
boolean removeFromData, boolean addToData,
boolean observed, boolean extend) {
long sTime = System.currentTimeMillis();
SNode curNode = table.getContent();
double denom = docWords[d].length;
// observation counts of this table per level
SparseCount[] tabObsCountPerLevel = getTableObsCountPerLevel(d, table);
if (observed) {
for (int s : table.getCustomers()) {
SNode[] curPath = getPathFromNode(table.getContent());
for (int n = 0; n < words[d][s].length; n++) {
docValues[d] -= curPath[z[d][s][n]].getRegressionParameter() / denom;
}
}
}
if (removeFromModel) {
removeObservationsFromPath(table.getContent(), tabObsCountPerLevel);
}
if (removeFromData) {
for (int s : table.getCustomers()) {
for (int n = 0; n < words[d][s].length; n++) {
docLevelDist[d].decrement(z[d][s][n]);
}
}
removeTableFromPath(table.getContent());
}
// debug
// boolean condition = d < 5;
// current assignment
int[] curLevelCounts = new int[L];
for (int s : table.getCustomers()) {
for (int n = 0; n < words[d][s].length; n++) {
curLevelCounts[z[d][s][n]]++;
}
}
while (curNode.isEmpty()) {
curNode = curNode.getParent();
}
SNode[] path = getPathFromNode(curNode);
double curResLlh = getPathResponseLogLikelihood(d, path, curLevelCounts);
// debug
// if (condition) {
// logln("table = " + table.getTableId());
// for (SNode p : path) {
// logln("path " + p.toString());
// for (int s : table.getCustomers()) {
// System.out.println("s = " + s + ". " + MiscUtils.arrayToString(z[d][s]));
// System.out.println(">>> cur res: " + curResLlh);
// propose a path and level assignments
SNode proposedNode = samplePathFromPrior(globalTreeRoot, extend);
SNode[] proposedPath = getPathFromNode(proposedNode);
HashMap<Integer, int[]> proposedZs = new HashMap<Integer, int[]>();
for (int s : table.getCustomers()) {
int[] ppZs = new int[words[d][s].length];
for (int n = 0; n < words[d][s].length; n++) {
double[] lps = new double[L];
for (int ll = 0; ll < L; ll++) {
// word log likelihood
double wordLlh;
if (ll < proposedPath.length) {
wordLlh = proposedPath[ll].getLogProbability(words[d][s][n]);
} else { // approx using ancestor
wordLlh = proposedPath[proposedPath.length - 1].getLogProbability(words[d][s][n]);
}
lps[ll] = docLevelDist[d].getLogLikelihood(ll) + wordLlh;
}
int idx = SamplerUtils.logMaxRescaleSample(lps);
ppZs[n] = idx;
}
proposedZs.put(s, ppZs);
}
int[] newLevelCounts = new int[L];
for (int s : proposedZs.keySet()) {
int[] ppZs = proposedZs.get(s);
for (int n = 0; n < ppZs.length; n++) {
newLevelCounts[ppZs[n]]++;
}
}
double newResLlh = getPathResponseLogLikelihood(d, proposedPath, newLevelCounts);
// debug
// if (condition) {
// logln("\nd = " + d);
// for (SNode p : proposedPath) {
// logln("pp-path " + p.toString());
// for (int s : table.getCustomers()) {
// System.out.println("s = " + s + ". " + MiscUtils.arrayToString(proposedZs.get(s)));
// System.out.println(">>> new res: " + newResLlh);
// System.out.println();
// >>> TODO: need to recompute this
double ratio = Math.min(1, Math.exp(newResLlh - curResLlh));
SNode newLeaf;
double randNum = rand.nextDouble();
// debug
// if (d < 10) {
// logln("d = " + d
// + ". tab = " + table.getTableId()
// + "\t" + MiscUtils.formatDouble(newResLlh)
// + "\t" + MiscUtils.formatDouble(curResLlh)
// + "\t" + MiscUtils.formatDouble(ratio)
// + "\t" + randNum);
if (randNum < ratio) { // accept
newLeaf = proposedNode;
for (int s : proposedZs.keySet()) {
int[] ppZs = proposedZs.get(s);
System.arraycopy(ppZs, 0, z[d][s], 0, words[d][s].length);
}
tabObsCountPerLevel = getTableObsCountPerLevel(d, table);
numAccepts++;
} else {
newLeaf = curNode;
}
numProposes++;
// debug
if (curNode == null || curNode.equals(newLeaf)) {
numTableAsgnsChange++;
}
// if pick an internal node, create the path from the internal node to leave
if (newLeaf.getLevel() < L - 1) {
newLeaf = this.createNewPath(newLeaf);
}
// update
table.setContent(newLeaf);
if (addToModel) {
addObservationsToPath(table.getContent(), tabObsCountPerLevel);
}
if (addToData) {
for (int s : table.getCustomers()) {
for (int n = 0; n < words[d][s].length; n++) {
docLevelDist[d].increment(z[d][s][n]);
}
}
addTableToPath(table.getContent());
}
if (observed) {
for (int s : table.getCustomers()) {
SNode[] curPath = getPathFromNode(table.getContent());
for (int n = 0; n < words[d][s].length; n++) {
docValues[d] += curPath[z[d][s][n]].getRegressionParameter() / denom;
}
}
}
return System.currentTimeMillis() - sTime;
}
/**
* Recursively sample a path from prior distribution.
*
* @param curNode The current node
*/
private SNode samplePathFromPrior(SNode curNode, boolean extend) {
if (isLeafNode(curNode)) {
return curNode;
}
ArrayList<Integer> children = new ArrayList<Integer>();
ArrayList<Double> probs = new ArrayList<Double>();
for (SNode child : curNode.getChildren()) {
children.add(child.getIndex());
probs.add((double) child.getNumTables());
}
if (extend) {
children.add(PSEUDO_NODE_INDEX);
probs.add(gammas[curNode.getLevel()]);
}
int idx = SamplerUtils.scaleSample(probs);
int nodeIdx = children.get(idx);
if (nodeIdx == PSEUDO_NODE_INDEX) {
return curNode;
} else {
return samplePathFromPrior(curNode.getChild(nodeIdx), extend);
}
}
/**
* Sample the assignments for a sentence. This is done as follows
*
* * Remove the table assignment of the current sentence and all level
* assignments of tokens in this sentence.
*
* * Block sample both a new table assignment AND all level assignments for
* tokens in the sentence. For existing table, sample level assignments
* using the current path. For a new table, sample a path from prior and
* sample level assignments on this sampled path.
*
* * Update with the new table assignment and level assignments
*
* @param d Document index
* @param s Sentence index
* @param removeFromModel Whether the current observations should be removed
* from the tree
* @param addToModel Whether the observations should be added to the tree
* with the newly sampled assignments
* @param removeFromData Whether the current table assignment should be
* removed
* @param addToData Whether the new table assignment should be added
* @param observed Whether the response variable is observed
* @param extend Whether the tree is changeable
*/
private long sampleSentenceAssignmentsApprox(int d, int s,
boolean removeFromModel, boolean addToModel,
boolean removeFromData, boolean addToData,
boolean observed, boolean extend) {
long sTime = System.currentTimeMillis();
STable curTable = this.c[d][s];
int[] curZs = new int[words[d][s].length];
System.arraycopy(z[d][s], 0, curZs, 0, curZs.length);
SparseCount[] sentObsCountPerLevel = getSentObsCountPerLevel(d, s);
double denom = docWords[d].length;
// remove current assignments
if (observed) {
SNode[] curPath = getPathFromNode(curTable.getContent());
for (int n = 0; n < words[d][s].length; n++) {
docValues[d] -= curPath[curZs[n]].getRegressionParameter() / denom;
}
}
if (removeFromData) {
for (int n = 0; n < words[d][s].length; n++) {
docLevelDist[d].decrement(z[d][s][n]);
sentLevelCounts[d][s][z[d][s][n]]
}
localRestaurants[d].removeCustomerFromTable(s, curTable.getIndex());
if (curTable.isEmpty()) {
removeTableFromPath(curTable.getContent());
localRestaurants[d].removeTable(curTable.getIndex());
}
}
if (removeFromModel) {
removeObservationsFromPath(curTable.getContent(), sentObsCountPerLevel);
}
// sample
ArrayList<Integer> tableIndices = new ArrayList<Integer>();
ArrayList<Double> tableLps = new ArrayList<Double>();
HashMap<SNode, int[]> proposedZs = new HashMap<SNode, int[]>();
HashMap<SNode, Double> proposedLps = new HashMap<SNode, Double>();
// path log prior
HashMap<SNode, Double> pathLogpriors = new HashMap<SNode, Double>();
computePathLogPrior(pathLogpriors, globalTreeRoot, 0.0, extend);
ArrayList<SNode> allPathNodes = new ArrayList<SNode>();
ArrayList<Double> allPathLogpriors = new ArrayList<Double>();
for (SNode node : pathLogpriors.keySet()) {
allPathNodes.add(node);
allPathLogpriors.add(pathLogpriors.get(node));
}
int newTabSampledIdx = SamplerUtils.logMaxRescaleSample(allPathLogpriors);
SNode newTabSampledNode = allPathNodes.get(newTabSampledIdx);
double newTabLp = 0.0;
int[] newTableZs = new int[words[d][s].length];
SNode[] path = getPathFromNode(newTabSampledNode);
// sample level for each token
for (int n = 0; n < words[d][s].length; n++) {
double[] lps = new double[L];
for (int ll = 0; ll < L; ll++) {
// word log likelihood
double wordLlh;
if (ll < path.length) {
wordLlh = path[ll].getLogProbability(words[d][s][n]);
} else { // approx using ancestor
wordLlh = path[path.length - 1].getLogProbability(words[d][s][n]);
}
lps[ll] = docLevelDist[d].getLogLikelihood(ll) + wordLlh;
}
int idx = SamplerUtils.logMaxRescaleSample(lps);
newTabLp += lps[idx];
newTableZs[n] = idx;
}
proposedZs.put(newTabSampledNode, newTableZs);
proposedLps.put(newTabSampledNode, newTabLp);
// propose assignments
proposeTokenAssignments(d, s, proposedZs, proposedLps);
// path response llhs
HashMap<SNode, Double> pathResLlhs = new HashMap<SNode, Double>();
if (observed) {
computePathResponseLogLikelihood(pathResLlhs, docValues[d], denom,
responses[d], proposedZs);
}
// debug
// boolean condition = (d == 10);
// if (condition) {
// logln("ppZs: " + proposedZs.size()
// + "\tppLps: " + proposedLps.size()
// + "\tprior" + pathLogpriors.size()
// + "\tres: " + pathResLlhs.size());
// sample table for this sentence
for (STable table : this.localRestaurants[d].getTables()) {
tableIndices.add(table.getIndex());
SNode pathNode = table.getContent();
double resLlh = 0.0;
if (observed) {
resLlh = pathResLlhs.get(pathNode);
}
double lp = Math.log(table.getNumCustomers())
+ proposedLps.get(pathNode)
+ resLlh;
tableLps.add(lp);
// debug
// if (condition) {
// logln("iter = " + iter
// + ". d = " + d
// + ". s = " + s
// + ". table: " + table.getIndex()
// + ". # custs: " + table.getNumCustomers()
// + ". leaf: " + table.getContent().getPathString()
// + ". " + MiscUtils.formatDouble(Math.log(table.getNumCustomers()))
// + ". " + MiscUtils.formatDouble(proposedLps.get(pathNode))
// + ". " + MiscUtils.formatDouble(resLlh)
// + ". " + MiscUtils.formatDouble(lp));
}
tableIndices.add(PSEUDO_TABLE_INDEX);
double newTabLogPrior = logAlpha;
double newTabWordLlh = proposedLps.get(newTabSampledNode);
double newTabResLlh = pathResLlhs.get(newTabSampledNode);
double newTabLogprob = newTabLogPrior + newTabWordLlh + newTabResLlh;
tableLps.add(newTabLogprob);
// debug
// if (condition) {
// logln("iter = " + iter
// + ". d = " + d
// + ". s = " + s
// + ". new table: "
// + ". " + MiscUtils.formatDouble(newTabLogPrior)
// + ". " + MiscUtils.formatDouble(newTabWordLlh)
// + ". " + MiscUtils.formatDouble(newTabResLlh)
// + ". " + MiscUtils.formatDouble(newTabLogprob));
// update new assignments
// sample
int sampledIndex = SamplerUtils.logMaxRescaleSample(tableLps);
int tableIdx = tableIndices.get(sampledIndex);
// debug
// if (condition) {
// logln(">>> sIdx: " + sampledIndex
// + "\t" + tableIdx);
if (curTable != null && curTable.getIndex() != tableIdx) {
numSentAsntsChange++;
}
STable table;
int[] newZs;
if (tableIdx == PSEUDO_NODE_INDEX) {
// sample path for a new table
int newTableIdx = localRestaurants[d].getNextTableIndex();
table = new STable(iter, newTableIdx, null, d);
localRestaurants[d].addTable(table);
newZs = proposedZs.get(newTabSampledNode);
if (!isLeafNode(newTabSampledNode)) {
newTabSampledNode = createNewPath(newTabSampledNode);
}
table.setContent(newTabSampledNode);
addTableToPath(table.getContent());
} else {
table = localRestaurants[d].getTable(tableIdx);
newZs = proposedZs.get(table.getContent());
}
c[d][s] = table;
System.arraycopy(newZs, 0, z[d][s], 0, words[d][s].length);
sentObsCountPerLevel = getSentObsCountPerLevel(d, s);
if (addToData) {
for (int n = 0; n < words[d][s].length; n++) {
docLevelDist[d].increment(z[d][s][n]);
sentLevelCounts[d][s][z[d][s][n]]++;
}
localRestaurants[d].addCustomerToTable(s, c[d][s].getIndex());
}
if (addToModel) {
addObservationsToPath(c[d][s].getContent(), sentObsCountPerLevel);
}
if (observed) {
SNode[] curPath = getPathFromNode(curTable.getContent());
for (int n = 0; n < words[d][s].length; n++) {
docValues[d] += curPath[curZs[n]].getRegressionParameter() / denom;
}
}
return System.currentTimeMillis() - sTime;
}
private long sampleSentenceAssignmentsExact(int d, int s,
boolean removeFromModel, boolean addToModel,
boolean removeFromData, boolean addToData,
boolean observed, boolean extend) {
long sTime = System.currentTimeMillis();
STable curTable = this.c[d][s];
int[] curZs = new int[words[d][s].length];
System.arraycopy(z[d][s], 0, curZs, 0, curZs.length);
SparseCount[] sentObsCountPerLevel = getSentObsCountPerLevel(d, s);
double denom = docWords[d].length;
if (observed) {
SNode[] curPath = getPathFromNode(curTable.getContent());
for (int n = 0; n < words[d][s].length; n++) {
docValues[d] -= curPath[curZs[n]].getRegressionParameter() / denom;
}
}
if (removeFromData) {
for (int n = 0; n < words[d][s].length; n++) {
docLevelDist[d].decrement(z[d][s][n]);
sentLevelCounts[d][s][z[d][s][n]]
}
localRestaurants[d].removeCustomerFromTable(s, curTable.getIndex());
if (curTable.isEmpty()) {
removeTableFromPath(curTable.getContent());
localRestaurants[d].removeTable(curTable.getIndex());
}
}
if (removeFromModel) {
removeObservationsFromPath(curTable.getContent(), sentObsCountPerLevel);
}
// for each possible path, sample a new set of level assignments for
// tokens in this sentence.
HashMap<SNode, int[]> proposedZs = new HashMap<SNode, int[]>();
HashMap<SNode, Double> proposedLps = new HashMap<SNode, Double>();
proposeTokenAssignments(d, s, proposedZs, proposedLps, extend);
// path log prior
HashMap<SNode, Double> pathLogpriors = new HashMap<SNode, Double>();
computePathLogPrior(pathLogpriors, globalTreeRoot, 0.0, extend);
// path response llhs
HashMap<SNode, Double> pathResLlhs = new HashMap<SNode, Double>();
if (observed) {
computePathResponseLogLikelihood(pathResLlhs, docValues[d],
denom, responses[d], proposedZs);
}
// sample table for this sentence
ArrayList<Integer> tableIndices = new ArrayList<Integer>();
ArrayList<Double> tableLps = new ArrayList<Double>();
for (STable table : this.localRestaurants[d].getTables()) {
tableIndices.add(table.getIndex());
SNode pathNode = table.getContent();
double resLlh = 0.0;
if (observed) {
resLlh = pathResLlhs.get(pathNode);
}
double lp = Math.log(table.getNumCustomers())
+ proposedLps.get(pathNode)
+ resLlh;
tableLps.add(lp);
// debug
// if (d == 0) {
// logln("iter = " + iter
// + ". d = " + d
// + ". s = " + s
// + ". table: " + table.getIndex()
// + ". leaf: " + table.getContent().getPathString()
// + ". " + MiscUtils.formatDouble(Math.log(table.getNumCustomers()))
// + ". " + MiscUtils.formatDouble(proposedLps.get(pathNode))
// + ". " + MiscUtils.formatDouble(resLlh)
// + ". " + MiscUtils.formatDouble(lp));
}
tableIndices.add(PSEUDO_TABLE_INDEX);
double newTabLp = logAlpha
+ computeMarginals(pathLogpriors, proposedLps, pathResLlhs, observed);
tableLps.add(newTabLp);
// debug
// if (d == 0) {
// logln("iter = " + iter
// + ". d = " + d
// + ". s = " + s
// + ". new table: "
// + ". " + MiscUtils.formatDouble(newTabLp));
// sample
int sampledIndex = SamplerUtils.logMaxRescaleSample(tableLps);
int tableIdx = tableIndices.get(sampledIndex);
// debug
// if (d == 0) {
// logln(">>> sIdx: " + sampledIndex
// + "\t" + tableIdx);
if (curTable != null && curTable.getIndex() != tableIdx) {
numSentAsntsChange++;
}
STable table;
int[] newZs;
if (tableIdx == PSEUDO_NODE_INDEX) {
// sample path for a new table
int newTableIdx = localRestaurants[d].getNextTableIndex();
table = new STable(iter, newTableIdx, null, d);
localRestaurants[d].addTable(table);
SNode newNode = samplePath(pathLogpriors, proposedLps, pathResLlhs, observed);
newZs = proposedZs.get(newNode);
if (!isLeafNode(newNode)) {
newNode = createNewPath(newNode);
}
table.setContent(newNode);
addTableToPath(table.getContent());
} else {
table = localRestaurants[d].getTable(tableIdx);
newZs = proposedZs.get(table.getContent());
}
c[d][s] = table;
System.arraycopy(newZs, 0, z[d][s], 0, words[d][s].length);
sentObsCountPerLevel = getSentObsCountPerLevel(d, s);
if (addToData) {
for (int n = 0; n < words[d][s].length; n++) {
docLevelDist[d].increment(z[d][s][n]);
sentLevelCounts[d][s][z[d][s][n]]++;
}
localRestaurants[d].addCustomerToTable(s, c[d][s].getIndex());
}
if (addToModel) {
addObservationsToPath(c[d][s].getContent(), sentObsCountPerLevel);
}
if (observed) {
SNode[] curPath = getPathFromNode(curTable.getContent());
for (int n = 0; n < words[d][s].length; n++) {
docValues[d] += curPath[curZs[n]].getRegressionParameter() / denom;
}
}
return System.currentTimeMillis() - sTime;
}
/**
* Sample a path
*
* @param logPriors Path log priors
* @param wordLlhs Path word log likelihoods
* @param resLlhs Path response variable log likelihoods
*/
SNode samplePath(
HashMap<SNode, Double> logPriors,
HashMap<SNode, Double> wordLlhs,
HashMap<SNode, Double> resLlhs,
boolean observed) {
ArrayList<SNode> pathList = new ArrayList<SNode>();
ArrayList<Double> logProbs = new ArrayList<Double>();
for (SNode node : logPriors.keySet()) {
double lp = logPriors.get(node) + wordLlhs.get(node);
if (observed) {
lp += resLlhs.get(node);
}
pathList.add(node);
logProbs.add(lp);
}
int sampledIndex = SamplerUtils.logMaxRescaleSample(logProbs);
SNode path = pathList.get(sampledIndex);
return path;
}
/**
* Propose the assignments for all tokens in a given sentence considering
* only paths that are current assigned to table in the document.
*
* @param d The document index
* @param s The sentence index
* @param ppAssignments Map to store the proposed assignments
* @param ppLogprobs Map to store the corresponding log probabilities of the
* proposed assignments
*/
void proposeTokenAssignments(int d, int s,
HashMap<SNode, int[]> ppAssignments,
HashMap<SNode, Double> ppLogprobs) {
// log prior of each level: shared across document
double[] logpriors = new double[L];
for (int ll = 0; ll < L; ll++) {
logpriors[ll] = docLevelDist[d].getLogLikelihood(ll);
}
for (STable table : localRestaurants[d].getTables()) {
SNode node = table.getContent();
if (ppAssignments.containsKey(node)) {
continue;
}
int[] asgns = new int[words[d][s].length];
double lp = 0.0;
SNode[] path = getPathFromNode(node);
// sample level for each token
for (int n = 0; n < words[d][s].length; n++) {
double[] lps = new double[L];
for (int ll = 0; ll < L; ll++) {
// word log likelihood
double wordLlh;
if (ll < path.length) {
wordLlh = path[ll].getLogProbability(words[d][s][n]);
} else { // approx using ancestor
wordLlh = path[path.length - 1].getLogProbability(words[d][s][n]);
}
lps[ll] = logpriors[ll] + wordLlh;
}
int idx = SamplerUtils.logMaxRescaleSample(lps);
asgns[n] = idx;
lp += lps[idx];
}
ppAssignments.put(node, asgns);
ppLogprobs.put(node, lp);
}
}
/**
* Propose the assignments for all tokens in a given sentence considering
* all possible paths in the global tree.
*
* @param d The document index
* @param s The sentence index
* @param ppAssignments Map to store the proposed assignments
* @param ppLogprobs Map to store the corresponding log probabilities of the
* proposed assignments
* @param extend Whether extending the tree
*/
void proposeTokenAssignments(int d, int s,
HashMap<SNode, int[]> ppAssignments,
HashMap<SNode, Double> ppLogprobs,
boolean extend) {
// log prior of each level: shared across document
double[] logpriors = new double[L];
for (int ll = 0; ll < L; ll++) {
logpriors[ll] = docLevelDist[d].getLogLikelihood(ll);
}
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
for (SNode child : node.getChildren()) {
stack.add(child);
}
if (!extend && !isLeafNode(node)) {
continue;
}
int[] asgns = new int[words[d][s].length];
double lp = 0.0;
SNode[] path = getPathFromNode(node);
// sample level for each token
for (int n = 0; n < words[d][s].length; n++) {
double[] lps = new double[L];
for (int ll = 0; ll < L; ll++) {
// word log likelihood
double wordLlh;
if (ll < path.length) {
wordLlh = path[ll].getLogProbability(words[d][s][n]);
} else { // approx using ancestor
wordLlh = path[path.length - 1].getLogProbability(words[d][s][n]);
}
lps[ll] = logpriors[ll] + wordLlh;
}
int idx = SamplerUtils.logMaxRescaleSample(lps);
asgns[n] = idx;
lp += lps[idx];
}
ppAssignments.put(node, asgns);
ppLogprobs.put(node, lp);
}
}
/**
* Compute the log probability of a new table, marginalized over all
* possible paths
*
* @param pathLogPriors The log priors of each path
* @param pathWordLogLikelihoods The word likelihoods
* @param pathResLogLikelihoods The response variable likelihoods
*/
double computeMarginals(
HashMap<SNode, Double> pathLogPriors,
HashMap<SNode, Double> pathWordLogLikelihoods,
HashMap<SNode, Double> pathResLogLikelihoods,
boolean resObserved) {
double marginal = 0.0;
for (SNode node : pathLogPriors.keySet()) {
double logprior = pathLogPriors.get(node);
double loglikelihood = pathWordLogLikelihoods.get(node);
double lp = logprior + loglikelihood;
if (resObserved) {
lp += pathResLogLikelihoods.get(node);
}
if (marginal == 0.0) {
marginal = lp;
} else {
marginal = SamplerUtils.logAdd(marginal, lp);
}
}
return marginal;
}
/**
* Compute the log likelihoods of an author response when assigning a set of
* tokens (represented by their level assignments) to each path in the tree.
*
* @param nodeResLogProbs Map to store the results
* @param curAuthorVal Current author value
* @param denom
*/
void computePathResponseLogLikelihood(
HashMap<SNode, Double> nodeResLogProbs,
double curAuthorVal, double denom,
double authorResponse,
HashMap<SNode, int[]> proposedZs) {
for (SNode pathNode : proposedZs.keySet()) {
SNode[] path = getPathFromNode(pathNode);
int[] ppZs = proposedZs.get(pathNode);
int[] levelCounts = new int[L];
for (int ii = 0; ii < ppZs.length; ii++) {
levelCounts[ppZs[ii]]++;
}
double addReg = 0.0;
int level;
for (level = 0; level < path.length; level++) {
addReg += path[level].getRegressionParameter() * levelCounts[level] / denom;
}
double authorMean = curAuthorVal + addReg;
double resLlh = StatisticsUtils.logNormalProbability(
authorResponse, authorMean, sqrtRho);
nodeResLogProbs.put(pathNode, resLlh);
}
}
/**
* Compute the log probability of the response variable when the given table
* is assigned to each path
*
* @param d The document index
* @param table The table
*/
private HashMap<SNode, Double> computePathResponseLogLikelihood(
int d,
STable table,
boolean extend) {
HashMap<SNode, Double> resLlhs = new HashMap<SNode, Double>();
// int author = authors[d];
// double denom = docWords[d].length * authorDocIndices[author].length;
// Stack<SNode> stack = new Stack<SNode>();
// stack.add(globalTreeRoot);
// while (!stack.isEmpty()) {
// SNode node = stack.pop();
// for (SNode child : node.getChildren()) {
// stack.add(child);
// if (!extend && !isLeafNode(node)) {
// continue;
// SNode[] path = getPathFromNode(node);
// double addReg = 0.0;
// for (int level = 0; level < path.length; level++) {
// for (int s : table.getCustomers()) {
// addReg += path[level].getRegressionParameter()
// * sentLevelCounts[d][s][level] / denom;
// double authorMean = docValues[author] + addReg;
// double resLlh = StatisticsUtils.logNormalProbability(
// responses[author], authorMean, sqrtRho);
// resLlhs.put(node, resLlh);
return resLlhs;
}
/**
* Recursively compute the log probability of each path in the global tree
*
* @param nodeLogProbs HashMap to store the results
* @param curNode Current node in the recursive call
* @param parentLogProb The log probability passed from the parent node
*/
void computePathLogPrior(
HashMap<SNode, Double> nodeLogProbs,
SNode curNode,
double parentLogProb,
boolean extend) {
double newWeight = parentLogProb;
if (!isLeafNode(curNode)) {
double logNorm = Math.log(curNode.getNumTables() + gammas[curNode.getLevel()]);
newWeight += logGammas[curNode.getLevel()] - logNorm;
for (SNode child : curNode.getChildren()) {
double childWeight = parentLogProb + Math.log(child.getNumTables()) - logNorm;
computePathLogPrior(nodeLogProbs, child, childWeight, extend);
}
}
if (!extend && !isLeafNode(curNode)) {
return;
}
nodeLogProbs.put(curNode, newWeight);
}
/**
* Compute the log probability of assigning a set of words to each path in
* the tree
*
* @param nodeDataLlhs HashMap to store the result
* @param curNode The current node in recursive calls
* @param tokenCountPerLevel Token counts per level
* @param parentDataLlh The value passed from the parent node
*/
void computePathWordLogLikelihood(
HashMap<SNode, Double> nodeDataLlhs,
SNode curNode,
SparseCount[] tokenCountPerLevel,
double parentDataLlh,
boolean extend) {
int level = curNode.getLevel();
double nodeDataLlh = curNode.getLogProbability(tokenCountPerLevel[level]);
// populate to child nodes
for (SNode child : curNode.getChildren()) {
computePathWordLogLikelihood(nodeDataLlhs, child, tokenCountPerLevel,
parentDataLlh + nodeDataLlh, extend);
}
if (!extend && !isLeafNode(curNode)) {
return;
}
// store the data llh from the root to this current node
double storeDataLlh = parentDataLlh + nodeDataLlh;
level++;
while (level < L) { // if this is an internal node, add llh of new child node
DirMult dirMult;
if (curNode.getTopic() == null) {
dirMult = new DirMult(V, betas[level] * V, 1.0 / V);
} else {
dirMult = new DirMult(V, betas[level] * V, curNode.getTopic());
}
storeDataLlh += dirMult.getLogLikelihood(tokenCountPerLevel[level].getObservations());
level++;
}
nodeDataLlhs.put(curNode, storeDataLlh);
}
/**
* Get the observation counts per level of a given table
*
* @param d The document index
* @param table The table
*/
SparseCount[] getTableObsCountPerLevel(int d, STable table) {
// observations of sentences currently being assign to this table
SparseCount[] obsCountPerLevel = new SparseCount[L];
for (int l = 0; l < L; l++) {
obsCountPerLevel[l] = new SparseCount();
}
for (int s : table.getCustomers()) {
for (int n = 0; n < words[d][s].length; n++) {
int level = z[d][s][n];
int obs = words[d][s][n];
obsCountPerLevel[level].increment(obs);
}
}
return obsCountPerLevel;
}
/**
* Sample all topics. This is done by performing bottom-up smoothing and
* top-down sampling.
*/
protected long sampleTopics() {
if (verbose) {
logln("Sampling topics ...");
}
long sTime = System.currentTimeMillis();
// get all leaves of the tree
ArrayList<SNode> leaves = new ArrayList<SNode>();
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
if (node.getChildren().isEmpty()) {
leaves.add(node);
}
for (SNode child : node.getChildren()) {
stack.add(child);
}
}
// bottom-up smoothing to compute pseudo-counts from children
Queue<SNode> queue = new LinkedList<SNode>();
for (SNode leaf : leaves) {
queue.add(leaf);
}
while (!queue.isEmpty()) {
SNode node = queue.poll();
if (node.isLeaf()) {
continue;
}
SNode parent = node.getParent();
if (!node.isRoot() && !queue.contains(parent)) {
queue.add(parent);
}
if (this.pathAssumption == PathAssumption.MINIMAL) {
node.getPseudoCountsFromChildrenMin();
} else if (this.pathAssumption == PathAssumption.MAXIMAL) {
node.getPseudoCountsFromChildrenMax();
} else {
throw new RuntimeException("Path assumption " + this.pathAssumption
+ " is not supported.");
}
}
// top-down sampling to get topics
queue = new LinkedList<SNode>();
queue.add(globalTreeRoot);
while (!queue.isEmpty()) {
SNode node = queue.poll();
for (SNode child : node.getChildren()) {
queue.add(child);
}
node.sampleTopic(betas[node.getLevel()] * V, betas[node.getLevel()]);
}
return System.currentTimeMillis() - sTime;
}
private long updateParameters() {
if (verbose) {
logln("--- Optimizing regression parameters ...");
}
long sTime = System.currentTimeMillis();
ArrayList<SNode> flattenTree = flattenTreeWithoutRoot();
int numNodes = flattenTree.size();
double[] paramSigmas = new double[V + numNodes];
double[] paramMeans = new double[V + numNodes];
for (int v = 0; v < V; v++) {
paramMeans[v] = hyperparams.get(TAU_MEAN);
paramSigmas[v] = hyperparams.get(TAU_SIGMA);
}
HashMap<SNode, Integer> nodeIndices = new HashMap<SNode, Integer>();
for (int i = 0; i < flattenTree.size(); i++) {
SNode node = flattenTree.get(i);
nodeIndices.put(node, i);
paramSigmas[V + i] = sigmas[node.getLevel()];
paramMeans[V + i] = mus[node.getLevel()];
}
double[][] designMatrix = new double[D][V + numNodes];
for (int d = 0; d < D; d++) {
System.arraycopy(lexDesignMatrix[d], 0, designMatrix[d], 0, V);
double[] docTopicDist = new double[numNodes];
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
SNode[] path = getPathFromNode(c[d][s].getContent());
for (int l = 1; l < L; l++) {
int nodeIdx = nodeIndices.get(path[l]);
docTopicDist[nodeIdx] += (double) sentLevelCounts[d][s][l]
/ docWords[d].length;
}
}
for (int ii = 0; ii < numNodes; ii++) {
designMatrix[d][ii + V] += docTopicDist[ii] / docWords[d].length;
}
}
GurobiMLRL2Norm mlr = new GurobiMLRL2Norm(designMatrix, responses);
mlr.setSigmas(paramSigmas);
mlr.setMeans(paramMeans);
mlr.setRho(hyperparams.get(RHO));
double[] weights = mlr.solve();
System.arraycopy(weights, 0, lexParams, 0, V);
for (int i = 0; i < numNodes; i++) {
flattenTree.get(i).setRegressionParameter(weights[i + V]);
}
this.updateAuthorValues();
long etime = System.currentTimeMillis() - sTime;
return etime;
}
/**
* Get the observation counts per level of a sentence given the current
* token assignments.
*
* @param d The document index
* @param s The sentence index
*/
protected SparseCount[] getSentObsCountPerLevel(int d, int s) {
SparseCount[] counts = new SparseCount[L];
for (int ll = 0; ll < L; ll++) {
counts[ll] = new SparseCount();
}
for (int n = 0; n < words[d][s].length; n++) {
int type = words[d][s][n];
int level = z[d][s][n];
counts[level].increment(type);
}
return counts;
}
/**
* Check whether a given node is a leaf node.
*
* @param node The node
*/
boolean isLeafNode(SNode node) {
return node.getLevel() == L - 1;
}
/**
* Parse the node path string.
*
* @param nodePath The node path string
*/
public int[] parseNodePath(String nodePath) {
String[] ss = nodePath.split(":");
int[] parsedPath = new int[ss.length];
for (int i = 0; i < ss.length; i++) {
parsedPath[i] = Integer.parseInt(ss[i]);
}
return parsedPath;
}
/**
* Get a node in the tree given a parsed path
*
* @param parsedPath The parsed path
*/
private SNode getNode(int[] parsedPath) {
SNode node = globalTreeRoot;
for (int i = 1; i < parsedPath.length; i++) {
node = node.getChild(parsedPath[i]);
}
return node;
}
/**
* Get a list of node in the current tree without the root.
*/
ArrayList<SNode> flattenTreeWithoutRoot() {
ArrayList<SNode> flattenTree = new ArrayList<SNode>();
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
if (!node.isRoot()) {
flattenTree.add(node);
}
for (SNode child : node.getChildren()) {
stack.add(child);
}
}
return flattenTree;
}
/**
* Add a customer to a path. A path is specified by the pointer to its leaf
* node. If the given node is not a leaf node, an exception will be thrown.
* The number of customers at each node on the path will be incremented.
*
* @param leafNode The leaf node of the path
*/
void addTableToPath(SNode leafNode) {
SNode node = leafNode;
while (node != null) {
node.incrementNumTables();
node = node.getParent();
}
}
/**
* Remove a customer from a path. A path is specified by the pointer to its
* leaf node. The number of customers at each node on the path will be
* decremented. If the number of customers at a node is 0, the node will be
* removed.
*
* @param leafNode The leaf node of the path
* @return Return the node that specifies the path that the leaf node is
* removed from. If a lower-level node has no customer, it will be removed
* and the lowest parent node on the path that has non-zero number of
* customers will be returned.
*/
SNode removeTableFromPath(SNode leafNode) {
SNode retNode = leafNode;
SNode node = leafNode;
while (node != null) {
node.decrementNumTables();
if (node.isEmpty()) {
retNode = node.getParent();
node.getParent().removeChild(node.getIndex());
}
node = node.getParent();
}
return retNode;
}
/**
* Add a set of observations (given their level assignments) to a path
*
* @param leafNode The leaf node identifying the path
* @param observations The observations per level
*/
SNode[] addObservationsToPath(SNode leafNode, SparseCount[] observations) {
SNode[] path = getPathFromNode(leafNode);
for (int l = 0; l < L; l++) {
addObservationsToNode(path[l], observations[l]);
}
return path;
}
/**
* Add a set of observations to a node. This will (1) add the set of
* observations to the node's topic, and (2) add the token counts for
* switches from the root to the node.
*
* @param node The node
* @param observations The set of observations
*/
void addObservationsToNode(SNode node, SparseCount observations) {
for (int obs : observations.getIndices()) {
int count = observations.getCount(obs);
node.getContent().changeCount(obs, count);
}
}
/**
* Remove a set of observations (given their level assignments) from a path
*
* @param leafNode The leaf node identifying the path
* @param observations The observations per level
*/
SNode[] removeObservationsFromPath(SNode leafNode, SparseCount[] observations) {
SNode[] path = getPathFromNode(leafNode);
for (int l = 0; l < L; l++) {
removeObservationsFromNode(path[l], observations[l]);
}
return path;
}
/**
* Remove a set of observations from a node. This will (1) remove the set of
* observations from the node's topic, and (2) remove the token counts from
* the switches from the root to the node.
*
* @param node The node
* @param observations The set of observations
*/
void removeObservationsFromNode(SNode node, SparseCount observations) {
for (int obs : observations.getIndices()) {
int count = observations.getCount(obs);
node.getContent().changeCount(obs, -count);
}
}
/**
* Create a new path from an internal node.
*
* @param internalNode The internal node
*/
SNode createNewPath(SNode internalNode) {
SNode node = internalNode;
for (int l = internalNode.getLevel(); l < L - 1; l++) {
node = this.createNode(node);
}
return node;
}
/**
* Create a node given a parent node
*
* @param parent The parent node
*/
SNode createNode(SNode parent) {
int nextChildIndex = parent.getNextChildIndex();
int level = parent.getLevel() + 1;
DirMult dmm = new DirMult(V, betas[level] * V, uniform);
double regParam = SamplerUtils.getGaussian(mus[level], sigmas[level]);
SNode child = new SNode(iter, nextChildIndex, level, dmm, regParam, parent);
return parent.addChild(nextChildIndex, child);
}
@Override
public double getLogLikelihood() {
double wordLlh = 0.0;
double treeLogProb = 0.0;
double regParamLgprob = 0.0;
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
wordLlh += node.getLogProbability(node.getContent().getSparseCounts());
regParamLgprob += StatisticsUtils.logNormalProbability(node.getRegressionParameter(),
mus[node.getLevel()], Math.sqrt(sigmas[node.getLevel()]));
if (!isLeafNode(node)) {
treeLogProb += node.getLogJointProbability(gammas[node.getLevel()]);
}
for (SNode child : node.getChildren()) {
stack.add(child);
}
}
double levelLp = 0.0;
double restLgprob = 0.0;
for (int d = 0; d < D; d++) {
levelLp += docLevelDist[d].getLogLikelihood();
restLgprob += localRestaurants[d].getJointProbabilityAssignments(hyperparams.get(ALPHA));
}
double resLlh = 0.0;
if (responses != null) {
double[] regValues = getRegressionValues();
for (int d = 0; d < D; d++) {
resLlh += StatisticsUtils.logNormalProbability(responses[d],
regValues[d], sqrtRho);
}
}
logln("^^^ word-llh = " + MiscUtils.formatDouble(wordLlh)
+ ". tree = " + MiscUtils.formatDouble(treeLogProb)
+ ". rest = " + MiscUtils.formatDouble(restLgprob)
+ ". level = " + MiscUtils.formatDouble(levelLp)
+ ". reg param = " + MiscUtils.formatDouble(regParamLgprob)
+ ". response = " + MiscUtils.formatDouble(resLlh));
double llh = wordLlh + treeLogProb + levelLp + regParamLgprob + resLlh + restLgprob;
return llh;
}
@Override
public double getLogLikelihood(ArrayList<Double> tParams) {
throw new RuntimeException("Hyperparameter optimization is not supported");
}
@Override
public void updateHyperparameters(ArrayList<Double> tParams) {
throw new RuntimeException("Hyperparameter optimization is not supported");
}
@Override
public String getCurrentState() {
StringBuilder str = new StringBuilder();
str.append(printGlobalTreeSummary()).append("\n");
str.append(printLocalRestaurantSummary()).append("\n");
return str.toString();
}
@Override
public void output(File samplerFile) {
this.outputState(samplerFile.getAbsolutePath());
}
@Override
public void input(File samplerFile) {
this.inputModel(samplerFile.getAbsolutePath());
}
public void inputFinalModel() {
File reportFolder = new File(getSamplerFolderPath(), ReportFolder);
this.inputModel(new File(reportFolder, "iter-" + MAX_ITER + ".zip").getAbsolutePath());
}
@Override
public void outputState(String filepath) {
if (verbose) {
logln("--- Outputing current state to " + filepath + "\n");
}
try {
// model
StringBuilder modelStr = new StringBuilder();
for (int v = 0; v < V; v++) {
modelStr.append(lexParams[v]).append("\t");
}
modelStr.append("\n");
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
modelStr.append(node.getPathString()).append("\n");
modelStr.append(node.getIterationCreated()).append("\n");
modelStr.append(node.getNumTables()).append("\n");
modelStr.append(node.getRegressionParameter()).append("\n");
modelStr.append(DirMult.output(node.getContent())).append("\n");
modelStr.append(DirMult.outputDistribution(node.getContent().
getSamplingDistribution())).append("\n");
for (SNode child : node.getChildren()) {
stack.add(child);
}
}
// assignments
StringBuilder assignStr = new StringBuilder();
for (int d = 0; d < D; d++) {
assignStr.append(d)
.append("\t").append(localRestaurants[d].getNumTables())
.append("\n");
assignStr.append(DirMult.output(docLevelDist[d])).append("\n");
for (STable table : localRestaurants[d].getTables()) {
assignStr.append(table.getIndex()).append("\n");
assignStr.append(table.getIterationCreated()).append("\n");
assignStr.append(table.getContent().getPathString()).append("\n");
}
}
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
if (isValidSentence(d, s)) {
assignStr.append(d)
.append(":").append(s)
.append("\t").append(c[d][s].getIndex())
.append("\n");
}
}
}
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
if (isValidSentence(d, s)) {
for (int n = 0; n < words[d][s].length; n++) {
assignStr.append(d)
.append(":").append(s)
.append(":").append(n)
.append("\t").append(z[d][s][n])
.append("\n");
}
}
}
}
// output to a compressed file
this.outputZipFile(filepath, modelStr.toString(), assignStr.toString());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while outputing to " + filepath);
}
}
@Override
public void inputState(String filepath) {
if (verbose) {
logln("--- Reading state from " + filepath + "\n");
}
try {
inputModel(filepath);
inputAssignments(filepath);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
if (debug) {
validate("--- Loaded.");
}
}
void inputModel(String zipFilepath) {
if (verbose) {
logln("
}
try {
// initialize
this.initializeModelStructure();
String filename = IOUtils.removeExtension(IOUtils.getFilename(zipFilepath));
BufferedReader reader = IOUtils.getBufferedReader(zipFilepath, filename + ModelFileExt);
// lexical weights
String line = reader.readLine();
String[] sline = line.split("\t");
this.lexParams = new double[V];
for (int v = 0; v < V; v++) {
this.lexParams[v] = Double.parseDouble(sline[v]);
}
// topic tree
HashMap<String, SNode> nodeMap = new HashMap<String, SNode>();
while ((line = reader.readLine()) != null) {
String pathStr = line;
int iterCreated = Integer.parseInt(reader.readLine());
int numTables = Integer.parseInt(reader.readLine());
double regParam = Double.parseDouble(reader.readLine());
DirMult dmm = DirMult.input(reader.readLine());
double[] dist = DirMult.inputDistribution(reader.readLine());
dmm.setSamplingDistribution(dist);
// create node
int lastColonIndex = pathStr.lastIndexOf(":");
SNode parent = null;
if (lastColonIndex != -1) {
parent = nodeMap.get(pathStr.substring(0, lastColonIndex));
}
String[] pathIndices = pathStr.split(":");
int nodeIndex = Integer.parseInt(pathIndices[pathIndices.length - 1]);
int nodeLevel = pathIndices.length - 1;
SNode node = new SNode(iterCreated, nodeIndex,
nodeLevel, dmm, regParam, parent);
node.setTopic(dist);
node.changeNumTables(numTables);
if (node.getLevel() == 0) {
globalTreeRoot = node;
}
if (parent != null) {
parent.addChild(node.getIndex(), node);
}
nodeMap.put(pathStr, node);
}
reader.close();
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
if (!isLeafNode(node)) {
node.fillInactiveChildIndices();
for (SNode child : node.getChildren()) {
stack.add(child);
}
}
}
validateModel("Loading model " + filename);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while loading model from "
+ zipFilepath);
}
}
void inputAssignments(String zipFilepath) throws Exception {
if (verbose) {
logln("
}
// initialize
this.initializeDataStructure();
String filename = IOUtils.removeExtension(IOUtils.getFilename(zipFilepath));
BufferedReader reader = IOUtils.getBufferedReader(zipFilepath, filename + AssignmentFileExt);
String[] sline;
for (int d = 0; d < D; d++) {
sline = reader.readLine().split("\t");
if (d != Integer.parseInt(sline[0])) {
throw new RuntimeException("Mismatch. "
+ d + " vs. " + sline[0]);
}
int numTables = Integer.parseInt(sline[1]);
docLevelDist[d] = DirMult.input(reader.readLine());
for (int i = 0; i < numTables; i++) {
int tabIndex = Integer.parseInt(reader.readLine());
int iterCreated = Integer.parseInt(reader.readLine());
SNode leafNode = getNode(parseNodePath(reader.readLine()));
STable table = new STable(iterCreated, tabIndex, leafNode, d);
localRestaurants[d].addTable(table);
}
}
for (int d = 0; d < D; d++) {
localRestaurants[d].fillInactiveTableIndices();
}
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
sline = reader.readLine().split("\t");
if (!sline[0].equals(d + ":" + s)) {
throw new RuntimeException("Mismatch");
}
int tableIndex = Integer.parseInt(sline[1]);
STable table = localRestaurants[d].getTable(tableIndex);
c[d][s] = table;
localRestaurants[d].addCustomerToTable(s, tableIndex);
}
}
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
STable table = c[d][s];
SNode[] path = getPathFromNode(table.getContent());
for (int n = 0; n < words[d][s].length; n++) {
sline = reader.readLine().split("\t");
if (!sline[0].equals(d + ":" + s + ":" + n)) {
throw new RuntimeException("Mismatch. "
+ sline[0] + " vs. "
+ (d + ":" + s + ":" + n));
}
z[d][s][n] = Integer.parseInt(sline[1]);
path[z[d][s][n]].getContent().increment(words[d][s][n]);
sentLevelCounts[d][s][z[d][s][n]]++;
}
}
}
reader.close();
}
@Override
public void validate(String msg) {
logln("Validating ... " + msg);
validateModel(msg);
validateAssignments(msg);
}
protected void validateModel(String msg) {
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
if (!isLeafNode(node)) {
int childNumCusts = 0;
for (SNode child : node.getChildren()) {
childNumCusts += child.getNumTables();
stack.add(child);
}
if (childNumCusts != node.getNumTables()) {
throw new RuntimeException(msg + ". Numbers of customers mismatch. "
+ node.toString());
}
}
if (this.isLeafNode(node) && node.isEmpty()) {
throw new RuntimeException(msg + ". Leaf node " + node.toString()
+ " is empty");
}
}
}
protected void validateAssignments(String msg) {
// validate sentence assignments
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
if (words[d][s].length == 0) {
if (this.c[d][s] != NULL_TABLE) {
throw new RuntimeException("Assigning empty sentence to "
+ "a table. Sentence " + d + "-" + s + " is "
+ "assigned to " + this.c[d][s].toString());
}
}
}
}
for (int d = 0; d < D; d++) {
int totalCusts = 0;
for (STable table : localRestaurants[d].getTables()) {
totalCusts += table.getNumCustomers();
}
int numValidSentences = 0;
for (int s = 0; s < words[d].length; s++) {
if (isValidSentence(d, s)) {
numValidSentences++;
}
}
if (totalCusts != numValidSentences) {
for (STable table : localRestaurants[d].getTables()) {
System.out.println(table.toString() + ". customers: " + table.getCustomers().toString());
}
throw new RuntimeException(msg + ". Numbers of customers in restaurant " + d
+ " mismatch. " + totalCusts + " vs. " + words[d].length);
}
HashMap<STable, Integer> tableCustCounts = new HashMap<STable, Integer>();
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
Integer count = tableCustCounts.get(c[d][s]);
if (count == null) {
tableCustCounts.put(c[d][s], 1);
} else {
tableCustCounts.put(c[d][s], count + 1);
}
}
if (tableCustCounts.size() != localRestaurants[d].getNumTables()) {
throw new RuntimeException(msg + ". Numbers of tables mismatch in"
+ " restaurant " + d
+ ". " + tableCustCounts.size()
+ " vs. " + localRestaurants[d].getNumTables());
}
for (STable table : localRestaurants[d].getTables()) {
if (table.getNumCustomers() != tableCustCounts.get(table)) {
System.out.println("Table: " + table.toString());
for (int s : table.getCustomers()) {
System.out.println("--- s = " + s + ". " + c[d][s].toString());
}
System.out.println(tableCustCounts.get(table));
throw new RuntimeException(msg + ". Number of customers "
+ "mismatch. Table " + table.toString()
+ ". " + table.getNumCustomers() + " vs. " + tableCustCounts.get(table));
}
}
}
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
if (words[d][s].length != StatisticsUtils.sum(sentLevelCounts[d][s])) {
throw new RuntimeException("Counts mismatch. d = " + d
+ ". s = " + s
+ ". " + words[d][s].length
+ " vs. " + StatisticsUtils.sum(sentLevelCounts[d][s]));
}
}
}
for (int d = 0; d < D; d++) {
int[] levelCounts = new int[L];
for (STable table : localRestaurants[d].getTables()) {
for (int s : table.getCustomers()) {
for (int n = 0; n < words[d][s].length; n++) {
levelCounts[z[d][s][n]]++;
}
}
}
for (int ll = 0; ll < L; ll++) {
if (levelCounts[ll] != docLevelDist[d].getCount(ll)) {
throw new RuntimeException(msg + ". Counts mismatch."
+ " d = " + d
+ " level = " + ll
+ " " + levelCounts[ll]
+ " vs. " + docLevelDist[d].getCount(ll));
}
}
}
for (int d = 0; d < D; d++) {
int numNonEmptySentences = 0;
for (int s = 0; s < words[d].length; s++) {
if (words[d][s].length > 0) {
numNonEmptySentences++;
}
}
int numCustomers = localRestaurants[d].getTotalNumCustomers();
if (numCustomers != numNonEmptySentences) {
throw new RuntimeException(msg + ". Number of non-empty sentences"
+ " mismatch. " + numNonEmptySentences + " vs. "
+ numCustomers);
}
}
}
public String printGlobalTreeSummary() {
StringBuilder str = new StringBuilder();
int[] nodeCountPerLevel = new int[L];
int[] obsCountPerLevel = new int[L];
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
int totalObs = 0;
int numEmptyLeaves = 0;
while (!stack.isEmpty()) {
SNode node = stack.pop();
nodeCountPerLevel[node.getLevel()]++;
obsCountPerLevel[node.getLevel()] += node.getContent().getCountSum();
totalObs += node.getContent().getCountSum();
if (isLeafNode(node)
&& node.getContent().getSparseCounts().getCountSum() == 0) {
numEmptyLeaves++;
}
for (SNode child : node.getChildren()) {
stack.add(child);
}
}
str.append("global tree:\n\t>>> node count per level: ");
for (int l = 0; l < L; l++) {
str.append(l).append("(")
.append(nodeCountPerLevel[l])
.append(", ").append(obsCountPerLevel[l])
.append(", ").append(MiscUtils.formatDouble(
(double) obsCountPerLevel[l] / nodeCountPerLevel[l]))
.append(");\t");
}
str.append("\n");
str.append("\t>>> # observations = ").append(totalObs)
.append("\n\t>>> # customers = ").append(globalTreeRoot.getNumTables())
.append("\n\t>>> # empty leaves = ").append(numEmptyLeaves);
return str.toString();
}
public String printGlobalTree() {
StringBuilder str = new StringBuilder();
str.append("global tree\n");
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
int totalObs = 0;
while (!stack.isEmpty()) {
SNode node = stack.pop();
for (int i = 0; i < node.getLevel(); i++) {
str.append("\t");
}
str.append(node.toString())
.append("\n");
totalObs += node.getContent().getCountSum();
for (SNode child : node.getChildren()) {
stack.add(child);
}
}
str.append(">>> # observations = ").append(totalObs)
.append("\n>>> # customers = ").append(globalTreeRoot.getNumTables())
.append("\n");
return str.toString();
}
public String printLocalRestaurantSummary() {
StringBuilder str = new StringBuilder();
str.append("local restaurants:\n");
int[] numTables = new int[D];
int totalTableCusts = 0;
for (int d = 0; d < D; d++) {
numTables[d] = localRestaurants[d].getNumTables();
for (STable table : localRestaurants[d].getTables()) {
totalTableCusts += table.getNumCustomers();
}
}
str.append("\t>>> # tables:")
.append(". min: ").append(MiscUtils.formatDouble(StatisticsUtils.min(numTables)))
.append(". max: ").append(MiscUtils.formatDouble(StatisticsUtils.max(numTables)))
.append(". avg: ").append(MiscUtils.formatDouble(StatisticsUtils.mean(numTables)))
.append(". total: ").append(MiscUtils.formatDouble(StatisticsUtils.sum(numTables)))
.append("\n");
str.append("\t>>> # customers: ").append(totalTableCusts);
return str.toString();
}
public String printLocalRestaurants() {
StringBuilder str = new StringBuilder();
for (int d = 0; d < D; d++) {
logln("restaurant d = " + d
+ ". # tables: " + localRestaurants[d].getNumTables()
+ ". # total customers: " + localRestaurants[d].getTotalNumCustomers());
for (STable table : localRestaurants[d].getTables()) {
logln("--- table: " + table.toString());
}
System.out.println();
}
return str.toString();
}
public String printLocalRestaurant(int d) {
StringBuilder str = new StringBuilder();
str.append("restaurant d = ").append(d)
.append(". # tables: ").append(localRestaurants[d].getNumTables())
.append(". # total customers: ").append(localRestaurants[d]
.getTotalNumCustomers()).append("\n");
for (STable table : localRestaurants[d].getTables()) {
str.append("--- table: ").append(table.toString()).append("\n");
}
return str.toString();
}
public void outputLexicalParameters(File filepath) {
if (this.wordVocab == null) {
throw new RuntimeException("The word vocab has not been assigned yet");
}
if (verbose) {
logln("Outputing lexical weights to " + filepath);
}
ArrayList<RankingItem<Integer>> sortedWeights = new ArrayList<RankingItem<Integer>>();
for (int v = 0; v < V; v++) {
sortedWeights.add(new RankingItem<Integer>(v, lexParams[v]));
}
Collections.sort(sortedWeights);
try {
BufferedWriter writer = IOUtils.getBufferedWriter(filepath);
for (int v = 0; v < V; v++) {
RankingItem<Integer> rankItem = sortedWeights.get(v);
int lexIdx = rankItem.getObject();
writer.write(lexIdx
+ "\t" + this.wordVocab.get(lexIdx)
+ "\t" + this.lexParams[lexIdx]
+ "\n");
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while outputing lexical weights to "
+ filepath);
}
}
/**
* Output topic coherence
*
* @param file Output file
* @param topicCoherence Topic coherence
*/
public void outputTopicCoherence(
File file,
MimnoTopicCoherence topicCoherence) {
if (verbose) {
System.out.println("Outputing topic coherence to file " + file);
}
if (this.wordVocab == null) {
throw new RuntimeException("The word vocab has not been assigned yet");
}
try {
BufferedWriter writer = IOUtils.getBufferedWriter(file);
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
for (SNode child : node.getChildren()) {
stack.add(child);
}
double[] distribution = node.getTopic();
int[] topic = SamplerUtils.getSortedTopic(distribution);
double score = topicCoherence.getCoherenceScore(topic);
writer.write(node.getPathString()
+ "\t" + node.getLevel()
+ "\t" + node.getIterationCreated()
+ "\t" + node.getContent().getCountSum()
+ "\t" + score);
for (int i = 0; i < topicCoherence.getNumTokens(); i++) {
writer.write("\t" + this.wordVocab.get(topic[i]));
}
writer.write("\n");
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while outputing "
+ "topic coherence to " + file);
}
}
/**
* Output top words for each topic in the tree to text file.
*
* @param outputFile The output file
* @param numWords Number of top words
*/
public void outputTopicTopWords(File outputFile, int numWords) {
if (this.wordVocab == null) {
throw new RuntimeException("The word vocab has not been assigned yet");
}
if (verbose) {
logln("Outputing top words to file " + outputFile);
}
StringBuilder str = new StringBuilder();
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
ArrayList<RankingItem<SNode>> rankChildren = new ArrayList<RankingItem<SNode>>();
for (SNode child : node.getChildren()) {
rankChildren.add(new RankingItem<SNode>(child, child.getRegressionParameter()));
}
Collections.sort(rankChildren);
for (RankingItem<SNode> item : rankChildren) {
stack.add(item.getObject());
}
if (node.getIterationCreated() >= MAX_ITER - LAG) {
continue;
}
// debug
HashMap<Integer, Integer> cs = node.getContent().getObservations();
ArrayList<RankingItem<Integer>> ranks = new ArrayList<RankingItem<Integer>>();
for (int ii : cs.keySet()) {
ranks.add(new RankingItem<Integer>(ii, cs.get(ii)));
}
Collections.sort(ranks);
double[] nodeTopic = node.getTopic();
String[] topWords = getTopWords(nodeTopic, numWords);
for (int i = 0; i < node.getLevel(); i++) {
str.append(" ");
}
str.append(node.getPathString())
.append(" (").append(node.getIterationCreated())
.append("; t:").append(node.getNumTables())
.append("; o:").append(node.getContent().getCountSum())
.append("; ").append(MiscUtils.formatDouble(node.getRegressionParameter()))
.append(")");
for (String topWord : topWords) {
str.append(" ").append(topWord);
}
str.append("\n\n");
}
try {
BufferedWriter writer = IOUtils.getBufferedWriter(outputFile);
writer.write(str.toString());
writer.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while outputing topics "
+ outputFile);
}
}
public void outputHTML(
File htmlFile,
String[] docIds,
String[][] rawSentences,
int numSents,
int numWords,
String url) {
if (verbose) {
logln("--- Outputing result to HTML file " + htmlFile);
}
// rank sentences for each path
HashMap<SNode, ArrayList<RankingItem<String>>> pathRankSentMap = getRankingSentences();
StringBuilder str = new StringBuilder();
str.append("<!DOCTYPE html>\n<html>\n");
// header containing styles and javascript functions
str.append("<head>\n");
str.append("<link type=\"text/css\" rel=\"stylesheet\" "
+ "href=\"http://argviz.umiacs.umd.edu/teaparty/framing.css\">\n"); // style
str.append("<script type=\"text/javascript\" "
+ "src=\"http://argviz.umiacs.umd.edu/teaparty/framing.js\"></script>\n"); // script
str.append("</head>\n"); // end head
// start body
str.append("<body>\n");
str.append("<table>\n");
str.append("<tbody>\n");
Stack<SNode> stack = new Stack<SNode>();
stack.add(globalTreeRoot);
while (!stack.isEmpty()) {
SNode node = stack.pop();
ArrayList<RankingItem<SNode>> rankChildren = new ArrayList<RankingItem<SNode>>();
for (SNode child : node.getChildren()) {
rankChildren.add(new RankingItem<SNode>(child, child.getRegressionParameter()));
}
Collections.sort(rankChildren);
for (RankingItem<SNode> rankChild : rankChildren) {
stack.add(rankChild.getObject());
}
double[] nodeTopic = node.getTopic();
String[] topWords = getTopWords(nodeTopic, numWords);
if (node.getLevel() == 1) {
str.append("<tr class=\"level").append(node.getLevel()).append("\">\n");
str.append("<td>\n")
.append("[Topic ").append(node.getPathString())
.append("] ")
.append(" (")
.append(node.getNumChildren())
.append("; ").append(node.getNumTables())
.append("; ").append(node.getContent().getCountSum())
.append("; ").append(formatter.format(node.getRegressionParameter()))
.append(")");
for (String topWord : topWords) {
str.append(" ").append(topWord);
}
str.append("</td>\n");
str.append("</tr>\n");
} else if (node.getLevel() == 2) {
ArrayList<RankingItem<String>> rankSents = pathRankSentMap.get(node);
if (rankSents == null || rankSents.size() < 10) {
continue;
}
Collections.sort(rankSents);
// node info
str.append("<tr class=\"level").append(node.getLevel()).append("\">\n");
str.append("<td>\n")
.append("<a style=\"text-decoration:underline;color:blue;\" onclick=\"showme('")
.append(node.getPathString())
.append("');\" id=\"toggleDisplay\">")
.append("[")
.append(node.getPathString())
.append("]</a>")
.append(" (").append(node.getNumTables())
.append("; ").append(node.getContent().getCountSum())
.append("; ").append(formatter.format(node.getRegressionParameter()))
.append(")");
for (String topWord : topWords) {
str.append(" ").append(topWord);
}
str.append("</td>\n");
str.append("</tr>\n");
// sentences
str.append("<tr class=\"level").append(L).append("\"")
.append(" id=\"").append(node.getPathString()).append("\"")
.append(" style=\"display:none;\"")
.append(">\n");
str.append("<td>\n");
for (int ii = 0; ii < Math.min(numSents, rankSents.size()); ii++) {
RankingItem<String> sent = rankSents.get(ii);
int d = Integer.parseInt(sent.getObject().split("-")[0]);
int s = Integer.parseInt(sent.getObject().split("-")[1]);
String debateId = docIds[d].substring(0, docIds[d].indexOf("_"));
if (debateId.startsWith("pre-")) {
debateId = debateId.substring(4);
}
str.append("<a href=\"")
.append(url)
.append(debateId).append(".xml")
.append("\" ")
.append("target=\"_blank\">")
.append(docIds[d]).append("_").append(s)
.append("</a> ")
.append(rawSentences[d][s])
.append("<br/>\n");
str.append("</br>");
}
str.append("</td>\n</tr>\n");
}
}
str.append("</tbody>\n");
str.append("</table>\n");
str.append("</body>\n");
str.append("</html>");
// output to file
try {
BufferedWriter writer = IOUtils.getBufferedWriter(htmlFile);
writer.write(str.toString());
writer.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while outputing HTML to "
+ htmlFile);
}
}
private HashMap<SNode, ArrayList<RankingItem<String>>> getRankingSentences() {
HashMap<SNode, ArrayList<RankingItem<String>>> pathRankSentMap =
new HashMap<SNode, ArrayList<RankingItem<String>>>();
for (int d = 0; d < D; d++) {
for (STable table : localRestaurants[d].getTables()) {
SNode pathNode = table.getContent();
ArrayList<RankingItem<String>> rankSents = pathRankSentMap.get(pathNode);
if (rankSents == null) {
rankSents = new ArrayList<RankingItem<String>>();
}
for (int s : table.getCustomers()) {
if (words[d][s].length < 10) { // filter out too short sentences
continue;
}
double logprob = 0.0;
for (int n = 0; n < words[d][s].length; n++) {
if (z[d][s][n] == L - 1) {
logprob += pathNode.getLogProbability(words[d][s][n]);
}
}
if (logprob != 0) {
rankSents.add(new RankingItem<String>(d + "-" + s, logprob / words[d][s].length));
}
}
pathRankSentMap.put(pathNode, rankSents);
}
}
return pathRankSentMap;
}
protected void sampleNewDocuments(
File stateFile,
int[][][] newWords,
String outputResultFile) throws Exception {
if (verbose) {
System.out.println();
logln("Perform regression using model from " + stateFile);
logln("--- Test burn-in: " + this.testBurnIn);
logln("--- Test max-iter: " + this.testMaxIter);
logln("--- Test sample-lag: " + this.testSampleLag);
}
this.words = newWords;
this.responses = null;
this.D = this.words.length;
this.prepareDataStatistics();
if (verbose) {
logln("--- # documents:\t" + D);
logln("--- # tokens:\t" + tokenCount);
logln("--- # sentences:\t" + sentCount);
}
try {
inputModel(stateFile.getAbsolutePath());
// updateAverageTopicsPerLevel();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while loading model from "
+ stateFile);
}
// initialize structure for test data
initializeDataStructure();
if (verbose) {
logln("Initialized data structure");
logln(printGlobalTreeSummary());
logln(printLocalRestaurantSummary());
}
// initialize random assignments
initializeTestAssignments();
updateAuthorValues();
if (verbose) {
logln("Initialized random assignments");
logln(printGlobalTreeSummary());
logln(printLocalRestaurantSummary());
}
if (debug) {
validateAssignments("Initialized");
}
// iterate
ArrayList<double[]> predResponsesList = new ArrayList<double[]>();
for (iter = 0; iter < testMaxIter; iter++) {
double loglikelihood = getLogLikelihood();
if (verbose) {
String str = "Iter " + iter + "/" + testMaxIter
+ "\t llh = " + MiscUtils.formatDouble(loglikelihood)
+ "\n*** *** # sents change: " + numSentAsntsChange
+ " / " + sentCount
+ " (" + (double) numSentAsntsChange / sentCount + ")"
+ "\n*** *** # tables change: " + numTableAsgnsChange
+ " / " + globalTreeRoot.getNumTables()
+ " (" + (double) numTableAsgnsChange / globalTreeRoot.getNumTables() + ")"
+ "\n" + getCurrentState()
+ "\n";
if (iter < BURN_IN) {
logln("--- Burning in. " + str);
} else {
logln("--- Sampling. " + str);
}
}
numSentAsntsChange = 0;
for (int d = 0; d < D; d++) {
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
// if this document has only 1 sentence, no sampling is needed
if (words[d].length > 1) {
sampleSentenceAssignmentsExact(d, s, !REMOVE, !ADD,
REMOVE, ADD, !OBSERVED, !EXTEND);
}
}
// for (STable table : this.localRestaurants[d].getTables()) {
// samplePathForTable(d, table,
// !REMOVE, !ADD, REMOVE, ADD,
// !OBSERVED, !EXTEND);
}
updateAuthorValues();
if (verbose && iter % testSampleLag == 0) {
logln("--- iter = " + iter + " / " + testMaxIter);
}
if (iter >= testBurnIn && iter % testSampleLag == 0) {
double[] predResponses = getRegressionValues();
predResponsesList.add(predResponses);
}
if (responses != null) {
logln("--- iter = " + iter + " / " + testMaxIter);
double[] predResponses = getRegressionValues();
evaluateRegressPrediction(responses, predResponses);
}
}
// output result during test time
if (verbose) {
logln("--- Outputing result to " + outputResultFile);
}
PredictionUtils.outputSingleModelRegressions(
new File(outputResultFile),
predResponsesList);
}
private void initializeTestAssignments() {
for (int d = 0; d < D; d++) {
HashMap<SNode, STable> nodeTableMap = new HashMap<SNode, STable>();
for (int s = 0; s < words[d].length; s++) {
if (!isValidSentence(d, s)) {
continue;
}
SparseCount obs = new SparseCount();
for (int n = 0; n < words[d][s].length; n++) {
obs.increment(words[d][s][n]);
}
// recursively sample a node for this sentence
SNode leafNode = recurseNode(globalTreeRoot, obs);
STable table = nodeTableMap.get(leafNode);
if (table == null) {
int tabIdx = localRestaurants[d].getNextTableIndex();
table = new STable(iter, tabIdx, leafNode, d);
localRestaurants[d].addTable(table);
addTableToPath(leafNode);
nodeTableMap.put(leafNode, table);
}
localRestaurants[d].addCustomerToTable(s, table.getIndex());
c[d][s] = table;
// sample level for each token
SNode[] path = getPathFromNode(c[d][s].getContent());
for (int n = 0; n < words[d][s].length; n++) {
double[] logprobs = new double[L];
for (int ll = 0; ll < L; ll++) {
logprobs[ll] = docLevelDist[d].getLogLikelihood(ll)
+ path[ll].getLogProbability(words[d][s][n]);
}
int lvl = SamplerUtils.logMaxRescaleSample(logprobs);
z[d][s][n] = lvl;
sentLevelCounts[d][s][z[d][s][n]]++;
docLevelDist[d].increment(z[d][s][n]);
}
}
}
}
class SNode extends TopicTreeNode<SNode, DirMult> {
private final int born;
private int numTables;
private double regression;
SNode(int iter, int index, int level,
DirMult content,
double regParam,
SNode parent) {
super(index, level, content, parent);
this.born = iter;
this.numTables = 0;
this.regression = regParam;
}
public int getIterationCreated() {
return this.born;
}
/**
* Get the log probability of a set of observations given the topic at
* this node.
*
* @param obs The set of observations
*/
double getLogProbability(SparseCount obs) {
if (this.getTopic() == null) {
return this.content.getLogLikelihood(obs.getObservations());
} else {
double val = 0.0;
for (int o : obs.getIndices()) {
val += obs.getCount(o) * this.getLogProbability(o);
}
return val;
}
}
@Override
public double getLogProbability(int obs) {
return this.content.getLogLikelihood(obs);
}
double getLogJointProbability(double gamma) {
ArrayList<Integer> numChildrenCusts = new ArrayList<Integer>();
for (SNode child : this.getChildren()) {
numChildrenCusts.add(child.getNumTables());
}
return SamplerUtils.getAssignmentJointLogProbability(numChildrenCusts,
gamma);
}
double getRegressionParameter() {
return this.regression;
}
void setRegressionParameter(double reg) {
this.regression = reg;
}
int getNumTables() {
return this.numTables;
}
void decrementNumTables() {
this.numTables
}
void incrementNumTables() {
this.numTables++;
}
void changeNumTables(int delta) {
this.numTables += delta;
}
boolean isEmpty() {
return this.numTables == 0;
}
@Override
public void sampleTopic(double beta, double gamma) {
int V = content.getDimension();
double[] meanVector = new double[V];
Arrays.fill(meanVector, beta / V);
if (!this.isRoot()) { // root
double[] parentTopic = (parent.getContent()).getSamplingDistribution();
for (int v = 0; v < V; v++) {
meanVector[v] += parentTopic[v] * gamma;
}
}
SparseCount observations = this.content.getSparseCounts();
for (int obs : observations.getIndices()) {
meanVector[obs] += observations.getCount(obs);
}
for (int obs : this.pseudoCounts.getIndices()) {
meanVector[obs] += this.pseudoCounts.getCount(obs);
}
double[] ts = new double[V];
double sum = 0.0;
for (int v = 0; v < V; v++) {
ts[v] = randoms.nextGamma(meanVector[v], 1);
if (ts[v] <= 0) {
ts[v] = 0.001;
}
sum += ts[v];
}
// normalize
for (int v = 0; v < V; v++) {
ts[v] /= sum;
}
// Dirichlet dir = new Dirichlet(meanVector);
// double[] topic = dir.nextDistribution();
for (int v = 0; v < V; v++) {
if (ts[v] == 0) {
throw new RuntimeException("v: " + v
+ "\t" + ts[v]
+ "\t" + meanVector[v]
+ "\t" + sum);
}
}
this.setTopic(ts);
}
@Override
public void setTopic(double[] topic) {
this.content.setSamplingDistribution(topic);
this.logTopics = new double[topic.length];
for (int v = 0; v < topic.length; v++) {
this.logTopics[v] = Math.log(topic[v]);
}
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("[")
.append(getPathString())
.append(" (").append(born).append(")")
.append(" #ch = ").append(getNumChildren())
.append(", #c = ").append(getNumTables())
.append(", #o = ").append(getContent().getCountSum())
.append(", reg = ").append(MiscUtils.formatDouble(regression))
.append("]");
return str.toString();
}
void validate(String msg) {
int maxChildIndex = PSEUDO_NODE_INDEX;
for (SNode child : this.getChildren()) {
if (maxChildIndex < child.getIndex()) {
maxChildIndex = child.getIndex();
}
}
for (int i = 0; i < maxChildIndex; i++) {
if (!inactiveChildren.contains(i) && !isChild(i)) {
throw new RuntimeException(msg + ". Child inactive indices"
+ " have not been updated. Node: " + this.toString()
+ ". Index " + i + " is neither active nor inactive");
}
}
}
}
class STable extends FullTable<Integer, SNode> {
private final int born;
private final int restIndex;
public STable(int iter, int index,
SNode content, int restId) {
super(index, content);
this.born = iter;
this.restIndex = restId;
}
public int getRestaurantIndex() {
return this.restIndex;
}
public boolean containsCustomer(int c) {
return this.customers.contains(c);
}
public int getIterationCreated() {
return this.born;
}
public String getTableId() {
return restIndex + ":" + index;
}
@Override
public int hashCode() {
String hashCodeStr = getTableId();
return hashCodeStr.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if ((obj == null) || (this.getClass() != obj.getClass())) {
return false;
}
STable r = (STable) (obj);
return r.index == this.index
&& r.restIndex == this.restIndex;
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("[")
.append(getTableId())
.append(", ").append(born)
.append(", ").append(getNumCustomers())
.append("]")
.append(" >> ").append(getContent() == null ? "null" : getContent().toString());
return str.toString();
}
}
/**
* Run Gibbs sampling on test data using multiple models learned which are
* stored in the ReportFolder. The runs on multiple models are parallel.
*
* @param newWords Words of new documents
* @param newAuthors Authors of new documents
* @param numAuthors Number of authors in the test data
* @param iterPredFolder Output folder
* @param sampler The configured sampler
*/
// public static void parallelTest(int[][][] newWords, int[] newAuthors, int numAuthors,
// File iterPredFolder, AuthorSHLDA_MH sampler) {
// File reportFolder = new File(sampler.getSamplerFolderPath(), ReportFolder);
// if (!reportFolder.exists()) {
// throw new RuntimeException("Report folder not found. " + reportFolder);
// // debug
// System.out.println("# new docs: " + newWords.length);
// System.out.println("# new authors: " + newAuthors.length);
// System.out.println("# new authors: " + numAuthors);
// String[] filenames = reportFolder.list();
// try {
// IOUtils.createFolder(iterPredFolder);
// ArrayList<Thread> threads = new ArrayList<Thread>();
// for (int i = 0; i < filenames.length; i++) {
// String filename = filenames[i];
// if (!filename.contains("zip")) {
// continue;
// File stateFile = new File(reportFolder, filename);
// File partialResultFile = new File(iterPredFolder,
// IOUtils.removeExtension(filename) + ".txt");
// AuthorSHLDAMHTestRunner runner = new AuthorSHLDAMHTestRunner(sampler,
// newWords, newAuthors,
// numAuthors, stateFile.getAbsolutePath(),
// partialResultFile.getAbsolutePath());
// Thread thread = new Thread(runner);
// threads.add(thread);
// // run MAX_NUM_PARALLEL_THREADS threads at a time
// runThreads(threads);
// } catch (Exception e) {
// e.printStackTrace();
// throw new RuntimeException("Exception while sampling during parallel test.");
public static void main(String[] args) {
run(args);
}
public static String getHelpString() {
return "java -cp dist/segan.jar " + SHLDA.class.getName() + " -help";
}
private static void addOptions() {
// directories
addOption("output", "Output folder");
addOption("dataset", "Dataset");
addOption("data-folder", "Processed data folder");
addOption("format-folder", "Folder holding formatted data");
addOption("format-file", "Format file");
// sampler configurations
addOption("burnIn", "Burn-in");
addOption("maxIter", "Maximum number of iterations");
addOption("sampleLag", "Sample lag");
addOption("report", "Report interval.");
addOption("seeded-asgn-file", "Directory of file containing the "
+ "seeded assignments.");
// hyperparameters
addOption("T", "Lexical regression regularizer");
addOption("init-branch-factor", "Initial branching factors at each level. "
+ "The length of this array should be equal to L-1 (where L "
+ "is the number of levels in the tree).");
addOption("num-topics", "Number of topics for initialization");
addOption("num-frames", "Number of frames per-topic for initialization");
addOption("gem-mean", "GEM mean. [0.5]");
addOption("gem-scale", "GEM scale. [50]");
addOption("betas", "Dirichlet hyperparameter for topic distributions."
+ " [1, 0.5, 0.25] for a 3-level tree.");
addOption("gammas", "DP hyperparameters. [1.0, 1.0] for a 3-level tree");
addOption("mus", "Prior means for topic regression parameters."
+ " [0.0, 0.0, 0.0] for a 3-level tree and standardized"
+ " response variable.");
addOption("sigmas", "Prior variances for topic regression parameters."
+ " [0.0001, 0.5, 1.0] for a 3-level tree and stadardized"
+ " response variable.");
addOption("rho", "Prior variance for response variable. [1.0]");
addOption("tau-mean", "Prior mean of lexical regression parameters. [0.0]");
addOption("tau-scale", "Prior scale of lexical regression parameters. [1.0]");
addOption("num-lex-items", "Number of non-zero lexical regression parameters."
+ " Defaule: vocabulary size.");
// cross validation
addOption("cv-folder", "Cross validation folder");
addOption("num-folds", "Number of folds");
addOption("fold", "The cross-validation fold to run");
addOption("run-mode", "Running mode");
options.addOption("paramOpt", false, "Whether hyperparameter "
+ "optimization using slice sampling is performed");
options.addOption("z", false, "whether standardize (z-score normalization)");
options.addOption("v", false, "verbose");
options.addOption("d", false, "debug");
options.addOption("help", false, "Help");
options.addOption("train", false, "train");
options.addOption("dev", false, "development");
options.addOption("test", false, "test");
options.addOption("z", false, "z-normalization");
addOption("prediction-folder", "Prediction folder");
addOption("evaluation-folder", "Evaluation folder");
}
public static void run(String[] args) {
try {
parser = new BasicParser(); // create the command line parser
options = new Options(); // create the Options
addOptions();
cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
CLIUtils.printHelp(getHelpString(), options);
return;
}
if (cmd.hasOption("cv-folder")) {
runCrossValidation();
} else {
runModel();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Use option -help for all options.");
}
}
private static void runModel() throws Exception {
// sampling configurations
int numTopWords = CLIUtils.getIntegerArgument(cmd, "numTopwords", 20);
int burnIn = CLIUtils.getIntegerArgument(cmd, "burnIn", 5);
int maxIters = CLIUtils.getIntegerArgument(cmd, "maxIter", 10);
int sampleLag = CLIUtils.getIntegerArgument(cmd, "sampleLag", 5);
int repInterval = CLIUtils.getIntegerArgument(cmd, "report", 1);
boolean paramOpt = cmd.hasOption("paramOpt");
boolean verbose = cmd.hasOption("v");
boolean debug = cmd.hasOption("d");
// directories
String datasetName = CLIUtils.getStringArgument(cmd, "dataset", "amazon-data");
String datasetFolder = CLIUtils.getStringArgument(cmd, "data-folder",
"demo");
String resultFolder = CLIUtils.getStringArgument(cmd, "output",
"demo/amazon-data/format-response/model");
String formatFolder = CLIUtils.getStringArgument(cmd, "format-folder", "format-response");
String formatFile = CLIUtils.getStringArgument(cmd, "format-file", datasetName);
if (verbose) {
System.out.println("\nLoading formatted data ...");
}
ResponseTextDataset data = new ResponseTextDataset(datasetName, datasetFolder);
data.setFormatFilename(formatFile);
data.loadFormattedData(new File(data.getDatasetFolderPath(), formatFolder));
if (cmd.hasOption("topic-coherence")) {
data.prepareTopicCoherence(numTopWords);
}
if (cmd.hasOption("z")) {
data.zNormalize();
} else {
System.out.println("[WARNING] Running with unnormalized responses.");
}
// parameters
int L = CLIUtils.getIntegerArgument(cmd, "tree-height", 3);
double[] defaultPis = new double[L];
for (int ii = 0; ii < L; ii++) {
defaultPis[ii] = 1000 / 3;
}
double[] pis = CLIUtils.getDoubleArrayArgument(cmd, "pis", defaultPis, ",");
double[] defaultBetas = new double[L];
defaultBetas[0] = 1;
for (int i = 1; i < L; i++) {
defaultBetas[i] = 1.0 / (i + 1);
}
double[] betas = CLIUtils.getDoubleArrayArgument(cmd, "betas", defaultBetas, ",");
double[] defaultGammas = new double[L - 1];
for (int i = 0; i < defaultGammas.length; i++) {
defaultGammas[i] = 1.0 / (i + 1);
}
double[] gammas = CLIUtils.getDoubleArrayArgument(cmd, "gammas", defaultGammas, ",");
InitialState initState = InitialState.PRESET;
double[] defaultMus = new double[L];
for (int i = 0; i < L; i++) {
defaultMus[i] = 0.0;
}
double[] mus = CLIUtils.getDoubleArrayArgument(cmd, "mus", defaultMus, ",");
double[] defaultSigmas = new double[L];
defaultSigmas[0] = 0.0001; // root node
defaultSigmas[1] = 50;
defaultSigmas[2] = 250;
double[] sigmas = CLIUtils.getDoubleArrayArgument(cmd, "sigmas", defaultSigmas, ",");
double tau_mean = CLIUtils.getDoubleArgument(cmd, "tau-mean", 0.0);
double tau_scale = CLIUtils.getDoubleArgument(cmd, "tau-sigma", 1000);
double alpha = CLIUtils.getDoubleArgument(cmd, "alpha", 1.0);
double rho = CLIUtils.getDoubleArgument(cmd, "rho", 5);
// initialization
String branchFactorStr = CLIUtils.getStringArgument(cmd,
"init-branch-factor", "16-3");
String[] sstr = branchFactorStr.split("-");
int[] branch = new int[sstr.length];
for (int ii = 0; ii < branch.length; ii++) {
branch[ii] = Integer.parseInt(sstr[ii]);
}
SHLDA sampler = new SHLDA();
sampler.setVerbose(verbose);
sampler.setDebug(debug);
sampler.setLog(true);
sampler.setReport(true);
sampler.setWordVocab(data.getWordVocab());
String seededAsgnFile = cmd.getOptionValue("seeded-asgn-file");
sampler.setSeededAssignmentFile(seededAsgnFile);
initState = InitialState.SEEDED;
sampler.configure(resultFolder,
data.getWordVocab().size(), L,
alpha,
rho,
tau_mean, tau_scale,
betas, gammas,
mus, sigmas,
pis,
branch,
initState,
PathAssumption.MAXIMAL,
paramOpt,
burnIn, maxIters, sampleLag, repInterval);
File samplerFolder = new File(resultFolder, sampler.getSamplerFolder());
IOUtils.createFolder(samplerFolder);
// train
if (cmd.hasOption("train")) {
sampler.train(data.getSentenceWords(), data.getResponses());
sampler.initialize();
sampler.iterate();
sampler.outputTopicTopWords(new File(samplerFolder, TopWordFile), numTopWords);
}
if (cmd.hasOption("test")) {
File predictionFolder = new File(sampler.getSamplerFolderPath(),
CLIUtils.getStringArgument(cmd, "prediction-folder", "predictions"));
IOUtils.createFolder(predictionFolder);
File evaluationFolder = new File(sampler.getSamplerFolderPath(),
CLIUtils.getStringArgument(cmd, "evaluation-folder", "evaluations"));
IOUtils.createFolder(evaluationFolder);
// test in parallel
sampler.test(data);
double[] predictions = PredictionUtils.evaluateRegression(
predictionFolder, evaluationFolder, data.getDocIds(),
data.getResponses());
PredictionUtils.outputRegressionPredictions(
new File(predictionFolder,
AbstractExperiment.PREDICTION_FILE),
data.getDocIds(), data.getResponses(), predictions);
PredictionUtils.outputRegressionResults(
new File(evaluationFolder,
AbstractExperiment.RESULT_FILE), data.getResponses(),
predictions);
}
}
private static void runCrossValidation() throws Exception {
}
}
|
package org.wiztools.restclient.ui;
import java.io.File;
import javax.swing.Icon;
import javax.swing.filechooser.FileView;
import org.wiztools.restclient.FileType;
/**
*
* @author Subhash
*/
public class RCFileView extends FileView {
@Override
public String getTypeDescription(final File f){
final String type = FileType.getType(f);
switch (type) {
case FileType.REQUEST_EXT:
return "Request";
case FileType.RESPONSE_EXT:
return "Response";
case FileType.ARCHIVE_EXT:
return "Archive";
}
return null;
}
public static final String iconBasePath = "org/wiztools/restclient/";
public static final Icon FOLDER_ICON = UIUtil.getIconFromClasspath(iconBasePath + "fv_folder.png");
public static final Icon FILE_ICON = UIUtil.getIconFromClasspath(iconBasePath + "fv_file.png");
public static final Icon REQUEST_ICON = UIUtil.getIconFromClasspath(iconBasePath + "fv_request.png");
public static final Icon RESPONSE_ICON = UIUtil.getIconFromClasspath(iconBasePath + "fv_response.png");
public static final Icon ARCHIVE_ICON = UIUtil.getIconFromClasspath(iconBasePath + "fv_archive.png");
@Override
public Icon getIcon(final File f){
Icon icon;
String type = FileType.getType(f);
if(f.isDirectory()){
icon = FOLDER_ICON;
}
else if(FileType.REQUEST_EXT.equals(type)){
icon = REQUEST_ICON;
}
else if(FileType.RESPONSE_EXT.equals(type)){
icon = RESPONSE_ICON;
}
else if(FileType.ARCHIVE_EXT.equals(type)){
icon = ARCHIVE_ICON;
}
else{
icon = FILE_ICON;
}
return icon;
}
}
|
package org.revapi.maven;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
/**
* @author Lukas Krejci
* @since 0.7.0
*/
@Mojo(name = "report-fork", defaultPhase = LifecyclePhase.SITE,
requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME)
@Execute(phase = LifecyclePhase.PACKAGE)
public class ReportForkMojo extends ReportMojo {
}
|
package rslingo.rslil.ui.handlers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.xtext.ui.resource.IResourceSetProvider;
import com.google.inject.Inject;
import rslingo.rslil.rSLIL.Date;
import rslingo.rslil.rSLIL.GlossaryTerm;
import rslingo.rslil.rSLIL.PackageProject;
import rslingo.rslil.rSLIL.PackageSystem;
import rslingo.rslil.rSLIL.Project;
import rslingo.rslil.rSLIL.Stakeholder;
import rslingo.rslil.rSLIL.SystemRelation;
import rslingo.rslil.rSLIL.TermType;
import rslingo.rslil.ui.windows.MenuCommand;
import rslingo.rslil.ui.windows.MenuCommandWindow;
public class ExportExcelHandler extends AbstractHandler {
private static final String PLUGIN_ID = "rslingo.rslil";
private static final String GEN_FOLDER = "src-gen";
private static final String DOCS_FOLDER = "docs";
private static final String FILE_EXT = ".rslil";
private static final String DEF_WORD_PATH = "RSL-IL-ExcelTemplate.xlsx";
private final String RSLINGO_PATH = Platform.getInstallLocation()
.getURL().getPath().substring(1)
+ "RSLingo/";
@Inject
IResourceSetProvider resourceSetProvider;
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow workbenchWindow = HandlerUtil.getActiveWorkbenchWindowChecked(event);
Shell shell = workbenchWindow.getShell();
ISelection selection = HandlerUtil.getActiveMenuSelection(event);
// Check if the command was triggered using the ContextMenu
if (selection != null) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
IFile file = (IFile) structuredSelection.getFirstElement();
generateExcel(file, shell);
} else {
IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
IFile file = (IFile) activeEditor.getEditorInput().getAdapter(IFile.class);
generateExcel(file, shell);
}
} else {
MenuCommand cmd = new MenuCommand() {
@Override
public void execute(IProject project, IFile file) {
generateExcel(file, shell);
}
};
MenuCommandWindow window = new MenuCommandWindow(shell, cmd, false, FILE_EXT);
window.open();
}
return null;
}
private void generateExcel(IFile file, Shell shell) {
IProject project = file.getProject();
IFolder srcGenFolder = project.getFolder(GEN_FOLDER);
try {
if (!srcGenFolder.exists()) {
srcGenFolder.create(true, true, new NullProgressMonitor());
}
IFolder docsFolder = srcGenFolder.getFolder(DOCS_FOLDER);
if (!docsFolder.exists()) {
docsFolder.create(true, true, new NullProgressMonitor());
}
} catch (Exception e) {
e.printStackTrace();
}
// Start a new Thread to avoid blocking the UI
Job job = new Job("Exporting to Excel...") {
@Override
protected IStatus run(IProgressMonitor monitor) {
URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
//URI.createURI("platform:/resource/rslingo.rslil/src/example.rslil"), true);
ResourceSet resourceSet = resourceSetProvider.get(project);
Resource resource = resourceSet.getResource(uri, true);
if (resource.getContents().get(0) instanceof PackageProject) {
PackageProject packageProj = (PackageProject) resource.getContents().get(0);
// Deal with the Main file mode
if (packageProj.getImports().size() > 0
&& packageProj.getPackageSystems().size() == 0) {
packageProj = DocumentHelper.getFullPackageProject(project, resourceSet, packageProj);
}
try {
InputStream from = new FileInputStream(RSLINGO_PATH + DEF_WORD_PATH);
XSSFWorkbook workbook = new XSSFWorkbook(from);
// TODO: Write Sheets
writeProject(packageProj.getProject(), workbook);
writeSystems(packageProj, workbook);
writeSystemRelations(packageProj, workbook);
writeGlossary(packageProj, workbook);
writeStakeholders(packageProj, workbook);
// Write the Document in file system
String fileName = file.getName().split(FILE_EXT)[0];
File to = new File(project.getLocation().toOSString()
+ "/" + GEN_FOLDER + "/" + DOCS_FOLDER
+ "/" + fileName + ".xlsx");
FileOutputStream out = new FileOutputStream(to);
workbook.write(out);
out.close();
workbook.close();
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
System.out.println(fileName + ".xlsx generated!");
} catch (Exception e) {
return new Status(Status.ERROR, PLUGIN_ID, e.getMessage(), e);
}
return Status.OK_STATUS;
} else {
shell.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
String message = "You should run this command using the Main file associated to this file!";
MessageDialog errorDialog = new MessageDialog(shell, "RSLingo Studio",
null, message, MessageDialog.ERROR, new String[] { "OK" }, 0);
errorDialog.open();
}
});
return Status.OK_STATUS;
}
}
};
job.setUser(true);
job.schedule();
}
private void writeProject(Project project, XSSFWorkbook workbook) {
XSSFSheet sheet = workbook.getSheet("project");
XSSFRow rowId = (XSSFRow) DocumentHelper.getCell(sheet, "PPID").getRow();
DocumentHelper.replaceText(rowId, "PPID", project.getName());
XSSFRow rowName = (XSSFRow) DocumentHelper.getCell(sheet, "PNAME").getRow();
if (project.getNameAlias() != null) {
DocumentHelper.replaceText(rowName, "PNAME", project.getNameAlias());
} else {
DocumentHelper.replaceText(rowName, "PNAME", "");
}
XSSFRow rowType = (XSSFRow) DocumentHelper.getCell(sheet, "PTYPE").getRow();
DocumentHelper.replaceText(rowType, "PTYPE", project.getType());
XSSFRow rowDomain = (XSSFRow) DocumentHelper.getCell(sheet, "PDOMAIN").getRow();
DocumentHelper.replaceText(rowDomain, "PDOMAIN", project.getDomain());
Cell cellPStart = DocumentHelper.getCell(sheet, "PPSTART");
Cell cellPEnd = DocumentHelper.getCell(sheet, "PPEND");
if (project.getPlanned() != null) {
setDateCell(project.getPlanned().getStart(), workbook, cellPStart);
setDateCell(project.getPlanned().getEnd(), workbook, cellPEnd);
} else {
cellPStart.setCellValue("");
cellPEnd.setCellValue("");
}
Cell cellAStart = DocumentHelper.getCell(sheet, "PASTART");
Cell cellAEnd = DocumentHelper.getCell(sheet, "PAEND");
if (project.getActual() != null) {
// Set Date cell and apply style
if (project.getActual().getEnd() != null) {
} else {
cellAEnd.setCellValue("");
}
} else {
cellAStart.setCellValue("");
cellAEnd.setCellValue("");
}
XSSFRow rowCustomer = (XSSFRow) DocumentHelper.getCell(sheet, "PCUSTOMER").getRow();
XSSFRow rowSupplier = (XSSFRow) DocumentHelper.getCell(sheet, "PSUPPLIER").getRow();
XSSFRow rowPartners = (XSSFRow) DocumentHelper.getCell(sheet, "PPARTNERS").getRow();
if (project.getOrganizations() != null) {
DocumentHelper.replaceText(rowCustomer, "PCUSTOMER", "");
DocumentHelper.replaceText(rowSupplier, "PSUPPLIER", "");
DocumentHelper.replaceText(rowPartners, "PPARTNERS", "");
} else {
DocumentHelper.replaceText(rowCustomer, "PCUSTOMER", project.getProgress().getValue());
DocumentHelper.replaceText(rowSupplier, "PSUPPLIER", project.getProgress().getValue());
DocumentHelper.replaceText(rowPartners, "PPARTNERS", project.getOrganizations().getPartners());
}
XSSFRow rowProgress = (XSSFRow) DocumentHelper.getCell(sheet, "PPROGRESS").getRow();
if (project.getProgress() != null) {
DocumentHelper.replaceText(rowProgress, "PPROGRESS", project.getProgress().getValue());
} else {
DocumentHelper.replaceText(rowProgress, "PPROGRESS", "");
}
XSSFRow rowSummary = (XSSFRow) DocumentHelper.getCell(sheet, "PSUMMARY").getRow();
DocumentHelper.replaceText(rowSummary, "PSUMMARY", project.getSummary());
XSSFRow rowDescription = (XSSFRow) DocumentHelper.getCell(sheet, "PDESCRIPTION").getRow();
DocumentHelper.replaceText(rowDescription, "PDESCRIPTION", project.getDescription());
// Delete the Template Row
// XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "PPID").getRow();
// sheet.shiftRows(tRow.getRowNum() + 1, sheet.getLastRowNum(), -1);
}
private void writeSystems(PackageProject project, XSSFWorkbook workbook) {
XSSFSheet sheet = workbook.getSheet("systems");
XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "SID").getRow();
for (PackageSystem packageSystem : project.getPackageSystems()) {
XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1);
DocumentHelper.cloneRow(workbook, sheet, nRow, tRow);
rslingo.rslil.rSLIL.System system = packageSystem.getSystem();
DocumentHelper.replaceText(nRow, "SID", system.getName());
if (system.getNameAlias() != null) {
DocumentHelper.replaceText(nRow, "SNAME", system.getNameAlias());
} else {
DocumentHelper.replaceText(nRow, "SNAME", "");
}
if (system.getDescription() != null) {
DocumentHelper.replaceText(nRow, "SDESCRIPTION", system.getDescription());
} else {
DocumentHelper.replaceText(nRow, "SDESCRIPTION", "");
}
DocumentHelper.replaceText(nRow, "STYPE", system.getType());
DocumentHelper.replaceText(nRow, "SSCOPE", system.getScope());
if (system.getPartOf() != null) {
DocumentHelper.replaceText(nRow, "SPARTOF", system.getPartOf().getName());
} else {
DocumentHelper.replaceText(nRow, "SPARTOF", "");
}
}
// Delete the Template Row
sheet.shiftRows(tRow.getRowNum() + 1, sheet.getLastRowNum(), -1);
}
private void writeSystemRelations(PackageProject project, XSSFWorkbook workbook) {
XSSFSheet sheet = workbook.getSheet("systems.relations");
XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "SRSOURCE").getRow();
for (SystemRelation relation : project.getSystemRelations()) {
XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1);
DocumentHelper.cloneRow(workbook, sheet, nRow, tRow);
DocumentHelper.replaceText(nRow, "SRSOURCE", relation.getSource().getName());
DocumentHelper.replaceText(nRow, "SRTARGET", relation.getTarget().getName());
DocumentHelper.replaceText(nRow, "SRCATEGORY", relation.getCategory());
DocumentHelper.replaceText(nRow, "SRTYPE", relation.getType());
if (relation.getDescription() != null) {
DocumentHelper.replaceText(nRow, "SRDESCRIPTION", relation.getDescription());
} else {
DocumentHelper.replaceText(nRow, "SRDESCRIPTION", "");
}
}
// Delete the Template Row
sheet.shiftRows(tRow.getRowNum() + 1, sheet.getLastRowNum(), -1);
}
private void writeGlossary(PackageProject project, XSSFWorkbook workbook) {
XSSFSheet sheet = workbook.getSheet("glossary");
XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "GTID").getRow();
for (GlossaryTerm term : project.getGlossaryTerms()) {
XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1);
DocumentHelper.cloneRow(workbook, sheet, nRow, tRow);
DocumentHelper.replaceText(nRow, "GTID", term.getName());
if (term.getNameAlias() != null) {
DocumentHelper.replaceText(nRow, "GTNAME", term.getNameAlias());
} else {
DocumentHelper.replaceText(nRow, "GTNAME", "");
}
if (term.getDescription() != null) {
DocumentHelper.replaceText(nRow, "GTDESCRIPTION", term.getDescription());
} else {
DocumentHelper.replaceText(nRow, "GTDESCRIPTION", "");
}
String type = term.getType().getRefType().getType();
for (TermType termType : term.getType().getRefs()) {
type += "; " + termType.getType();
}
DocumentHelper.replaceText(nRow, "GTTYPE", type);
if (term.getAcronym() != null) {
DocumentHelper.replaceText(nRow, "GTACRONYM", term.getAcronym());
} else {
DocumentHelper.replaceText(nRow, "GTACRONYM", "");
}
if (term.getPos() != null) {
DocumentHelper.replaceText(nRow, "GTPOS", term.getPos());
} else {
DocumentHelper.replaceText(nRow, "GTPOS", "");
}
if (term.getSynonym() != null) {
DocumentHelper.replaceText(nRow, "GTSYNONYM", term.getSynonym());
} else {
DocumentHelper.replaceText(nRow, "GTSYNONYM", "");
}
if (term.getHypernym() != null) {
DocumentHelper.replaceText(nRow, "GTHYPERNYM", term.getHypernym());
} else {
DocumentHelper.replaceText(nRow, "GTHYPERNYM", "");
}
}
// Delete the Template Row
sheet.shiftRows(tRow.getRowNum() + 1, sheet.getLastRowNum(), -1);
}
private void writeStakeholders(PackageProject project, XSSFWorkbook workbook) {
XSSFSheet sheet = workbook.getSheet("stakeholders");
XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "STKID").getRow();
for (Stakeholder stakeholder : project.getStakeholders()) {
XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1);
DocumentHelper.cloneRow(workbook, sheet, nRow, tRow);
DocumentHelper.replaceText(nRow, "STKID", stakeholder.getName());
if (stakeholder.getNameAlias() != null) {
DocumentHelper.replaceText(nRow, "STKNAME", stakeholder.getNameAlias());
} else {
DocumentHelper.replaceText(nRow, "STKNAME", "");
}
if (stakeholder.getDescription() != null) {
DocumentHelper.replaceText(nRow, "STKDESCRIPTION", stakeholder.getDescription());
} else {
DocumentHelper.replaceText(nRow, "STKDESCRIPTION", "");
}
DocumentHelper.replaceText(nRow, "STKTYPE", stakeholder.getType());
DocumentHelper.replaceText(nRow, "STKCATEGORY", stakeholder.getCategory());
if (stakeholder.getIsA() != null) {
DocumentHelper.replaceText(nRow, "STKISA", stakeholder.getIsA().getName());
} else {
DocumentHelper.replaceText(nRow, "STKISA", "");
}
if (stakeholder.getPartOf() != null) {
DocumentHelper.replaceText(nRow, "STKPARTOF", stakeholder.getPartOf().getName());
} else {
DocumentHelper.replaceText(nRow, "STKPARTOF", "");
}
}
// Delete the Template Row
sheet.shiftRows(tRow.getRowNum() + 1, sheet.getLastRowNum(), -1);
}
private void setDateCell(Date date, XSSFWorkbook workbook, Cell cellDate) {
String dateVal = date.getDay() + "-"
+ DocumentHelper.getNumberOfRSLILMonth(date.getMonth().getName())
+ "-" + date.getYear();
XSSFCreationHelper createHelper = workbook.getCreationHelper();
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-mmm-yyyy"));
cellDate.setCellValue(DocumentHelper.parseDate(dateVal));
cellDate.setCellStyle(cellStyle);
}
}
|
package com.taobao.zeus.schedule.mvc;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import com.taobao.zeus.client.ZeusException;
import com.taobao.zeus.jobs.JobContext;
import com.taobao.zeus.jobs.sub.tool.CancelHadoopJob;
import com.taobao.zeus.model.JobDescriptor;
import com.taobao.zeus.model.JobDescriptor.JobScheduleType;
import com.taobao.zeus.model.JobHistory;
import com.taobao.zeus.model.JobStatus;
import com.taobao.zeus.model.JobStatus.Status;
import com.taobao.zeus.model.JobStatus.TriggerType;
import com.taobao.zeus.mvc.AppEvent;
import com.taobao.zeus.mvc.Controller;
import com.taobao.zeus.mvc.Dispatcher;
import com.taobao.zeus.schedule.hsf.CacheJobDescriptor;
import com.taobao.zeus.schedule.mvc.event.Events;
import com.taobao.zeus.schedule.mvc.event.JobFailedEvent;
import com.taobao.zeus.schedule.mvc.event.JobLostEvent;
import com.taobao.zeus.schedule.mvc.event.JobMaintenanceEvent;
import com.taobao.zeus.schedule.mvc.event.JobSuccessEvent;
import com.taobao.zeus.schedule.mvc.event.ScheduleTriggerEvent;
import com.taobao.zeus.socket.master.Master;
import com.taobao.zeus.socket.master.MasterContext;
import com.taobao.zeus.store.GroupManager;
import com.taobao.zeus.store.JobBean;
import com.taobao.zeus.store.JobHistoryManager;
import com.taobao.zeus.util.DateUtil;
import com.taobao.zeus.util.PropertyKeys;
public class JobController extends Controller {
private final String jobId;
private CacheJobDescriptor cache;
private JobHistoryManager jobHistoryManager;
private GroupManager groupManager;
private Master master;
private MasterContext context;
private static Logger log = LogManager.getLogger(JobController.class);
public JobController(MasterContext context, Master master, String jobId) {
this.jobId = jobId;
this.jobHistoryManager = context.getJobHistoryManager();
groupManager = context.getGroupManager();
this.cache = new CacheJobDescriptor(jobId, groupManager);
this.master = master;
this.context = context;
registerEventTypes(Events.Initialize);
}
private final Date getForver(){
try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2099-12-31 23:59:59");
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
@Override
public boolean canHandle(AppEvent event, boolean bubbleDown) {
if (super.canHandle(event, bubbleDown)) {
JobDescriptor jd = cache.getJobDescriptor();
if (jd == null) {
autofix();
return false;
}
return jd.getAuto();
}
return false;
}
@Override
public void handleEvent(AppEvent event) {
try {
if (event instanceof JobSuccessEvent) {
successEventHandle((JobSuccessEvent) event);
} else if (event instanceof JobFailedEvent) {
failedEventHandle((JobFailedEvent) event);
} else if (event instanceof ScheduleTriggerEvent) {
triggerEventHandle((ScheduleTriggerEvent) event);
} else if (event instanceof JobMaintenanceEvent) {
maintenanceEventHandle((JobMaintenanceEvent) event);
} else if (event instanceof JobLostEvent) {
lostEventHandle((JobLostEvent) event);
} else if (event.getType() == Events.Initialize) {
initializeEventHandle();
}
} catch (Exception e) {
// catchjobjob
ScheduleInfoLog.error("JobId:" + jobId + " handleEvent error", e);
}
}
private void initializeEventHandle() {
JobStatus jobStatus = groupManager.getJobStatus(jobId);
// System.out.println("jobId: "+jobId+" jobStatus:"+jobStatus.getStatus());
if (jobStatus != null) {
// RUNNING
if (jobStatus.getStatus() == Status.RUNNING) {
log.error("jobId=" + jobId
+ " RUNNINGJOB...");
// jobid kill
String operator = null;
if (jobStatus.getHistoryId() != null) {
JobHistory history = jobHistoryManager
.findJobHistory(jobStatus.getHistoryId());
// history
if (history != null
&& history.getStatus() == Status.RUNNING) {
operator = history.getOperator();
try {
JobContext temp = JobContext.getTempJobContext(JobContext.MANUAL_RUN);
history.setIllustrate("running");
temp.setJobHistory(history);
new CancelHadoopJob(temp).run();
master.run(history);
} catch (Exception e) {
}
}
}else{
JobHistory history = new JobHistory();
history.setIllustrate("running");
history.setOperator(operator);
history.setTriggerType(TriggerType.MANUAL_RECOVER);
history.setJobId(jobId);
JobDescriptor jobDescriptor = groupManager.getUpstreamJobBean(jobId).getJobDescriptor();
history.setToJobId(jobDescriptor.getToJobId());
if(jobDescriptor != null){
history.setOperator(jobDescriptor.getOwner() == null ? null : jobDescriptor.getOwner());
}
context.getJobHistoryManager().addJobHistory(history);
master.run(history);
}
}
}
JobDescriptor jd = cache.getJobDescriptor();
if (jd.getAuto() && jd.getScheduleType() == JobScheduleType.Independent) {
String cronExpression = jd.getCronExpression();
try {
CronTrigger trigger = new CronTrigger(jd.getId(), "zeus",
cronExpression);
/
/**
* Job
*
* @param event
*/
private void maintenanceEventHandle(JobMaintenanceEvent event) {
if (event.getType() == Events.UpdateJob
&& jobId.equals(event.getJobId())) {
autofix();
}
}
/**
* JOB
*
* @param event
*/
private void lostEventHandle(JobLostEvent event) {
if (event.getType() == Events.UpdateJob
&& jobId.equals(event.getJobId())) {
cache.refresh();
JobDescriptor jd = cache.getJobDescriptor();
if(jd!=null && jd.getAuto()){
JobStatus jobStatus = groupManager.getJobStatus(jobId);
if(jobStatus.getStatus() == null || jobStatus.getStatus() == Status.WAIT){
Date now = new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
String currentDateStr = df.format(now)+"0000";
if(Long.parseLong(jobId) < Long.parseLong(currentDateStr)){
JobHistory history = new JobHistory();
history.setIllustrate(",");
history.setTriggerType(TriggerType.SCHEDULE);
history.setJobId(jobId);
history.setToJobId(jd.getToJobId());
history.setExecuteHost(jd.getHost());
if(jd != null){
history.setOperator(jd.getOwner() == null ? null : jd.getOwner());
}
context.getJobHistoryManager().addJobHistory(history);
master.run(history);
ScheduleInfoLog.info("JobId:" + jobId + " roll lost back lost ");
}
}
}
}
}
/**
*
*
* @param event
*/
private void successEventHandle(JobSuccessEvent event) {
if (event.getTriggerType() == TriggerType.MANUAL) {
return;
}
String eId = event.getJobId();
JobDescriptor jobDescriptor = cache.getJobDescriptor();
if (jobDescriptor == null) {
autofix();
return;
}
if (!jobDescriptor.getAuto()) {
return;
}
if (jobDescriptor.getScheduleType() == JobScheduleType.Independent) {
return;
}
if (jobDescriptor.getScheduleType() == JobScheduleType.CyleJob) {
cycleJobSuccessHandle(event);
return;
}
if (!jobDescriptor.getDependencies().contains(eId)) {
return;
}
JobStatus jobStatus = null;
synchronized (this) {
jobStatus = groupManager.getJobStatus(jobId);
JobBean bean = groupManager.getUpstreamJobBean(jobId);
String cycle = bean.getHierarchyProperties().getProperty(
PropertyKeys.DEPENDENCY_CYCLE);
if (cycle != null && !"".equals(cycle)) {
Map<String, String> dep = jobStatus.getReadyDependency();
//Job
if ("sameday".equals(cycle)) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String now = format.format(new Date());
for (String key : new HashSet<String>(dep.keySet())) {
String d = format.format(new Date(Long.valueOf(dep
.get(key))));
if (!now.equals(d)) {
jobStatus.getReadyDependency().remove(key);
ScheduleInfoLog.info("JobId:" + jobId
+ " remove overdue dependency " + key);
}
}
}
}
ScheduleInfoLog.info("JobId:" + jobId
+ " received a successed dependency job with jobId:"
+ event.getJobId());
ScheduleInfoLog.info("JobId:" + jobId + " the dependency jobId:"
+ event.getJobId() + " record it");
jobStatus.getReadyDependency().put(eId,
String.valueOf(new Date().getTime()));
groupManager.updateJobStatus(jobStatus);
}
boolean allComplete = true;
for (String key : jobDescriptor.getDependencies()) {
if (jobStatus.getReadyDependency().get(key) == null) {
allComplete = false;
break;
}
}
if (allComplete) {
ScheduleInfoLog.info("JobId:" + jobId
+ " all dependency jobs is ready,run!");
startNewJob(event.getTriggerType(), jobDescriptor, jobId);
} else {
ScheduleInfoLog.info("JobId:" + jobId
+ " some of dependency is not ready,waiting!");
}
}
private void startNewJob(TriggerType type, JobDescriptor jobDescriptor,
String jobID) {
JobHistory history = new JobHistory();
history.setIllustrate("");
history.setTriggerType(TriggerType.SCHEDULE);
history.setJobId(jobId);
System.out.println("operator "+jobDescriptor.getOwner());
history.setOperator(jobDescriptor.getOwner() == null ? null : jobDescriptor.getOwner());
history.setToJobId(jobDescriptor.getToJobId() == null ? null : jobDescriptor.getToJobId());
history.setExecuteHost(jobDescriptor.getHost());
context.getJobHistoryManager().addJobHistory(history);
history = master.run(history);
if (history.getStatus() == Status.FAILED) {
ZeusJobException exception = new ZeusJobException(
history.getJobId(), history.getLog().getContent());
JobFailedEvent jfe = new JobFailedEvent(jobDescriptor.getId(),
type, history, exception);
ScheduleInfoLog.info("JobId:" + jobId
+ " is fail,dispatch the fail event");
context.getDispatcher().forwardEvent(jfe);
}
}
private void cycleJobSuccessHandle(JobSuccessEvent event) {
String eId = event.getJobId();
JobDescriptor jobDescriptor = cache.getJobDescriptor();
JobDescriptor jd = jobDescriptor.getCopy();
JobDescriptor eIobDescriptor = groupManager.getJobDescriptor(eId)
.getX();
String nextStartTime = null;
String nextSSTime = null;
String nextSETime = null;
long nextTS = 0;
if (eId.equals(jobId)
&& (jobDescriptor.getDependencies() == null || jobDescriptor
.getDependencies().isEmpty())) {
try {
if (jobDescriptor.getCycle().equals("hour")) {
nextStartTime = DateUtil.getDelayTime(1,
jobDescriptor.getStartTime());
nextSSTime = DateUtil.getDelayTime(1,
jobDescriptor.getStatisStartTime());
nextSETime = DateUtil.getDelayTime(1,
jobDescriptor.getStatisEndTime());
nextTS = jobDescriptor.getStartTimestamp() + 60 * 60 * 1000;
}
if (jobDescriptor.getCycle().equals("day")) {
nextStartTime = DateUtil.getDelayTime(24,
jobDescriptor.getStartTime());
nextSSTime = DateUtil.getDelayTime(24,
jobDescriptor.getStatisStartTime());
nextSETime = DateUtil.getDelayTime(24,
jobDescriptor.getStatisEndTime());
nextTS = jobDescriptor.getStartTimestamp() + 24 * 60 * 60
* 1000;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jd.setStartTime(nextStartTime);
jd.setStatisEndTime(nextSETime);
jd.setStatisStartTime(nextSSTime);
jd.setStartTimestamp(nextTS);
JobStatus js = new JobStatus();
js.setJobId(eId);
js.setStatus(JobStatus.Status.WAIT);
try {
groupManager.updateJob(jd.getOwner(), jd);
groupManager.updateJobStatus(js);
} catch (ZeusException e) {
log.error("", e);
e.printStackTrace();
}
//initCycleJob(jd);
cache.refresh();
return;
}
if (!jobDescriptor.getDependencies().contains(eId)) {
return;
}
JobStatus jobStatus = null;
synchronized (this) {
jobStatus = groupManager.getJobStatus(jobId);
ScheduleInfoLog.info("JobId:" + jobId
+ " received a successed dependency job with jobId:" + eId
+ " statisTime:" + event.getStatisEndTime());
jobStatus.getReadyDependency().put(eId, event.getStatisEndTime());
groupManager.updateJobStatus(jobStatus);
}
boolean allComplete = true;
for (String key : jobDescriptor.getDependencies()) {
if (jobStatus.getReadyDependency().get(key) == null
|| !jobStatus.getReadyDependency().get(key)
.equals(jobDescriptor.getStatisEndTime())) {
allComplete = false;
break;
}
}
String cycle = jobDescriptor.getDepdCycleJob().get(eId);
for (Entry<String, String> entry : jobDescriptor.getDepdCycleJob()
.entrySet()) {
if (!entry.getValue().equals(cycle)) {
ScheduleInfoLog.error("JobId:" + jobId
+ " has different cycle dependence", null);
allComplete = false;
break;
}
}
if (allComplete) {
if (eIobDescriptor.getCycle().equals(jobDescriptor.getCycle())) {
jd.setStatisEndTime(jobDescriptor.getStatisEndTime());
jd.setStartTime(jobDescriptor.getStartTime());
jd.setStatisStartTime(jobDescriptor.getStatisStartTime());
jd.setId(jobId);
jd.setCycle(jobDescriptor.getCycle());
try {
if (jobDescriptor.getCycle().equals("hour")) {
jobDescriptor.setStatisStartTime(DateUtil.getDelayTime(
1, jobDescriptor.getStatisStartTime()));
jobDescriptor.setStatisEndTime(DateUtil.getDelayTime(
1, jobDescriptor.getStatisEndTime()));
jobDescriptor.setStartTime(DateUtil.getDelayTime(
1, jobDescriptor.getStartTime()));
}
if(jobDescriptor.getCycle().equals("day")){
jobDescriptor.setStatisStartTime(DateUtil.getDelayTime(
24, jobDescriptor.getStatisStartTime()));
jobDescriptor.setStatisEndTime(DateUtil.getDelayTime(
24, jobDescriptor.getStatisEndTime()));
jobDescriptor.setStartTime(DateUtil.getDelayTime(
24, jobDescriptor.getStartTime()));
}
groupManager.updateJob(jobDescriptor.getOwner(), jobDescriptor);
cache.refresh();
} catch (ParseException e) {
ScheduleInfoLog.error("parse date failed", e);
} catch (ZeusException e) {
ScheduleInfoLog.error("update job failed", e);
}
ScheduleInfoLog.info("JobId:"+jobId+" all dependence for "+jd.getStatisEndTime()+" is ready,start");
runJob(jd);
} else {
if (event.getStatisEndTime().equals(
jobDescriptor.getStatisEndTime())) {
jd.setStatisEndTime(jobDescriptor.getStatisEndTime());
jd.setStartTime(jobDescriptor.getStartTime());
jd.setStatisStartTime(jobDescriptor.getStatisStartTime());
jd.setId(jobId);
jd.setCycle(jobDescriptor.getCycle());
try {
jobDescriptor.setStatisStartTime(DateUtil.getDelayTime(
24, jobDescriptor.getStatisStartTime()));
jobDescriptor.setStatisEndTime(DateUtil.getDelayTime(
24, jobDescriptor.getStatisEndTime()));
jobDescriptor.setStartTime(DateUtil.getDelayTime(
24, jobDescriptor.getStartTime()));
groupManager.updateJob(jobDescriptor.getOwner(), jobDescriptor);
cache.refresh();
} catch (ParseException e) {
ScheduleInfoLog.error("parse date failed", e);
} catch (ZeusException e) {
ScheduleInfoLog.error("update job failed", e);
}
ScheduleInfoLog.info("JobId:"+jobId+" all dependence for "+jd.getStatisEndTime()+" is ready,start");
runJob(jd);
}
}
} else {
ScheduleInfoLog.info("JobId:" + jobId + " is not ready,waiting!");
}
}
/**
*
*
* ? JobJobJobJob 1. 2.
*
* @param event
*/
private void failedEventHandle(JobFailedEvent event) {
JobDescriptor jobDescriptor = cache.getJobDescriptor();
if (jobDescriptor == null) {
autofix();
return;
}
if (!jobDescriptor.getAuto()) {
return;
}
if (jobDescriptor.getDependencies().contains(event.getJobId())) {// JobJob
return;
//job
/*if (event.getTriggerType() == TriggerType.SCHEDULE) {// Job
//
// SCHEDULE
// Job
ZeusJobException exception = new ZeusJobException(event
.getJobException().getCauseJobId(), "jobId:"
+ jobDescriptor.getId() + " Job"
+ event.getJobId() + " ", event.getJobException());
ScheduleInfoLog.info("jobId:" + jobId
+ " is fail,as dependendy jobId:"
+ jobDescriptor.getId() + " is failed");
// History
JobHistory history = new JobHistory();
history.setStartTime(new Date());
history.setEndTime(new Date());
history.setExecuteHost(null);
history.setJobId(jobId);
history.setToJobId(jobDescriptor.getToJobId() == null ? null : jobDescriptor.getToJobId());
history.setTriggerType(event.getTriggerType());
history.setStatus(Status.FAILED);
history.getLog().appendZeusException(exception);
history.setStatisEndTime(jobDescriptor.getStatisEndTime());
history.setTimezone(jobDescriptor.getTimezone());
history.setCycle(jobDescriptor.getCycle());
history.setOperator(jobDescriptor.getOwner() == null ? null : jobDescriptor.getOwner());
history = jobHistoryManager.addJobHistory(history);
jobHistoryManager.updateJobHistoryLog(history.getId(), history
.getLog().getContent());
JobFailedEvent jfe = new JobFailedEvent(jobDescriptor.getId(),
event.getTriggerType(), history, exception);
ScheduleInfoLog.info("JobId:" + jobId
+ " is fail,dispatch the fail event");
//
context.getDispatcher().forwardEvent(jfe);
}*/
}
}
/**
* jobjob
*
*/
private void autofix() {
cache.refresh();
JobDescriptor jd = cache.getJobDescriptor();
if (jd == null) {// null
// job
context.getDispatcher().removeController(this);
destory();
ScheduleInfoLog.info("schedule remove job with jobId:" + jobId);
return;
}
JobDetail detail = null;
try {
detail = context.getScheduler().getJobDetail(jobId, "zeus");
} catch (SchedulerException e) {
log.error(e);
}
if (!jd.getAuto()) {
if (detail != null) {
try {
context.getScheduler().deleteJob(jobId, "zeus");
log.error("schedule remove job with jobId:" + jobId);
} catch (SchedulerException e) {
log.error(e);
}
}
return;
}
if (jd.getScheduleType() == JobScheduleType.Dependent) {
if (detail != null) {
try {
context.getScheduler().deleteJob(jobId, "zeus");
ScheduleInfoLog
.info("JobId:"
+ jobId
+ " from independent to dependent ,remove from schedule");
} catch (SchedulerException e) {
log.error(e);
}
}
} else if (jd.getScheduleType() == JobScheduleType.Independent) {
ScheduleInfoLog.info("JobId:" + jobId + " independent job,update");
try {
if (detail != null) {
context.getScheduler().deleteJob(jobId, "zeus");
ScheduleInfoLog.info("JobId:" + jobId
+ " remove from schedule");
}
CronTrigger trigger = new CronTrigger(jd.getId(), "zeus",
jd.getCronExpression());
detail = new JobDetail(jd.getId(), "zeus", TimerJob.class);
detail.getJobDataMap().put("jobId", jd.getId());
detail.getJobDataMap().put("dispatcher",
context.getDispatcher());
context.getScheduler().scheduleJob(detail, trigger);
ScheduleInfoLog.info("JobId:" + jobId
+ " add job to schedule for refresh");
} catch (SchedulerException e) {
log.error(e);
} catch (ParseException e) {
log.error(e);
}
} else if (jd.getScheduleType() == JobScheduleType.CyleJob
&& (jd.getDependencies() == null || jd.getDependencies()
.isEmpty())) {
initCycleJob(jd);
}
}
/**
*
*
* @param event
*/
private void triggerEventHandle(ScheduleTriggerEvent event) {
String eId = event.getJobId();
JobDescriptor jobDescriptor = cache.getJobDescriptor();
if (jobDescriptor == null) {// jobautofix
autofix();
return;
}
if (!eId.equals(jobDescriptor.getId())) {
return;
}
ScheduleInfoLog.info("JobId:" + jobId
+ " receive a timer trigger event,statisTime is:"
+ jobDescriptor.getStatisEndTime());
runJob(jobDescriptor);
}
private void runJob(JobDescriptor jobDescriptor) {
JobHistory history = new JobHistory();
history.setJobId(jobDescriptor.getId());
history.setToJobId(jobDescriptor.getToJobId() == null ? null : jobDescriptor.getToJobId());
history.setTriggerType(TriggerType.SCHEDULE);
history.setStatisEndTime(jobDescriptor.getStatisEndTime());
history.setTimezone(jobDescriptor.getTimezone());
history.setCycle(jobDescriptor.getCycle());
history.setExecuteHost(jobDescriptor.getHost());
history.setOperator(jobDescriptor.getOwner() == null ? null : jobDescriptor.getOwner());
context.getJobHistoryManager().addJobHistory(history);
master.run(history);
}
/*
* private void run(final JobDescriptor jobDescriptor,final TriggerType
* type,String illustrate){ // JobStatus
* status=groupManager.getJobStatus(jobId);
* status.setStatus(Status.RUNNING); final JobHistory history=new
* JobHistory(); history.setJobId(jobId); history.setTriggerType(type);
* history.setIllustrate(illustrate); history.setStatus(Status.RUNNING);
* jobHistoryManager.addJobHistory(history);
* groupManager.updateJobStatus(status);
*
* Thread thread=new Thread(new Runnable() {
*
* @Override public void run() {
* ScheduleInfoLog.info("JobId:"+jobId+" run start"); boolean success=false;
* Exception exception=null; try { int
* exitCode=workerService.executeJob(history.getId()); if(exitCode==0 ||
* exitCode==ExitCodes.NOTIFY_ZK_FAIL){ success=true; }else{ success=false;
* } } catch (Exception e) { success=false; exception=e;
* log.error(String.format("JobId:%s run failed ", jobDescriptor.getId()),
* e); } JobStatus jobstatus=groupManager.getJobStatus(jobId);
* jobstatus.setStatus(Status.WAIT); if(success &&
* (type==TriggerType.SCHEDULE || type==TriggerType.MANUAL_RECOVER )){
* ScheduleInfoLog.info("JobId:"+jobId+" clear ready dependency");
* jobstatus.setReadyDependency(new HashMap<String, String>()); }
* groupManager.updateJobStatus(jobstatus);
*
*
* if(!success){ // if(exception!=null){ exception=new
* ZeusException(String.format("JobId:%s run failed ",
* jobDescriptor.getId()), exception); }else{ exception=new
* ZeusException(String.format("JobId:%s run failed ",
* jobDescriptor.getId())); }
* ScheduleInfoLog.info("JobId:"+jobId+" run fail and dispatch the fail event"
* ); JobFailedEvent jfe=new
* JobFailedEvent(jobDescriptor.getId(),type,jobHistoryManager
* .findJobHistory(history.getId()),exception);
* dispatcher.forwardEvent(jfe); }else{ if(type==TriggerType.SCHEDULE ||
* type==TriggerType.MANUAL_RECOVER){ //
* ScheduleInfoLog.info("JobId:"
* +jobId+" run success and dispatch the success event"); JobSuccessEvent
* jse=new JobSuccessEvent(jobDescriptor.getId(),TriggerType.SCHEDULE);
* dispatcher.forwardEvent(jse); } }
*
* } }); thread.start();
*
*
* }
*/
public String getJobId() {
return jobId;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof JobController)) {
return false;
}
JobController jc = (JobController) obj;
return jobId.equals(jc.getJobId());
}
@Override
public int hashCode() {
return jobId.hashCode();
}
public static class TimerJob implements Job {
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
String jobId = context.getJobDetail().getJobDataMap()
.getString("jobId");
Dispatcher dispatcher = (Dispatcher) context.getJobDetail()
.getJobDataMap().get("dispatcher");
ScheduleTriggerEvent ste = new ScheduleTriggerEvent(jobId);
dispatcher.forwardEvent(ste);
}
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
JobDescriptor jd = cache.getJobDescriptor();
if (jd == null) {
sb.append("JobId:" + jobId + " null");
} else {
sb.append("JobId:" + jobId).append(
" auto:" + cache.getJobDescriptor().getAuto());
sb.append(" dependency:"
+ cache.getJobDescriptor().getDependencies());
}
JobDetail detail = null;
try {
detail = context.getScheduler().getJobDetail(jobId, "zeus");
} catch (SchedulerException e) {
}
if (detail == null) {
sb.append("job not in scheduler");
} else {
sb.append("job is in scheduler");
}
return sb.toString();
}
}
|
package org.securegraph.test;
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.securegraph.*;
import org.securegraph.mutation.ElementMutation;
import org.securegraph.property.PropertyValue;
import org.securegraph.property.StreamingPropertyValue;
import org.securegraph.query.Compare;
import org.securegraph.query.DefaultGraphQuery;
import org.securegraph.query.GeoCompare;
import org.securegraph.query.TextPredicate;
import org.securegraph.test.util.LargeStringInputStream;
import org.securegraph.type.GeoCircle;
import org.securegraph.type.GeoPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import static org.junit.Assert.*;
import static org.securegraph.test.util.IterableUtils.assertContains;
import static org.securegraph.util.IterableUtils.count;
import static org.securegraph.util.IterableUtils.toList;
@RunWith(JUnit4.class)
public abstract class GraphTestBase {
private static final Logger LOGGER = LoggerFactory.getLogger(GraphTestBase.class);
public static final Visibility VISIBILITY_A = new Visibility("a");
public static final Visibility VISIBILITY_B = new Visibility("b");
public static final Visibility VISIBILITY_EMPTY = new Visibility("");
public final Authorizations AUTHORIZATIONS_A;
public final Authorizations AUTHORIZATIONS_B;
public final Authorizations AUTHORIZATIONS_C;
public final Authorizations AUTHORIZATIONS_A_AND_B;
public final Authorizations AUTHORIZATIONS_EMPTY;
public static final int LARGE_PROPERTY_VALUE_SIZE = 1024 + 1;
protected Graph graph;
protected abstract Graph createGraph() throws Exception;
public Graph getGraph() {
return graph;
}
public GraphTestBase() {
AUTHORIZATIONS_A = createAuthorizations("a");
AUTHORIZATIONS_B = createAuthorizations("b");
AUTHORIZATIONS_C = createAuthorizations("c");
AUTHORIZATIONS_A_AND_B = createAuthorizations("a", "b");
AUTHORIZATIONS_EMPTY = createAuthorizations();
}
protected abstract Authorizations createAuthorizations(String... auths);
@Before
public void before() throws Exception {
graph = createGraph();
}
@After
public void after() throws Exception {
graph.shutdown();
graph = null;
}
@Test
public void testAddVertexWithId() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals("v1", v.getId());
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_A, v.getVisibility());
v = graph.getVertex("", AUTHORIZATIONS_A);
assertNull(v);
v = graph.getVertex(null, AUTHORIZATIONS_A);
assertNull(v);
}
@Test
public void testAddVertexWithoutId() {
Vertex v = graph.addVertex(VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(v);
Object vertexId = v.getId();
assertNotNull(vertexId);
v = graph.getVertex(vertexId, AUTHORIZATIONS_A);
assertNotNull(v);
assertNotNull(vertexId);
}
@Test
public void testAddStreamingPropertyValue() throws IOException, InterruptedException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()), String.class);
String largePropertyName = "propLarge/\\*!@
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty(largePropertyName, propLarge, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Object> propSmallValues = v1.getPropertyValues("propSmall");
assertEquals(1, count(propSmallValues));
Object propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
StreamingPropertyValue value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1".getBytes().length, value.getLength());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
Iterable<Object> propLargeValues = v1.getPropertyValues(largePropertyName);
assertEquals(1, count(propLargeValues));
Object propLargeValue = propLargeValues.iterator().next();
assertTrue(largePropertyName + " was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue.getBytes().length, value.getLength());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
propSmallValues = v1.getPropertyValues("propSmall");
assertEquals(1, count(propSmallValues));
propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1".getBytes().length, value.getLength());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
propLargeValues = v1.getPropertyValues(largePropertyName);
assertEquals(1, count(propLargeValues));
propLargeValue = propLargeValues.iterator().next();
assertTrue(largePropertyName + " was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue.getBytes().length, value.getLength());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
}
@Test
public void testAddVertexPropertyWithMetadata() {
Map<String, Object> prop1Metadata = new HashMap<String, Object>();
prop1Metadata.put("metadata1", "metadata1Value");
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
Property prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertNotNull(prop1Metadata);
assertEquals(1, prop1Metadata.keySet().size());
assertEquals("metadata1Value", prop1Metadata.get("metadata1"));
prop1Metadata.put("metadata2", "metadata2Value");
v.prepareMutation()
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertEquals(2, prop1Metadata.keySet().size());
assertEquals("metadata1Value", prop1Metadata.get("metadata1"));
assertEquals("metadata2Value", prop1Metadata.get("metadata2"));
// make sure we clear out old values
prop1Metadata = new HashMap<String, Object>();
v.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertEquals(0, prop1Metadata.keySet().size());
}
@Test
public void testAddVertexWithProperties() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getProperties("prop2")));
assertEquals("value2", v.getPropertyValues("prop2").iterator().next());
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getProperties("prop2")));
assertEquals("value2", v.getPropertyValues("prop2").iterator().next());
}
@Test
public void testAddVertexWithPropertiesWithTwoDifferentVisibilities() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1a", VISIBILITY_A)
.setProperty("prop1", "value1b", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(v.getProperties("prop1")));
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(v.getProperties("prop1")));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1a", v.getPropertyValue("prop1"));
v = graph.getVertex("v1", AUTHORIZATIONS_B);
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1b", v.getPropertyValue("prop1"));
}
@Test
public void testMultivaluedProperties() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.addPropertyValue("propid3a", "prop3", "value3a", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("value1a", v.getPropertyValues("prop1").iterator().next());
assertEquals("value2a", v.getPropertyValues("prop2").iterator().next());
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
assertEquals(3, count(v.getProperties()));
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2b", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getPropertyValues("prop1")));
assertEquals("value1b", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getPropertyValues("prop2")));
assertEquals("value2b", v.getPropertyValues("prop2").iterator().next());
assertEquals(1, count(v.getPropertyValues("prop3")));
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
assertEquals(3, count(v.getProperties()));
v.addPropertyValue("propid1b", "prop1", "value1a-new", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertContains("value1b", v.getPropertyValues("prop1"));
assertContains("value1a-new", v.getPropertyValues("prop1"));
assertEquals(4, count(v.getProperties()));
}
@Test
public void testMultivaluedPropertyOrder() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("a", "prop", "a", VISIBILITY_A)
.addPropertyValue("aa", "prop", "aa", VISIBILITY_A)
.addPropertyValue("b", "prop", "b", VISIBILITY_A)
.addPropertyValue("0", "prop", "0", VISIBILITY_A)
.addPropertyValue("A", "prop", "A", VISIBILITY_A)
.addPropertyValue("Z", "prop", "Z", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("0", v1.getPropertyValue("prop", 0));
assertEquals("A", v1.getPropertyValue("prop", 1));
assertEquals("Z", v1.getPropertyValue("prop", 2));
assertEquals("a", v1.getPropertyValue("prop", 3));
assertEquals("aa", v1.getPropertyValue("prop", 4));
assertEquals("b", v1.getPropertyValue("prop", 5));
}
@Test
public void testRemoveProperty() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid1b", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
v.removeProperty("prop1", AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v.getProperties()));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop2", "value2a").vertices()));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1a").vertices()));
v.removeProperty("propid2a", "prop2", AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(0, count(v.getProperties()));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v.getProperties()));
}
@Test
public void testRemoveElement() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v.prepareMutation()
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1").vertices()));
graph.removeVertex(v, AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v);
assertEquals(0, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1").vertices()));
}
@Test
public void testAddVertexWithVisibility() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_A);
Iterable<Vertex> cVertices = graph.getVertices(AUTHORIZATIONS_C);
assertEquals(0, count(cVertices));
Iterable<Vertex> aVertices = graph.getVertices(AUTHORIZATIONS_A);
assertEquals(1, count(aVertices));
assertEquals("v1", aVertices.iterator().next().getId());
Iterable<Vertex> bVertices = graph.getVertices(AUTHORIZATIONS_B);
assertEquals(1, count(bVertices));
assertEquals("v2", bVertices.iterator().next().getId());
Iterable<Vertex> allVertices = graph.getVertices(AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(allVertices));
}
@Test
public void testGetVerticesWithIds() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v1b", VISIBILITY_A)
.setProperty("prop1", "v1b", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop1", "v2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("prop1", "v3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
List<Object> ids = new ArrayList<Object>();
ids.add("v2");
ids.add("v1");
Iterable<Vertex> vertices = graph.getVertices(ids, AUTHORIZATIONS_A);
boolean foundV1 = false, foundV2 = false;
for (Vertex v : vertices) {
if (v.getId().equals("v1")) {
assertEquals("v1", v.getPropertyValue("prop1"));
foundV1 = true;
} else if (v.getId().equals("v2")) {
assertEquals("v2", v.getPropertyValue("prop1"));
foundV2 = true;
} else {
assertTrue("Unexpected vertex id: " + v.getId(), false);
}
}
assertTrue("v1 not found", foundV1);
assertTrue("v2 not found", foundV2);
List<Vertex> verticesInOrder = graph.getVerticesInOrder(ids, AUTHORIZATIONS_A);
assertEquals(2, verticesInOrder.size());
assertEquals("v2", verticesInOrder.get(0).getId());
assertEquals("v1", verticesInOrder.get(1).getId());
}
@Test
public void testGetEdgesWithIds() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A)
.setProperty("prop1", "e1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1a", v1, v2, "", VISIBILITY_A)
.setProperty("prop1", "e1a", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", v1, v3, "", VISIBILITY_A)
.setProperty("prop1", "e2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e3", v2, v3, "", VISIBILITY_A)
.setProperty("prop1", "e3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
List<Object> ids = new ArrayList<Object>();
ids.add("e1");
ids.add("e2");
Iterable<Edge> edges = graph.getEdges(ids, AUTHORIZATIONS_A);
boolean foundE1 = false, foundE2 = false;
for (Edge e : edges) {
if (e.getId().equals("e1")) {
assertEquals("e1", e.getPropertyValue("prop1"));
foundE1 = true;
} else if (e.getId().equals("e2")) {
assertEquals("e2", e.getPropertyValue("prop1"));
foundE2 = true;
} else {
assertTrue("Unexpected vertex id: " + e.getId(), false);
}
}
assertTrue("e1 not found", foundE1);
assertTrue("e2 not found", foundE2);
}
@Test
public void testRemoveVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.removeVertex(v1, AUTHORIZATIONS_A);
assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A)));
}
@Test
public void testRemoveVertexWithProperties() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.removeVertex(v1, AUTHORIZATIONS_A);
assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
}
@Test
public void testAddEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(e);
assertEquals("e1", e.getId());
assertEquals("label1", e.getLabel());
assertEquals("v1", e.getVertexId(Direction.OUT));
assertEquals(v1, e.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", e.getVertexId(Direction.IN));
assertEquals(v2, e.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, e.getVisibility());
e = graph.getEdge("e1", AUTHORIZATIONS_B);
assertNull(e);
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertNotNull(e);
assertEquals("e1", e.getId());
assertEquals("label1", e.getLabel());
assertEquals("v1", e.getVertexId(Direction.OUT));
assertEquals(v1, e.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", e.getVertexId(Direction.IN));
assertEquals(v2, e.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, e.getVisibility());
}
@Test
public void testGetEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label2", v1, v2, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2to1", v2, v1, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(3, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(Direction.IN, AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.BOTH, "label1", AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.OUT, "label1", AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, "label1", AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.OUT, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
}
@Test
public void testAddEdgeWithProperties() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.setProperty("propB", "valueB", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
assertEquals(0, count(e.getPropertyValues("propB")));
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
assertEquals("valueB", e.getPropertyValues("propB").iterator().next());
assertEquals("valueA", e.getPropertyValue("propA"));
assertEquals("valueB", e.getPropertyValue("propB"));
}
@Test
public void testRemoveEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
try {
graph.removeEdge("e1", AUTHORIZATIONS_B);
} catch (IllegalArgumentException e) {
// expected
}
assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.removeEdge("e1", AUTHORIZATIONS_A);
assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_A)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(0, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
}
@Test
public void testAddEdgeWithVisibility() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_B, AUTHORIZATIONS_B);
Iterable<Edge> aEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A);
assertEquals(1, count(aEdges));
Edge e1 = aEdges.iterator().next();
assertNotNull(e1);
assertEquals("edgeA", e1.getLabel());
Iterable<Edge> bEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_B);
assertEquals(1, count(bEdges));
Edge e2 = bEdges.iterator().next();
assertNotNull(e2);
assertEquals("edgeB", e2.getLabel());
Iterable<Edge> allEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(allEdges));
}
@Test
public void testGraphQuery() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).limit(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(2).vertices();
assertEquals(0, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(2).vertices();
assertEquals(1, count(vertices));
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A).edges();
assertEquals(1, count(edges));
}
@Test
public void testGraphQueryWithQueryString() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.setProperty("description", "This is vertex 1 - dog.", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
v2.setProperty("description", "This is vertex 2 - cat.", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query("vertex", AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_A).vertices();
assertEquals(1, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_B).vertices();
assertEquals(0, count(vertices));
}
@Test
public void testGraphQueryHas() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.setProperty("birthDate", new DateOnly(1989, 1, 5), VISIBILITY_A)
.setProperty("lastAccessed", createDate(2014, 2, 24, 13, 0, 5), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_A)
.setProperty("birthDate", new DateOnly(1984, 1, 5), VISIBILITY_A)
.setProperty("lastAccessed", createDate(2014, 2, 25, 13, 0, 5), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("lastAccessed", Compare.EQUAL, createDate(2014, 2, 24, 13, 0, 5))
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN_EQUAL, 25)
.vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.IN, new Integer[]{25})
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.IN, new Integer[]{25, 30})
.vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN, 26)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN_EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.NOT_EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("lastAccessed", Compare.EQUAL, new DateOnly(2014, 2, 24))
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query("*", AUTHORIZATIONS_A)
.has("age", Compare.IN, new Integer[]{25, 30})
.vertices();
assertEquals(2, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurity() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurityCantSeeVertex() {
graph.prepareVertex("v1", VISIBILITY_B)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
assertEquals(0, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurityCantSeeProperty() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
assertEquals(0, count(vertices));
}
@Test
public void testGraphQueryEdgeHasWithSecurity() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.prepareVertex("v3", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", v1, v2, "edge", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", v1, v3, "edge", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.edges();
assertEquals(1, count(edges));
}
@Test
public void testGraphQueryHasWithSpaces() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "Joe Ferner", VISIBILITY_A)
.setProperty("propWithHyphen", "hyphen-word", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "Joe Smith", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query("Ferner", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query("joe", AUTHORIZATIONS_A)
.vertices();
assertEquals(2, count(vertices));
if (!isUsingDefaultQuery(graph)) {
vertices = graph.query("joe AND ferner", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
}
if (!isUsingDefaultQuery(graph)) {
vertices = graph.query("joe smith", AUTHORIZATIONS_A)
.vertices();
List<Vertex> verticesList = toList(vertices);
assertEquals(2, verticesList.size());
boolean foundV1 = false;
boolean foundV2 = false;
for (Vertex v : verticesList) {
if (v.getId().equals("v1")) {
foundV1 = true;
} else if (v.getId().equals("v2")) {
foundV2 = true;
} else {
throw new RuntimeException("Invalid vertex id: " + v.getId());
}
}
assertTrue(foundV1);
assertTrue(foundV2);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe")
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe Ferner")
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("propWithHyphen", TextPredicate.CONTAINS, "hyphen-word")
.vertices();
assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryHasWithSpacesAndFieldedQueryString() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "Joe Ferner", VISIBILITY_A)
.setProperty("propWithHyphen", "hyphen-word", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "Joe Smith", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
if (!isUsingDefaultQuery(graph)) {
Iterable<Vertex> vertices = graph.query("name:\"joe ferner\"", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
}
}
protected boolean isUsingDefaultQuery(Graph graph) {
return graph.query(AUTHORIZATIONS_A) instanceof DefaultGraphQuery;
}
@Test
public void testGraphQueryGeoPoint() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297, "Reston, VA"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9544, -77.3464, "Reston, VA"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 1))
.vertices());
assertEquals(1, count(vertices));
GeoPoint geoPoint = (GeoPoint) vertices.get(0).getPropertyValue("location");
assertEquals(38.9186, geoPoint.getLatitude(), 0.001);
assertEquals(-77.2297, geoPoint.getLongitude(), 0.001);
assertEquals("Reston, VA", geoPoint.getDescription());
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 25))
.vertices());
assertEquals(2, count(vertices));
}
private Date createDate(int year, int month, int day) {
return new GregorianCalendar(year, month, day).getTime();
}
private Date createDate(int year, int month, int day, int hour, int min, int sec) {
return new GregorianCalendar(year, month, day, hour, min, sec).getTime();
}
@Test
public void testGraphQueryRange() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 20, 29)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 30)
.vertices();
assertEquals(2, count(vertices));
}
@Test
public void testVertexQuery() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.setProperty("prop1", "value1", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
v2.setProperty("prop1", "value2", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
v3.setProperty("prop1", "value3", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Iterable<Vertex> vertices = v1.query(AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
assertContains(v2, vertices);
assertContains(v3, vertices);
vertices = v1.query(AUTHORIZATIONS_A)
.has("prop1", "value2")
.vertices();
assertEquals(1, count(vertices));
assertContains(v2, vertices);
Iterable<Edge> edges = v1.query(AUTHORIZATIONS_A).edges();
assertEquals(2, count(edges));
assertContains(ev1v2, edges);
assertContains(ev1v3, edges);
edges = v1.query(AUTHORIZATIONS_A).edges(Direction.OUT);
assertEquals(2, count(edges));
assertContains(ev1v2, edges);
assertContains(ev1v3, edges);
}
@Test
public void testFindPaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v2
graph.addEdge(v2, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
List<Path> paths = toList(graph.findPaths(v1, v4, 2, AUTHORIZATIONS_A));
// v1 -> v2 -> v4
// v1 -> v3 -> v4
assertEquals(2, paths.size());
boolean found2 = false;
boolean found3 = false;
for (Path path : paths) {
assertEquals(3, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v2.getId().equals(id)) {
found2 = true;
} else if (v3.getId().equals(id)) {
found3 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v4.getId());
}
i++;
}
}
assertTrue("v2 not found in path", found2);
assertTrue("v3 not found in path", found3);
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
paths = toList(graph.findPaths(v4, v1, 2, AUTHORIZATIONS_A));
// v4 -> v2 -> v1
// v4 -> v3 -> v1
assertEquals(2, paths.size());
found2 = false;
found3 = false;
for (Path path : paths) {
assertEquals(3, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v4.getId());
} else if (i == 1) {
if (v2.getId().equals(id)) {
found2 = true;
} else if (v3.getId().equals(id)) {
found3 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v1.getId());
}
i++;
}
}
assertTrue("v2 not found in path", found2);
assertTrue("v3 not found in path", found3);
}
@Test
public void testFindPathsMultiplePaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v3
graph.addEdge(v4, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v4 -> v2
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v5
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
v5 = graph.getVertex("v5", AUTHORIZATIONS_A);
List<Path> paths = toList(graph.findPaths(v1, v2, 2, AUTHORIZATIONS_A));
// v1 -> v4 -> v2
// v1 -> v3 -> v2
assertEquals(2, paths.size());
boolean found3 = false;
boolean found4 = false;
for (Path path : paths) {
assertEquals(3, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v3.getId().equals(id)) {
found3 = true;
} else if (v4.getId().equals(id)) {
found4 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v2.getId());
}
i++;
}
}
assertTrue("v3 not found in path", found3);
assertTrue("v4 not found in path", found4);
paths = toList(graph.findPaths(v1, v2, 3, AUTHORIZATIONS_A));
// v1 -> v4 -> v2
// v1 -> v3 -> v2
// v1 -> v3 -> v4 -> v2
// v1 -> v4 -> v3 -> v2
assertEquals(4, paths.size());
found3 = false;
found4 = false;
for (Path path : paths) {
if (path.length() == 3) {
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v3.getId().equals(id)) {
found3 = true;
} else if (v4.getId().equals(id)) {
found4 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v2.getId());
}
i++;
}
} else if (path.length() == 4) {
} else {
fail("Invalid path length " + path.length());
}
}
assertTrue("v3 not found in path", found3);
assertTrue("v4 not found in path", found4);
paths = toList(graph.findPaths(v1, v5, 2, AUTHORIZATIONS_A));
assertEquals(0, paths.size());
paths = toList(graph.findPaths(v1, v5, 3, AUTHORIZATIONS_A));
// v1 -> v4 -> v2 -> v5
// v1 -> v3 -> v2 -> v5
assertEquals(2, paths.size());
found3 = false;
found4 = false;
for (Path path : paths) {
assertEquals(4, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v3.getId().equals(id)) {
found3 = true;
} else if (v4.getId().equals(id)) {
found4 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v2.getId());
} else if (i == 3) {
assertEquals(id, v5.getId());
}
i++;
}
}
assertTrue("v3 not found in path", found3);
assertTrue("v4 not found in path", found4);
}
@Test
public void testGetVerticesFromVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(3, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(0, count(v1.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(2, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(1, count(v2.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v2.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A);
assertEquals(2, count(v3.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(0, count(v3.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(2, count(v3.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
assertEquals(1, count(v4.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(0, count(v4.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v4.getVertices(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testBlankVisibilityString() {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
v = graph.getVertex("v1", AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_EMPTY, v.getVisibility());
}
@Test
public void testElementMutationDoesntChangeObjectUntilSave() {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
v.setProperty("prop1", "value1", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
ElementMutation<Vertex> m = v.prepareMutation()
.setProperty("prop1", "value2", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_A);
assertEquals(1, count(v.getProperties()));
assertEquals("value1", v.getPropertyValue("prop1"));
m.save(AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(v.getProperties()));
assertEquals("value2", v.getPropertyValue("prop1"));
assertEquals("value2", v.getPropertyValue("prop2"));
}
@Test
public void testFindRelatedEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev2v3 = graph.addEdge("e v2->v3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev3v1 = graph.addEdge("e v3->v1", v3, v1, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
List<Object> vertexIds = new ArrayList<Object>();
vertexIds.add("v1");
vertexIds.add("v2");
vertexIds.add("v3");
Iterable<Object> edges = toList(graph.findRelatedEdges(vertexIds, AUTHORIZATIONS_A));
assertEquals(4, count(edges));
assertContains(ev1v2.getId(), edges);
assertContains(ev1v3.getId(), edges);
assertContains(ev2v3.getId(), edges);
assertContains(ev3v1.getId(), edges);
}
@Test
public void testEmptyPropertyMutation() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.prepareMutation().save(AUTHORIZATIONS_A_AND_B);
}
@Test
public void testTextIndex() throws Exception {
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define();
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define(); // try calling define twice
graph.defineProperty("both").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.defineProperty("fullText").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("exactMatch").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("none", "Test Value", VISIBILITY_A)
.setProperty("both", "Test Value", VISIBILITY_A)
.setProperty("fullText", "Test Value", VISIBILITY_A)
.setProperty("exactMatch", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("Test Value", v1.getPropertyValue("none"));
assertEquals("Test Value", v1.getPropertyValue("both"));
assertEquals("Test Value", v1.getPropertyValue("fullText"));
assertEquals("Test Value", v1.getPropertyValue("exactMatch"));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("fullText", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals("exact match shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", "Test").vertices()));
assertEquals("unindexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", "Test").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", "Test Value").vertices()));
assertEquals("default has predicate is equals which shouldn't work for full text", 0, count(graph.query(AUTHORIZATIONS_A).has("fullText", "Test Value").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", "Test Value").vertices()));
if (count(graph.query(AUTHORIZATIONS_A).has("none", "Test Value").vertices()) != 0) {
LOGGER.warn("default has predicate is equals which shouldn't work for un-indexed");
}
}
@Test
public void testFieldBoost() throws Exception {
if (!graph.isFieldBoostSupported()) {
LOGGER.warn("Boost not supported");
return;
}
graph.defineProperty("a")
.dataType(String.class)
.textIndexHint(TextIndexHint.ALL)
.boost(1)
.define();
graph.defineProperty("b")
.dataType(String.class)
.textIndexHint(TextIndexHint.ALL)
.boost(2)
.define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("a", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("b", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
assertVertexIds(graph.query("Test", AUTHORIZATIONS_A).vertices(), new String[]{"v2", "v1"});
}
@Test
public void testVertexBoost() throws Exception {
if (!graph.isEdgeBoostSupported()) {
LOGGER.warn("Boost not supported");
return;
}
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.prepareVertex("v3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.addEdge("e1", v3, v2, "link", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertVertexIds(graph.query(AUTHORIZATIONS_A).vertices(), new String[]{"v2", "v3", "v1"});
}
@Test
public void testValueTypes() throws Exception {
Date date = createDate(2014, 2, 24, 13, 0, 5);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("int", 5, VISIBILITY_A)
.setProperty("bigDecimal", new BigDecimal(10), VISIBILITY_A)
.setProperty("double", 5.6, VISIBILITY_A)
.setProperty("float", 6.4f, VISIBILITY_A)
.setProperty("string", "test", VISIBILITY_A)
.setProperty("byte", (byte) 5, VISIBILITY_A)
.setProperty("long", (long) 5, VISIBILITY_A)
.setProperty("boolean", true, VISIBILITY_A)
.setProperty("geopoint", new GeoPoint(77, -33), VISIBILITY_A)
.setProperty("short", (short) 5, VISIBILITY_A)
.setProperty("date", date, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("int", 5).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("double", 5.6).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("float", 6.4f).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("string", "test").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("byte", 5).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("long", 5).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("boolean", true).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("short", 5).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("date", date).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigDecimal", 10).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("geopoint", GeoCompare.WITHIN, new GeoCircle(77, -33, 1)).vertices()));
}
@Test
public void testChangeVisibilityVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1);
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertNotNull(v1);
// change to same visibility
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1);
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertNotNull(v1);
}
@Test
public void testChangeVisibilityVertexProperties() {
Map<String, Object> prop1Metadata = new HashMap<String, Object>();
prop1Metadata.put("prop1_key1", "value1");
Map<String, Object> prop2Metadata = new HashMap<String, Object>();
prop2Metadata.put("prop2_key1", "value1");
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_EMPTY)
.setProperty("prop2", "value2", prop2Metadata, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1.getProperty("prop1"));
assertNotNull(v1.getProperty("prop2"));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1").vertices()));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("prop1", "value1").vertices()));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertNotNull(v1.getProperty("prop2"));
// alter and set property in one mutation
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_A)
.setProperty("prop1", "value1New", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals("value1New", v1.getPropertyValue("prop1"));
// alter visibility to the same visibility
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_A)
.setProperty("prop1", "value1New2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals("value1New2", v1.getPropertyValue("prop1"));
}
@Test
public void testChangeVisibilityEdge() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
// test that we can see the edge with A and not B
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
// change the edge
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
// test that we can see the edge with B and not A
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
// change the edge visibility to same
e1 = graph.getEdge("e1", AUTHORIZATIONS_B);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
// test that we can see the edge with B and not A
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
}
@Test
public void testChangeVisibilityOnBadPropertyName() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_EMPTY)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
try {
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility("propBad", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
fail("show throw");
} catch (SecureGraphException ex) {
assertNotNull(ex);
}
}
@Test
public void testChangeVisibilityOnStreamingProperty() throws IOException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()), String.class);
String largePropertyName = "propLarge/\\*!@
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty(largePropertyName, propLarge, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility("propSmall", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility(largePropertyName, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
}
@Test
public void testChangePropertyMetadata() {
Map<String, Object> prop1Metadata = new HashMap<String, Object>();
prop1Metadata.put("prop1_key1", "valueOld");
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_EMPTY)
.setProperty("prop2", "value2", null, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterPropertyMetadata("prop1", "prop1_key1", "valueNew")
.save(AUTHORIZATIONS_A_AND_B);
assertEquals("valueNew", v1.getProperty("prop1").getMetadata().get("prop1_key1"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("valueNew", v1.getProperty("prop1").getMetadata().get("prop1_key1"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterPropertyMetadata("prop2", "prop2_key1", "valueNew")
.save(AUTHORIZATIONS_A_AND_B);
assertEquals("valueNew", v1.getProperty("prop2").getMetadata().get("prop2_key1"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("valueNew", v1.getProperty("prop2").getMetadata().get("prop2_key1"));
}
@Test
public void testIsVisibilityValid() {
assertFalse(graph.isVisibilityValid(VISIBILITY_A, AUTHORIZATIONS_C));
assertTrue(graph.isVisibilityValid(VISIBILITY_B, AUTHORIZATIONS_A_AND_B));
assertTrue(graph.isVisibilityValid(VISIBILITY_B, AUTHORIZATIONS_B));
assertTrue(graph.isVisibilityValid(VISIBILITY_EMPTY, AUTHORIZATIONS_A));
}
@Test
public void testModifyVertexWithLowerAuthorizationThenOtherProperties() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.setProperty("prop1", "value1New", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop2", "value2")
.vertices();
assertVertexIds(vertices, new String[]{"v1"});
}
@Test
public void testPartialUpdateOfVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1New", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop2", "value2")
.vertices();
assertVertexIds(vertices, new String[]{"v1"});
}
protected void assertVertexIds(Iterable<Vertex> vertices, String[] ids) {
List<Vertex> verticesList = toList(vertices);
assertEquals("ids length mismatch", ids.length, verticesList.size());
for (int i = 0; i < ids.length; i++) {
assertEquals("at offset: " + i, ids[i], verticesList.get(i).getId());
}
}
}
|
package com.google.musicanalysis.site;
import com.google.musicanalysis.util.Secrets;
import com.google.musicanalysis.util.URLEncodedBuilder;
import com.google.gson.JsonParser;
import com.google.musicanalysis.util.URLEncodedBuilder;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
@WebServlet("/api/youtube")
public class YoutubeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// retrieve Youtube API key and access token
String API_KEY = "";
HttpSession session = null;
String accessToken = "";
try {
API_KEY = Secrets.getSecretString("YOUTUBE_API_KEY");
session = req.getSession();
accessToken = session.getAttribute("youtube_access_token").toString();
} catch (NullPointerException e) {
res.setStatus(401);
return;
}
// make http request to youtube API
var youtubeParam = new URLEncodedBuilder()
.add("part", "topicDetails")
.add("myRating", "like")
.add("key", API_KEY);
URI youtubeUri = URI.create("https:
var httpClient = HttpClient.newHttpClient();
var youtubeReq = HttpRequest.newBuilder(youtubeUri)
.header("Authorization", "Bearer " + accessToken)
.header("Accept", "application/json")
.GET()
.build();
// get response to Youtube API
var youtubeRes = httpClient.sendAsync(youtubeReq, BodyHandlers.ofString()).join();
var youtubeResBody = youtubeRes.body();
res.getWriter().write(youtubeResBody);
}
}
|
package io.spine.server.rejection;
import com.google.protobuf.StringValue;
import io.spine.base.Error;
import io.spine.core.Ack;
import io.spine.core.Rejection;
import io.spine.core.RejectionClass;
import io.spine.core.RejectionEnvelope;
import io.spine.grpc.MemoizingObserver;
import io.spine.server.delivery.Consumers;
import io.spine.server.rejection.given.AnotherInvalidProjectNameDelegate;
import io.spine.server.rejection.given.BareDispatcher;
import io.spine.server.rejection.given.CommandAwareSubscriber;
import io.spine.server.rejection.given.CommandMessageAwareSubscriber;
import io.spine.server.rejection.given.ContextAwareSubscriber;
import io.spine.server.rejection.given.FaultySubscriber;
import io.spine.server.rejection.given.InvalidOrderSubscriber;
import io.spine.server.rejection.given.InvalidProjectNameDelegate;
import io.spine.server.rejection.given.InvalidProjectNameSubscriber;
import io.spine.server.rejection.given.MultipleRejectionSubscriber;
import io.spine.server.rejection.given.PostponedDispatcherRejectionDelivery;
import io.spine.server.rejection.given.RejectionMessageSubscriber;
import io.spine.server.rejection.given.VerifiableSubscriber;
import io.spine.test.rejection.command.StartProject;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.Executor;
import static io.spine.core.Status.StatusCase.ERROR;
import static io.spine.grpc.StreamObservers.memoizingObserver;
import static io.spine.server.rejection.given.Given.cannotModifyDeletedEntity;
import static io.spine.server.rejection.given.Given.invalidProjectNameRejection;
import static io.spine.server.rejection.given.Given.missingOwnerRejection;
import static io.spine.test.rejection.ProjectRejections.InvalidProjectName;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* @author Alex Tymchenko
*/
@SuppressWarnings({"ClassWithTooManyMethods",
"OverlyCoupledClass",
"InstanceVariableNamingConvention"})
// OK as for the test class for one of the primary framework features
public class RejectionBusShould {
private RejectionBus rejectionBus;
private PostponedDispatcherRejectionDelivery postponedDelivery;
private Executor delegateDispatcherExecutor;
private RejectionBus rejectionBusWithPostponedExecution;
@Before
public void setUp() {
this.rejectionBus = RejectionBus.newBuilder()
.build();
this.delegateDispatcherExecutor = spy(directExecutor());
this.postponedDelivery =
new PostponedDispatcherRejectionDelivery(delegateDispatcherExecutor);
this.rejectionBusWithPostponedExecution =
RejectionBus.newBuilder()
.setDispatcherRejectionDelivery(postponedDelivery)
.build();
}
@SuppressWarnings("MethodMayBeStatic") /* it cannot, as its result is used in {@code org.mockito.Mockito.spy() */
private Executor directExecutor() {
return new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
};
}
@Test
public void have_builder() {
assertNotNull(RejectionBus.newBuilder());
}
@Test
public void return_associated_DispatcherDelivery() {
final DispatcherRejectionDelivery delivery = mock(DispatcherRejectionDelivery.class);
final RejectionBus result = RejectionBus.newBuilder()
.setDispatcherRejectionDelivery(delivery)
.build();
assertEquals(delivery, result.delivery());
}
@Test
public void return_direct_DispatcherDelivery_if_none_customized() {
final DispatcherRejectionDelivery actual = rejectionBus.delivery();
assertTrue(actual instanceof DispatcherRejectionDelivery.DirectDelivery);
}
@Test // as the RejectionBus instances do not support enrichment yet.
public void not_enrich_rejection_messages() {
final Rejection original = invalidProjectNameRejection();
final RejectionEnvelope enriched = rejectionBus.enrich(RejectionEnvelope.of(original));
assertEquals(original, enriched.getOuterObject());
}
@Test(expected = IllegalArgumentException.class)
public void reject_object_with_no_subscriber_methods() {
rejectionBus.register(new RejectionSubscriber());
}
@Test
public void register_rejection_subscriber() {
final RejectionSubscriber subscriberOne = new InvalidProjectNameSubscriber();
final RejectionSubscriber subscriberTwo = new InvalidProjectNameSubscriber();
rejectionBus.register(subscriberOne);
rejectionBus.register(subscriberTwo);
final RejectionClass rejectionClass = RejectionClass.of(InvalidProjectName.class);
assertTrue(rejectionBus.hasDispatchers(rejectionClass));
final Collection<RejectionDispatcher<?>> dispatchers = rejectionBus.getDispatchers(
rejectionClass);
assertTrue(dispatchers.contains(subscriberOne));
assertTrue(dispatchers.contains(subscriberTwo));
}
@Test
public void unregister_subscribers() {
final RejectionSubscriber subscriberOne = new InvalidProjectNameSubscriber();
final RejectionSubscriber subscriberTwo = new InvalidProjectNameSubscriber();
rejectionBus.register(subscriberOne);
rejectionBus.register(subscriberTwo);
final RejectionClass rejectionClass = RejectionClass.of(
InvalidProjectName.class);
rejectionBus.unregister(subscriberOne);
// Check that the 2nd subscriber with the same rejection subscriber method remains
// after the 1st subscriber unregisters.
final Collection<RejectionDispatcher<?>> subscribers =
rejectionBus.getDispatchers(rejectionClass);
assertFalse(subscribers.contains(subscriberOne));
assertTrue(subscribers.contains(subscriberTwo));
// Check that after 2nd subscriber us unregisters he's no longer in
rejectionBus.unregister(subscriberTwo);
assertFalse(rejectionBus.getDispatchers(rejectionClass)
.contains(subscriberTwo));
}
@Test
public void call_subscriber_when_rejection_posted() {
final InvalidProjectNameSubscriber subscriber = new InvalidProjectNameSubscriber();
final Rejection rejection = invalidProjectNameRejection();
rejectionBus.register(subscriber);
rejectionBus.post(rejection);
final Rejection handled = subscriber.getRejectionHandled();
// Compare the content without command ID, which is different in the remembered
assertEquals(rejection.getMessage(), handled.getMessage());
assertEquals(rejection.getContext()
.getCommand()
.getMessage(),
handled.getContext()
.getCommand()
.getMessage());
assertEquals(rejection.getContext()
.getCommand()
.getContext(),
handled.getContext()
.getCommand()
.getContext());
}
@Test
public void call_subscriber_by_rejection_and_command_message_when_rejection_posted() {
final MultipleRejectionSubscriber subscriber = new MultipleRejectionSubscriber();
rejectionBus.register(subscriber);
final Class<StartProject> commandMessageCls = StartProject.class;
final Rejection rejection = cannotModifyDeletedEntity(commandMessageCls);
rejectionBus.post(rejection);
assertEquals(1, subscriber.numberOfSubscriberCalls());
assertEquals(commandMessageCls, subscriber.commandMessageClass());
}
@Test
public void call_subscriber_by_rejection_message_only() {
final MultipleRejectionSubscriber subscriber = new MultipleRejectionSubscriber();
rejectionBus.register(subscriber);
final Class<StringValue> commandMessageCls = StringValue.class;
final Rejection rejection = cannotModifyDeletedEntity(commandMessageCls);
rejectionBus.post(rejection);
assertEquals(1, subscriber.numberOfSubscriberCalls());
assertNull(subscriber.commandMessageClass());
}
@Test
public void register_dispatchers() {
final RejectionDispatcher<?> dispatcher = new BareDispatcher();
rejectionBus.register(dispatcher);
final RejectionClass rejectionClass = RejectionClass.of(InvalidProjectName.class);
assertTrue(rejectionBus.getDispatchers(rejectionClass)
.contains(dispatcher));
}
@Test
public void call_dispatchers() {
final BareDispatcher dispatcher = new BareDispatcher();
rejectionBus.register(dispatcher);
rejectionBus.post(invalidProjectNameRejection());
assertTrue(dispatcher.isDispatchCalled());
}
@Test
public void not_call_dispatchers_if_dispatcher_rejection_execution_postponed() {
final BareDispatcher dispatcher = new BareDispatcher();
rejectionBusWithPostponedExecution.register(dispatcher);
final Rejection rejection = invalidProjectNameRejection();
rejectionBusWithPostponedExecution.post(rejection);
assertFalse(dispatcher.isDispatchCalled());
final boolean rejectionPostponed = postponedDelivery.isPostponed(rejection, dispatcher);
assertTrue(rejectionPostponed);
}
@Test
public void deliver_postponed_rejection_to_dispatcher_using_configured_executor() {
final BareDispatcher dispatcher = new BareDispatcher();
rejectionBusWithPostponedExecution.register(dispatcher);
final Rejection rejection = invalidProjectNameRejection();
rejectionBusWithPostponedExecution.post(rejection);
final Set<RejectionEnvelope> postponedRejections = postponedDelivery.getPostponedRejections();
final RejectionEnvelope postponedRejection = postponedRejections.iterator()
.next();
verify(delegateDispatcherExecutor, never()).execute(any(Runnable.class));
postponedDelivery.deliverNow(postponedRejection, Consumers.idOf(dispatcher));
assertTrue(dispatcher.isDispatchCalled());
verify(delegateDispatcherExecutor).execute(any(Runnable.class));
}
@Test
public void pick_proper_consumer_by_consumer_id_when_delivering_to_delegates_of_same_rejection() {
final InvalidProjectNameDelegate first = new InvalidProjectNameDelegate();
final AnotherInvalidProjectNameDelegate second = new AnotherInvalidProjectNameDelegate();
final DelegatingRejectionDispatcher<String> firstDispatcher =
DelegatingRejectionDispatcher.of(first);
final DelegatingRejectionDispatcher<String> secondDispatcher =
DelegatingRejectionDispatcher.of(second);
rejectionBusWithPostponedExecution.register(firstDispatcher);
rejectionBusWithPostponedExecution.register(secondDispatcher);
final Rejection rejection = invalidProjectNameRejection();
rejectionBusWithPostponedExecution.post(rejection);
final Set<RejectionEnvelope> postponedRejections = postponedDelivery.getPostponedRejections();
final RejectionEnvelope postponedRejection = postponedRejections.iterator()
.next();
verify(delegateDispatcherExecutor, never()).execute(any(Runnable.class));
postponedDelivery.deliverNow(postponedRejection, Consumers.idOf(firstDispatcher));
assertTrue(first.isDispatchCalled());
verify(delegateDispatcherExecutor).execute(any(Runnable.class));
assertFalse(second.isDispatchCalled());
}
@Test
public void unregister_dispatchers() {
final RejectionDispatcher<?> dispatcherOne = new BareDispatcher();
final RejectionDispatcher<?> dispatcherTwo = new BareDispatcher();
final RejectionClass rejectionClass = RejectionClass.of(InvalidProjectName.class);
rejectionBus.register(dispatcherOne);
rejectionBus.register(dispatcherTwo);
rejectionBus.unregister(dispatcherOne);
final Set<RejectionDispatcher<?>> dispatchers = rejectionBus.getDispatchers(rejectionClass);
// Check we don't have 1st dispatcher, but have 2nd.
assertFalse(dispatchers.contains(dispatcherOne));
assertTrue(dispatchers.contains(dispatcherTwo));
rejectionBus.unregister(dispatcherTwo);
assertFalse(rejectionBus.getDispatchers(rejectionClass)
.contains(dispatcherTwo));
}
@Test
public void catch_exceptions_caused_by_subscribers() {
final VerifiableSubscriber faultySubscriber = new FaultySubscriber();
rejectionBus.register(faultySubscriber);
rejectionBus.post(invalidProjectNameRejection());
assertTrue(faultySubscriber.isMethodCalled());
}
@Test
public void unregister_registries_on_close() throws Exception {
final RejectionBus rejectionBus = RejectionBus.newBuilder()
.build();
rejectionBus.register(new BareDispatcher());
rejectionBus.register(new InvalidProjectNameSubscriber());
final RejectionClass rejectionClass = RejectionClass.of(InvalidProjectName.class);
rejectionBus.close();
assertTrue(rejectionBus.getDispatchers(rejectionClass)
.isEmpty());
}
@Test
public void support_short_form_subscriber_methods() {
final RejectionMessageSubscriber subscriber = new RejectionMessageSubscriber();
checkRejection(subscriber);
}
@Test
public void support_context_aware_subscriber_methods() {
final ContextAwareSubscriber subscriber = new ContextAwareSubscriber();
checkRejection(subscriber);
}
@Test
public void support_command_msg_aware_subscriber_methods() {
final CommandMessageAwareSubscriber subscriber = new CommandMessageAwareSubscriber();
checkRejection(subscriber);
}
@Test
public void support_command_aware_subscriber_methods() {
final CommandAwareSubscriber subscriber = new CommandAwareSubscriber();
checkRejection(subscriber);
}
@Test(
expected = IllegalArgumentException.class
// In Bus -> No message types are forwarded by this dispatcher.
)
public void not_support_subscriber_methods_with_wrong_parameter_sequence() {
final RejectionDispatcher<?> subscriber = new InvalidOrderSubscriber();
rejectionBus.register(subscriber);
rejectionBus.post(missingOwnerRejection());
}
@Test
public void report_dead_messages() {
final MemoizingObserver<Ack> observer = memoizingObserver();
rejectionBus.post(missingOwnerRejection(), observer);
assertTrue(observer.isCompleted());
final Ack result = observer.firstResponse();
assertNotNull(result);
assertEquals(ERROR, result.getStatus().getStatusCase());
final Error error = result.getStatus().getError();
assertEquals(UnhandledRejectionException.class.getCanonicalName(), error.getType());
}
@Test
public void have_log() {
assertNotNull(RejectionBus.log());
}
private void checkRejection(VerifiableSubscriber subscriber) {
final Rejection rejection = missingOwnerRejection();
rejectionBus.register(subscriber);
rejectionBus.post(rejection);
assertTrue(subscriber.isMethodCalled());
subscriber.verifyGot(rejection);
}
}
|
package org.oskari.cache;
import fi.nls.oskari.cache.JedisManager;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.util.OskariRuntimeException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class JedisSubscriberClient extends JedisPubSub {
private final static Logger LOG = LogFactory.getLogger(JedisSubscriberClient.class);
private ExecutorService service = Executors.newFixedThreadPool(1);
private String functionalityId;
private Jedis client;
private Map<String, List<MessageListener>> listeners = new HashMap<>();
/**
* Same as JedisManager.publish() but this uses the same functionality id <> channel separation as when
* listening to the messages.
*
* Mostly for documentary purposes on how you SHOULD send a message so the subscriber with the same
* functionality id will catch it.
*
* @param functionalityId
* @param channel
* @param message
* @return
*/
public static long sendMessage(String functionalityId, String channel, String message) {
// we can use the same client to send AND subscribe so using JdeisManagers pooled connections for sending
return JedisManager.publish(JedisSubscriberClient.getChannel(functionalityId, channel), message);
}
/**
* For sending messages with JedisManager you can use this method to construct the channel for the functionality id/channel combo.
* @param functionalityId
* @param channel
* @return
*/
public static String getChannel(String functionalityId, String channel) {
return functionalityId + "_" + channel;
}
public JedisSubscriberClient(String functionalityId) {
if (functionalityId == null) {
throw new OskariRuntimeException("Requires functionalityId");
}
this.functionalityId = functionalityId;
startListening(getFullChannelPrefix());
}
/**
* The main method for listening to messages for the functionality
* @param channel
* @param listener
*/
public void addListener(String channel, MessageListener listener) {
List<MessageListener> existingListeners = listeners.computeIfAbsent(channel, key -> new ArrayList<>());
existingListeners.add(listener);
}
/**
* Same as the other sendMessage but since it's called through the subscriber instance we already know the functionality id.
* @param channel
* @param message
* @return
*/
public long sendMessage(String channel, String message) {
return JedisSubscriberClient.sendMessage(functionalityId, channel, message);
}
/**
* Removes listeners and closes connection to Redis. A "destroy"/cleanup method and you can't use the subscriber
* after calling this.
*/
public void stopListening() {
listeners.clear();
try {
// shutdown thread so it's not reconnecting
service.shutdown();
} catch (Exception ignored) {
LOG.ignore("Error shutting down listener thread", ignored);
}
try {
// unsubscribe from Redis
// closes the client it was passed as well
this.unsubscribe();
} catch (Exception ignored) {
LOG.ignore("Error unsubscribing while shutting down", ignored);
}
}
/**
* Not meant to be overridden. It's just a method we are overriding from JedisPubSub.
* @param pattern
* @param channel
* @param message
*/
@Override
public void onPMessage(String pattern, String channel, String message) {
getListeners(channel).stream().forEach(l -> l.onMessage(message));
}
private String getFullChannelPrefix() {
return JedisManager.PUBSUB_CHANNEL_PREFIX + functionalityId + "_";
}
private List<MessageListener> getListeners(String channel) {
String prefix = getFullChannelPrefix();
if (channel == null || !channel.startsWith(prefix)) {
return Collections.emptyList();
}
String key = channel.substring(prefix.length());
return listeners.getOrDefault(key, Collections.emptyList());
}
private void startListening(String prefix) {
// if subscribe raises en exception the Thread will end
// and the executor will execute the next task -> reconnecting the client
service.execute(() -> {
try (Jedis jedis = createClient()) {
LOG.info("Subscribing to all channels starting with", prefix);
// Subscribe is a blocking action hence the thread
// Also we don't care about pooling here since
// the client remains blocked for subscription
jedis.psubscribe(this, prefix + "*");
} catch (Exception e) {
LOG.error(e,"Problem listening to channel:", prefix);
} finally {
client = null;
}
});
}
// "A client subscribed to one or more channels should not issue commands,
// although it can subscribe and unsubscribe to and from other channels."
// "Make sure the subscriber and publisher threads do not share the same Jedis connection."
// NOTE!! create a new client for subscriptions instead of using pool to make sure clients don't conflict
private Jedis createClient() {
if (client == null) {
client = new Jedis(JedisManager.getHost(), JedisManager.getPort());
}
return client;
}
}
|
package org.slc.sli.manager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.slc.sli.config.ConfigUtil;
import org.slc.sli.config.Field;
import org.slc.sli.config.ViewConfig;
import org.slc.sli.entity.GenericEntity;
import org.slc.sli.util.Constants;
/**
* PopulationManager facilitates creation of logical aggregations of EdFi entities/associations such as a
* student summary comprised of student profile, enrollment, program, and assessment information in order to
* deliver the Population Summary interaction.
*
* @author Robert Bloh rbloh@wgen.net
*
*/
public class PopulationManager {
private static Logger log = LoggerFactory.getLogger(PopulationManager.class);
@Autowired
private EntityManager entityManager;
public PopulationManager() {
}
public SortedSet<String> sortByGradeLevel(final String token, Map<String, List<GenericEntity>> historicalData) {
SortedSet<String> results = new TreeSet<String>(Collections.reverseOrder());
for (Map.Entry<String, List<GenericEntity>> studentData : historicalData.entrySet()) {
List<GenericEntity> list = studentData.getValue();
//get the assessment list
for (GenericEntity entity : list) {
results.add(entity.getString("gradeLevelWhenTaken"));
}
//sort by the school year
Collections.sort(list, new GradeLevelComparator());
}
return results;
}
/**
* Get the list of student summaries identified by the student id list and authorized for the
* security token
*
* @param token
* - the principle authentication token
* @param studentIds
* - the student id list
* @param sessionId
* - The id of the current session so you can get historical context.
* @return studentList
* - the student summary entity list
*/
public List<GenericEntity> getStudentSummaries(String token, List<String> studentIds, ViewConfig viewConfig, String sessionId) {
// Initialize student summaries
List<GenericEntity> studentSummaries = entityManager.getStudents(token, studentIds);
// Get student programs
List<GenericEntity> studentPrograms = entityManager.getPrograms(token, studentIds);
Map<String, Object> studentProgramMap = new HashMap<String, Object>();
for (GenericEntity studentProgram : studentPrograms) {
List<String> programs = (List<String>) studentProgram.get(Constants.ATTR_PROGRAMS);
studentProgramMap.put(studentProgram.getString(Constants.ATTR_STUDENT_ID), programs);
}
// Get student assessments
long startTime = System.nanoTime();
Map<String, Object> studentAssessmentMap = new HashMap<String, Object>();
for (String studentId : studentIds) {
List<GenericEntity> studentAssessments = getStudentAssessments(token, studentId, viewConfig);
studentAssessmentMap.put(studentId, studentAssessments);
}
double endTime = (System.nanoTime() - startTime) * 1.0e-9;
log.warn("@@@@@@@@@@@@@@@@@@ Benchmark for assessment: " + endTime + "\t Avg per student: " + endTime / studentIds.size());
Map<String, Object> studentAttendanceMap = createStudentAttendanceMap(token, studentIds, sessionId);
// Add programs, attendance, and student assessment results to summaries
for (GenericEntity studentSummary : studentSummaries) {
String id = studentSummary.getString(Constants.ATTR_ID);
studentSummary.put(Constants.ATTR_PROGRAMS, studentProgramMap.get(id));
studentSummary.put(Constants.ATTR_STUDENT_ASSESSMENTS, studentAssessmentMap.get(id));
studentSummary.put(Constants.ATTR_STUDENT_ATTENDANCES, studentAttendanceMap.get(id));
}
return studentSummaries;
}
public Map<String, Object> createStudentAttendanceMap(String token, List<String> studentIds, String sessionId) {
// Get attendance
Map<String, Object> studentAttendanceMap = new HashMap<String, Object>();
long startTime = System.nanoTime();
List<String> dates = getSessionDates(token, sessionId);
for (String studentId : studentIds) {
List<GenericEntity> studentAttendance = getStudentAttendance(token, studentId, dates.get(0), dates.get(1));
if (studentAttendance != null && !studentAttendance.isEmpty())
studentAttendanceMap.put(studentId, studentAttendance);
}
double endTime = (System.nanoTime() - startTime) * 1.0e-9;
log.warn("@@@@@@@@@@@@@@@@@@ Benchmark for attendance: " + endTime + "\t Avg per student: " + endTime / studentIds.size());
return studentAttendanceMap;
}
private List<GenericEntity> getStudentAttendance(String token, String studentId, String startDate, String endDate) {
return entityManager.getAttendance(token, studentId, startDate, endDate);
}
/**
* Get a list of assessment results for one student, filtered by assessment name
*
* @param username
* @param studentId
* @param config
* @return
*/
private List<GenericEntity> getStudentAssessments(String username, String studentId, ViewConfig config) {
// get list of assmt names from config
List<Field> dataFields = ConfigUtil.getDataFields(config, Constants.FIELD_TYPE_ASSESSMENT);
Set<String> assmtNames = getAssmtNames(dataFields);
// get all assessments for student
List<GenericEntity> assmts = entityManager.getStudentAssessments(username, studentId);
// filter out unwanted assmts
List<GenericEntity> filteredAssmts = new ArrayList<GenericEntity>();
filteredAssmts.addAll(assmts);
/* To do this right, we'll need all the assessments under the assmt family's name, and
* we'll require assessment metadata for it
for (Assessment assmt : assmts) {
if (assmtNames.contains(assmt.getAssessmentName()))
filteredAssmts.add(assmt);
}
*/
return filteredAssmts;
}
/*
* Get names of assessments we need data for
*/
private Set<String> getAssmtNames(List<Field> dataFields) {
Set<String> assmtNames = new HashSet<String>();
for (Field field : dataFields) {
String fieldValue = field.getValue();
assmtNames.add(fieldValue.substring(0, fieldValue.indexOf('.')));
}
return assmtNames;
}
/**
* Get assessments from the api, given student assessment data
*
* @param username
* @param studentAssessments
* @return
*/
public List<GenericEntity> getAssessments(String username, List<GenericEntity> studentSummaries) {
// get the list of assessment ids from the student assessments
List<String> assmtIds = extractAssessmentIds(studentSummaries);
// get the assessment objects from the api
List<GenericEntity> assmts = entityManager.getAssessments(username, assmtIds);
return assmts;
}
/**
* Helper method to grab the assessment ids from the student assessment results
*
* @return
*/
private List<String> extractAssessmentIds(List<GenericEntity> studentSummaries) {
List<String> assmtIds = new ArrayList<String>();
// loop through student summaries, grab student assessment lists
for (GenericEntity studentSummary : studentSummaries) {
List<GenericEntity> studentAssmts = (List<GenericEntity>) studentSummary.get(Constants.ATTR_STUDENT_ASSESSMENTS);
for (GenericEntity studentAssmt : studentAssmts) {
// add assessment id to the list
String assmtId = studentAssmt.getString(Constants.ATTR_ASSESSMENT_ID);
if (!(assmtIds.contains(assmtId))) {
assmtIds.add(assmtId);
}
}
}
return assmtIds;
}
/**
* Returns a list of historical data for a given subject area
* @param token Security token
* @param studentIds List of student ids
* @param subjectArea The subject area to search for
* @return
*/
public Map<String, List<GenericEntity>> getStudentHistoricalAssessments(final String token, List<String> studentIds, String subjectArea) {
Map<String, List<GenericEntity>> results = new HashMap<String, List<GenericEntity>>();
//build the params
Map<String, String> params = new HashMap<String, String>();
params.put(Constants.ATTR_SUBJECTAREA, subjectArea);
params.put(Constants.PARAM_INCLUDE_FIELDS, Constants.ATTR_COURSE_TITLE);
for (String studentId : studentIds) {
log.debug("Historical data [studentId] " + studentId);
//get the corses in the subject area for the f=given student
List<GenericEntity> courses = entityManager.getCourses(token, studentId, params);
log.debug("Historical data [courses] " + courses);
for (GenericEntity course : courses) {
log.debug("Historical data [course] " + course);
//get the studentCourseAssociation for the given student and course
List<GenericEntity> associations = getStudentCourseAssociations(token, studentId, course.getString(Constants.ATTR_ID));
log.debug("Historical data [studentTranscriptAssociations] " + associations);
for (GenericEntity association : associations) {
log.debug("Historical data [studentTranscriptAssocitaion] " + association);
//remove unwanted entries
association.remove(Constants.ATTR_ID);
association.remove("entityType");
//add in the extra data
association.put(Constants.ATTR_COURSE_TITLE, course.getString(Constants.ATTR_COURSE_TITLE));
association.put(Constants.ATTR_SUBJECTAREA, subjectArea);
association.put(Constants.ATTR_COURSE_ID, course.getString(Constants.ATTR_ID));
log.debug("Historical data [return type] " + association);
if (results.get(studentId) != null) {
results.get(studentId).add(association);
} else {
List<GenericEntity> list = new ArrayList<GenericEntity>();
list.add(association);
results.put(studentId, list);
}
}
}
}
return results;
}
/**
* Apply school year data to the historical assessment data set and
* return a sorted set of school years
* @param token Security token
* @param historicalData The historical assessment data
* @return
*/
public SortedSet<String> applyShoolYear(final String token, Map<String, List<GenericEntity>> historicalData) {
SortedSet<String> results = new TreeSet<String>(Collections.reverseOrder());
for (Map.Entry<String, List<GenericEntity>> studentData : historicalData.entrySet()) {
String studentId = studentData.getKey();
List<GenericEntity> list = studentData.getValue();
//get the assessment list
for (GenericEntity entity : list) {
//get the school year
String schoolYear = getSchoolYear(token, studentId, entity.getString(Constants.ATTR_COURSE_ID));
entity.put(Constants.ATTR_SCHOOL_YEAR, schoolYear);
results.add(schoolYear);
}
//sort by the school year
Collections.sort(list, new SchoolYearComparator());
}
return results;
}
/**
* Returns a list of studentCourseAssociations for a given student and course Id
* @param token Security token
* @param studentId The student Id
* @param courseId The course Id
* @return
*/
protected List<GenericEntity> getStudentCourseAssociations(final String token, final String studentId, String courseId) {
//build the params
Map<String, String> params = new HashMap<String, String>();
params.put(Constants.ATTR_COURSE_ID, courseId);
params.put(Constants.PARAM_INCLUDE_FIELDS, Constants.ATTR_FINAL_LETTER_GRADE);
return entityManager.getStudentTranscriptAssociations(token, studentId, params);
}
/**
* Returns the school year for a given student and a course
* @param token Security token
* @param studentId The student Id
* @param courseId The course Id
* @return
*/
protected String getSchoolYear(final String token, final String studentId, final String courseId) {
SortedSet<String> schoolYears = new TreeSet<String>();
String schoolYear = null;
//build the params
Map<String, String> params = new HashMap<String, String>();
params.put(Constants.PARAM_INCLUDE_FIELDS, Constants.ATTR_SCHOOL_YEAR);
//get the sections
List<GenericEntity> sections = getSections(token, studentId, courseId);
for (GenericEntity section : sections) {
GenericEntity entity = entityManager.getEntity(token, Constants.ATTR_SESSIONS, section.getString(Constants.ATTR_SESSION_ID), params);
schoolYears.add(entity.getString(Constants.ATTR_SCHOOL_YEAR));
}
//if we have a school year, then pick the last(latest) from the sorted map
if (!schoolYears.isEmpty()) {
schoolYear = schoolYears.last();
}
return schoolYear;
}
/**
* Returns a list of sections for the given student and course
* @param token Security token
* @param studentId The student Id
* @param courseId The course Id
* @return
*/
protected List<GenericEntity> getSections(final String token, final String studentId, final String courseId) {
Map<String, String> params = new HashMap<String, String>();
params.put(Constants.ATTR_COURSE_ID, courseId);
params.put(Constants.PARAM_INCLUDE_FIELDS, Constants.ATTR_SESSION_ID);
return entityManager.getSections(token, studentId, params);
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* Get student entity
* @param token
* @param studentId
* @return
*/
public GenericEntity getStudent(String token, String studentId) {
return entityManager.getStudent(token, studentId);
}
/**
* Get student with additional info for CSI panel
* @param token
* @param studentId
* @return
*/
public GenericEntity getStudentForCSIPanel(String token, String studentId) {
return entityManager.getStudentForCSIPanel(token, studentId);
}
private List<String> getSessionDates(String token, String sessionId) {
//Get the session first.
GenericEntity session = entityManager.getSession(token, sessionId);
List<String> dates = new ArrayList<String>();
if (session.containsKey("beginDate")) {
dates.add(session.getString("beginDate"));
dates.add(session.getString("endDate"));
} else {
dates.add("");
dates.add("");
}
return dates;
}
/**
* Compare two GenericEntities by the school year
* @author srupasinghe
*
*/
class SchoolYearComparator implements Comparator<GenericEntity> {
public int compare(GenericEntity e1, GenericEntity e2) {
return e2.getString("schoolYear").compareTo(e1.getString("schoolYear"));
}
}
/**
* Compare two GenericEntities by grade level
* @author srupasinghe
*
*/
class GradeLevelComparator implements Comparator<GenericEntity> {
public int compare(GenericEntity e1, GenericEntity e2) {
if (e1.getString("gradeLevelWhenTaken") == null || e2.getString("gradeLevelWhenTaken") == null) {
return 0;
}
return e2.getString("gradeLevelWhenTaken").compareTo(e1.getString("gradeLevelWhenTaken"));
}
}
}
|
/**
* @author dgeorge
*
* $Id: UserManagerImpl.java,v 1.33 2009-05-28 18:47:31 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.32 2008/06/18 17:53:31 pandyas
* Removed commented out lines needed for authentication
*
* Revision 1.31 2008/05/21 19:03:56 pandyas
* Modified advanced search to prevent SQL injection
* Re: Apps Scan run 05/15/2008
*
* Revision 1.30 2007/08/07 15:01:25 pandyas
* replace log statements
*
* Revision 1.29 2007/07/31 12:02:21 pandyas
* VCDE silver level and caMOD 2.3 changes
*
* Revision 1.28 2007/04/17 17:32:42 pandyas
* Added debug for e-mail from LDAP - testing bug for PM e-mail
*
* Revision 1.27 2007/03/27 18:39:41 pandyas
* changed debug statments to clean up output - done testing changes
*
* Revision 1.26 2007/03/20 14:11:11 pandyas
* Added logging to debug QA tier
*
* Revision 1.25 2006/12/22 17:03:32 pandyas
* Reversed commented out ocde for authentication
*
* Revision 1.24 2006/09/14 17:39:52 georgeda
* solved file not found issue - jboss location was wrong
*
* Revision 1.22 2006/08/17 18:15:37 pandyas
* Defect# 410: Externalize properties files - Code changes to get properties
*
* Revision 1.21 2006/05/15 13:39:21 georgeda
* Cleaned up contact info management
*
* Revision 1.20 2006/05/08 13:34:27 georgeda
* Reformat and clean up warnings
*
* Revision 1.19 2006/04/20 19:09:26 georgeda
* Backed out another change
*
* Revision 1.18 2006/04/19 15:08:44 georgeda
* Uncomment login checking
*
* Revision 1.17 2006/04/17 19:11:05 pandyas
* caMod 2.1 OM changes
*
* Revision 1.16 2005/12/06 22:00:04 georgeda
* Defect #253, only check roles when there is a username
*
* Revision 1.15 2005/12/06 14:50:45 georgeda
* Defect #253, change the lowecase to the login action so that roles match
*
* Revision 1.14 2005/12/05 19:35:17 schroedn
* Defect #253 - Covert username to all lowercase before validating
*
* Revision 1.13 2005/11/29 16:13:04 georgeda
* Check for null password in login
*
* Revision 1.12 2005/11/18 21:05:37 georgeda
* Defect #130, added superuser
*
* Revision 1.11 2005/11/08 22:32:44 georgeda
* LDAP changes
*
* Revision 1.10 2005/11/07 13:58:29 georgeda
* Dynamically update roles
*
* Revision 1.9 2005/10/24 13:28:06 georgeda
* Cleanup changes
*
* Revision 1.8 2005/10/17 13:10:16 georgeda
* Get contact information
*
* Revision 1.7 2005/10/13 17:00:06 georgeda
* Cleanup
*
* Revision 1.6 2005/09/30 19:49:58 georgeda
* Make sure user is in db
*
* Revision 1.5 2005/09/22 18:55:49 georgeda
* Get coordinator from user in properties file
*
* Revision 1.4 2005/09/22 15:15:17 georgeda
* More changes
*
* Revision 1.3 2005/09/16 15:52:57 georgeda
* Changes due to manager re-write
*
*
*/
package gov.nih.nci.camod.service.impl;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.*;
import gov.nih.nci.camod.service.UserManager;
import gov.nih.nci.camod.util.LDAPUtil;
import gov.nih.nci.common.persistence.Search;
import gov.nih.nci.security.AuthenticationManager;
import gov.nih.nci.security.SecurityServiceProvider;
import gov.nih.nci.security.exceptions.CSException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
/**
* Implementation of class used to wrap the CSM implementation
*/
public class UserManagerImpl extends BaseManager implements UserManager {
private AuthenticationManager theAuthenticationMgr = null;
/**
* Constructor gets reference to authorization manager
*/
UserManagerImpl() {
log.debug("Entering UserManagerImpl");
try {
log.debug("Entering main try");
theAuthenticationMgr = SecurityServiceProvider
.getAuthenticationManager(Constants.UPT_CONTEXT_NAME);
log.debug("theAuthenticationMgrtoString(): " + theAuthenticationMgr.toString());
} catch (CSException ex) {
log.error("Error getting authentication managers", ex);
} catch (Throwable e) {
log.error("Error getting authentication managers", e);
}
log.debug("Exiting UserManagerImpl");
}
/**
* Get a list of roles for a user
*
* @param inUsername
* the login name of the user
*
* @return the list of roles associated with the user
* @throws Exception
*/
public List getRolesForUser(String inUsername) throws Exception {
log.debug("Entering getRolesForUser");
List<String> theRoles = new ArrayList<String>();
try {
Person thePerson = new Person();
thePerson.setUsername(inUsername);
List thePeople = Search.query(thePerson);
if (thePeople.size() > 0) {
thePerson = (Person) thePeople.get(0);
Set theRoleSet = thePerson.getRoleCollection();
Iterator it = theRoleSet.iterator();
while (it.hasNext()) {
Role theRole = (Role) it.next();
theRoles.add(theRole.getName());
}
// Check for superuser priv
try {
// Get from default bundle
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System
.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(
camodPropertiesFileName);
camodProperties.load(in);
} catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theSuperusers = camodProperties
.getProperty("superuser.usernames");
StringTokenizer theTokenizer = new StringTokenizer(
theSuperusers, ",");
while (theTokenizer.hasMoreTokens()) {
if (theTokenizer.nextToken().equals(inUsername)) {
theRoles.add(Constants.Admin.Roles.SUPER_USER);
break;
}
}
} catch (Exception e) {
log.error("Cannot get superuser information from bundle", e);
}
} else {
throw new IllegalArgumentException("User: " + inUsername
+ " not in caMOD database");
}
} catch (Exception e) {
log.error("Unable to get roles for user (" + inUsername + ": ", e);
throw e;
}
log.debug("User: " + inUsername + " and roles: " + theRoles);
log.debug("Exiting getRolesForUser");
return theRoles;
}
/**
* Get a list of users for a particular role
*
* @param inRoleName
* is the name of the role
*
* @return the list of users associated with the role
* @throws Exception
*/
public List<String> getUsersForRole(String inRoleName) throws Exception {
log.debug("Entering getUsersForRole");
List<String> theUsersForRole = new ArrayList<String>();
Role theRole = new Role();
theRole.setName(inRoleName);
try {
List theRoles = Search.query(theRole);
if (theRoles.size() > 0) {
theRole = (Role) theRoles.get(0);
// Get the users for the role
Set<Party> theUsers = theRole.getPartyCollection();
Iterator theIterator = theUsers.iterator();
// Go through the list of returned Party objects
while (theIterator.hasNext()) {
Object theObject = theIterator.next();
// Only add when it's actually a person
if (theObject instanceof Person) {
Person thePerson = (Person) theObject;
theUsersForRole.add(thePerson.getUsername());
}
}
} else {
log.warn("Role not found in database: " + inRoleName);
}
} catch (Exception e) {
log.error("Unable to get roles for user: ", e);
throw e;
}
log.debug("Role: " + inRoleName + " and users: " + theUsersForRole);
log.debug("Exiting getUsersForRole");
return theUsersForRole;
}
/**
* Get an e-mail address for a user
*
* @param inUsername
* is the login name of the user
*
* @return the list of users associated with the role
*/
public String getEmailForUser(String inUsername) {
log.debug("Entering getEmailForUser");
log.debug("Username: " + inUsername);
String theEmail = "";
try {
theEmail = LDAPUtil.getEmailAddressForUser(inUsername);
log.debug("<getEmailForUser> theEmail: " + theEmail.toString());
} catch (Exception e) {
log.debug("Could not fetch user from LDAP", e);
}
log.debug("Exiting getEmailForUser");
return theEmail;
}
/**
* Update the roles for the current user
*/
public void updateCurrentUserRoles(HttpServletRequest inRequest) {
String theCurrentUser = (String) inRequest.getSession().getAttribute(
Constants.CURRENTUSER);
try {
List theRoles = getRolesForUser(theCurrentUser);
inRequest.getSession().setAttribute(Constants.CURRENTUSERROLES,
theRoles);
} catch (Exception e) {
log.debug("Unable to update user roles for " + theCurrentUser, e);
}
}
/**
* Get an e-mail address for the coordinator
*
* @return the list of users associated with the role
*/
public String getEmailForCoordinator() {
log.debug("Entering getEmailForCoordinator");
String theEmail = "";
try {
// Get from default bundle
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System
.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(
camodPropertiesFileName);
camodProperties.load(in);
} catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties
.getProperty("coordinator.username");
log.debug("theCoordinator: " + theCoordinator.toString());
theEmail = getEmailForUser(theCoordinator);
} catch (Exception e) {
log.warn("Unable to get coordinator email: ", e);
}
log.debug("Exiting getEmailForCoordinator");
return theEmail;
}
/**
* Log in a user and get roles.
*
* @param inUsername
* is the login name of the user
* @param inPassword
* password
* @param inRequest
* Used to store the roles
*
* @return the list of users associated with the role
*/
public boolean login(String inUsername, String inPassword,
HttpServletRequest inRequest) {
boolean loginOk = false;
try {
log.debug("login method inside try");
// Work around bug in CSM. Empty passwords pass
if (inPassword.trim().length() != 0) {
loginOk = theAuthenticationMgr.login(inUsername, inPassword);
// Does the user exist? Must also be in our database to login
List theRoles = getRolesForUser(inUsername);
inRequest.getSession().setAttribute(Constants.CURRENTUSERROLES,
theRoles);
}
} catch (Exception e) {
log.error("Error logging in user: ", e);
loginOk = false;
}
return loginOk;
}
}
|
package com.intellij.codeInsight.daemon;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightingSettingsPerFile;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.InspectionProfileManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.components.ExportableApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.psi.PsiElement;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
import java.io.File;
public class DaemonCodeAnalyzerSettings implements NamedJDOMExternalizable, Cloneable, ExportableApplicationComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings");
public DaemonCodeAnalyzerSettings() {
}
public static DaemonCodeAnalyzerSettings getInstance() {
return ApplicationManager.getApplication().getComponent(DaemonCodeAnalyzerSettings.class);
}
public File[] getExportFiles() {
return new File[]{PathManager.getOptionsFile(this)};
}
public String getPresentableName() {
return "Error highlighting settings";
}
public boolean NEXT_ERROR_ACTION_GOES_TO_ERRORS_FIRST = false;
public int AUTOREPARSE_DELAY = 300;
public boolean SHOW_ADD_IMPORT_HINTS = true;
public String NO_AUTO_IMPORT_PATTERN = "[a-z].?";
public boolean SUPPRESS_WARNINGS = true;
public boolean SHOW_METHOD_SEPARATORS = false;
public int ERROR_STRIPE_MARK_MIN_HEIGHT = 3;
private InspectionProfileImpl myInspectionProfile;
public InspectionProfileImpl getInspectionProfile() {
if (myInspectionProfile == null) {
final String[] avaliableProfileNames = InspectionProfileManager.getInstance().getAvaliableProfileNames();
if (avaliableProfileNames == null || avaliableProfileNames.length == 0){
//can't be
return null;
} else {
myInspectionProfile = InspectionProfileManager.getInstance().getProfile(avaliableProfileNames[0]);
}
}
if (!myInspectionProfile.wasInitialized()) {
myInspectionProfile.load();
}
return myInspectionProfile;
}
public InspectionProfileImpl getInspectionProfile(PsiElement psiRoot){
InspectionProfileImpl inspectionProfile = psiRoot == null ? null : HighlightingSettingsPerFile.getInstance(psiRoot.getProject()).getInspectionProfile(psiRoot);
return inspectionProfile != null ? inspectionProfile : getInspectionProfile();
}
//set in error settings to hightlight only
public void setInspectionProfile(InspectionProfileImpl inspectionProfile) {
myInspectionProfile = inspectionProfile;
}
public boolean isCodeHighlightingChanged(DaemonCodeAnalyzerSettings oldSettings) {
try {
Element rootNew = new Element("root");
writeExternal(rootNew);
Element rootOld = new Element("root");
oldSettings.writeExternal(rootOld);
if (JDOMUtil.areElementsEqual(rootOld, rootNew)) {
oldSettings.myInspectionProfile.writeExternal(rootOld);
myInspectionProfile.writeExternal(rootNew);
return !JDOMUtil.areElementsEqual(rootOld, rootNew);
}
else {
return true;
}
}
catch (WriteExternalException e) {
LOG.error(e);
}
return false;
}
public String getComponentName() {
return "DaemonCodeAnalyzerSettings";
}
public void initComponent() { }
public void disposeComponent() {
}
public String getExternalFileName() {
return "editor.codeinsight";
}
public Object clone() {
DaemonCodeAnalyzerSettings settings = new DaemonCodeAnalyzerSettings();
InspectionProfileImpl inspectionProfile = new InspectionProfileImpl("copy", InspectionProfileManager.getInstance());
inspectionProfile.copyFrom(getInspectionProfile());
settings.myInspectionProfile = inspectionProfile;
settings.AUTOREPARSE_DELAY = AUTOREPARSE_DELAY;
settings.SHOW_ADD_IMPORT_HINTS = SHOW_ADD_IMPORT_HINTS;
settings.SHOW_METHOD_SEPARATORS = SHOW_METHOD_SEPARATORS;
settings.NO_AUTO_IMPORT_PATTERN = NO_AUTO_IMPORT_PATTERN;
return settings;
}
public void readExternal(Element element) throws InvalidDataException {
DefaultJDOMExternalizer.readExternal(this, element);
InspectionProfileConvertor.getInstance().storeEditorHighlightingProfile(element);
String profileName = element.getAttributeValue("profile");
if (profileName != null) {
myInspectionProfile = InspectionProfileManager.getInstance().getProfile(profileName);
}
else {
myInspectionProfile =
InspectionProfileManager.getInstance().getProfile(InspectionProfileConvertor.OLD_HIGHTLIGHTING_SETTINGS_PROFILE);
}
}
public void writeExternal(Element element) throws WriteExternalException {
DefaultJDOMExternalizer.writeExternal(this, element);
//clone
if (myInspectionProfile != null) {
element.setAttribute("profile", myInspectionProfile.getName());
}
else {
element.setAttribute("profile", "Default");
}
}
public boolean isImportHintEnabled() {
return SHOW_ADD_IMPORT_HINTS;
}
public void setImportHintEnabled(boolean isImportHintEnabled) {
SHOW_ADD_IMPORT_HINTS = isImportHintEnabled;
}
}
|
package net.sourceforge.texlipse.editor;
import net.sourceforge.texlipse.actions.TexInsertMathSymbolAction;
import net.sourceforge.texlipse.model.TexCommandContainer;
import net.sourceforge.texlipse.model.TexCommandEntry;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.editors.text.TextEditorActionContributor;
/**
* This class creates the math symbol menu
*
* @author Boris von Loesch
*
*/
public class TexEditorActionContributor extends TextEditorActionContributor {
private TexInsertMathSymbolAction[] greekSmall;
private TexInsertMathSymbolAction[] greekCapital;
private TexInsertMathSymbolAction[] arrows;
private TexInsertMathSymbolAction[] stdCompare;
private TexInsertMathSymbolAction[] stdBinOp;
private TexInsertMathSymbolAction[] stdBraces;
private TexInsertMathSymbolAction[] stdAccents;
/**
* Fills the actions array with the TexCommandEntries from commands
*
* @param actions
* @param commands
*/
private void createMathActions(TexInsertMathSymbolAction[] actions, TexCommandEntry[] commands) {
for (int i = 0; i < commands.length; i++) {
actions[i] = new TexInsertMathSymbolAction(commands[i]);
}
}
public TexEditorActionContributor() {
super();
greekSmall = new TexInsertMathSymbolAction[TexCommandContainer.greekSmall.length];
greekCapital = new TexInsertMathSymbolAction[TexCommandContainer.greekCapital.length];
arrows = new TexInsertMathSymbolAction[TexCommandContainer.stdArrows.length];
stdCompare = new TexInsertMathSymbolAction[TexCommandContainer.stdCompare.length];
stdBinOp = new TexInsertMathSymbolAction[TexCommandContainer.stdBinOpSymbols.length];
stdBraces = new TexInsertMathSymbolAction[TexCommandContainer.stdBraces.length];
stdAccents = new TexInsertMathSymbolAction[TexCommandContainer.stdAccents.length];
createMathActions(greekSmall, TexCommandContainer.greekSmall);
createMathActions(greekCapital, TexCommandContainer.greekCapital);
createMathActions(arrows, TexCommandContainer.stdArrows);
createMathActions(stdCompare, TexCommandContainer.stdCompare);
createMathActions(stdBinOp, TexCommandContainer.stdBinOpSymbols);
createMathActions(stdBraces, TexCommandContainer.stdBraces);
createMathActions(stdAccents, TexCommandContainer.stdAccents);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorActionBarContributor#contributeToMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
public void contributeToMenu(IMenuManager menuManager) {
super.contributeToMenu(menuManager);
//Add a new group to the navigation/goto menu
IMenuManager gotoMenu = menuManager.findMenuUsingPath(IWorkbenchActionConstants.M_NAVIGATE+"/"+IWorkbenchActionConstants.GO_TO);
if (gotoMenu != null) {
gotoMenu.add(new Separator("additions2"));
}
IMenuManager editMenu = menuManager.findMenuUsingPath(IWorkbenchActionConstants.M_WINDOW);
MenuManager manager = new MenuManager("Latex Symbols");
if (editMenu != null) {
menuManager.insertBefore(IWorkbenchActionConstants.M_WINDOW, manager);
MenuManager smallGreekMenu = new MenuManager("Greek lower case");
MenuManager captialGreekMenu = new MenuManager("Greek upper case");
MenuManager arrowsMenu = new MenuManager("Arrows");
MenuManager compareMenu = new MenuManager("Compare symbols");
MenuManager stdBinOpMenu = new MenuManager("Binary Operator");
MenuManager stdBracesMenu = new MenuManager("Braces");
MenuManager stdAccentsMenu = new MenuManager("Accents");
manager.add(captialGreekMenu);
manager.add(smallGreekMenu);
manager.add(new Separator());
manager.add(arrowsMenu);
manager.add(compareMenu);
manager.add(stdBinOpMenu);
manager.add(stdBracesMenu);
manager.add(new Separator());
manager.add(stdAccentsMenu);
for (int i = 0; i < greekSmall.length; i++)
smallGreekMenu.add(greekSmall[i]);
for (int i = 0; i < greekCapital.length; i++)
captialGreekMenu.add(greekCapital[i]);
for (int i = 0; i < arrows.length; i++)
arrowsMenu.add(arrows[i]);
for (int i = 0; i < stdCompare.length; i++)
compareMenu.add(stdCompare[i]);
for (int i = 0; i < stdBinOp.length; i++)
stdBinOpMenu.add(stdBinOp[i]);
for (int i = 0; i < stdBraces.length; i++)
stdBracesMenu.add(stdBraces[i]);
for (int i = 0; i < stdAccents.length; i++)
stdAccentsMenu.add(stdAccents[i]);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IEditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart)
*/
@Override
public void setActiveEditor(IEditorPart part) {
super.setActiveEditor(part);
for (int i = 0; i < greekSmall.length; i++)
greekSmall[i].setActiveEditor(part);
for (int i = 0; i < greekCapital.length; i++)
greekCapital[i].setActiveEditor(part);
for (int i = 0; i < arrows.length; i++)
arrows[i].setActiveEditor(part);
for (int i = 0; i < stdCompare.length; i++)
stdCompare[i].setActiveEditor(part);
for (int i = 0; i < stdBinOp.length; i++)
stdBinOp[i].setActiveEditor(part);
for (int i = 0; i < stdBraces.length; i++)
stdBraces[i].setActiveEditor(part);
for (int i = 0; i < stdAccents.length; i++)
stdAccents[i].setActiveEditor(part);
}
}
|
package com.example.bot.spring;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.net.URISyntaxException;
import java.net.URI;
import java.sql.*;
import javax.sql.DataSource;
import java.lang.Override;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import com.google.common.io.ByteStreams;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.client.MessageContentResponse;
import com.linecorp.bot.model.ReplyMessage;
import com.linecorp.bot.model.Multicast;
import com.linecorp.bot.model.PushMessage;
import com.linecorp.bot.model.action.MessageAction;
import com.linecorp.bot.model.action.PostbackAction;
import com.linecorp.bot.model.action.URIAction;
import com.linecorp.bot.model.event.BeaconEvent;
import com.linecorp.bot.model.event.Event;
import com.linecorp.bot.model.event.FollowEvent;
import com.linecorp.bot.model.event.JoinEvent;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.PostbackEvent;
import com.linecorp.bot.model.event.UnfollowEvent;
import com.linecorp.bot.model.event.message.AudioMessageContent;
import com.linecorp.bot.model.event.message.ImageMessageContent;
import com.linecorp.bot.model.event.message.LocationMessageContent;
import com.linecorp.bot.model.event.message.StickerMessageContent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.event.message.VideoMessageContent;
import com.linecorp.bot.model.event.source.GroupSource;
import com.linecorp.bot.model.event.source.RoomSource;
import com.linecorp.bot.model.event.source.Source;
import com.linecorp.bot.model.message.AudioMessage;
import com.linecorp.bot.model.message.ImageMessage;
import com.linecorp.bot.model.message.ImagemapMessage;
import com.linecorp.bot.model.message.LocationMessage;
import com.linecorp.bot.model.message.Message;
import com.linecorp.bot.model.message.StickerMessage;
import com.linecorp.bot.model.message.TemplateMessage;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.message.VideoMessage;
import com.linecorp.bot.model.message.imagemap.ImagemapArea;
import com.linecorp.bot.model.message.imagemap.ImagemapBaseSize;
import com.linecorp.bot.model.message.imagemap.MessageImagemapAction;
import com.linecorp.bot.model.message.imagemap.URIImagemapAction;
import com.linecorp.bot.model.message.template.ButtonsTemplate;
import com.linecorp.bot.model.message.template.CarouselColumn;
import com.linecorp.bot.model.message.template.CarouselTemplate;
import com.linecorp.bot.model.message.template.ConfirmTemplate;
import com.linecorp.bot.model.profile.UserProfileResponse;
import com.linecorp.bot.model.response.BotApiResponse;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import com.linecorp.bot.spring.boot.annotation.LineMessageHandler;
import lombok.NonNull;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@LineMessageHandler
@RestController
@Component
public class KitchenSinkController {
@Autowired
private LineMessagingClient lineMessagingClient;
@EventMapping
public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception {
TextMessageContent message = event.getMessage();
handleTextContent(event.getReplyToken(), event, message);
}
@EventMapping
public void handleStickerMessageEvent(MessageEvent<StickerMessageContent> event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleLocationMessageEvent(MessageEvent<LocationMessageContent> event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleImageMessageEvent(MessageEvent<ImageMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleAudioMessageEvent(MessageEvent<AudioMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleVideoMessageEvent(MessageEvent<VideoMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleUnfollowEvent(UnfollowEvent event) {
log.info("unfollowed this bot: {}", event);
}
@EventMapping
public void handleFollowEvent(FollowEvent event) {
String replyToken = event.getReplyToken();
this.replyText(replyToken, "bot telah di ikuti info lebih lanjut /help");
}
@EventMapping
public void handleJoinEvent(JoinEvent event) {
String replyToken = event.getReplyToken();
this.replyText(replyToken, "Bot telah bergabung ke grup info lebih lanjut /help" );
}
@EventMapping
public void handlePostbackEvent(PostbackEvent event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleBeaconEvent(BeaconEvent event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleOtherEvent(Event event) {
log.info("Received message(Ignored): {}", event);
}
private void reply(@NonNull String replyToken, @NonNull Message message) {
reply(replyToken, Collections.singletonList(message));
}
private void reply(@NonNull String replyToken, @NonNull List<Message> messages) {
try {
BotApiResponse apiResponse = lineMessagingClient
.replyMessage(new ReplyMessage(replyToken, messages))
.get();
log.info("Sent messages: {}", apiResponse);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
private void replyText(@NonNull String replyToken, @NonNull String message) {
if (replyToken.isEmpty()) {
throw new IllegalArgumentException("replyToken must not be empty");
}
if (message.length() > 1000) {
message = message.substring(0, 1000 - 2) + "……";
}
this.reply(replyToken, new TextMessage(message));
}
private void push(@NonNull String To, @NonNull Message message) {
push(To, Collections.singletonList(message));
}
private void push(@NonNull String To, @NonNull List<Message> messages) {
try {
BotApiResponse apiResponse = lineMessagingClient
.pushMessage(new PushMessage(To, messages))
.get();
log.info("Sent messages: {}", apiResponse);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
public void pushText(@NonNull String To, @NonNull String message) {
if (To.isEmpty()) {
throw new IllegalArgumentException("replyToken must not be empty");
}
if (message.length() > 1000) {
message = message.substring(0, 1000 - 2);
}
this.push(To, new TextMessage(message));
}
private String DB1(String userId,String groupId,Connection connection){
String Messages="";
try{
Statement stmt = connection.createStatement();
Statement stmt2 = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT \"UserId\",\"GroupId\" FROM \"Tabel Pemain\" WHERE \"Tabel Pemain\".\"GroupId\" = '"+groupId+"'");
ResultSet rs2 = stmt2.executeQuery("SELECT \"UserId\",\"GroupId\" FROM \"Tabel Pemain\" WHERE \"Tabel Pemain\".\"UserId\" = '"+userId+"'");
boolean cek = rs.next();
boolean cek2 = rs2.next();
if (!cek){
if(!cek2){
stmt.executeUpdate("INSERT INTO \"Tabel Pemain\" (\"UserId\",\"GroupId\") VALUES ('"+userId+"','"+groupId+"')");
stmt.executeUpdate("INSERT INTO ticks (\"Condition\",\"GroupId\",\"tick\") VALUES (0,'"+groupId+"',now() + INTERVAL '7 HOUR')");
Messages = "Insert";
}
else{
Messages = "Pemain ada digame lain";
}
}else{
Messages = "Sudah ada game";
}
rs.close();
stmt.close();
rs2.close();
stmt2.close();
}catch(SQLException e){
Messages = e.getMessage();
}
return Messages;
}
private String DB2(String userId,String groupId,Connection connection){
String Messages="";
try{
Statement stmt = connection.createStatement();
Statement stmt2 = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT \"UserId\",\"GroupId\" FROM \"Tabel Pemain\" WHERE \"Tabel Pemain\".\"UserId\" = '"+userId+"'");
ResultSet rs2 = stmt2.executeQuery("SELECT COUNT(\"GroupId\") AS \"GroupId\" FROM \"Tabel Pemain\" WHERE \"Tabel Pemain\".\"GroupId\" = '"+groupId+"' GROUP BY \"GroupId\"");
boolean cek = rs.next();
boolean cek2 = rs2.next();
if (!cek){
if(cek2){
if((rs2.getInt("GroupId")>0)){
stmt.executeUpdate("INSERT INTO \"Tabel Pemain\" (\"UserId\",\"GroupId\") VALUES ('"+userId+"','"+groupId+"')");
Messages = "Insert";
}else{
Messages = "Game Belum ada";
}
}
}else{
Messages = "Sudah terdaftar di grup lain";
}
rs.close();
stmt.close();
rs2.close();
stmt2.close();
}catch(SQLException e){
Messages = e.getMessage();
}
return Messages;
}
private void handleTextContent(String replyToken, Event event, TextMessageContent content)
throws Exception {
Connection connection = getConnection();
String text = content.getText();
log.info("Got text message from {}: {}", replyToken, text);
if (text.indexOf("/create")>=0){
Source source = event.getSource();
String groupId="";
if (source instanceof GroupSource) {
groupId = ((GroupSource) source).getGroupId();
}else if (source instanceof RoomSource) {
groupId = ((RoomSource) source).getRoomId();
}else{
groupId = event.getSource().getUserId();
}
String userId = event.getSource().getUserId();
if (userId != null && groupId != null) {
String check =DB1(userId,groupId,connection);
if (check=="Insert"){
UserProfileResponse profile = lineMessagingClient.getProfile(userId).get();
this.pushText(groupId,profile.getDisplayName()+" Memulai Permainan");
this.push(groupId,new TemplateMessage("Teka Teki Indonesia",
new ButtonsTemplate(
createUri("/static/buttons/1040.jpg"),
"Teka Teki Indonesia",
"Mari Bermain permainan teka teki indonesia",
Arrays.asList(
new MessageAction("Join Game",
"/join")
)
)
)
);
}else{
this.pushText(groupId,"Tidak bisa membuat permainan karena "+ check);
}
} else {
this.replyText(replyToken, "Tolong izinkan Bot mengakses akun / update ke LINE versi baru");
}
}else if (text.indexOf("/join")>=0){
Source source = event.getSource();
String groupId="";
if (source instanceof GroupSource) {
groupId = ((GroupSource) source).getGroupId();
}else if (source instanceof RoomSource) {
groupId = ((RoomSource) source).getRoomId();
}else{
groupId = event.getSource().getUserId();
}
String userId = event.getSource().getUserId();
if (userId != null && groupId != null) {
String check = DB2(userId,groupId,getConnection());
if (check=="Insert"){
UserProfileResponse profile = lineMessagingClient.getProfile(userId).get();
this.replyText(replyToken,profile.getDisplayName()+" Bergabung ke Permainan");
} else {
UserProfileResponse profile = lineMessagingClient.getProfile(userId).get();
this.replyText(replyToken,profile.getDisplayName()+" tidak bisa bergabung dalam permainan karena "+check);
}
} else {
this.replyText(replyToken, "Tolong izinkan Bot mengakses akun / update ke LINE versi baru");
}
}else if (text.indexOf("/start")>=0){
Source source = event.getSource();
String groupId="";
if (source instanceof GroupSource) {
groupId = ((GroupSource) source).getGroupId();
}else if (source instanceof RoomSource) {
groupId = ((RoomSource) source).getRoomId();
}else{
groupId = event.getSource().getUserId();
}
try{
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT \"GroupId\",\"Condition\" FROM ticks WHERE ticks.\"GroupId\" = '"+groupId+"'");
if(rs.next()){
if (rs.getInt("Condition")==0){
Statement stmt2 = connection.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT \"Id\", \"Pertanyaan\" , \"Jawaban\" FROM \"Tabel Pertanyaan\" ORDER BY random() LIMIT 1");
if(rs2.next()){
stmt.executeUpdate("INSERT INTO \"tabel Jawaban\" (\"Jawaban\",\"GroupId\") VALUES ('"+rs2.getString("Jawaban")+"','"+groupId+"')");
stmt.executeUpdate("UPDATE ticks SET \"Condition\" = 1 , tick = now() + INTERVAL '7 HOUR'"
+ "WHERE ticks.\"Condition\" = 0 AND ticks.\"GroupId\" = '"+groupId+"'");
this.pushText(groupId,""+ rs2.getString("Pertanyaan"));
this.pushText(groupId,"Permainan Dimulai");
rs2.close();
stmt2.close();
}
}else {
this.pushText(groupId,"Permainan Sudah Dimulai");
}
} else{
this.pushText(groupId,"Tidak ada Permainan");
}
rs.close();
stmt.close();
}catch(SQLException e){
e.getMessage();
}
}else if (text.indexOf("/stop")>=0){
Source source = event.getSource();
String groupId="";
if (source instanceof GroupSource) {
groupId = ((GroupSource) source).getGroupId();
}else if (source instanceof RoomSource) {
groupId = ((RoomSource) source).getRoomId();
}else{
groupId = event.getSource().getUserId();
}
try{
Statement stmt = connection.createStatement();
stmt.executeUpdate("DELETE FROM ticks WHERE \"ticks\".\"GroupId\" = '"+groupId+"'");
stmt.executeUpdate("DELETE FROM \"tabel Jawaban\" WHERE \"tabel Jawaban\".\"GroupId\" = '"+groupId+"'");
stmt.executeUpdate("DELETE FROM \"Tabel Pemain\" WHERE \"Tabel Pemain\".\"GroupId\" = '"+groupId+"'");
stmt.executeUpdate("DELETE FROM \"Tabel Skor\" WHERE \"Tabel Skor\".\"GroupId\" = '"+groupId+"'");
stmt.close();
}catch(SQLException e){
e.getMessage();
}
this.pushText(groupId,"Permainan Dihentikan");
}else if (text.indexOf("/help")>=0){
this.replyText(replyToken,
"feature /help : bantuan\n"+"/create : Membuat game\n"+"/join:Memasuki game\n"+"/skor:melihat skor\n"+"/id:melihat id\n"+
"/Start:memulai game\n"+"/stop : Menghentikan Game\n"+"/leave:keluar dari grup\n");
}else if (text.indexOf("/skor")>=0){
Source source = event.getSource();
String groupId="";
if (source instanceof GroupSource) {
groupId = ((GroupSource) source).getGroupId();
}else if (source instanceof RoomSource) {
groupId = ((RoomSource) source).getRoomId();
}else{
groupId = event.getSource().getUserId();
}
try{
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT \"UserId\",\"Skor\" FROM \"Tabel Skor\" WHERE \"Tabel Skor\".\"GroupId\" = '"+groupId+"'");
String tabelskor = "Tabel Skor Sebagai Berikut = \n";
while (rs.next()){
UserProfileResponse profile = lineMessagingClient.getProfile(rs.getString("UserId")).get();
tabelskor += profile.getDisplayName();
tabelskor += " = " + rs.getInt("Skor")+"\n";
}
this.replyText(replyToken,tabelskor);
rs.close();
stmt.close();
}catch(SQLException e){
e.getMessage();
}
}else if (text.indexOf("/leave")>=0){
Source source = event.getSource();
if (source instanceof GroupSource) {
this.replyText(replyToken, "Bot meninggalkan grup");
lineMessagingClient.leaveGroup(((GroupSource) source).getGroupId()).get();
} else if (source instanceof RoomSource) {
this.replyText(replyToken, "Bot meninggalkan ruangan");
lineMessagingClient.leaveRoom(((RoomSource) source).getRoomId()).get();
} else {
this.replyText(replyToken, "ini room 1:1 tidak bisa menggunakan perintah /leave");
}
}else if (text.indexOf("/id")>=0){
Source source = event.getSource();
String groupId="";
String userId = event.getSource().getUserId();
if (source instanceof GroupSource) {
groupId = ((GroupSource) source).getGroupId();
}else if (source instanceof RoomSource) {
groupId = ((RoomSource) source).getRoomId();
}else{
groupId = event.getSource().getUserId();
}
if (groupId!=""){
UserProfileResponse profile = lineMessagingClient.getProfile(userId).get();
this.replyText(replyToken, "ID : " + groupId +"\nNama : "+ profile.getDisplayName());
}else{
this.replyText(replyToken, "Tolong izinkan Bot mengakses akun / update ke LINE versi baru");
}
}else{
Source source = event.getSource();
String groupId="";
if (source instanceof GroupSource) {
groupId = ((GroupSource) source).getGroupId();
}else if (source instanceof RoomSource) {
groupId = ((RoomSource) source).getRoomId();
}else{
groupId = event.getSource().getUserId();
}
String userId = event.getSource().getUserId();
try{
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT \"Jawaban\",\"GroupId\" FROM \"tabel Jawaban\" WHERE \"GroupId\" = '"+groupId+"'");
if(rs.next()){
if (text==rs.getString("Jawaban")){
Statement stmt2 = connection.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT \"Id\", \"Pertanyaan\" , \"Jawaban\" FROM \"Tabel Pertanyaan\" ORDER BY random() LIMIT 1");
if (rs2.next()){
stmt.executeUpdate("UPDATE ticks SET tick = now() + INTERVAL '7 HOUR'"
+ "ticks.\"GroupId\" = '"+groupId+"'");
stmt.executeUpdate("DELETE FROM \"tabel Jawaban\" WHERE \"GroupId\" = '"+groupId+"'");
stmt.executeUpdate("INSERT INTO \"tabel Jawaban\" (\"Jawaban\",\"GroupId\") VALUES ('"+rs2.getString("Jawaban")+"','"+groupId+"')");
stmt.executeUpdate("IF EXIST (SELECT * FROM \"Tabel Skor\" WHERE GroupId = '"+groupId+"' AND UserId = '"+ userId + "') THEN"
+ "UPDATE \"Tabel Skor\" SET \"Skor\" = \"Skor\"+1 WHERE GroupId = '"+groupId+"' AND UserId = '"+ userId + "')"
+ "ELSE"
+ "INSERT INTO \"Tabel Skor\" (\"UserId\",\"GroupId\",\"Skor\") VALUES('"+userId+"','"+groupId+"',1)");
UserProfileResponse profile = lineMessagingClient.getProfile(userId).get();
this.pushText(groupId,profile.getDisplayName()+" Berhasil menjawab");
this.pushText(groupId,""+ rs2.getString("Pertanyaan"));
}
rs2.close();
stmt2.close();
}
}
rs.close();
stmt.close();
}catch(SQLException e){
e.getMessage();
}
}
connection.close();
}
public static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
private static String createUri(String path) {
return ServletUriComponentsBuilder.fromCurrentContextPath()
.path(path).build()
.toUriString();
}
private void system(String... args) {
ProcessBuilder processBuilder = new ProcessBuilder(args);
try {
Process start = processBuilder.start();
int i = start.waitFor();
log.info("result: {} => {}", Arrays.toString(args), i);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
log.info("Interrupted", e);
Thread.currentThread().interrupt();
}
}
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="UserId", defaultValue="") String User,@RequestParam(value="message", defaultValue="") String message) {
this.pushText(User, message);
return new Greeting(User,message);
}
@RequestMapping("/db")
public Databasing databasing(@RequestParam(value="QuestionId", defaultValue="0") int questionId,@RequestParam(value="Question", defaultValue="") String question,@RequestParam(value="Answer", defaultValue="") String answer) {
if (questionId>0){
try{
Connection connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("DELETE FROM \"Tabel Pertanyaan\" WHERE \"Tabel Pertanyaan\".\"Id\" = "+questionId);
stmt.executeUpdate("INSERT INTO \"Tabel Pertanyaan\" (\"Id\",\"Pertanyaan\",\"Jawaban\") VALUES ('"+questionId+"','"+question+"','"+answer+"')");
connection.close();
}catch(SQLException e){
e.getMessage();
}catch(URISyntaxException err){
err.getMessage();
}
}
return new Databasing(questionId,question,answer);
}
@Scheduled(fixedRate = 1000)
public void GameStart() {
try{
Connection connection = getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT \"Condition\",\"GroupId\" FROM ticks WHERE ticks.tick <= now() + INTERVAL '6 HOUR 59 MINUTES'");
while (rs.next()) {
if (rs.getInt("Condition")==0){
Statement stmt2 = connection.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT \"Id\", \"Pertanyaan\" , \"Jawaban\" FROM \"Tabel Pertanyaan\" ORDER BY random() LIMIT 1");
if(rs2.next()){
stmt.executeUpdate("INSERT INTO \"tabel Jawaban\" (\"Jawaban\",\"GroupId\") VALUES ('"+rs2.getString("Jawaban")+"','"+rs.getString("GroupId")+"')");
stmt.executeUpdate("UPDATE ticks SET \"Condition\" = 1 , tick = now() + INTERVAL '7 HOUR'"
+ "WHERE ticks.tick <= now() + INTERVAL '6 HOUR 59 MINUTES' AND ticks.\"GroupId\" = '"+rs.getString("GroupId")+"'");
this.pushText(rs.getString("GroupId"),""+ rs2.getString("Pertanyaan"));
this.pushText(rs.getString("GroupId"),"Permainan Dimulai");
rs2.close();
stmt2.close();
}
}else if (rs.getInt("Condition")==1){
Statement stmt2 = connection.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT \"Id\", \"Pertanyaan\" , \"Jawaban\" FROM \"Tabel Pertanyaan\" ORDER BY random() LIMIT 1");
if(rs2.next()){
stmt.executeUpdate("UPDATE ticks SET tick = now() + INTERVAL '7 HOUR'"
+ "WHERE ticks.tick <= now() + INTERVAL '6 HOUR 59 MINUTES' AND ticks.\"GroupId\" = '"+rs.getString("GroupId")+"'");
stmt.executeUpdate("DELETE FROM \"tabel Jawaban\" WHERE \"GroupId\" = '"+rs.getString("GroupId")+"'");
stmt.executeUpdate("INSERT INTO \"tabel Jawaban\" (\"Jawaban\",\"GroupId\") VALUES ('"+rs2.getString("Jawaban")+"','"+rs.getString("GroupId")+"')");
this.push(rs.getString("Id"), new ImageMessage(CreateUri("/static/question/1.jpg"),CreateUri("/static/question/1.jpg")));
this.pushText(rs.getString("GroupId"),""+ rs2.getString("Pertanyaan"));
rs2.close();
stmt2.close();
}
}
}
rs.close();
stmt.close();
connection.close();
}catch(SQLException e){
e.getMessage();
}catch(URISyntaxException err){
err.getMessage();
}
}
}
|
package iotcore.service.device.binding;
import java.util.Optional;
import org.apache.qpid.proton.message.Message;
import org.apache.qpid.proton.message.impl.MessageImpl;
import io.vertx.core.Vertx;
import io.vertx.proton.ProtonClient;
import io.vertx.proton.ProtonConnection;
import io.vertx.proton.ProtonSender;
import iot.core.services.device.registry.serialization.AmqpByteSerializer;
import iot.core.services.device.registry.serialization.AmqpSerializer;
import iot.core.services.device.registry.serialization.jackson.JacksonSerializer;
import iot.core.utils.address.AddressProvider;
import iot.core.utils.address.DefaultAddressProvider;
import iotcore.service.device.AlwaysPassingDeviceSchemaValidator;
import iotcore.service.device.Device;
import iotcore.service.device.DeviceRegistry;
import iotcore.service.device.InMemoryDeviceRegistry;
public class DeviceRegistryBinding {
private final DeviceRegistry deviceRegistry;
private final AmqpSerializer serializer = AmqpByteSerializer.of(JacksonSerializer.json());
private AddressProvider addressProvider = new DefaultAddressProvider();
public DeviceRegistryBinding(DeviceRegistry deviceRegistry) {
this.deviceRegistry = deviceRegistry;
}
public void start() {
Vertx vertx = Vertx.vertx();
ProtonClient client = ProtonClient.create(vertx);
client.connect("localhost", 5672, connectionResult -> {
if (connectionResult.succeeded()) {
ProtonConnection connection = connectionResult.result();
bindServiceToConnection(connection);
} else {
connectionResult.cause().printStackTrace();
}
});
}
private void bindServiceToConnection(ProtonConnection connection) {
connection.open();
String address = addressProvider.requestAddress("device");
connection.createReceiver(address).handler((delivery, msg) -> {
ProtonSender sender = connection.createSender(null).open();
String replyTo = msg.getReplyTo();
String verb = msg.getProperties().getSubject();
if (verb == null) {
return;
}
switch (verb) {
case "create": {
Device device = serializer.decode(msg.getBody(), Device.class);
String deviceId = deviceRegistry.create(device);
sendReply(sender, replyTo, deviceId);
break;
}
case "save": {
Device device = serializer.decode(msg.getBody(), Device.class);
String deviceId = deviceRegistry.save(device);
sendReply(sender, replyTo, deviceId);
break;
}
case "update": {
Device device = serializer.decode(msg.getBody(), Device.class);
deviceRegistry.update(device);
sendReply(sender, replyTo, null);
break;
}
case "findById": {
String deviceId = serializer.decode(msg.getBody(), String.class);
Optional<Device> device = deviceRegistry.findById(deviceId);
sendReply(sender, replyTo, device.get());
break;
}
}
}).open();
}
void sendReply(ProtonSender sender, String replyTo, Object reply) {
Message message = new MessageImpl();
message.setBody(serializer.encode(reply));
message.setAddress(replyTo);
sender.send(message);
}
public static void main(String[] args) {
new DeviceRegistryBinding(new InMemoryDeviceRegistry(new AlwaysPassingDeviceSchemaValidator())).start();
}
}
|
package org.sagebionetworks.repo.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.sagebionetworks.repo.model.AuthorizationConstants;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.QueryResults;
import org.sagebionetworks.repo.model.ServiceConstants;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.entity.query.EntityQuery;
import org.sagebionetworks.repo.model.entity.query.EntityQueryResults;
import org.sagebionetworks.repo.queryparser.ParseException;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.repo.web.UrlHelpers;
import org.sagebionetworks.repo.web.service.ServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
@RequestMapping(UrlHelpers.REPO_PATH)
public class QueryController extends BaseController {
@Autowired
private ServiceProvider serviceProvider;
/**
* Post a structured <a href="${org.sagebionetworks.repo.model.entity.query.EntityQuery}">EntityQuery</a> and get a structured
* <a href="${org.sagebionetworks.repo.model.entity.query.EntityQueryResults}">EntityQueryResults</a>.
* @param userId
* @param query
* @param request
* @return
* @throws DatastoreException
* @throws ParseException
* @throws NotFoundException
* @throws UnauthorizedException
*/
@Deprecated
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = UrlHelpers.QUERY, method = RequestMethod.POST)
public @ResponseBody EntityQueryResults structuredQuery(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@RequestBody EntityQuery query,
HttpServletRequest request)
throws DatastoreException, ParseException, NotFoundException, UnauthorizedException {
return serviceProvider.getNodeQueryService().structuredQuery(userId, query);
}
@Deprecated
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.QUERY, method = RequestMethod.GET)
public @ResponseBody QueryResults query(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@RequestParam(value = ServiceConstants.QUERY_PARAM, required = true) String query,
HttpServletRequest request)
throws DatastoreException, ParseException, NotFoundException, UnauthorizedException {
return serviceProvider.getNodeQueryService().query(userId, query, request);
}
}
|
package reignierOfDKE;
import reignierOfDKE.C.MapComplexity;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.MapLocation;
import battlecode.common.RobotController;
import battlecode.common.TerrainTile;
public class Core extends Soldier {
public static final int id = 500;
// for navigation to save place
private boolean reachedSavePlace = false;
private int encounteredObstacles = 0;
private MapLocation savePlace;
private boolean secondInitFinished = false;
private Team[] teams;
private PathFinderAStarFast pathFinderAStarFast;
// information about opponent
private MapLocation[] brdCastingOppSoldiersLocations;
public Core(RobotController rc) {
super(rc);
}
@Override
protected void init() throws GameActionException {
rc.setIndicatorString(0, "DUALCORE - OOOOH YEAH");
Channel.resetMapComplexity(rc);
MapLocation oppHq = rc.senseEnemyHQLocation();
MapLocation ourHq = rc.senseHQLocation();
Direction saveDir = oppHq.directionTo(ourHq);
savePlace = ourHq.add(saveDir, 3);
pathFinderGreedy = new PathFinderGreedy(rc, randall);
pathFinderGreedy.setTarget(savePlace);
teams = Team.getTeams(rc);
Channel.signalAlive(rc, id);
determinePathFinder();
}
@Override
protected void act() throws GameActionException {
Channel.signalAlive(rc, id);
if (!reachedSavePlace && encounteredObstacles < 3) {
if (rc.isActive()) {
// move to save place
if (!pathFinderGreedy.move()) {
encounteredObstacles++;
}
reachedSavePlace = rc.getLocation().equals(savePlace)
|| encounteredObstacles > 2;
}
return;
} else if (!secondInitFinished) {
// do remaining initialization parts after reaching a save location
// init pathFinder to help other soldiers build the reduced map
if (Channel.getMapComplexity(rc).equals(MapComplexity.COMPLEX)) {
pathFinderAStarFast = new PathFinderAStarFast(rc, id);
}
Channel.signalAlive(rc, id);
secondInitFinished = true;
}
analyzeOpponentBehavior();
}
private void determinePathFinder() {
TerrainTile[][] map = pathFinderGreedy.map;
int rating = 0;
for (int y = 1; y < pathFinderGreedy.ySize; y += 2) {
Channel.signalAlive(rc, id);
for (int x = 0; x < pathFinderGreedy.xSize; x += 2) {
if (map[y][x].equals(TerrainTile.VOID)) {
rating -= 6;
} else {
rating++;
}
}
}
if (rating > 0) {
Channel.broadcastMapComplexity(rc, MapComplexity.SIMPLE);
} else {
Channel.broadcastMapComplexity(rc, MapComplexity.COMPLEX);
}
}
private void analyzeOpponentBehavior() {
brdCastingOppSoldiersLocations = rc.senseBroadcastingRobotLocations(rc
.getTeam().opponent());
if (Soldier.size(brdCastingOppSoldiersLocations) < 1) {
// prevent NullPtrException
brdCastingOppSoldiersLocations = new MapLocation[0];
}
int countBrdCastingOppSoldiers = brdCastingOppSoldiersLocations.length;
Channel.broadcastCountOppBrdCastingSoldiers(rc,
countBrdCastingOppSoldiers);
MapLocation oppSoldiersCenter = getCenter(brdCastingOppSoldiersLocations);
Channel.broadcastPositionalCenterOfOpponent(rc, oppSoldiersCenter);
int oppSoldiersMeanDistToCenter = getMeanDistance(
brdCastingOppSoldiersLocations, oppSoldiersCenter);
Channel.broadcastOpponentMeanDistToCenter(rc,
oppSoldiersMeanDistToCenter);
int milk = (int) rc.senseTeamMilkQuantity(rc.getTeam().opponent());
Channel.broadcastOpponentMilkQuantity(rc, milk);
}
private MapLocation getCenter(MapLocation[] locations) {
int y = 0;
int x = 0;
if (Soldier.size(locations) < 1) {
return pathFinderGreedy.hqEnemLoc;
}
for (MapLocation loc : locations) {
y += loc.y;
x += loc.x;
}
return new MapLocation(y / locations.length, x / locations.length);
}
private int getMeanDistance(MapLocation[] locations, MapLocation to) {
if (Soldier.size(locations) < 1) {
return 100000;
}
int dist = 0;
for (MapLocation loc : locations) {
dist += PathFinder.getManhattanDist(loc, to);
}
return dist / locations.length;
}
}
|
// 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,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// 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 phasereditor.scene.ui.editor;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DragDetectEvent;
import org.eclipse.swt.events.DragDetectListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.wb.swt.SWTResourceManager;
import org.json.JSONObject;
import phasereditor.assetpack.core.IAssetFrameModel;
import phasereditor.assetpack.core.ImageAssetModel;
import phasereditor.scene.core.EditorComponent;
import phasereditor.scene.core.NameComputer;
import phasereditor.scene.core.ObjectModel;
import phasereditor.scene.core.ParentComponent;
import phasereditor.scene.core.SceneModel;
import phasereditor.scene.core.SpriteModel;
import phasereditor.scene.core.TextureComponent;
import phasereditor.scene.core.TransformComponent;
import phasereditor.scene.ui.editor.undo.SceneSnapshotOperation;
import phasereditor.ui.ZoomCanvas;
/**
* @author arian
*
*/
public class SceneCanvas extends ZoomCanvas implements MouseListener, MouseMoveListener, DragDetectListener {
private static final String SCENE_COPY_STAMP = "--scene--copy--stamp
public static final int X_LABELS_HEIGHT = 18;
public static final int Y_LABEL_WIDTH = 18;
private SceneEditor _editor;
private SceneObjectRenderer _renderer;
private float _renderModelSnapX;
private float _renderModelSnapY;
List<Object> _selection;
private SceneModel _sceneModel;
private DragObjectsEvents _dragObjectsEvents;
private SelectionEvents _selectionEvents;
public SceneCanvas(Composite parent, int style) {
super(parent, style);
_selection = new ArrayList<>();
addPaintListener(this);
_dragObjectsEvents = new DragObjectsEvents(this);
_selectionEvents = new SelectionEvents(this);
addDragDetectListener(this);
addMouseListener(this);
addMouseMoveListener(this);
init_DND();
}
private void init_DND() {
{
int options = DND.DROP_MOVE | DND.DROP_DEFAULT;
DropTarget target = new DropTarget(this, options);
Transfer[] types = { LocalSelectionTransfer.getTransfer() };
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
var loc = toDisplay(0, 0);
var x = event.x - loc.x;
var y = event.y - loc.y;
if (event.data instanceof Object[]) {
selectionDropped(x, y, (Object[]) event.data);
}
if (event.data instanceof IStructuredSelection) {
selectionDropped(x, y, ((IStructuredSelection) event.data).toArray());
}
}
});
}
}
public float[] viewToModel(int x, int y) {
var calc = calc();
var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH;
var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT;
return new float[] { modelX, modelY };
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void selectionDropped(int x, int y, Object[] data) {
var nameComputer = new NameComputer(_sceneModel.getRootObject());
var beforeSnapshot = SceneSnapshotOperation.takeSnapshot(_editor);
var calc = calc();
var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH;
var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT;
var newModels = new ArrayList<ObjectModel>();
for (var obj : data) {
if (obj instanceof ImageAssetModel) {
obj = ((ImageAssetModel) obj).getFrame();
}
if (obj instanceof IAssetFrameModel) {
var frame = (IAssetFrameModel) obj;
var sprite = new SpriteModel();
var name = nameComputer.newName(frame.getKey());
EditorComponent.set_editorName(sprite, name);
TransformComponent.set_x(sprite, modelX);
TransformComponent.set_y(sprite, modelY);
TextureComponent.set_frame(sprite, (IAssetFrameModel) obj);
newModels.add(sprite);
}
}
for (var model : newModels) {
ParentComponent.addChild(_sceneModel.getRootObject(), model);
}
var afterSnapshot = SceneSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new SceneSnapshotOperation(beforeSnapshot, afterSnapshot, "Drop assets"));
setSelection_from_internal((List) newModels);
redraw();
_editor.refreshOutline();
_editor.setDirty(true);
_editor.getEditorSite().getPage().activate(_editor);
}
public void init(SceneEditor editor) {
_editor = editor;
_sceneModel = editor.getSceneModel();
_renderer = new SceneObjectRenderer(this);
}
public SceneEditor getEditor() {
return _editor;
}
public SceneObjectRenderer getSceneRenderer() {
return _renderer;
}
@Override
public void dispose() {
super.dispose();
// TODO:
// _renderer.dispose();
}
@Override
protected void customPaintControl(PaintEvent e) {
renderBackground(e);
renderGrid(e);
var tx = new Transform(getDisplay());
tx.translate(Y_LABEL_WIDTH, X_LABELS_HEIGHT);
_renderer.renderScene(e.gc, tx, _editor.getSceneModel());
renderSelection(e.gc);
renderLabels(e);
}
private void renderSelection(GC gc) {
for (var obj : _selection) {
if (obj instanceof ObjectModel) {
var model = (ObjectModel) obj;
var bounds = _renderer.getObjectBounds(model);
if (obj instanceof ParentComponent) {
if (!ParentComponent.get_children(model).isEmpty()) {
var childrenBounds = _renderer.getObjectChildrenBounds(model);
if (childrenBounds != null) {
var merge = SceneObjectRenderer.joinBounds(bounds, childrenBounds);
gc.setAlpha(150);
gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_GREEN));
gc.drawPolygon(new int[] { (int) merge[0], (int) merge[1], (int) merge[2], (int) merge[3],
(int) merge[4], (int) merge[5], (int) merge[6], (int) merge[7] });
gc.setAlpha(255);
}
}
}
if (bounds != null) {
gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLUE));
gc.drawPolygon(new int[] { (int) bounds[0], (int) bounds[1], (int) bounds[2], (int) bounds[3],
(int) bounds[4], (int) bounds[5], (int) bounds[6], (int) bounds[7] });
}
}
}
}
private void renderBackground(PaintEvent e) {
var gc = e.gc;
gc.setBackground(getBackgroundColor());
gc.setForeground(getGridColor());
gc.fillRectangle(0, 0, e.width, e.height);
}
@SuppressWarnings("static-method")
private Color getGridColor() {
return SWTResourceManager.getColor(200, 200, 200);
}
@SuppressWarnings("static-method")
private Color getBackgroundColor() {
return SWTResourceManager.getColor(180, 180, 180);
}
private void renderGrid(PaintEvent e) {
var gc = e.gc;
gc.setForeground(getGridColor());
// paint labels
var calc = calc();
var initialModelSnapX = 5f;
var initialModelSnapY = 5f;
// if (_settingsModel.isEnableStepping()) {
// initialModelSnapX = _settingsModel.getStepWidth();
// initialModelSnapY = _settingsModel.getStepHeight();
var modelSnapX = 10f;
var modelSnapY = 10f;
var viewSnapX = 0f;
var viewSnapY = 0f;
int i = 1;
while (viewSnapX < 10) {
modelSnapX = (float) Math.pow(initialModelSnapX, i);
viewSnapX = calc.modelToViewWidth(modelSnapX);
i++;
}
_renderModelSnapX = modelSnapX;
_renderModelSnapY = modelSnapY;
var modelNextSnapX = modelSnapX * 4;
var modelNextNextSnapX = modelSnapX * 8;
i = 1;
while (viewSnapY < 10) {
modelSnapY = (float) Math.pow(initialModelSnapY, i);
viewSnapY = calc.modelToViewHeight(modelSnapY);
i++;
}
var modelNextSnapY = modelSnapY * 4;
var modelNextNextSnapY = modelSnapY * 8;
var modelStartX = calc.viewToModelX(0);
var modelStartY = calc.viewToModelY(0);
var modelRight = calc.viewToModelX(e.width);
var modelBottom = calc.viewToModelY(e.height);
modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX;
modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY;
i = 0;
while (true) {
var modelX = modelStartX + i * modelSnapX;
if (modelX > modelRight) {
break;
}
if (modelX % modelNextNextSnapX == 0) {
gc.setAlpha(255);
gc.setLineWidth(2);
} else if (modelX % modelNextSnapX == 0) {
gc.setAlpha(200);
} else {
gc.setAlpha(150);
}
var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH;
gc.drawLine((int) viewX, X_LABELS_HEIGHT, (int) viewX, e.height);
gc.setLineWidth(1);
i++;
}
gc.setAlpha(255);
i = 0;
while (true) {
var modelY = modelStartY + i * modelSnapY;
if (modelY > modelBottom) {
break;
}
var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT;
if (modelY % modelNextNextSnapY == 0) {
gc.setLineWidth(2);
gc.setAlpha(255);
} else if (modelY % modelNextSnapY == 0) {
gc.setAlpha(200);
} else {
gc.setAlpha(150);
}
gc.drawLine(X_LABELS_HEIGHT, (int) viewY, e.width, (int) viewY);
gc.setLineWidth(1);
i++;
}
gc.setAlpha(255);
}
private void renderLabels(PaintEvent e) {
var gc = e.gc;
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
gc.setBackground(getBackgroundColor());
gc.setAlpha(220);
gc.fillRectangle(0, 0, e.width, X_LABELS_HEIGHT);
gc.fillRectangle(0, 0, Y_LABEL_WIDTH, e.height);
gc.setAlpha(255);
// paint labels
var modelSnapX = _renderModelSnapX;
var modelSnapY = 10f;
var calc = calc();
var modelStartX = calc.viewToModelX(0);
var modelStartY = calc.viewToModelY(0);
var modelRight = calc.viewToModelX(e.width);
var modelBottom = calc.viewToModelY(e.height);
int i;
i = 2;
while (true) {
float viewSnapX = calc.modelToViewWidth(modelSnapX);
if (viewSnapX > 80) {
break;
}
modelSnapX = _renderModelSnapX * i;
i++;
}
i = 2;
while (true) {
float viewSnapY = calc.modelToViewWidth(modelSnapY);
if (viewSnapY > 80) {
break;
}
modelSnapY = _renderModelSnapY * i;
i++;
}
modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX;
modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY;
i = 0;
while (true) {
var modelX = modelStartX + i * modelSnapX;
if (modelX > modelRight) {
break;
}
var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH;
if (viewX >= Y_LABEL_WIDTH && viewX <= e.width - Y_LABEL_WIDTH) {
String label = Integer.toString((int) modelX);
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
gc.drawString(label, (int) viewX + 5, 0, true);
gc.setForeground(getGridColor());
gc.drawLine((int) viewX, 0, (int) viewX, X_LABELS_HEIGHT);
}
i++;
}
gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, e.width, X_LABELS_HEIGHT);
i = 0;
while (true) {
var modelY = modelStartY + i * modelSnapY;
if (modelY > modelBottom) {
break;
}
var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT;
if (viewY >= X_LABELS_HEIGHT && viewY <= e.height - X_LABELS_HEIGHT) {
String label = Integer.toString((int) modelY);
var labelExtent = gc.stringExtent(label);
var tx = new Transform(getDisplay());
tx.translate(0, viewY + 5 + labelExtent.x);
tx.rotate(-90);
gc.setTransform(tx);
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
gc.drawString(label, 0, 0, true);
gc.setTransform(null);
tx.dispose();
gc.setForeground(getGridColor());
gc.drawLine(0, (int) viewY, Y_LABEL_WIDTH, (int) viewY);
}
i++;
}
gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, Y_LABEL_WIDTH, e.height);
gc.setAlpha(255);
}
@Override
protected Point getImageSize() {
return new Point(1, 1);
}
ObjectModel pickObject(int x, int y) {
return pickObject(_sceneModel.getRootObject(), x, y);
}
private ObjectModel pickObject(ObjectModel model, int x, int y) {
if (model instanceof ParentComponent) {
if (EditorComponent.get_editorClosed(model) /* || groupModel.isPrefabInstance() */) {
var polygon = _renderer.getObjectChildrenBounds(model);
if (hitsPolygon(x, y, polygon)) {
return model;
}
} else {
var children = ParentComponent.get_children(model);
for (int i = children.size() - 1; i >= 0; i
var model2 = children.get(i);
var pick = pickObject(model2, x, y);
if (pick != null) {
return pick;
}
}
}
}
var polygon = _renderer.getObjectBounds(model);
if (hitsPolygon(x, y, polygon)) {
return model;
}
return null;
}
void setSelection_from_internal(List<Object> list) {
var sel = new StructuredSelection(list);
_selection = list;
_editor.getEditorSite().getSelectionProvider().setSelection(sel);
if (_editor.getOutline() != null) {
_editor.getOutline().setSelection_from_external(sel);
}
}
private static boolean hitsPolygon(int x, int y, float[] polygon) {
if (polygon == null) {
return false;
}
int npoints = polygon.length / 2;
if (npoints <= 2) {
return false;
}
var xpoints = new int[npoints];
var ypoints = new int[npoints];
for (int i = 0; i < npoints; i++) {
xpoints[i] = (int) polygon[i * 2];
ypoints[i] = (int) polygon[i * 2 + 1];
}
int hits = 0;
int lastx = xpoints[npoints - 1];
int lasty = ypoints[npoints - 1];
int curx, cury;
// Walk the edges of the polygon
for (int i = 0; i < npoints; lastx = curx, lasty = cury, i++) {
curx = xpoints[i];
cury = ypoints[i];
if (cury == lasty) {
continue;
}
int leftx;
if (curx < lastx) {
if (x >= lastx) {
continue;
}
leftx = curx;
} else {
if (x >= curx) {
continue;
}
leftx = lastx;
}
double test1, test2;
if (cury < lasty) {
if (y < cury || y >= lasty) {
continue;
}
if (x < leftx) {
hits++;
continue;
}
test1 = x - curx;
test2 = y - cury;
} else {
if (y < lasty || y >= cury) {
continue;
}
if (x < leftx) {
hits++;
continue;
}
test1 = x - lastx;
test2 = y - lasty;
}
if (test1 < (test2 / (lasty - cury) * (lastx - curx))) {
hits++;
}
}
return ((hits & 1) != 0);
}
public void setSelection_from_external(IStructuredSelection selection) {
_selection = new ArrayList<>(List.of(selection.toArray()));
redraw();
}
public void reveal(ObjectModel model) {
var objBounds = _renderer.getObjectBounds(model);
if (objBounds == null) {
return;
}
var x1 = objBounds[0];
var y1 = objBounds[1];
var x2 = objBounds[4];
var y2 = objBounds[5];
var w = x2 - x1;
var h = y2 - y1;
var canvasBounds = getBounds();
setOffsetX((int) (getOffsetX() - x1 + Y_LABEL_WIDTH + canvasBounds.width / 2 - w / 2));
setOffsetY((int) (getOffsetY() - y1 + X_LABELS_HEIGHT + canvasBounds.height / 2 - h / 2));
redraw();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void selectAll() {
var list = new ArrayList<ObjectModel>();
var root = getEditor().getSceneModel().getRootObject();
root.visitChildren(model -> list.add(model));
setSelection_from_internal((List) list);
redraw();
}
public void delete() {
var beforeData = SceneSnapshotOperation.takeSnapshot(_editor);
for (var obj : _selection) {
var model = (ObjectModel) obj;
ParentComponent.removeFromParent(model);
}
redraw();
_editor.setDirty(true);
_editor.setSelection(StructuredSelection.EMPTY);
var afterData = SceneSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new SceneSnapshotOperation(beforeData, afterData, "Delete objects"));
}
public void copy() {
var sel = new StructuredSelection(
filterChidlren(_selection.stream().map(o -> (ObjectModel) o).collect(toList()))
.stream().map(model -> {
var data = new JSONObject();
data.put(SCENE_COPY_STAMP, true);
model.write(data);
// convert the local position to a global position
if (model instanceof TransformComponent) {
var parent = ParentComponent.get_parent(model);
var globalPoint = new float[] { 0, 0 };
if (parent != null) {
globalPoint = _renderer.localToScene(parent, TransformComponent.get_x(model),
TransformComponent.get_y(model));
}
data.put(TransformComponent.x_name, globalPoint[0]);
data.put(TransformComponent.y_name, globalPoint[1]);
}
return data;
}).toArray());
LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer();
transfer.setSelection(sel);
Clipboard cb = new Clipboard(getDisplay());
cb.setContents(new Object[] { sel.toArray() }, new Transfer[] { transfer });
cb.dispose();
}
public void cut() {
copy();
delete();
}
public void paste() {
var root = getEditor().getSceneModel().getRootObject();
paste(root, true);
}
public void paste(ObjectModel parent, boolean placeAtCursorPosition) {
var beforeData = SceneSnapshotOperation.takeSnapshot(_editor);
LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer();
Clipboard cb = new Clipboard(getDisplay());
Object content = cb.getContents(transfer);
cb.dispose();
if (content == null) {
return;
}
var editor = getEditor();
var project = editor.getEditorInput().getFile().getProject();
var copyElements = ((IStructuredSelection) content).toArray();
List<ObjectModel> pasteModels = new ArrayList<>();
// create the copies
for (var obj : copyElements) {
if (obj instanceof JSONObject) {
var data = (JSONObject) obj;
if (data.has(SCENE_COPY_STAMP)) {
String type = data.getString("-type");
var newModel = SceneModel.createModel(type);
newModel.read(data, project);
pasteModels.add(newModel);
}
}
}
// remove the children
pasteModels = filterChidlren(pasteModels);
var cursorPoint = toControl(getDisplay().getCursorLocation());
var localCursorPoint = _renderer.sceneToLocal(parent, cursorPoint.x, cursorPoint.y);
// set new id and editorName
var nameComputer = new NameComputer(_sceneModel.getRootObject());
float[] offsetPoint;
{
var minX = Float.MAX_VALUE;
var minY = Float.MAX_VALUE;
for (var model : pasteModels) {
if (model instanceof TransformComponent) {
var x = TransformComponent.get_x(model);
var y = TransformComponent.get_y(model);
minX = Math.min(minX, x);
minY = Math.min(minY, y);
}
}
offsetPoint = new float[] { minX - localCursorPoint[0], minY - localCursorPoint[1] };
}
for (var model : pasteModels) {
model.visit(model2 -> {
model2.setId(UUID.randomUUID().toString());
var name = EditorComponent.get_editorName(model2);
name = nameComputer.newName(name);
EditorComponent.set_editorName(model2, name);
});
if (model instanceof TransformComponent) {
// TODO: honor the snapping settings
var x = TransformComponent.get_x(model);
var y = TransformComponent.get_y(model);
if (placeAtCursorPosition) {
// if (offsetPoint == null) {
// offsetPoint = new float[] { x - localCursorPoint[0], y - localCursorPoint[1]
TransformComponent.set_x(model, x - offsetPoint[0]);
TransformComponent.set_y(model, y - offsetPoint[1]);
} else {
var point = _renderer.sceneToLocal(parent, x, y);
TransformComponent.set_x(model, point[0]);
TransformComponent.set_y(model, point[1]);
}
}
}
// add to the root object
for (var model : pasteModels) {
ParentComponent.addChild(parent, model);
}
editor.setSelection(new StructuredSelection(pasteModels));
editor.setDirty(true);
var afterData = SceneSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new SceneSnapshotOperation(beforeData, afterData, "Paste objects."));
}
public static List<ObjectModel> filterChidlren(List<ObjectModel> models) {
var result = new ArrayList<>(models);
for (var i = 0; i < models.size(); i++) {
for (var j = 0; j < models.size(); j++) {
if (i != j) {
var a = models.get(i);
var b = models.get(j);
if (ParentComponent.isDescendentOf(a, b)) {
result.remove(a);
}
}
}
}
return result;
}
@Override
public void mouseDoubleClick(MouseEvent e) {
}
@Override
public void mouseDown(MouseEvent e) {
}
@Override
public void mouseUp(MouseEvent e) {
if (_dragDetected) {
_dragDetected = false;
if (_dragObjectsEvents.isDragging()) {
_dragObjectsEvents.done();
}
return;
}
_selectionEvents.updateSelection(e);
}
@Override
public void mouseMove(MouseEvent e) {
if (_dragObjectsEvents.isDragging()) {
_dragObjectsEvents.update(e);
}
}
private boolean _dragDetected;
@Override
public void dragDetected(DragDetectEvent e) {
_dragDetected = true;
var obj = pickObject(e.x, e.y);
if (_selection.contains(obj)) {
_dragObjectsEvents.start(e);
}
}
}
|
package components.model;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import models.Application;
import models.ApplicationComponent;
import models.Communication;
import org.jgrapht.alg.CycleDetector;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DirectedPseudograph;
import play.libs.Json;
import java.util.Random;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
public class ApplicationTypeGraph {
private final DirectedPseudograph<ApplicationComponent, CommunicationEdge> componentGraph;
private final DirectedPseudograph<ApplicationComponent, CommunicationEdge>
mandatoryComponentGraph;
private ApplicationTypeGraph(Application application) {
componentGraph = GraphFactory.of(application);
mandatoryComponentGraph = GraphFactory.of(application, true);
}
public static ApplicationTypeGraph of(Application application) {
checkNotNull(application);
return new ApplicationTypeGraph(application);
}
private CycleDetector<ApplicationComponent, CommunicationEdge> cycleDetector() {
return new CycleDetector<>(mandatoryComponentGraph);
}
public boolean hasCycle() {
return cycleDetector().detectCycles();
}
public Set<ApplicationComponent> cycles() {
return cycleDetector().findCycles();
}
public JsonNode toJson() {
final ObjectNode objectNode = Json.newObject().with("elements");
final ArrayNode nodes = objectNode.putArray("nodes");
this.componentGraph.vertexSet().forEach(applicationComponent -> {
final ObjectNode vertex = nodes.addObject();
vertex.with("data").put("id", applicationComponent.getUuid())
.put("name", applicationComponent.getComponent().getName());
});
final ArrayNode edges = objectNode.putArray("edges");
this.componentGraph.edgeSet().forEach(communicationEdge -> {
final ObjectNode edge = edges.addObject();
edge.with("data").put("id", new Random().nextInt())
.put("source", componentGraph.getEdgeSource(communicationEdge).getUuid())
.put("target", componentGraph.getEdgeTarget(communicationEdge).getUuid());
if (communicationEdge.isMandatory()) {
edge.put("classes", "mandatory");
}
});
return objectNode;
}
private static class CommunicationEdge extends DefaultEdge {
private final Communication communication;
private CommunicationEdge(Communication communication) {
this.communication = communication;
}
public Communication communication() {
return communication;
}
public boolean isMandatory() {
return communication().isMandatory();
}
}
private static class GraphFactory {
public static DirectedPseudograph<ApplicationComponent, CommunicationEdge> of(
Application application, boolean onlyMandatory) {
DirectedPseudograph<ApplicationComponent, CommunicationEdge> componentGraph =
new DirectedPseudograph<>(CommunicationEdge.class);
application.getApplicationComponents().forEach(componentGraph::addVertex);
application.communications().stream()
.filter(communication -> !onlyMandatory || communication.isMandatory()).forEach(
communication -> componentGraph
.addEdge(communication.getSource(), communication.getTarget(),
new CommunicationEdge(communication)));
return componentGraph;
}
public static DirectedPseudograph<ApplicationComponent, CommunicationEdge> of(
Application application) {
return GraphFactory.of(application, false);
}
}
}
|
package ed.util;
import java.io.File;
import org.testng.annotations.Test;
import ed.js.JSFunction;
import ed.js.func.JSFunctionCalls0;
import ed.util.ScriptTestInstance;
import ed.js.engine.Scope;
import ed.js.Shell;
import ed.MyAsserts;
import ed.appserver.JSFileLibrary;
/**
* Dynamic test instance for testing any 10genPlatform script
*
* Code stolen lock, stock and barrel from ConvertTest. Uses exact same convention
* and scheme for comparing output
*/
public abstract class ScriptTestInstanceBase extends MyAsserts implements ScriptTestInstance{
File _file;
public ScriptTestInstanceBase() {
}
public void setTestScriptFile(File f) {
_file = f;
}
public File getTestScriptFile() {
return _file;
}
/**
* Test method for running a script
*
* @throws Exception in case of failure
*/
@Test
public void test() throws Exception {
// System.out.println("ScriptTestInstanceBase : running " + _file);
Scope scope = Scope.newGlobal().child(new File("/tmp"));
scope.setGlobal( true );
scope.makeThreadLocal();
preTest(scope);
Shell.addNiceShellStuff(scope);
scope.put( "exit" , new JSFunctionCalls0(){
public Object call( Scope s , Object crap[] ){
System.err.println("JSTestInstance : exit() called from " + _file.toString() + " Ignoring.");
return null;
}
} , true );
try {
JSFunction f = convert();
JSFileLibrary lib = new ed.appserver.JSFileLibrary( _file.getParentFile() , "asd" , scope );
JSFileLibrary.addPath( f , lib );
f.call(scope);
validateOutput(scope);
}
catch (RuntimeException re) {
throw new Exception("For file " + _file.toString(), re);
}
finally {
scope.kill();
}
}
}
|
package _0_ordering;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
public class KeepOrderTest {
@Test
public void shouldKeepElementsOrder() throws Exception {
List<Integer> list = IntStream.range(0, 10)
.boxed()
.parallel()
.map(i -> i * i)
.filter(i -> i % 2 != 0)
.collect(toList());
System.out.println("list = " + list);
assertThat(list, is(sorted(Integer::compare)));
}
@Test
public void shouldScrambleElements() throws Exception {
List<Integer> list = new ArrayList<>();
IntStream.range(0, 10)
.boxed()
.parallel()
.map(i -> i * i)
.filter(i -> i % 2 != 0)
.forEach(list::add);
System.out.println("list = " + list);
assertThat(list, is(not(sorted(Integer::compare))));
}
private <T> Matcher<List<T>> sorted(Comparator<T> comparator) {
return new TypeSafeMatcher<List<T>>() {
@Override
protected boolean matchesSafely(List<T> list) {
for (int i = 1; i < list.size(); i++) {
T previous = list.get(i - 1);
T current = list.get(i);
if (!areInOrder(previous, current)) {
return false;
}
}
return true;
}
private boolean areInOrder(T previous, T current) {
return comparator.compare(previous, current) <= 0;
}
@Override
public void describeTo(Description description) {
description.appendText("sorted");
}
};
}
}
|
package com.whd.test;
import com.whd.Util;
import com.whd.WhdAuth;
import com.whd.WhdException;
import org.junit.Test;
public class AuthUnitTest {
/*
@Test
public void testAuthenticatePassword() throws WhdException {
WhdAuth auth = new WhdAuth(TestDetails.whdUri, Util.WhdAuthType.PASSWORD, TestDetails.username, TestDetails.password);
// If authenticate() fails, then WhdException will be thrown,
// failing the test case
auth.authenticate();
}
@Test
public void testAuthenticateSessionKey() throws WhdException {
WhdAuth auth = new WhdAuth(TestDetails.whdUri, Util.WhdAuthType.PASSWORD, TestDetails.username, null);
// If authenticate() fails, then WhdException will be thrown,
// failing the test case
auth.authenticate(TestDetails.password);
}
@Test
public void testAuthenticateApiKey() {
WhdAuth auth = new WhdAuth(TestDetails.whdUri, Util.WhdAuthType.PASSWORD, TestDetails.username, TestDetails.apiKey);
// TODO: Assert if auth is valid, how??
}
@Test(expected=WhdException.class)
public void testAuthenticateSessionKeyFail() throws WhdException {
WhdAuth auth = new WhdAuth(TestDetails.whdUri, Util.WhdAuthType.PASSWORD, TestDetails.username, null);
auth.authenticate(TestDetails.password+"abc");
}
@Test(expected=WhdException.class)
public void testAuthenticatePasswordFail() throws WhdException {
WhdAuth auth = new WhdAuth(TestDetails.whdUri, Util.WhdAuthType.PASSWORD, TestDetails.username, TestDetails.password+ "abc");
auth.authenticate();
}
*/
}
|
package gov.adlnet.xapi;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.UUID;
import com.google.gson.*;
import gov.adlnet.xapi.client.AgentClient;
import gov.adlnet.xapi.model.Account;
import gov.adlnet.xapi.model.Agent;
import gov.adlnet.xapi.model.AgentProfile;
import gov.adlnet.xapi.model.Person;
import gov.adlnet.xapi.util.Base64;
import junit.framework.TestCase;
public class AgentTest extends TestCase {
private static final String LRS_URI = "https://lrs.adlnet.gov/xAPI";
private static final String USERNAME = "jXAPI";
private static final String PASSWORD = "password";
private static final String MBOX = "mailto:test@example.com";
private String PUT_PROFILE_ID;
private String POST_PROFILE_ID;
public void setUp() throws IOException{
PUT_PROFILE_ID = UUID.randomUUID().toString();
POST_PROFILE_ID = UUID.randomUUID().toString();
AgentClient client = new AgentClient(LRS_URI, USERNAME, PASSWORD);
Agent a = new Agent();
a.setMbox(MBOX);
JsonObject puobj = new JsonObject();
puobj.addProperty("puttest", "puttest");
AgentProfile ap = new AgentProfile(a, PUT_PROFILE_ID);
ap.setProfile(puobj);
HashMap<String, String> putEtag = new HashMap<String, String>();
putEtag.put("If-Match", "*");
assertTrue(client.putAgentProfile(ap, putEtag));
JsonObject pobj = new JsonObject();
pobj.addProperty("posttest", "posttest");
AgentProfile poap = new AgentProfile(a, POST_PROFILE_ID);
poap.setProfile(pobj);
HashMap<String, String> postEtag = new HashMap<String, String>();
postEtag.put("If-Match", "*");
assertTrue(client.postAgentProfile(poap, postEtag));
}
public void tearDown() throws IOException{
AgentClient client = new AgentClient(LRS_URI, USERNAME, PASSWORD);
Agent a = new Agent();
a.setMbox(MBOX);
boolean putResp = client.deleteAgentProfile(new AgentProfile(a, PUT_PROFILE_ID), "*");
assertTrue(putResp);
boolean postResp = client.deleteAgentProfile(new AgentProfile(a, POST_PROFILE_ID), "*");
assertTrue(postResp);
}
public void testAgentClient() throws IOException {
String encodedCreds = Base64.encodeToString((USERNAME + ":" + PASSWORD).getBytes(), Base64.NO_WRAP);
URL lrs_url = new URL(LRS_URI);
AgentClient client = new AgentClient(LRS_URI, encodedCreds);
assertNotNull(client);
// Verify the client can do something.
Agent a = new Agent();
a.setMbox(MBOX);
Person p = client.getPerson(a);
assertNotNull(p);
assertEquals(p.getMbox()[0], MBOX);
client = null;
p = null;
client = new AgentClient(lrs_url, encodedCreds);
assertNotNull(client);
// Verify the client can do something.
p = client.getPerson(a);
assertNotNull(p);
assertEquals(p.getMbox()[0], MBOX);
}
public void testGetProfile() throws IOException {
AgentClient client = new AgentClient(LRS_URI, USERNAME, PASSWORD);
Agent a = new Agent();
a.setMbox(MBOX);
JsonElement putProfile = client.getAgentProfile(new AgentProfile(a, PUT_PROFILE_ID));
assertNotNull(putProfile);
assertTrue(putProfile.isJsonObject());
JsonObject obj = (JsonObject)putProfile;
assertEquals(obj.getAsJsonPrimitive("puttest").getAsString(), "puttest");
AgentProfile ap = new AgentProfile();
ap.setAgent(a);
ap.setProfileId(POST_PROFILE_ID);
JsonElement postProfile = client.getAgentProfile(ap);
assertNotNull(postProfile);
assertTrue(postProfile.isJsonObject());
JsonObject pobj = (JsonObject)postProfile;
assertEquals(pobj.getAsJsonPrimitive("posttest").getAsString(), "posttest");
}
public void testGetProfiles() throws IOException{
AgentClient client = new AgentClient(LRS_URI, USERNAME, PASSWORD);
Agent a = new Agent();
a.setMbox(MBOX);
JsonArray profiles = client.getAgentProfiles(a, "");
assertNotNull(profiles);
assertTrue(profiles.size() >= 2);
}
public void testPutProfileIfNoneMatch() throws IOException{}
public void testPostProfileIfNoneMatch() throws IOException{}
public void testPutProfileBadEtag() throws IOException{}
public void testPostProfileBadEtag() throws IOException{}
public void testGetProfilesWithSince() throws IOException{
AgentClient client = new AgentClient(LRS_URI, USERNAME, PASSWORD);
Agent a = new Agent();
a.setMbox(MBOX);
JsonArray profiles = client.getAgentProfiles(a, "2014-05-02T17:28:47.00Z");
assertNotNull(profiles);
assertTrue(profiles.size() >= 2);
}
public void testGetPerson() throws IOException{
AgentClient client = new AgentClient(LRS_URI, USERNAME, PASSWORD);
Agent a = new Agent();
a.setMbox(MBOX);
Person p = client.getPerson(a);
assertNotNull(p);
assertEquals(p.getMbox()[0], MBOX);
}
}
|
package org.agmip.dome;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import org.agmip.ace.AcePathfinder;
import org.agmip.ace.util.AcePathfinderUtil;
import org.agmip.util.JSONAdapter;
import org.agmip.util.MapUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EngineTest {
private static final Logger log = LoggerFactory.getLogger(EngineTest.class);
private ArrayList<HashMap<String, String>> rules;
private Engine e;
private void createRule(String method, String var, String args) {
createEngineRule(e, method, var, args, false);
}
private void createEngineRule(Engine eng, String method, String var, String args, boolean isGenerator) {
HashMap<String, String> rule = new HashMap<String, String>();
rule.put("cmd", method);
if (var != null) {
rule.put("variable", var);
}
if (args != null) {
rule.put("args", args);
}
if (isGenerator) {
eng.addGenerator(rule);
} else {
eng.addRule(rule);
}
}
@Before
public void startUp() {
rules = new ArrayList<HashMap<String,String>>();
// This should only be used within the confines of a test.
e = new Engine();
}
@Test
public void CommandTest() {
createRule("NOTHING", null, null);
createRule("INFO", null, null);
createRule("REPLACE", null, null);
createRule("REPLACE", "icdat", "OFFSET()|$PDATE|-30");
// We are just testing commands, no data required.
e.apply(new HashMap<String, Object>());
}
@Test
public void StaticFillTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
createRule("FILL", "exname", "Sample");
createRule("FILL", "pdate", "20121024");
createRule("FILL", "icdat", "$pdate");
createRule("FILL", "APSIM_CULID", "sb120");
e.apply(testMap);
log.info("SFNnT: {}", testMap.toString());
}
@Test
public void StaticFillBlanksTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "exname", "StaticFillBlanks");
AcePathfinderUtil.insertValue(testMap, "ic_name", "StaticFillBlankIC");
AcePathfinderUtil.insertValue(testMap, "pdate", "19810101");
log.info("SFBT Pre: {}", testMap.toString());
createRule("FILL", "exname", "Failed");
createRule("FILL", "exp_dur", "1");
createRule("FILL", "ic_name", "Failed");
createRule("FILL", "icdat", "$pdate");
createRule("FILL", "pdate", "99999999");
createRule("FILL", "crid", "MAZ");
e.apply(testMap);
log.info("SFBT Post: {}", testMap.toString());
}
@Test
public void StaticReplaceNonexistentTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
createRule("REPLACE", "exname", "Root");
createRule("REPLACE", "icdat", "19810101");
createRule("REPLACE", "pdate", "19840219");
e.apply(testMap);
log.info("SRNT: {}", testMap.toString());
}
@Test
public void StaticReplaceActualTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "exname", "StaticFillBlanks");
AcePathfinderUtil.insertValue(testMap, "ic_name", "StaticFillBlankIC");
AcePathfinderUtil.insertValue(testMap, "pdate", "19810101");
AcePathfinderUtil.insertValue(testMap, "crid", "MAZ");
AcePathfinderUtil.insertValue(testMap, "pdate", "19840101");
AcePathfinderUtil.insertValue(testMap, "crid", "SUC");
log.info("SRAT Pre: {}", testMap.toString());
createRule("REPLACE", "exname", "StaticReplaceActual");
createRule("REPLACE", "ic_name", "StaticReplaceActualIC");
createRule("REPLACE", "crid", "WHB");
e.apply(testMap);
log.info("SRAT Post: {}", testMap.toString());
}
@Test
public void CalcReplaceBlankICDATFromEvent() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "pdate", "19810101");
AcePathfinderUtil.insertValue(testMap, "pdate", "19820101");
createRule("REPLACE", "icdat", "OFFSET_DATE()|$pdate|-7");
e.apply(testMap);
log.info("CRBIFE: {}", testMap.toString());
}
@Test
public void CalcReplaceExistingICDATFromEvent() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "pdate", "19810101");
AcePathfinderUtil.insertValue(testMap, "icdat", "19800101");
createRule("REPLACE", "icdat", "OFFSET_DATE()|$pdate|-7");
e.apply(testMap);
log.info("CREIFE: {}", testMap.toString());
}
@Test
public void CalcReplaceExistingPdateFromEvent() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "pdate", "19810101");
AcePathfinderUtil.insertValue(testMap, "pdate", "19820101");
AcePathfinderUtil.insertValue(testMap, "pdate", "19830101");
AcePathfinderUtil.insertValue(testMap, "sdat", "19800101", "");
log.info("==== START ====\nStarting Map: {}", testMap.toString());
createRule("REPLACE", "pdate", "OFFSET_DATE()|$pdate|-7");
createRule("FILL", "icdat", "OFFSET_DATE()|$pdate|-30");
createRule("FILL", "sdat", "OFFSET_DATE()|$icdat|-30");
e.apply(testMap);
log.info("CREPDE: {}", testMap.toString());
}
@Test
public void CalcReplaceMultiplyTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "icbl", "20");
AcePathfinderUtil.insertValue(testMap, "icbl", "30");
AcePathfinderUtil.insertValue(testMap, "sllb", "10");
AcePathfinderUtil.insertValue(testMap, "sllb", "15");
createRule("REPLACE", "sllb", "MULTIPLY()|$sllb|2");
e.apply(testMap);
log.info("CRMT: {}", testMap.toString());
}
@Test
public void CalcFillICH2OTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "sllb", "30");
AcePathfinderUtil.insertValue(testMap, "slll", "0.22");
AcePathfinderUtil.insertValue(testMap, "sldul", "0.32");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.9");
AcePathfinderUtil.insertValue(testMap, "sllb", "50");
AcePathfinderUtil.insertValue(testMap, "slll", "0.15");
AcePathfinderUtil.insertValue(testMap, "sldul", "0.24");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.01");
createRule("FILL", "ich2o", "PCTAWC()|45");
e.apply(testMap);
log.info("CFIh2oT: {}", testMap.toString());
}
@Test
public void CalcFillFullICH2OTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "sllb", "30");
AcePathfinderUtil.insertValue(testMap, "slll", "0.22");
AcePathfinderUtil.insertValue(testMap, "sldul", "0.32");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.9");
AcePathfinderUtil.insertValue(testMap, "sllb", "50");
AcePathfinderUtil.insertValue(testMap, "slll", "0.15");
AcePathfinderUtil.insertValue(testMap, "sldul", "0.24");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.01");
AcePathfinderUtil.insertValue(testMap, "icbl", "25");
AcePathfinderUtil.insertValue(testMap, "icbl", "30");
createRule("FILL", "ich2o", "PCTAWC()|45");
e.apply(testMap);
log.info("CRIh2oT: {}", testMap.toString());
}
@Test
public void CalcReplaceFullICH2OTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "sllb", "30");
AcePathfinderUtil.insertValue(testMap, "slll", "0.22");
AcePathfinderUtil.insertValue(testMap, "sldul", "0.32");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.9");
AcePathfinderUtil.insertValue(testMap, "sllb", "50");
AcePathfinderUtil.insertValue(testMap, "slll", "0.15");
AcePathfinderUtil.insertValue(testMap, "sldul", "0.24");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.01");
AcePathfinderUtil.insertValue(testMap, "icbl", "25");
AcePathfinderUtil.insertValue(testMap, "icbl", "30");
createRule("REPLACE", "ich2o", "PCTAWC()|45");
e.apply(testMap);
log.info("CRIh2oT: {}", testMap.toString());
}
@Test
public void CalcFEDistTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "pdate", "19820312");
AcePathfinderUtil.insertValue(testMap, "fen_tot", "60");
log.info("=== FERT_DIST() TEST ===");
log.debug("Starting map: {}", testMap);
createRule("REPLACE", "fedate", "FERT_DIST()|2|FE005|AP002|10|14|33.3|45|66.7");
e.apply(testMap);
log.debug("Modified map: {}", testMap.toString());
log.info("=== END TEST ===");
}
@Test
public void CalcOMDistTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "pdate", "19820312");
AcePathfinderUtil.insertValue(testMap, "omamt", "1000");
log.info("=== OM_DIST() TEST ===");
log.debug("Starting map: {}", testMap);
createRule("FILL", "omdat", "OM_DIST()|-7|RE003|8.3|5|50|2.5");
e.apply(testMap);
log.debug("Modified Map: {}", testMap.toString());
log.info("=== END TEST ===");
}
@Test
public void CalcRootDistTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "sllb", "5");
AcePathfinderUtil.insertValue(testMap, "sllb", "15");
AcePathfinderUtil.insertValue(testMap, "sllb", "30");
AcePathfinderUtil.insertValue(testMap, "sllb", "60");
AcePathfinderUtil.insertValue(testMap, "sllb", "90");
AcePathfinderUtil.insertValue(testMap, "sllb", "120");
AcePathfinderUtil.insertValue(testMap, "sllb", "150");
AcePathfinderUtil.insertValue(testMap, "sllb", "180");
log.info("=== ROOT_DIST() TEST ===");
log.info("Starting map: {}", testMap.toString());
createRule("FILL", "sloc", "ROOT_DIST()|1.0|20|180");
e.apply(testMap);
log.info("Modified Map: {}", testMap.toString());
log.info("=== END TEST ===");
}
@Test
public void CalcStableCTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "icbl", "5");
AcePathfinderUtil.insertValue(testMap, "icbl", "15");
AcePathfinderUtil.insertValue(testMap, "icbl", "30");
AcePathfinderUtil.insertValue(testMap, "icbl", "60");
AcePathfinderUtil.insertValue(testMap, "icbl", "90");
AcePathfinderUtil.insertValue(testMap, "icbl", "120");
AcePathfinderUtil.insertValue(testMap, "icbl", "150");
AcePathfinderUtil.insertValue(testMap, "icbl", "180");
AcePathfinderUtil.insertValue(testMap, "sllb", "5");
AcePathfinderUtil.insertValue(testMap, "sloc", "2.00");
AcePathfinderUtil.insertValue(testMap, "sllb", "15");
AcePathfinderUtil.insertValue(testMap, "sloc", "1.00");
AcePathfinderUtil.insertValue(testMap, "sllb", "30");
AcePathfinderUtil.insertValue(testMap, "sloc", "1.00");
AcePathfinderUtil.insertValue(testMap, "sllb", "60");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.50");
AcePathfinderUtil.insertValue(testMap, "sllb", "90");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.10");
AcePathfinderUtil.insertValue(testMap, "sllb", "120");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.10");
AcePathfinderUtil.insertValue(testMap, "sllb", "150");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.04");
AcePathfinderUtil.insertValue(testMap, "sllb", "180");
AcePathfinderUtil.insertValue(testMap, "sloc", "0.24");
log.info("=== STABLEC() TEST ===");
log.info("Starting map: {}", testMap.toString());
createRule("FILL", "slsc", "STABLEC()|0.55|20|60");
e.apply(testMap);
log.info("Modified Map: {}", testMap.toString());
log.info("=== END TEST ===");
}
@Test
@Ignore
public void GenerateMachakosFastTest() {
log.info("=== GENERATE() TEST ===");
URL resource = this.getClass().getResource("/mach_fast.json");
String json = "";
try {
json = new Scanner(new File(resource.getPath()), "UTF-8").useDelimiter("\\A").next();
} catch (Exception ex) {
log.error("Unable to find mach_fast.json");
assertTrue(false);
}
createRule("REPLACE", "sc_year", "1981");
createRule("REPLACE", "exp_dur", "30");
createRule("REPLACE", "pdate", "REMOVE_ALL_EVENTS()");
createEngineRule(e, "REPLACE", "pdate", "AUTO_PDATE()|0501|0701|25|5", true);
e.enableGenerators();
HashMap<String, Object> testMap = new HashMap<String, Object>();
try {
testMap = JSONAdapter.fromJSON(json);
} catch (Exception ex) {
log.error("Unable to convert JSON");
assertTrue(false);
}
ArrayList<HashMap<String, Object>> fp = MapUtil.flatPack(testMap);
log.debug("Flatpack count: {}", fp.size());
HashMap<String, Object> tm = fp.get(0);
e.apply(tm);
ArrayList<HashMap<String, Object>> newExperiments = e.runGenerators(tm);
assertEquals("Improper number of generated experiments", 30, newExperiments.size());
int i = 0;
for(HashMap<String, Object> exp : newExperiments) {
i++;
log.debug("Generated Exp {}: {}", i, exp.toString());
}
log.info("=== END TEST ===");
}
@Test
@Ignore
public void GenerateMachakosFastTest2() {
log.info("=== GENERATE() TEST2 ===");
URL resource = this.getClass().getResource("/mach_fast.json");
String json = "";
try {
json = new Scanner(new File(resource.getPath()), "UTF-8").useDelimiter("\\A").next();
} catch (Exception ex) {
log.error("Unable to find mach_fast.json");
assertTrue(false);
}
createRule("REPLACE", "sc_year", "1981");
createRule("REPLACE", "exp_dur", "3");
createEngineRule(e, "REPLACE", "pdate", "AUTO_REPLICATE_EVENTS()", true);
e.enableGenerators();
HashMap<String, Object> testMap = new HashMap<String, Object>();
try {
testMap = JSONAdapter.fromJSON(json);
} catch (Exception ex) {
log.error("Unable to convert JSON");
assertTrue(false);
}
ArrayList<HashMap<String, Object>> fp = MapUtil.flatPack(testMap);
log.debug("Flatpack count: {}", fp.size());
HashMap<String, Object> tm = fp.get(0);
e.apply(tm);
ArrayList<HashMap<String, Object>> newExperiments = e.runGenerators(tm);
assertEquals("Improper number of generated experiments", 3, newExperiments.size());
int i = 0;
for(HashMap<String, Object> exp : newExperiments) {
i++;
log.debug("Generated Exp {}: {}", i, exp.toString());
}
log.info("=== END TEST ===");
}
@Test
@Ignore
public void GenerateMachakosFullTest() {
log.info("=== GENERATE() TEST ===");
URL resource = this.getClass().getResource("/mach_full.json");
String json = "";
try {
json = new Scanner(new File(resource.getPath()), "UTF-8").useDelimiter("\\A").next();
} catch (Exception ex) {
log.error("Unable to find mach_full.json");
assertTrue(false);
}
createRule("REPLACE", "sc_year", "1981");
createRule("REPLACE", "exp_dur", "30");
createRule("REPLACE", "pdate", "REMOVE_ALL_EVENTS()");
createEngineRule(e, "REPLACE", "pdate", "AUTO_PDATE()|0501|0701|25|5", true);
e.enableGenerators();
HashMap<String, Object> testMap = new HashMap<String, Object>();
try {
testMap = JSONAdapter.fromJSON(json);
} catch (Exception ex) {
log.error("Unable to convert JSON");
assertTrue(false);
}
ArrayList<HashMap<String, Object>> fp = MapUtil.flatPack(testMap);
ArrayList<HashMap<String, Object>> full = new ArrayList<HashMap<String, Object>>();
log.debug("Flatpack count: {}", fp.size());
for (HashMap<String, Object> tm : fp) {
e.apply(tm);
ArrayList<HashMap<String, Object>> newExperiments = e.runGenerators(tm);
full.addAll(newExperiments);
}
ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(testMap, "experiments");
exp.clear();
exp.addAll(full);
log.debug("Replaced with generated data");
fp = MapUtil.flatPack(testMap);
log.debug("Flatpack count: {}", fp.size());
Engine postEngine = new Engine();
createEngineRule(postEngine, "REPLACE", "fedate", "FERT_DIST()|2|FE005|AP002|10|14|33.3|45|66.7", false);
int i=0;
int target = fp.size();
for(HashMap<String, Object> post : fp) {
i++;
double pct = (i / target) * 100;
//if (pct % 5 == 0) {
log.debug("{}%", pct);
postEngine.apply(post);
}
log.debug("51st Entry: {}", Command.traverseAndGetSiblings(fp.get(51), "pdate"));
log.info("=== END TEST ===");
}
@Test
public void CalcTavAmpTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "w_date", "19890101");
AcePathfinderUtil.insertValue(testMap, "tmax", "26.3");
AcePathfinderUtil.insertValue(testMap, "tmin", "16.2");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890102");
AcePathfinderUtil.insertValue(testMap, "tmax", "25");
AcePathfinderUtil.insertValue(testMap, "tmin", "15.1");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890103");
AcePathfinderUtil.insertValue(testMap, "tmax", "25.1");
AcePathfinderUtil.insertValue(testMap, "tmin", "15.4");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890201");
AcePathfinderUtil.insertValue(testMap, "tmax", "27.9");
AcePathfinderUtil.insertValue(testMap, "tmin", "17.4");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890202");
AcePathfinderUtil.insertValue(testMap, "tmax", "27.9");
AcePathfinderUtil.insertValue(testMap, "tmin", "17.4");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890203");
AcePathfinderUtil.insertValue(testMap, "tmax", "28.1");
AcePathfinderUtil.insertValue(testMap, "tmin", "13.8");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890303");
AcePathfinderUtil.insertValue(testMap, "tmax", "27.5");
AcePathfinderUtil.insertValue(testMap, "tmin", "13");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890304");
AcePathfinderUtil.insertValue(testMap, "tmax", "31");
AcePathfinderUtil.insertValue(testMap, "tmin", "16.9");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890305");
AcePathfinderUtil.insertValue(testMap, "tmax", "32.3");
AcePathfinderUtil.insertValue(testMap, "tmin", "16.5");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900101");
AcePathfinderUtil.insertValue(testMap, "tmax", "20.4");
AcePathfinderUtil.insertValue(testMap, "tmin", "5.2");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900102");
AcePathfinderUtil.insertValue(testMap, "tmax", "20.1");
AcePathfinderUtil.insertValue(testMap, "tmin", "3.2");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900103");
AcePathfinderUtil.insertValue(testMap, "tmax", "25");
AcePathfinderUtil.insertValue(testMap, "tmin", "8.1");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900201");
AcePathfinderUtil.insertValue(testMap, "tmax", "29.6");
AcePathfinderUtil.insertValue(testMap, "tmin", "13.6");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900202");
AcePathfinderUtil.insertValue(testMap, "tmax", "29.2");
AcePathfinderUtil.insertValue(testMap, "tmin", "17.7");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900203");
AcePathfinderUtil.insertValue(testMap, "tmax", "30.4");
AcePathfinderUtil.insertValue(testMap, "tmin", "15.6");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900204");
AcePathfinderUtil.insertValue(testMap, "tmax", "28.3");
AcePathfinderUtil.insertValue(testMap, "tmin", "16.2");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900205");
AcePathfinderUtil.insertValue(testMap, "tmax", "19.4");
AcePathfinderUtil.insertValue(testMap, "tmin", "6.9");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900301");
AcePathfinderUtil.insertValue(testMap, "tmax", "26.2");
AcePathfinderUtil.insertValue(testMap, "tmin", "8.8");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900302");
AcePathfinderUtil.insertValue(testMap, "tmax", "26.2");
AcePathfinderUtil.insertValue(testMap, "tmin", "11.7");
AcePathfinderUtil.insertValue(testMap, "w_date", "19900303");
AcePathfinderUtil.insertValue(testMap, "tmax", "21.5");
AcePathfinderUtil.insertValue(testMap, "tmin", "10.8");
AcePathfinderUtil.insertValue(testMap, "w_date", "19901229");
AcePathfinderUtil.insertValue(testMap, "tmax", "29.3");
AcePathfinderUtil.insertValue(testMap, "tmin", "16.1");
AcePathfinderUtil.insertValue(testMap, "w_date", "19901230");
AcePathfinderUtil.insertValue(testMap, "tmax", "30.1");
AcePathfinderUtil.insertValue(testMap, "tmin", "17.4");
AcePathfinderUtil.insertValue(testMap, "w_date", "19901231");
AcePathfinderUtil.insertValue(testMap, "tmax", "25");
AcePathfinderUtil.insertValue(testMap, "tmin", "16.9");
log.info("=== TAVAMP() TEST ===");
log.info("Starting map: {}", testMap.toString());
createRule("FILL", "TAV,TAMP", "TAVAMP()");
e.apply(testMap);
log.info("Modified Map: {}", testMap.toString());
log.info("=== END TEST ===");
}
@Test
public void CalcEtoTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "wst_lat", "26.65");
AcePathfinderUtil.insertValue(testMap, "wst_long", "-80.633");
AcePathfinderUtil.insertValue(testMap, "wst_elev", "3.00");
AcePathfinderUtil.insertValue(testMap, "wndht", "10.00");
AcePathfinderUtil.insertValue(testMap, "amth", "0.3", "weather");
AcePathfinderUtil.insertValue(testMap, "bmth", "0.4", "weather");
AcePathfinderUtil.insertValue(testMap, "psyvnt", "Forced", "weather");
AcePathfinderUtil.insertValue(testMap, "w_date", "19890823");
AcePathfinderUtil.insertValue(testMap, "srad", "13.6");
AcePathfinderUtil.insertValue(testMap, "tmax", "26.4");
AcePathfinderUtil.insertValue(testMap, "tmin", "12.8");
AcePathfinderUtil.insertValue(testMap, "sunh", "");
AcePathfinderUtil.insertValue(testMap, "tavd", "");
AcePathfinderUtil.insertValue(testMap, "wind", "180");
AcePathfinderUtil.insertValue(testMap, "rhmnd", "30", AcePathfinder.INSTANCE.getPath("w_date"));
AcePathfinderUtil.insertValue(testMap, "rhmxd", "50", AcePathfinder.INSTANCE.getPath("w_date"));
AcePathfinderUtil.insertValue(testMap, "vprsd", "1.6");
AcePathfinderUtil.insertValue(testMap, "tdew", "13.5");
AcePathfinderUtil.insertValue(testMap, "tdry", "25.3");
AcePathfinderUtil.insertValue(testMap, "twet", "22.2");
log.info("=== REFET() TEST ===");
log.info("Starting map: {}", testMap.toString());
createRule("FILL", "ETO", "REFET()");
e.apply(testMap);
log.info("Modified Map: {}", testMap.toString());
log.info("=== END TEST ===");
}
@Test
public void CalcIcnDistTest() {
HashMap<String, Object> testMap = new HashMap<String, Object>();
AcePathfinderUtil.insertValue(testMap, "icbl", "15");
AcePathfinderUtil.insertValue(testMap, "icbl", "30");
AcePathfinderUtil.insertValue(testMap, "icbl", "60");
AcePathfinderUtil.insertValue(testMap, "icbl", "90");
AcePathfinderUtil.insertValue(testMap, "icbl", "120");
AcePathfinderUtil.insertValue(testMap, "icbl", "150");
AcePathfinderUtil.insertValue(testMap, "icbl", "180");
AcePathfinderUtil.insertValue(testMap, "sllb", "15");
AcePathfinderUtil.insertValue(testMap, "slbdm", "1.15");
AcePathfinderUtil.insertValue(testMap, "sllb", "30");
AcePathfinderUtil.insertValue(testMap, "slbdm", "1.16");
AcePathfinderUtil.insertValue(testMap, "sllb", "60");
AcePathfinderUtil.insertValue(testMap, "slbdm", "1.21");
AcePathfinderUtil.insertValue(testMap, "sllb", "90");
AcePathfinderUtil.insertValue(testMap, "slbdm", "1.23");
AcePathfinderUtil.insertValue(testMap, "sllb", "120");
AcePathfinderUtil.insertValue(testMap, "slbdm", "1.31");
AcePathfinderUtil.insertValue(testMap, "sllb", "150");
AcePathfinderUtil.insertValue(testMap, "slbdm", "1.31");
AcePathfinderUtil.insertValue(testMap, "sllb", "180");
AcePathfinderUtil.insertValue(testMap, "slbdm", "1.31");
log.info("=== ICN_DIST() TEST ===");
log.info("Starting map: {}", testMap.toString());
createRule("FILL", "icn_tot,ichn4,icno3", "ICN_DIST()|25");
e.apply(testMap);
log.info("Modified Map: {}", testMap.toString());
log.info("=== END TEST ===");
}
@After
public void tearDown() {
e = null;
}
}
|
package se.hiflyer.fettle;
import com.google.common.collect.Lists;
import org.junit.Test;
import se.hiflyer.fettle.builder.StateMachineBuilder;
import se.hiflyer.fettle.util.GuavaReplacement;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class Example {
@Test
public void usingBuilder() {
StateMachineBuilder<States,String> builder = Fettle.newBuilder(States.class, String.class);
builder.transition().from(States.INITIAL).to(States.ONE).on("foo").perform(new SoutAction("Performing fooTransition"));
builder.onEntry(States.ONE).perform(new SoutAction("Entering state ONE"));
StateMachineTemplate<States, String> stateMachineTemplate = builder.buildTransitionModel();
StateMachine<States, String> stateMachine = stateMachineTemplate.newStateMachine(States.INITIAL);
stateMachine.fireEvent("foo");
assertEquals(States.ONE, stateMachine.getCurrentState());
}
@Test
public void usingTransitionModelDirectly() {
MutableTransitionModel<States,String> model = Fettle.newTransitionModel(States.class, String.class);
List<Action<States,String>> actions = Lists.<Action<States, String>>newArrayList(new SoutAction("Performing fooTransition"));
model.addTransition(States.INITIAL, States.ONE, "foo", BasicConditions.ALWAYS, actions);
model.addEntryAction(States.ONE, new SoutAction("Entering state ONE"));
StateMachine<States, String> stateMachine = model.newStateMachine(States.INITIAL);
stateMachine.fireEvent("foo");
assertEquals(States.ONE, stateMachine.getCurrentState());
}
@Test
public void whenExample() throws Exception {
StateMachineBuilder<States,String> builder = Fettle.newBuilder(States.class, String.class);
Condition firstArgIsOne = new Condition() {
@Override
public boolean isSatisfied(Arguments args) {
return args.getNumberOfArguments() > 0 && args.getFirst().equals(1);
}
};
Condition noArguments = new Condition() {
@Override
public boolean isSatisfied(Arguments args) {
return args.getNumberOfArguments() == 0;
}
};
builder.transition().from(States.INITIAL).to(States.ONE).on("tick").when(BasicConditions.or(firstArgIsOne, noArguments));
StateMachine<States, String> stateMachine = builder.build(States.INITIAL);
stateMachine.fireEvent("tick", new Arguments(3));
assertEquals(States.INITIAL, stateMachine.getCurrentState());
stateMachine.fireEvent("tick", Arguments.NO_ARGS);
assertEquals(States.ONE, stateMachine.getCurrentState());
}
@Test
public void transitionActionExample() throws Exception {
StateMachineBuilder<States,String> builder = Fettle.newBuilder(States.class, String.class);
Action<States, String> action1 = new Action<States, String>() {
@Override
public void onTransition(States from, States to, String causedBy, Arguments args, StateMachine<States, String> statesStringStateMachine) {
// do whatever is desired
}
};
Action<States, String> action2 = new Action<States, String>() {
@Override
public void onTransition(States from, States to, String causedBy, Arguments args, StateMachine<States, String> statesStringStateMachine) {
// do whatever is desired
}
};
List<Action<States, String>> actions = GuavaReplacement.newArrayList();
actions.add(action1);
actions.add(action2);
builder.transition().from(States.INITIAL).to(States.ONE).on("foo").perform(actions);
}
@Test
public void entryExitActionExample() throws Exception {
StateMachineBuilder<States,String> builder = Fettle.newBuilder(States.class, String.class);
Action<States, String> action1 = new Action<States, String>() {
@Override
public void onTransition(States from, States to, String causedBy, Arguments args, StateMachine<States, String> statesStringStateMachine) {
// do whatever is desired
}
};
Action<States, String> action2 = new Action<States, String>() {
@Override
public void onTransition(States from, States to, String causedBy, Arguments args, StateMachine<States, String> statesStringStateMachine) {
// do whatever is desired
}
};
builder.onExit(States.INITIAL).perform(action1);
builder.onEntry(States.ONE).perform(action2);
}
private class SoutAction implements Action<States, String> {
private final String text;
public SoutAction(String text) {
this.text = text;
}
@Override
public void onTransition(States from, States to, String causedBy, Arguments args, StateMachine<States, String> stateMachine) {
System.out.println(text);
}
}
}
|
package ca.corefacility.bioinformatics.irida.ria.web.clients.dto;
import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableRequest;
/**
* UI request for client details for the clients table.
* Required to overwrite the default setSortColumn since
* @link ca.corefacility.bioinformatics.irida.model.IridaClientDetails} does not
* have a "name" attribute, instead it required a "clientId".
*/
public class ClientTableRequest extends TableRequest {
@Override
public void setSortColumn(String sortColumn) {
String column = sortColumn.equals("name") ? "clientId" : sortColumn;
super.setSortColumn(column);
}
}
|
package com.aldebaran.qi;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Future extends the standard Java {@link java.util.concurrent.Future} and represents the result of
* an asynchronous computation.
* <p>
* {@link Promise} and Future are two complementary concepts. They are designed to synchronise data
* between multiples threads. The Future holds the result of an asynchronous computation, from which
* you can retrieve the value of the result; the {@link Promise} sets the value of this computation,
* which resolves the associated Future.
*
* @param <T> The type of the result
*/
public class Future<T> implements java.util.concurrent.Future<T> {
// Loading QiMessaging JNI layer
static {
if (!EmbeddedTools.LOADED_EMBEDDED_LIBRARY) {
EmbeddedTools loader = new EmbeddedTools();
loader.loadEmbeddedLibraries();
}
}
public interface Callback<T> {
void onFinished(Future<T> future);
}
private static final int TIMEOUT_INFINITE = -1;
/**Canceled future*/
private static final Future<?> CANCELED_FUTURE = new Future();
// C++ Future
private long _fut;
/**Indicates if future has C reference*/
private boolean nativeFuture;
/**Known value for not native future*/
private T value;
/**Last error for not native future*/
private String error;
/**Cancel state for not native future*/
private boolean canceled;
// Native C API object functions
private native boolean qiFutureCallCancel(long pFuture);
private native boolean qiFutureCallCancelRequest(long pFuture);
private native Object qiFutureCallGet(long pFuture, int msecs) throws ExecutionException, TimeoutException;
private native boolean qiFutureCallIsCancelled(long pFuture);
private native boolean qiFutureCallIsDone(long pFuture);
private native boolean qiFutureCallConnect(long pFuture, Object callback, String className, Object[] args);
private native void qiFutureCallWaitWithTimeout(long pFuture, int timeout);
private native void qiFutureDestroy(long pFuture);
private native void qiFutureCallConnectCallback(long pFuture, Callback<?> callback, int futureCallbackType);
private static native long qiFutureCreate(Object value);
Future(long pFuture) {
_fut = pFuture;
this.nativeFuture = true;
}
/**
* Create future with known value
*
* @param value Known value
*/
Future(T value) {
this.nativeFuture = false;
this.value = value;
this.canceled = false;
}
/**
* Create future on error
*
* @param error Error
*/
Future(String error) {
this.nativeFuture = false;
this.error = error == null ? "" : error;
this.canceled = false;
}
/**
* Create a canceled future
*/
private Future() {
this.nativeFuture = false;
this.canceled = true;
}
public static <T> Future<T> of(T value) {
return new Future<T>(value);
}
public static <T> Future<T> cancelled() {
return (Future<T>)CANCELED_FUTURE;
}
public static <T> Future<T> fromError(String errorMessage) {
return new Future<T>(errorMessage);
}
public void sync(long timeout, TimeUnit unit) {
if(this.nativeFuture) {
qiFutureCallWaitWithTimeout(_fut, (int) unit.toMillis(timeout));
}
}
public void sync() {
this.sync(0, TimeUnit.SECONDS);
}
/**
* Callbacks to future can be set.
*
* @param callback com.aldebaran.qi.Callback implementation
* @param args Argument to be forwarded to callback functions.
* @return true on success.
* @since 1.20
*/
@Deprecated
public boolean addCallback(com.aldebaran.qi.Callback<T> callback, Object... args) {
if(!this.nativeFuture) {
if(this.error!=null) {
callback.onFailure(this, args);
}
else if(this.canceled) {
callback.onComplete(this, args);
}
else {
callback.onSuccess(this, args);
}
return true;
}
String className = callback.getClass().getName().replace('.', '/');
return qiFutureCallConnect(_fut, callback, className, args);
}
/**
* Prefer {@link #then(FutureFunction, FutureCallbackType)} instead (e.g. {@link QiCallback}).
*/
public void connect(Callback<T> callback, FutureCallbackType futureCallbackType) {
if(!this.nativeFuture) {
callback.onFinished(this);
}
else {
qiFutureCallConnectCallback(_fut, callback, futureCallbackType.nativeValue);
}
}
public void connect(Callback<T> callback) {
connect(callback, FutureCallbackType.Async);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if(!this.nativeFuture) {
return this.canceled;
}
// ignore mayInterruptIfRunning, can't map it to native libqi
// This must be a blocking call to be compliant with Java's Future
qiFutureCallCancel(_fut);
sync();
return isCancelled();
}
/**
* Sends asynchronously a request to cancel the execution of this task.
*/
public synchronized void requestCancellation() {
if(this.nativeFuture) {
// This call is compliant with native libqi's Future.cancel()
qiFutureCallCancelRequest(_fut);
}
}
@Deprecated
public synchronized boolean cancel() {
if(!this.nativeFuture) {
return this.canceled;
}
// Leave this method as it is (even if returning a boolean doesn't make sense)
// to avoid breaking projects that were already using it.
// Future projects should prefer using requestCancellation().
return qiFutureCallCancel(_fut);
}
@SuppressWarnings("unchecked")
private T get(int msecs) throws ExecutionException, TimeoutException {
if(!this.nativeFuture) {
if(this.error!=null) {
throw new ExecutionException(this.error, new Throwable());
}
if(this.canceled) {
throw new CancellationException();
}
return this.value;
}
Object result = qiFutureCallGet(_fut, msecs);
return (T) result;
}
@Override
public T get() throws ExecutionException {
try {
return get(TIMEOUT_INFINITE);
} catch (TimeoutException e) {
// should never happen
throw new RuntimeException(e);
}
}
@Override
public T get(long timeout, TimeUnit unit) throws ExecutionException, TimeoutException {
int msecs = (int) unit.toMillis(timeout);
return get(msecs);
}
/**
* Same as {@code get()}, but does not throw checked exceptions.
* <p>
* This is especially useful for getting the value of a future that we know is
* complete with success.
*
* @return the future value
*/
public T getValue() {
try {
return get();
} catch (ExecutionException e) {
// this is an error to call getValue() if the future is not finished with a value
throw new RuntimeException(e);
}
}
public ExecutionException getError() {
try {
get();
return null;
} catch (ExecutionException e) {
return e;
} catch (CancellationException e) {
return null;
}
}
public boolean hasError() {
return getError() != null;
}
public String getErrorMessage() {
// for convenience
ExecutionException e = getError();
if (e == null) {
return null;
}
Throwable cause = e.getCause();
if (cause instanceof QiException) {
return ((QiException) cause).getMessage();
}
return e.getMessage();
}
@Override
public synchronized boolean isCancelled() {
if(!this.nativeFuture) {
return this.canceled;
}
// inherited from java.util.concurrent.Future, it must match its semantics
// --> There is no way to verify that a cancel request resulted in the
// cancellation of the associated task, until the Future is done
return qiFutureCallIsCancelled(_fut);
}
@Override
public synchronized boolean isDone() {
return !this.nativeFuture || qiFutureCallIsDone(_fut);
}
private <Ret> Future<Ret> _then(final FutureFunction<Ret, T> function, final boolean chainOnFailure,
FutureCallbackType type) {
if(!this.nativeFuture) {
if(this.error != null) {
return Future.fromError(this.error);
}
if(this.canceled) {
return Future.cancelled();
}
// The value is know, but we want use a thread to have asynchronous call to not block current thread
// So just do has "native future"
}
// the promise must be sync according to the Callback (which may be Sync or Async according to the caller)
final Promise<Ret> promiseToNotify = new Promise<Ret>(FutureCallbackType.Sync);
// Adding the callback to the promise to be able to be able to forward the
// cancel request to the parent future/promise.
promiseToNotify.setOnCancel(new Promise.CancelRequestCallback<Ret>() {
@Override
public void onCancelRequested(Promise<Ret> promise) {
Future.this.requestCancellation();
}
});
connect(new Callback<T>() {
@Override
public void onFinished(Future<T> future) {
if (chainOnFailure || !notifyIfFailed(future, promiseToNotify)) {
chainFuture(future, function, promiseToNotify);
}
}
}, type);
return promiseToNotify.getFuture();
}
public <Ret> Future<Ret> then(FutureFunction<Ret, T> function, FutureCallbackType type) {
return _then(function, true, type);
}
public <Ret> Future<Ret> then(FutureFunction<Ret, T> function) {
return _then(function, true, FutureCallbackType.Async);
}
public <Ret> Future<Ret> andThen(FutureFunction<Ret, T> function, FutureCallbackType type) {
return _then(function, false, type);
}
public <Ret> Future<Ret> andThen(FutureFunction<Ret, T> function) {
return _then(function, false, FutureCallbackType.Async);
}
private static <Ret, Arg> Future<Ret> getNextFuture(Future<Arg> future, FutureFunction<Ret, Arg> function, Promise<Ret> promiseToNotify) {
try {
Future<Ret> nextFuture = function.execute(future);
final Future<Ret> result = (nextFuture != null) ? nextFuture : Future.<Ret>of(null);
promiseToNotify.setOnCancel(new Promise.CancelRequestCallback<Ret>() {
@Override
public void onCancelRequested(Promise<Ret> promise) {
result.requestCancellation();
}
});
// for convenience, the function can return null, which means a future with a null value
return result;
} catch (Throwable t) {
// print the trace because the future error is a string, so the stack trace is lost
t.printStackTrace();
return fromError(t.toString());
}
}
private static <T> void notifyPromiseFromFuture(Future<T> future, Promise<T> promiseToNotify) {
if(future.hasError()) {
if (!promiseToNotify.getFuture().isDone() || !promiseToNotify.getFuture().isCancelled()) {
promiseToNotify.setError(future.getErrorMessage());
}
}
else if(future.isCancelled()) {
if (!promiseToNotify.getFuture().isDone() || !promiseToNotify.getFuture().isCancelled()) {
promiseToNotify.setCancelled();
}
}
else {
if (!promiseToNotify.getFuture().isDone() || !promiseToNotify.getFuture().isCancelled()) {
promiseToNotify.setValue(future.getValue());
}
}
}
private static <Ret, Arg> void chainFuture(Future<Arg> future, FutureFunction<Ret, Arg> function,
final Promise<Ret> promiseToNotify) {
getNextFuture(future, function, promiseToNotify).connect(new Callback<Ret>() {
@Override
public void onFinished(Future<Ret> future) {
notifyPromiseFromFuture(future, promiseToNotify);
}
});
}
private static <T> boolean notifyIfFailed(Future<T> future, Promise<?> promiseToNotify) {
if(future.hasError()) {
if (!promiseToNotify.getFuture().isDone() || !promiseToNotify.getFuture().isCancelled()) {
promiseToNotify.setError(future.getErrorMessage());
}
return true;
}
if(future.isCancelled()) {
if (!promiseToNotify.getFuture().isDone() || !promiseToNotify.getFuture().isCancelled()) {
promiseToNotify.setCancelled();
}
return true;
}
return false;
}
/**
* Wait for all {@code futures} to complete.
* <p>
* The returning future finishes successfully if and only if all of the
* futures it waits for finish successfully.
* <p>
* Otherwise, it takes the state of the first failing future (due to
* cancellation or error).
*
* @param futures the futures to wait for
* @return a future waiting for all the others
*/
public static Future<Void> waitAll(final Future<?>... futures) {
if (futures.length == 0)
return Future.of(null);
class WaitData {
int runningFutures = futures.length;
boolean stopped;
}
final WaitData waitData = new WaitData();
final Promise<Void> promise = new Promise<Void>();
promise.setOnCancel(new Promise.CancelRequestCallback<Void>() {
@Override
public void onCancelRequested(Promise<Void> promise) {
for (Future<?> future : futures) {
future.requestCancellation();
}
}
});
for (Future<?> future : futures) {
((Future<Object>)future).connect(new Future.Callback<Object>() {
@Override
public void onFinished(Future<Object> future) {
synchronized (waitData) {
if (!waitData.stopped) {
if(future.isCancelled()) {
promise.setCancelled();
waitData.stopped = true;
}
else if(future.hasError()) {
promise.setError(future.getErrorMessage());
waitData.stopped = true;
}
else {
waitData.runningFutures
if (waitData.runningFutures == 0) {
promise.setValue(null);
}
}
}
}
}
});
}
return promise.getFuture();
}
/**
* Return a version of {@code this} future that waits until {@code futures} to
* finish.
* <p>
* The returning future finishes successfully if and only if {@code this}
* future and {@code futures} finish successfully.
* <p>
* Otherwise, it takes the state of {@code this} if it failed, or the first
* failing future from {@code futures}.
* <p>
* If {@code this} future does not finish successfully, it does not wait for
* {@code futures}.
*
* @param futures the futures to wait for
* @return future returning this future value when all {@code futures} are
* finished successfully
*/
public Future<T> waitFor(final Future<?>... futures) {
// do not wait for futures if this does not finish successfully
return andThen(new FutureFunction<T, T>() {
@Override
public Future<T> execute(Future<T> future) {
return waitAll(futures).andThen(new FutureFunction<T, Void>() {
@Override
public Future<T> execute(Future<Void> future) {
return Future.this;
}
});
}
});
}
/**
* Called by garbage collector
* Finalize is overriden to manually delete C++ data
*/
@Override
protected void finalize() throws Throwable {
if(this.nativeFuture) {
this.qiFutureDestroy(this._fut);
}
super.finalize();
}
}
|
package com.alekseyzhelo.evilislands.mobplugin.script.codeInsight;
import com.alekseyzhelo.evilislands.mobplugin.script.codeInsight.fixes.ChangeLvalueTypeFix;
import com.alekseyzhelo.evilislands.mobplugin.script.codeInsight.fixes.DeclareScriptFix;
import com.alekseyzhelo.evilislands.mobplugin.script.codeInsight.fixes.ImplementScriptFix;
import com.alekseyzhelo.evilislands.mobplugin.EIMessages;
import com.alekseyzhelo.evilislands.mobplugin.script.psi.*;
import com.alekseyzhelo.evilislands.mobplugin.script.psi.base.EICallableDeclaration;
import com.alekseyzhelo.evilislands.mobplugin.script.psi.base.EIScriptPsiElement;
import com.alekseyzhelo.evilislands.mobplugin.script.psi.references.FunctionCallReference;
import com.alekseyzhelo.evilislands.mobplugin.script.psi.references.MobObjectReference;
import com.alekseyzhelo.evilislands.mobplugin.script.util.EITypeToken;
import com.intellij.codeInsight.daemon.impl.quickfix.DeleteElementFix;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.PsiReference;
import org.jetbrains.annotations.NotNull;
import java.util.List;
// TODO finish, proper
public class EIScriptAnnotator extends EIVisitor implements Annotator {
private static final Logger LOG = Logger.getInstance(EIScriptAnnotator.class);
private AnnotationHolder myHolder = null;
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof EIScriptPsiElement) {
myHolder = holder;
try {
element.accept(this);
} finally {
myHolder = null;
}
}
}
@Override
public void visitScriptDeclaration(@NotNull EIScriptDeclaration scriptDeclaration) {
super.visitScriptDeclaration(scriptDeclaration);
ScriptPsiFile psiFile = (ScriptPsiFile) scriptDeclaration.getContainingFile();
if (psiFile.findScriptImplementation(scriptDeclaration.getName()) == null) {
PsiElement ident = scriptDeclaration.getNameIdentifier();
if (ident != null) {
Annotation annotation = markAsWarning(myHolder, ident,
EIMessages.message("warn.script.not.implemented", scriptDeclaration.getName()));
LocalQuickFix fix = new ImplementScriptFix();
InspectionManager inspectionManager = InspectionManager.getInstance(psiFile.getProject());
ProblemDescriptor descriptor = inspectionManager.createProblemDescriptor(ident, annotation.getMessage(), fix,
ProblemHighlightType.WARNING, true);
TextRange range = scriptDeclaration.getTextRange();
annotation.registerFix(fix, range, null, descriptor);
annotation.registerFix(
new DeleteElementFix(scriptDeclaration, EIMessages.message("fix.remove.element")),
range
);
}
}
}
@Override
public void visitScriptImplementation(@NotNull EIScriptImplementation scriptImplementation) {
super.visitScriptImplementation(scriptImplementation);
PsiReference reference = scriptImplementation.getReference();
if (reference.resolve() == null) {
PsiElement ident = scriptImplementation.getNameIdentifier();
if (ident != null) {
Annotation annotation = markAsError(myHolder, ident,
EIMessages.message("warn.script.not.declared", scriptImplementation.getName()));
// TODO: move to local quick fix provider in reference?
InspectionManager inspectionManager = InspectionManager.getInstance(scriptImplementation.getProject());
LocalQuickFix fix = new DeclareScriptFix(scriptImplementation);
ProblemDescriptor descriptor = inspectionManager.createProblemDescriptor(ident, annotation.getMessage(), fix,
ProblemHighlightType.ERROR, true);
TextRange range = new TextRange(
scriptImplementation.getTextRange().getStartOffset(),
ident.getTextRange().getEndOffset()
);
annotation.registerFix(fix, range, null, descriptor);
annotation.registerFix(
new DeleteElementFix(scriptImplementation, EIMessages.message("fix.remove.element")),
range
);
}
}
}
@Override
public void visitScriptExpression(@NotNull EIScriptExpression scriptExpression) {
super.visitScriptExpression(scriptExpression);
if (scriptExpression.getType() != EITypeToken.VOID) {
markAsWarning(myHolder, scriptExpression,
EIMessages.message("warn.script.expression.result.ignored", scriptExpression.getText()));
}
}
@Override
public void visitFunctionCall(@NotNull EIFunctionCall call) {
super.visitFunctionCall(call);
// TODO: uncomment!
// if (EIGSVar.isReadOrWrite(call)) {
// PsiElement varNameElement = EIGSVar.getVarNameElement(call);
// if (varNameElement != null &&
// varNameElement.getNode().getElementType() == ScriptTypes.CHARACTER_STRING) {
// String varName = EIGSVar.getVarName(varNameElement.getText());
// Map<String, EIGSVar> vars = ((ScriptPsiFile) call.getContainingFile()).findGSVars();
// EIGSVar gsVar = vars.get(varName);
// if (gsVar != null) {
// if (gsVar.getReads() == 0 && !varName.startsWith("z.")) {
// markAsWeakWarning(myHolder, varNameElement,
// gsVar.getWrites() == 1 ? GS_VAR_ONLY_WRITTEN_AND_ONCE_WARNING : GS_VAR_ONLY_WRITTEN_WARNING);
// if (gsVar.getWrites() == 0) {
// markAsWeakWarning(myHolder, varNameElement,
// gsVar.getReads() == 1 ? GS_VAR_ONLY_READ_AND_ONCE_WARNING : GS_VAR_ONLY_READ_WARNING);
// } else {
// LOG.error("GSVar is null for " + call);
// } else if (EIArea.isReadOrWrite(call)) {
// PsiElement areaIdElement = EIArea.getAreaIdElement(call);
// if (areaIdElement != null &&
// areaIdElement.getNode().getElementType() == ScriptTypes.FLOATNUMBER) {
// try {
// int areaId = Integer.parseInt(areaIdElement.getText());
// Map<Integer, EIArea> vars = ((ScriptPsiFile) call.getContainingFile()).findAreas();
// EIArea area = vars.get(areaId);
// if (area != null) {
// if (area.getReads() == 0) {
// markAsWarning(myHolder, areaIdElement, AREA_ONLY_WRITTEN_WARNING);
// if (area.getWrites() == 0) {
// markAsWarning(myHolder, areaIdElement, AREA_ONLY_READ_WARNING);
// } else {
// LOG.error("Area is null for " + call);
// } catch (NumberFormatException ignored) {
// //don't really care
FunctionCallReference reference = (FunctionCallReference) call.getReference();
PsiElement nameElement = call.getNameIdentifier();
PsiElement resolved = reference.resolve();
if (call.getParent() instanceof EIScriptIfBlock) {
if (resolved instanceof EIScriptDeclaration) {
markAsError(myHolder, nameElement, EIMessages.message("error.not.allowed.in.script.if"));
} else {
handleFunctionCallInIfBlock(myHolder, nameElement, (EIFunctionDeclaration) resolved);
}
} else {
handleFunctionOrScriptCall(call, myHolder, nameElement, resolved);
}
// TODO: same for For args!
if (resolved instanceof EICallableDeclaration) {
EICallableDeclaration callable = (EICallableDeclaration) resolved;
List<EIFormalParameter> formalParameters = callable.getCallableParams();
EIParams argumentHolder = call.getParams();
List<EIExpression> actualArguments = argumentHolder != null ? argumentHolder.getExpressionList() : null;
assert actualArguments != null;
int numErrors = 0;
int firstWrong = Integer.MAX_VALUE;
for (int i = 0; i < Math.max(formalParameters.size(), actualArguments.size()); i++) {
EIFormalParameter parameter = i < formalParameters.size() ? formalParameters.get(i) : null;
EIExpression expression = i < actualArguments.size() ? actualArguments.get(i) : null;
EIType expectedType = parameter != null ? parameter.getType() : null;
EITypeToken actualType = expression != null ? expression.getType() : null;
if (actualType == null || expectedType == null || !expectedType.getTypeToken().equals(actualType)) {
numErrors++;
firstWrong = Math.min(firstWrong, i);
}
}
if (numErrors > 0) {
if (numErrors > 1 || formalParameters.size() != actualArguments.size()) {
Annotation annotation = AnnotatorUtil.createBadCallArgumentsAnnotation(
myHolder,
callable,
argumentHolder
);
} else {
Annotation annotation = AnnotatorUtil.createIncompatibleCallTypesAnnotation(
myHolder,
formalParameters,
actualArguments,
firstWrong);
if (resolved instanceof EIScriptDeclaration) {
EIFormalParameter parameter = formalParameters.get(firstWrong);
EIExpression expression = actualArguments.get(firstWrong);
InspectionManager inspectionManager = InspectionManager.getInstance(resolved.getProject());
LocalQuickFix fix = new ChangeLvalueTypeFix(parameter, expression.getType());
ProblemDescriptor descriptor = inspectionManager.createProblemDescriptor(
expression,
annotation.getMessage(),
fix,
ProblemHighlightType.ERROR,
true
);
annotation.registerFix(fix, expression.getTextRange(), null, descriptor);
}
}
}
}
}
@Override
public void visitVariableAccess(@NotNull EIVariableAccess access) {
super.visitVariableAccess(access);
if (access.getReference().resolve() == null) {
markAsError(myHolder, access.getNameIdentifier(),
EIMessages.message("error.undefined.variable", access.getName()));
}
}
@Override
public void visitExpression(@NotNull EIExpression expression) {
super.visitExpression(expression);
PsiReference reference = expression.getReference();
if (reference instanceof MobObjectReference && reference.resolve() == null) {
markAsError(myHolder, expression, EIMessages.message("error.wrong.object.id", reference.getCanonicalText()));
}
}
@Override
public void visitAssignment(@NotNull EIAssignment assignment) {
super.visitAssignment(assignment);
EIVariableAccess access = assignment.getVariableAccess();
EITypeToken lType = access.getType();
EITypeToken rType = assignment.getExpression() != null ? assignment.getExpression().getType() : null;
if (lType == null || !lType.equals(rType)) {
Annotation annotation =
AnnotatorUtil.createIncompatibleTypesAnnotation(myHolder, assignment.getTextRange(), lType, rType);
PsiElement target = access.getReference().resolve();
if (lType != null && rType != null && target != null) {
// TODO: move to local quick fix provider in reference?
InspectionManager inspectionManager = InspectionManager.getInstance(assignment.getProject());
LocalQuickFix fix = new ChangeLvalueTypeFix((PsiNamedElement) target, rType);
ProblemDescriptor descriptor = inspectionManager.createProblemDescriptor(
access.getNameIdentifier(),
annotation.getMessage(),
fix,
ProblemHighlightType.ERROR,
true
);
annotation.registerFix(fix, assignment.getTextRange(), null, descriptor);
}
}
}
// TODO: redo, as well as markAsError
private void handleFunctionCallInIfBlock(@NotNull AnnotationHolder holder, PsiElement nameElement, EIFunctionDeclaration function) {
if (function == null) {
markAsError(holder, nameElement, EIMessages.message("error.unresolved.function", nameElement.getText()));
} else {
if (function.getType() == null || function.getType().getTypeToken() != EITypeToken.FLOAT) {
markAsError(holder, nameElement, EIMessages.message("error.not.allowed.in.script.if"));
}
}
}
private void handleFunctionOrScriptCall(@NotNull PsiElement element, @NotNull AnnotationHolder holder, PsiElement nameElement, PsiElement call) {
if (call == null) {
markAsError(holder, nameElement, EIMessages.message("error.unresolved.function.or.script", nameElement.getText()));
}
}
private Annotation markAsError(@NotNull AnnotationHolder holder, @NotNull PsiElement nameElement, @NotNull String errorString) {
Annotation annotation = holder.createErrorAnnotation(nameElement.getTextRange(), errorString);
// TODO: should I keep this?
annotation.setHighlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
return annotation;
}
private Annotation markAsWarning(@NotNull AnnotationHolder holder, @NotNull PsiElement element, @NotNull String warningString) {
return holder.createWarningAnnotation(element.getTextRange(), warningString);
}
private void markAsWeakWarning(@NotNull AnnotationHolder holder, @NotNull PsiElement nameElement, @NotNull String warningString) {
holder.createWeakWarningAnnotation(nameElement.getTextRange(), warningString).setHighlightType(ProblemHighlightType.WEAK_WARNING);
}
}
|
package com.fincatto.documentofiscal.nfe400.webservices.gerado;
import org.apache.axis2.client.Stub;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;
public class NFeInutilizacao4Stub extends org.apache.axis2.client.Stub {
private static int counter = 0;
protected org.apache.axis2.description.AxisOperation[] _operations;
// hashmaps to keep the fault mapping
@SuppressWarnings("rawtypes")
private final java.util.HashMap faultExceptionNameMap = new java.util.HashMap();
@SuppressWarnings("rawtypes")
private final java.util.HashMap faultExceptionClassNameMap = new java.util.HashMap();
@SuppressWarnings("rawtypes")
private final java.util.HashMap faultMessageMap = new java.util.HashMap();
private final javax.xml.namespace.QName[] opNameArray = null;
/**
* Constructor that takes in a configContext
*/
public NFeInutilizacao4Stub(final org.apache.axis2.context.ConfigurationContext configurationContext, final java.lang.String targetEndpoint) throws org.apache.axis2.AxisFault {
this(configurationContext, targetEndpoint, false);
}
/**
* Constructor that takes in a configContext and useseperate listner
*/
public NFeInutilizacao4Stub(final org.apache.axis2.context.ConfigurationContext configurationContext, final java.lang.String targetEndpoint, final boolean useSeparateListener) throws org.apache.axis2.AxisFault {
// To populate AxisService
this.populateAxisService();
this.populateFaults();
this._serviceClient = new org.apache.axis2.client.ServiceClient(configurationContext, this._service);
this._serviceClient.getOptions().setTo(new org.apache.axis2.addressing.EndpointReference(targetEndpoint));
this._serviceClient.getOptions().setUseSeparateListener(useSeparateListener);
// Set the soap version
this._serviceClient.getOptions().setSoapVersionURI(org.apache.axiom.soap.SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
}
/**
* Constructor taking the target endpoint
*/
public NFeInutilizacao4Stub(final java.lang.String targetEndpoint) throws org.apache.axis2.AxisFault {
this(null, targetEndpoint);
}
private static synchronized java.lang.String getUniqueSuffix() {
// reset the counter if it is greater than 99999
if (NFeInutilizacao4Stub.counter > 99999) {
NFeInutilizacao4Stub.counter = 0;
}
NFeInutilizacao4Stub.counter = NFeInutilizacao4Stub.counter + 1;
return System.currentTimeMillis() + "_" + NFeInutilizacao4Stub.counter;
}
private void populateAxisService() {
// creating the Service with a unique name
this._service = new org.apache.axis2.description.AxisService("NFeInutilizacao4" + NFeInutilizacao4Stub.getUniqueSuffix());
this.addAnonymousOperations();
// creating the operations
org.apache.axis2.description.AxisOperation __operation;
this._operations = new org.apache.axis2.description.AxisOperation[1];
__operation = new org.apache.axis2.description.OutInAxisOperation();
__operation.setName(new javax.xml.namespace.QName("http:
this._service.addOperation(__operation);
this._operations[0] = __operation;
}
// populates the faults
private void populateFaults() {
}
/**
* Auto generated method signature
*
* @param nfeDadosMsg0
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public NfeResultMsg nfeInutilizacaoNF(final NfeDadosMsg nfeDadosMsg0) throws java.rmi.RemoteException {
org.apache.axis2.context.MessageContext _messageContext = null;
try {
final org.apache.axis2.client.OperationClient _operationClient = this._serviceClient.createClient(this._operations[0].getName());
_operationClient.getOptions().setAction("http:
_operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);
this.addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&");
// create a message context
_messageContext = new org.apache.axis2.context.MessageContext();
// create SOAP envelope with that payload
org.apache.axiom.soap.SOAPEnvelope env;
env = this.toEnvelope(Stub.getFactory(_operationClient.getOptions().getSoapVersionURI()), nfeDadosMsg0, this.optimizeContent(new javax.xml.namespace.QName("http:
//Alteracao para correcao da inutilizacao da faixa de valores para o estado do Ceara
env.declareNamespace("http:
// adding SOAP soap_headers
this._serviceClient.addHeadersToEnvelope(env);
// set the message context with that soap envelope
_messageContext.setEnvelope(env);
// add the message contxt to the operation client
_operationClient.addMessageContext(_messageContext);
// execute the operation client
_operationClient.execute(true);
final org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient.getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE);
final org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope();
final java.lang.Object object = this.fromOM(_returnEnv.getBody().getFirstElement(), NfeResultMsg.class);
return (NfeResultMsg) object;
} catch (final org.apache.axis2.AxisFault f) {
final org.apache.axiom.om.OMElement faultElt = f.getDetail();
if (faultElt != null) {
if (this.faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeInutilizacaoNF"))) {
// make the fault by reflection
try {
final java.lang.String exceptionClassName = (java.lang.String) this.faultExceptionClassNameMap.get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeInutilizacaoNF"));
final java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName);
final java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(java.lang.String.class);
final java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage());
// message class
final java.lang.String messageClassName = (java.lang.String) this.faultMessageMap.get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeInutilizacaoNF"));
final java.lang.Class messageClass = java.lang.Class.forName(messageClassName);
final java.lang.Object messageObject = this.fromOM(faultElt, messageClass);
final java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", messageClass);
m.invoke(ex, messageObject);
throw new java.rmi.RemoteException(ex.getMessage(), ex);
} catch (final ClassCastException | InstantiationException | IllegalAccessException | java.lang.reflect.InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) {
// we cannot intantiate the class - throw the original Axis fault
throw f;
}
} else {
throw f;
}
} else {
throw f;
}
} finally {
if (_messageContext.getTransportOut() != null) {
_messageContext.getTransportOut().getSender().cleanup(_messageContext);
}
}
}
private boolean optimizeContent(final javax.xml.namespace.QName opName) {
if (this.opNameArray == null) {
return false;
}
for (final QName element : this.opNameArray) {
if (opName.equals(element)) {
return true;
}
}
return false;
}
private org.apache.axiom.soap.SOAPEnvelope toEnvelope(final org.apache.axiom.soap.SOAPFactory factory, final NfeDadosMsg param, final boolean optimizeContent, final javax.xml.namespace.QName elementQName) {
//try {
final org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();
emptyEnvelope.getBody().addChild(param.getOMElement(NfeDadosMsg.MY_QNAME, factory));
return emptyEnvelope;
// } catch (final org.apache.axis2.databinding.ADBException e) {
// throw org.apache.axis2.AxisFault.makeFault(e);
}
@SuppressWarnings("rawtypes")
private java.lang.Object fromOM(final org.apache.axiom.om.OMElement param, final java.lang.Class type) throws org.apache.axis2.AxisFault {
try {
if (NfeDadosMsg.class.equals(type)) {
return NfeDadosMsg.Factory.parse(param.getXMLStreamReaderWithoutCaching());
}
if (NfeResultMsg.class.equals(type)) {
return NfeResultMsg.Factory.parse(param.getXMLStreamReaderWithoutCaching());
}
} catch (final java.lang.Exception e) {
throw org.apache.axis2.AxisFault.makeFault(e);
}
return null;
}
public static class ExtensionMapper {
public static java.lang.Object getTypeObject(final java.lang.String namespaceURI, final java.lang.String typeName, final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
throw new org.apache.axis2.databinding.ADBException("Unsupported type " + namespaceURI + " " + typeName);
}
}
@SuppressWarnings("serial")
public static class NfeDadosMsg implements org.apache.axis2.databinding.ADBBean {
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName("http:
/**
* field for ExtraElement
*/
protected org.apache.axiom.om.OMElement localExtraElement;
/**
* Auto generated getter method
*
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getExtraElement() {
return this.localExtraElement;
}
/**
* Auto generated setter method
*
* @param param ExtraElement
*/
public void setExtraElement(final org.apache.axiom.om.OMElement param) {
this.localExtraElement = param;
}
/**
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) {
return factory.createOMElement(new org.apache.axis2.databinding.ADBDataSource(this, NfeDadosMsg.MY_QNAME));
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
this.serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix;
java.lang.String namespace;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
this.writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType) {
final java.lang.String namespacePrefix = this.registerPrefix(xmlWriter, "http:
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) {
this.writeAttribute("xsi", "http:
} else {
this.writeAttribute("xsi", "http:
}
}
if (this.localExtraElement != null) {
this.localExtraElement.serialize(xmlWriter);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(final java.lang.String namespace) {
if (namespace.equals("http:
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, final java.lang.String namespace, final java.lang.String localPart, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(writerPrefix, localPart, namespace);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = NfeDadosMsg.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeAttribute(writerPrefix, namespace, attName, attValue);
} else {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
xmlWriter.writeAttribute(prefix, namespace, attName, attValue);
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter, final java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = NfeDadosMsg.generatePrefix(namespace);
final javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
final java.lang.String uri = nsContext.getNamespaceURI(prefix);
if ((uri == null) || (uri.length() == 0)) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* Factory class that keeps the parse method
*/
public static class Factory {
@SuppressWarnings("unused")
private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(Factory.class);
/**
* static method to create the object Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable If this object is not an element, it is a complex type and the reader is at the event just after the outer start element Postcondition: If this object is an element, the reader is positioned at its end element If this object is a complex type, the reader is positioned at the end element of its outer element
*/
@SuppressWarnings({"unused", "rawtypes"})
public static NfeDadosMsg parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final NfeDadosMsg object = new NfeDadosMsg();
final int event;
javax.xml.namespace.QName currentQName = null;
final java.lang.String nillableValue = null;
final java.lang.String prefix = "";
final java.lang.String namespaceuri = "";
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
currentQName = reader.getName();
if (reader.getAttributeValue("http:
final java.lang.String fullTypeName = reader.getAttributeValue("http:
if (fullTypeName != null) {
java.lang.String nsPrefix = null;
if (fullTypeName.contains(":")) {
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = (nsPrefix == null) ? "" : nsPrefix;
final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"nfeDadosMsg".equals(type)) {
// find namespace for the prefix
final java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (NfeDadosMsg) ExtensionMapper.getTypeObject(nsUri, type, reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
final java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// use the QName from the parser as the name for the builder
final javax.xml.namespace.QName startQname1 = reader.getName();
// We need to wrap the reader so that it produces a fake START_DOCUMENT event
// this is needed by the builder classes
final org.apache.axis2.databinding.utils.NamedStaxOMBuilder builder1 = new org.apache.axis2.databinding.utils.NamedStaxOMBuilder(new org.apache.axis2.util.StreamWrapper(reader), startQname1);
object.setExtraElement(builder1.getOMElement());
reader.next();
} // End of if for expected property start element
else {
// 1 - A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// 2 - A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
} catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
} // end of factory class
@Override
public XMLStreamReader getPullParser(final QName arg0) {
return null;
}
}
@SuppressWarnings("serial")
public static class NfeResultMsg implements org.apache.axis2.databinding.ADBBean {
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName("http:
/**
* field for ExtraElement
*/
protected org.apache.axiom.om.OMElement localExtraElement;
/**
* Auto generated getter method
*
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getExtraElement() {
return this.localExtraElement;
}
/**
* Auto generated setter method
*
* @param param ExtraElement
*/
public void setExtraElement(final org.apache.axiom.om.OMElement param) {
this.localExtraElement = param;
}
/**
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) {
return factory.createOMElement(new org.apache.axis2.databinding.ADBDataSource(this, NfeResultMsg.MY_QNAME));
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
this.serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix;
java.lang.String namespace;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
this.writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType) {
final java.lang.String namespacePrefix = this.registerPrefix(xmlWriter, "http:
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) {
this.writeAttribute("xsi", "http:
} else {
this.writeAttribute("xsi", "http:
}
}
if (this.localExtraElement != null) {
this.localExtraElement.serialize(xmlWriter);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(final java.lang.String namespace) {
if (namespace.equals("http:
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, final java.lang.String namespace, final java.lang.String localPart, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(writerPrefix, localPart, namespace);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = NfeResultMsg.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeAttribute(writerPrefix, namespace, attName, attValue);
} else {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
xmlWriter.writeAttribute(prefix, namespace, attName, attValue);
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter, final java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = NfeResultMsg.generatePrefix(namespace);
final javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
final java.lang.String uri = nsContext.getNamespaceURI(prefix);
if ((uri == null) || (uri.length() == 0)) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* Factory class that keeps the parse method
*/
public static class Factory {
@SuppressWarnings("unused")
private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(Factory.class);
/**
* static method to create the object Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable If this object is not an element, it is a complex type and the reader is at the event just after the outer start element Postcondition: If this object is an element, the reader is positioned at its end element If this object is a complex type, the reader is positioned at the end element of its outer element
*/
@SuppressWarnings({"unused", "rawtypes"})
public static NfeResultMsg parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final NfeResultMsg object = new NfeResultMsg();
final int event;
javax.xml.namespace.QName currentQName = null;
java.lang.String nillableValue;
final java.lang.String prefix = "";
final java.lang.String namespaceuri = "";
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
currentQName = reader.getName();
nillableValue = reader.getAttributeValue("http:
if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
// Skip the element and report the null value. It cannot have subelements.
while (!reader.isEndElement()) {
reader.next();
}
return null;
}
if (reader.getAttributeValue("http:
final java.lang.String fullTypeName = reader.getAttributeValue("http:
if (fullTypeName != null) {
java.lang.String nsPrefix = null;
if (fullTypeName.contains(":")) {
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = (nsPrefix == null) ? "" : nsPrefix;
final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"nfeResultMsg".equals(type)) {
// find namespace for the prefix
final java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (NfeResultMsg) ExtensionMapper.getTypeObject(nsUri, type, reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
final java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// use the QName from the parser as the name for the builder
final javax.xml.namespace.QName startQname1 = reader.getName();
// We need to wrap the reader so that it produces a fake START_DOCUMENT event
// this is needed by the builder classes
final org.apache.axis2.databinding.utils.NamedStaxOMBuilder builder1 = new org.apache.axis2.databinding.utils.NamedStaxOMBuilder(new org.apache.axis2.util.StreamWrapper(reader), startQname1);
object.setExtraElement(builder1.getOMElement());
reader.next();
} // End of if for expected property start element
else {
// 1 - A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// 2 - A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
} catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
} // end of factory class
@Override
public XMLStreamReader getPullParser(final QName arg0) {
return null;
}
}
}
|
package com.netflix.simianarmy.aws.janitor.crawler.edda;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.simianarmy.Resource;
import com.netflix.simianarmy.aws.AWSResource;
import com.netflix.simianarmy.aws.AWSResourceType;
import com.netflix.simianarmy.client.edda.EddaClient;
import com.netflix.simianarmy.janitor.JanitorCrawler;
import com.netflix.simianarmy.janitor.JanitorMonkey;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.codehaus.jackson.JsonNode;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* The crawler to crawl AWS EBS volumes for Janitor monkey using Edda.
*/
public class EddaEBSVolumeJanitorCrawler implements JanitorCrawler {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(EddaEBSVolumeJanitorCrawler.class);
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
private static final int BATCH_SIZE = 50;
// The value below specifies how many days we want to look back in Edda to find the owner of old instances.
// In case of Edda keeps too much history data, without a reasonal data range, the query may fail.
private static final int LOOKBACK_DAYS = 90;
/**
* The field name for purpose.
*/
public static final String PURPOSE = "purpose";
/**
* The field name for deleteOnTermination.
*/
public static final String DELETE_ON_TERMINATION = "deleteOnTermination";
/**
* The field name for detach time.
*/
public static final String DETACH_TIME = "detachTime";
private final EddaClient eddaClient;
private final List<String> regions = Lists.newArrayList();
private final Map<String, String> instanceToOwner = Maps.newHashMap();
/**
* The constructor.
* @param eddaClient
* the Edda client
* @param regions
* the regions the crawler will crawl resources for
*/
public EddaEBSVolumeJanitorCrawler(EddaClient eddaClient, String... regions) {
Validate.notNull(eddaClient);
this.eddaClient = eddaClient;
Validate.notNull(regions);
for (String region : regions) {
this.regions.add(region);
updateInstanceToOwner(region);
}
LOGGER.info(String.format("Found owner for %d instances in %s", instanceToOwner.size(), this.regions));
}
private void updateInstanceToOwner(String region) {
LOGGER.info(String.format("Getting owners for all instances in region %s", region));
long startTime = DateTime.now().minusDays(LOOKBACK_DAYS).getMillis();
String url = String.format("%s/view/instances;_since=%d;state.name=running;tags.key=owner;"
+ "_expand:(instanceId,tags:(key,value))",
eddaClient.getBaseUrl(region), startTime);
JsonNode jsonNode = null;
try {
jsonNode = eddaClient.getJsonNodeFromUrl(url);
} catch (Exception e) {
LOGGER.error(String.format(
"Failed to get Jason node from edda for instance owners in region %s.", region), e);
}
if (jsonNode == null || !jsonNode.isArray()) {
throw new RuntimeException(String.format("Failed to get valid document from %s, got: %s", url, jsonNode));
}
for (Iterator<JsonNode> it = jsonNode.getElements(); it.hasNext();) {
JsonNode elem = it.next();
String instanceId = elem.get("instanceId").getTextValue();
JsonNode tags = elem.get("tags");
if (tags == null || !tags.isArray() || tags.size() == 0) {
continue;
}
for (Iterator<JsonNode> tagsIt = tags.getElements(); tagsIt.hasNext();) {
JsonNode tag = tagsIt.next();
String tagKey = tag.get("key").getTextValue();
if ("owner".equals(tagKey)) {
instanceToOwner.put(instanceId, tag.get("value").getTextValue());
break;
}
}
}
}
@Override
public EnumSet<?> resourceTypes() {
return EnumSet.of(AWSResourceType.EBS_VOLUME);
}
@Override
public List<Resource> resources(Enum resourceType) {
if ("EBS_VOLUME".equals(resourceType.name())) {
return getVolumeResources();
}
return Collections.emptyList();
}
@Override
public List<Resource> resources(String... resourceIds) {
return getVolumeResources(resourceIds);
}
@Override
public String getOwnerEmailForResource(Resource resource) {
return null;
}
private List<Resource> getVolumeResources(String... volumeIds) {
List<Resource> resources = Lists.newArrayList();
for (String region : regions) {
resources.addAll(getUnattachedVolumeResourcesInRegion(region, volumeIds));
addLastAttachmentInfo(resources);
}
return resources;
}
/**
* Gets all volumes that are not attached to any instance. Janitor Monkey only considers unattached volumes
* as cleanup candidates, so there is no need to get volumes that are in-use.
* @param region
* @return
*/
private List<Resource> getUnattachedVolumeResourcesInRegion(String region, String... volumeIds) {
String url = eddaClient.getBaseUrl(region) + "/aws/volumes;";
if (volumeIds != null && volumeIds.length != 0) {
url += StringUtils.join(volumeIds, ',');
LOGGER.info(String.format("Getting volumes in region %s for %d ids", region, volumeIds.length));
} else {
LOGGER.info(String.format("Getting all unattached volumes in region %s", region));
}
url += ";state=available;_expand:(volumeId,createTime,size,state,tags)";
JsonNode jsonNode = null;
try {
jsonNode = eddaClient.getJsonNodeFromUrl(url);
} catch (Exception e) {
LOGGER.error(String.format(
"Failed to get Jason node from edda for unattached volumes in region %s.", region), e);
}
if (jsonNode == null || !jsonNode.isArray()) {
throw new RuntimeException(String.format("Failed to get valid document from %s, got: %s", url, jsonNode));
}
List<Resource> resources = Lists.newArrayList();
for (Iterator<JsonNode> it = jsonNode.getElements(); it.hasNext();) {
resources.add(parseJsonElementToVolumeResource(region, it.next()));
}
return resources;
}
private Resource parseJsonElementToVolumeResource(String region, JsonNode jsonNode) {
Validate.notNull(jsonNode);
long createTime = jsonNode.get("createTime").asLong();
Resource resource = new AWSResource().withId(jsonNode.get("volumeId").getTextValue()).withRegion(region)
.withResourceType(AWSResourceType.EBS_VOLUME)
.withLaunchTime(new Date(createTime));
JsonNode tags = jsonNode.get("tags");
StringBuilder description = new StringBuilder();
JsonNode size = jsonNode.get("size");
description.append(String.format("size=%s", size == null ? "unknown" : size.getIntValue()));
if (tags == null || !tags.isArray() || tags.size() == 0) {
LOGGER.debug(String.format("No tags is found for %s", resource.getId()));
} else {
for (Iterator<JsonNode> it = tags.getElements(); it.hasNext();) {
JsonNode tag = it.next();
String key = tag.get("key").getTextValue();
String value = tag.get("value").getTextValue();
description.append(String.format("; %s=%s", key, value));
resource.setTag(key, value);
if (key.equals(PURPOSE)) {
resource.setAdditionalField(PURPOSE, value);
}
}
resource.setDescription(description.toString());
}
((AWSResource) resource).setAWSResourceState(jsonNode.get("state").getTextValue());
return resource;
}
/**
* Adds information of last attachement to the resources. To be compatible with the AWS implemenation of
* the same crawler, add the information to the JANITOR_META tag. It always uses the latest information
* to update the tag in this resource (not writing back to AWS) no matter if the tag exists.
* @param resources the volume resources
*/
private void addLastAttachmentInfo(List<Resource> resources) {
Validate.notNull(resources);
LOGGER.info(String.format("Updating the latest attachment info for %d resources", resources.size()));
Map<String, List<Resource>> regionToResources = Maps.newHashMap();
for (Resource resource : resources) {
List<Resource> regionalList = regionToResources.get(resource.getRegion());
if (regionalList == null) {
regionalList = Lists.newArrayList();
regionToResources.put(resource.getRegion(), regionalList);
}
regionalList.add(resource);
}
for (Map.Entry<String, List<Resource>> entry : regionToResources.entrySet()) {
LOGGER.info(String.format("Updating the latest attachment info for %d resources in region %s",
resources.size(), entry.getKey()));
for (List<Resource> batch : Lists.partition(entry.getValue(), BATCH_SIZE)) {
LOGGER.info(String.format("Processing batch of size %d", batch.size()));
String batchUrl = getBatchUrl(entry.getKey(), batch);
JsonNode batchResult = null;
try {
batchResult = eddaClient.getJsonNodeFromUrl(batchUrl);
} catch (IOException e) {
LOGGER.error("Failed to get response for the batch.", e);
}
Map<String, Resource> idToResource = Maps.newHashMap();
for (Resource resource : batch) {
idToResource.put(resource.getId(), resource);
}
if (batchResult == null || !batchResult.isArray()) {
throw new RuntimeException(String.format("Failed to get valid document from %s, got: %s",
batchUrl, batchResult));
}
Set<String> processedIds = Sets.newHashSet();
for (Iterator<JsonNode> it = batchResult.getElements(); it.hasNext();) {
JsonNode elem = it.next();
JsonNode data = elem.get("data");
String volumeId = data.get("volumeId").getTextValue();
Resource resource = idToResource.get(volumeId);
JsonNode attachments = data.get("attachments");
Validate.isTrue(attachments.isArray() && attachments.size() > 0);
JsonNode attachment = attachments.get(0);
JsonNode ltime = elem.get("ltime");
if (ltime == null || ltime.isNull()) {
continue;
}
DateTime detachTime = new DateTime(ltime.asLong());
processedIds.add(volumeId);
setAttachmentInfo(volumeId, attachment, detachTime, resource);
}
for (Map.Entry<String, Resource> volumeEntry : idToResource.entrySet()) {
String id = volumeEntry.getKey();
if (!processedIds.contains(id)) {
Resource resource = volumeEntry.getValue();
LOGGER.info(String.format("Volume %s never was attached, use createTime %s as the detachTime",
id, resource.getLaunchTime()));
setAttachmentInfo(id, null, new DateTime(resource.getLaunchTime().getTime()), resource);
}
}
}
}
}
private void setAttachmentInfo(String volumeId, JsonNode attachment, DateTime detachTime, Resource resource) {
String instanceId = null;
if (attachment != null) {
boolean deleteOnTermination = attachment.get(DELETE_ON_TERMINATION).getBooleanValue();
if (deleteOnTermination) {
LOGGER.info(String.format(
"Volume %s had set the deleteOnTermination flag as true", volumeId));
}
resource.setAdditionalField(DELETE_ON_TERMINATION, String.valueOf(deleteOnTermination));
instanceId = attachment.get("instanceId").getTextValue();
}
// The subclass can customize the way to get the owner for a volume
String owner = getOwnerEmailForResource(resource);
if (owner == null && instanceId != null) {
owner = instanceToOwner.get(instanceId);
}
resource.setOwnerEmail(owner);
String metaTag = makeMetaTag(instanceId, owner, detachTime);
LOGGER.info(String.format("Setting Janitor Metatag as %s for volume %s", metaTag, volumeId));
resource.setTag(JanitorMonkey.JANITOR_META_TAG, metaTag);
LOGGER.info(String.format("The last detach time of volume %s is %s", volumeId, detachTime));
resource.setAdditionalField(DETACH_TIME, String.valueOf(detachTime.getMillis()));
}
private String makeMetaTag(String instance, String owner, DateTime lastDetachTime) {
StringBuilder meta = new StringBuilder();
meta.append(String.format("%s=%s;",
JanitorMonkey.INSTANCE_TAG_KEY, instance == null ? "" : instance));
meta.append(String.format("%s=%s;", JanitorMonkey.OWNER_TAG_KEY, owner == null ? "" : owner));
meta.append(String.format("%s=%s", JanitorMonkey.DETACH_TIME_TAG_KEY,
lastDetachTime == null ? "" : AWSResource.DATE_FORMATTER.print(lastDetachTime)));
return meta.toString();
}
private String getBatchUrl(String region, List<Resource> batch) {
StringBuilder batchUrl = new StringBuilder(eddaClient.getBaseUrl(region) + "/aws/volumes/");
boolean isFirst = true;
for (Resource resource : batch) {
if (!isFirst) {
batchUrl.append(',');
} else {
isFirst = false;
}
batchUrl.append(resource.getId());
}
batchUrl.append(";data.state=in-use;_since=0;_expand;_meta:"
+ "(ltime,data:(volumeId,attachments:(deleteOnTermination,instanceId)))");
return batchUrl.toString();
}
}
|
package com.phylogeny.extrabitmanipulation.config;
import java.io.File;
import java.util.Arrays;
import org.apache.commons.lang3.StringUtils;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import com.phylogeny.extrabitmanipulation.init.ItemsExtraBitManipulation;
import com.phylogeny.extrabitmanipulation.item.ItemBitWrench;
import com.phylogeny.extrabitmanipulation.item.ItemSculptingTool;
import com.phylogeny.extrabitmanipulation.reference.Configs;
import com.phylogeny.extrabitmanipulation.reference.Reference;
import com.phylogeny.extrabitmanipulation.shape.Shape;
public class ConfigHandlerExtraBitManipulation
{
public static Configuration configFile;
public static final String VERSION = "Version";
public static final String SCULPTING_SETTINGS = "Sculpting Settings";
public static final String SCULPTING_DEFAULT_VALUES = "Default Values";
public static final String SCULPTING_PER_TOOL_OR_PER_PLAYER = "Per Tool or Per Player";
public static final String SCULPTING_DISPLAY_IN_CHAT = "Display In Chat";
public static final String RENDER_OVERLAYS = "Bit Wrench Overlays";
private static final String[] COLOR_NAMES = new String[]{"Red", "Green", "Blue"};
public static void setUpConfigs(File file)
{
configFile = new Configuration(file);
updateConfigs();
}
@SubscribeEvent
public void onConfigChanged(OnConfigChangedEvent event)
{
if (event.modID.equalsIgnoreCase(Reference.MOD_ID))
{
updateConfigs();
}
}
private static void updateConfigs()
{
try
{
String version = getVersion(VERSION);
if (!version.equals(Reference.VERSION))
{
removeCategory("curved sculpting wire properties");
removeCategory("curved sculpting spade properties");
removeCategory("straight sculpting wire properties");
removeCategory("flat sculpting spade properties");
}
removeCategory(VERSION);
getVersion(Reference.VERSION);
//SCULPTING SETTINGS
Configs.maxSemiDiameter = configFile. getInt("Max Semi-Diameter", SCULPTING_SETTINGS, 32, 1, Integer.MAX_VALUE,
"the maximum size (in bits) of sculpting shape semi-diameter (i.e. radius if it is a sphere). (default = 5 bits)");
Configs.maxWallThickness = configFile. getInt("Max Wall Thickness", SCULPTING_SETTINGS, 32, 1, Integer.MAX_VALUE,
"the maximum size (in bits) of hollow sculpting shapes. (default = 2 bits)");
Configs.displayNameDiameter = configFile.getBoolean("Display Name Diameter", SCULPTING_SETTINGS, true,
"If set to true, sculpting tool display names will indicate the diameter of their bit removal/addition areas. " +
"If set to false, they will indicate the radius (default = true)");
Configs.displayNameUseMeterUnits = configFile.getBoolean("Display Name Meter Units", SCULPTING_SETTINGS, false,
"If set to true, sculpting tool display names will indicate the size of their bit removal/addition areas in meters. " +
"If set to false, they will be in bits (default = false)");
Configs.semiDiameterPadding = configFile.getFloat("Semi-Diameter Padding", SCULPTING_SETTINGS, 0.2F, 0, 1,
"Distance (in bits) to add to the semi-diameter of a sculpting tool's bit removal/addition area shape. If set to zero, no padding " +
"will be added; spheres, for example, will have single bits protruding from each cardinal direction at any size, since only those " +
"bits of those layers will be exactly on the sphere's perimeter. If set to 1, there will effectively be no padding for the same reason, " +
"but the radius will be one bit larger than specified. A value between 0 and 1 is suggested. (default = 0.2 bits)");
Configs.placeBitsInInventory = configFile.getBoolean("Place Bits In Inventory", SCULPTING_SETTINGS, true,
"If set to true, when bits are removed from blocks with a sculpting tool, as many of them will be given to the player as is possible. " +
"Any bits that cannot fit in the player's inventory will be spawned in the world. If set to false, no attempt will be made to give them " +
"to the player; they will always be spawned in the world. (default = true)");
Configs.dropBitsInBlockspace = configFile.getBoolean("Drop Bits In Block Space", SCULPTING_SETTINGS, true,
"If set to true, when bits removed from blocks with a sculpting tool are spawned in the world, they will be spawned at a random " +
"point within the area that intersects the block space and the removal area bounding box (if 'Drop Bits Per Block' is true, they " +
"will be spawned in the block they are removed from; otherwise they will be spawned at the block they player right-clicked). " +
"If set to false, they will be spawned at the player, in the same way that items are spawned when throwing them on the ground " +
"by pressing Q. (default = true)");
Configs.bitSpawnBoxContraction = configFile.getFloat("Bit Spawn Box Contraction", SCULPTING_SETTINGS, 0.25F, 0, 0.5F,
"Amount in meters to contract the box that removed bits randomly spawn in (assuming they spawn in the block space as per 'Drop Bits In Block Space') " +
"If set to 0, there will be no contraction and they will be able to spawn anywhere in the box. If set to 0.5, the box will contract by half in all " +
"directions down to a point in the center of the original box and they will always spawn from that central point. The default of 0.25 (which is the " +
"default behavior when spawning items with Block.spawnAsEntity) contracts the box to half its original size. (default = 0.25 meters)");
Configs.dropBitsPerBlock = configFile.getBoolean("Drop Bits Per Block", SCULPTING_SETTINGS, true,
"When bits are removed from blocks with a sculpting tool, all the removed bits of each type are counted and a collection of item stacks are created " +
"of each item. For the sake of efficiency, the number of stacks generated is the minimum number necessary for that amount (Ex: 179 bits would become " +
"2 stacks of 64 and 1 stack of 51). If this config is set to true, the counts for each block will be added up and spawned after each block is modified. " +
"This means that when removing bits in global mode, the bits have the ability to spawn in the respective block spaces they are removed from. However, " +
"it also means that more stacks may be generated than necessary if all bits from all blocks removed were to be pooled. If this config is set to false, " +
"the bits will be added up and pooled together as they are removed from each block. Only once all blocks are modified will the entire collection of bits " +
"be spawned in the world or given to the player. While this is more efficient, it means that the effect of bits spawning in the block spaces they are removed " +
"from is not possible. Rather, the bits will either spawn in the space of the block clicked or spawn at the player as per 'Drop Bits In Block Space'. " +
"(default = true)");
Configs.dropBitsAsFullChiseledBlocks = configFile.getBoolean("Drop Bits As Full Chiseled Blocks", SCULPTING_SETTINGS, false,
"If set to true, full meter cubed blocks of bits that have all their bits removed will drop as full chiseled blocks. " +
"If set to false, they will drop normally as item stacks of bits (64 stacks of size 64). (default = false)");
//SCULPTING DATA SETTINGS
Configs.sculptMode = getSculptSettingIntFromStringArray("Mode", false, true, 0, 0,
"sculpting mode",
"sculpting mode (local mode affects only the block clicked - global/drawn modes affects any bits from any blocks that intersect " +
"the sculpting shape when a block is clicked (global) or when the mouse is released after a click and drag (drawn).",
ItemSculptingTool.MODE_TITLES);
Configs.sculptRotation = getSculptSettingInt("Rotation", false, true, 1, 0, 5,
"sculpting shape rotation",
"rotation value. 0 = down; 1 = up; 2 = north; 3 = south; 4 = west; 5 = east ", "up");
Configs.sculptShapeTypeCurved = getSculptSettingIntFromStringArray("Curved Shape", false, true, 0, 0,
"curved tool sculpting shape",
"sculpting shape.",
Arrays.copyOfRange(Shape.SHAPE_NAMES, 0, 3));
Configs.sculptShapeTypeFlat = getSculptSettingIntFromStringArray("Flat/Straight Shape", false, true, 0, 3,
"flat/straight tool sculpting shape",
"sculpting shape.",
Arrays.copyOfRange(Shape.SHAPE_NAMES, 3, 7));
Configs.sculptTargetBitGridVertexes = getSculptSettingBoolean("Target Bit Grid Vertexes", false, true, false,
"targeting mode",
"targeting mode (when sculpting in local/global mode either bits are targetted [the shape is centered on the center of the bit looked - the diameter is " +
"one (the center bit) plus/minus x number of bits (semi-diameter is x + 1/2 bit], or vertecies of the bit " +
"grid are targetted [the shape is centered on the corner (the one closest to the cursor) of the bit looked at (i.e. centered on a vertex of the " +
"grid) - the diameter is 2x number of bits (x is a true semi-diameter)]).");
Configs.sculptHollowShape = getSculptSettingBoolean("Hollow Shapes", false, true, false,
"sculpting shape hollowness",
"hollow property value (shape is either hollow or solid).");
Configs.sculptOpenEnds = getSculptSettingBoolean("Open Ends", false, true, false,
"hollow sculpting shape open-endedness",
"hollow sculpting shape open-ended property value (hollow shapes, such as cylinders, pyramids, etc., can have open or closed ends).");
Configs.sculptSemiDiameter = getSculptSettingInt("Semi-Diameter", true, true, 5, 0, Integer.MAX_VALUE,
"sculpting shape semi-diameter",
"sculpting shape semi-diameter (in bits).", "5 bits");
Configs.sculptWallThickness = getSculptSettingInt("Wall Thickness", false, true, 2, 1, Integer.MAX_VALUE,
"hollow sculpting shape wall thickness",
"hollow sculpting shape wall thickness (in bits).", "2 bits");
Configs.sculptSetBitWire = getSculptSettingItemStack("Wire Filter Bit Type", true, true, "minecraft:air",
"filtered bit type",
"filtered bit type (sculpting can remove only one bit type rather than any - this config sets the block [as specified " +
"by 'modID:name'] of the bit type that sculpting wires remove (an empty string, an unsupported block, or any misspelling " +
"will specify any/all bit types)).", "Any");
Configs.sculptSetBitWire.init();
Configs.sculptSetBitSpade = getSculptSettingItemStack("Spade Addition Bit Type", true, true, "minecraft:air",
"addition bit type",
"addition bit type (sets the block form [as specified by 'modID:name'] of the bit type that sculpting spades add to the " +
"world (an empty string, an unsupported block, or any misspelling will specify no bit type - the type will have to be set " +
"before the spade can be used)).", "None");
Configs.sculptSetBitSpade.init();
//ITEM PROPERTIES
for (Item item : Configs.itemPropertyMap.keySet())
{
ConfigProperty configProperty = (ConfigProperty) Configs.itemPropertyMap.get(item);
String itemTitle = configProperty.getTitle();
String category = itemTitle + " Properties";
boolean isWrench = item instanceof ItemBitWrench;
configProperty.takesDamage = getToolTakesDamage(itemTitle, category, configProperty.getTakesDamageDefault(), !isWrench);
configProperty.maxDamage = getToolMaxDamage(itemTitle, category, configProperty.getMaxDamageDefault(), 1, Integer.MAX_VALUE, !isWrench);
if (isWrench)
{
ItemsExtraBitManipulation.BitWrench.setMaxDamage(configProperty.takesDamage ? configProperty.maxDamage : 0);
}
}
//ITEM RECIPES
for (Item item : Configs.itemRecipeMap.keySet())
{
ConfigRecipe configRecipe = (ConfigRecipe) Configs.itemRecipeMap.get(item);
String itemTitle = configRecipe.getTitle();
String category = itemTitle + " Recipe";
configRecipe.isEnabled = getRecipeEnabled(itemTitle, category, configRecipe.getIsEnabledDefault());
configRecipe.isShaped = getRecipeShaped(itemTitle, category, configRecipe.getIsShapedDefault());
configRecipe.useOreDictionary = getRecipeOreDictionary(itemTitle, category, configRecipe.getUseOreDictionaryDefault());
configRecipe.recipe = getRecipeList(itemTitle, category, configRecipe.getRecipeDefault());
}
//RENDER OVERLAYS
Configs.disableOverlays = configFile.getBoolean("Disable Overlay Rendering", RENDER_OVERLAYS, false,
"Prevents overlays from rendering. (default = false)");
Configs.rotationPeriod = getDouble(configFile, "Rotation Period", RENDER_OVERLAYS, 180, 1, Double.MAX_VALUE,
"Number of frames over which the cyclical arrow overlay used in block/texture rotation will complete one rotation. If this is " +
"set to the minimum value of 1, no rotation will occur. (default = 3 seconds at 60 fps)");
Configs.mirrorPeriod = getDouble(configFile, "Mirror Oscillation Period", RENDER_OVERLAYS, 50, 1, Double.MAX_VALUE,
"Number of frames over which the bidirectional arrow overlay used in block/texture mirroring will complete one oscillation. If this is " +
"set to the minimum value of 1, no oscillation will occur. (default = 0.83 seconds at 60 fps)");
Configs.mirrorAmplitude = getDouble(configFile, "Mirror Oscillation Amplitude", RENDER_OVERLAYS, 0.1, 0, Double.MAX_VALUE,
"Half the total travel distance of the bidirectional arrow overlay used in block/texture mirroring as measured from the center of " +
"the block face the player is looking at. If this is set to the minimum value of 0, no oscillation will occur. (default = 0.1 meters)");
Configs.translationScalePeriod = getDouble(configFile, "Translation Scale Period", RENDER_OVERLAYS, 80, 1, Double.MAX_VALUE,
"Number of frames over which the circle overlay used in block translation will complete one cycle of scaling from a point to " +
"full-sized or vice versa. If this is set to the minimum value of 1, no scaling will occur. (default = 1.33 seconds at 60 fps)");
Configs.translationDistance = getDouble(configFile, "Arrow Movement Distance", RENDER_OVERLAYS, 0.75, 0, Double.MAX_VALUE,
"Total travel distance of the arrowhead overlay used in block/texture translation/rotation as measured from the center of " +
"the block face the player is looking at. If this is set to the minimum value of 0, only one arrow head will be rendered and " +
"no movement will occur. (default = 0.75 meters)");
Configs.translationOffsetDistance = getDouble(configFile, "Arrow Spacing", RENDER_OVERLAYS, 0.25, 0, Double.MAX_VALUE,
"Distance between the three moving arrowhead overlays used in block/texture translation/rotation. If this is set to the minimum " +
"value of 0, only one arrow head will be rendered. (default = 1/3 of the default distance of 0.75 meters, i.e. evenly spaced)");
Configs.translationFadeDistance = getDouble(configFile, "Arrow Fade Distance", RENDER_OVERLAYS, 0.3, 0, Double.MAX_VALUE,
"Distance over which the arrowhead overlay used in block/texture translation/rotation will fade in (as well as out) as it moves. " +
"If this is set to the minimum value of 0, no fading will occur. (default = 0.3 meters)");
Configs.translationMovementPeriod = getDouble(configFile, "Arrow Movement Period", RENDER_OVERLAYS, 120, 1, Double.MAX_VALUE,
"Number of frames over which the arrowhead overlay used in block/texture translation/rotation will travel from one end to the " +
"other of the distance specified by 'Arrow Movement Distance'. If this is set to the minimum value of 1, no movement will occur. " +
"(default = 2 seconds at 60 fps)");
//RENDER SCULPTING TOOL SHAPES
for (int i = 0; i < Configs.itemShapes.length; i++)
{
ConfigShapeRender configShapeRender = Configs.itemShapes[i];
String category = configShapeRender.getTitle();
configShapeRender.renderInnerShape = getShapeRender(category, true, configShapeRender.getRenderInnerShapeDefault());
configShapeRender.renderOuterShape = getShapeRender(category, false, configShapeRender.getRenderOuterShapeDefault());
configShapeRender.innerShapeAlpha = getShapeAlpha(category, true, configShapeRender.getInnerShapeAlphaDefault());
configShapeRender.outerShapeAlpha = getShapeAlpha(category, false, configShapeRender.getOuterShapeAlphaDefault());
configShapeRender.red = getShapeColor(category, 0, configShapeRender.getRedDefault());
configShapeRender.green = getShapeColor(category, 1, configShapeRender.getGreenDefault());
configShapeRender.blue = getShapeColor(category, 2, configShapeRender.getBlueDefault());
configShapeRender.lineWidth = getShapeLineWidth(category, configShapeRender.getLineWidthDefault());
}
}
catch (Exception e)
{
System.out.println(Reference.MOD_NAME + " configurations failed to update.");
e.printStackTrace();
}
finally
{
if (configFile.hasChanged())
{
configFile.save();
}
}
}
private static ConfigSculptSettingBoolean getSculptSettingBoolean(String name, boolean defaultPerTool, boolean defaultDisplayInChat, boolean defaultValue,
String toolTipSecondary, String toolTipDefaultValue)
{
boolean perTool = getPerTool(name, defaultPerTool, toolTipSecondary);
boolean displayInChat = getDisplayInChat(name, defaultDisplayInChat, toolTipSecondary);
boolean defaultBoolean = configFile.getBoolean(name, SCULPTING_DEFAULT_VALUES, defaultValue,
getToolTipSculptSetting(toolTipDefaultValue, Boolean.toString(defaultValue)));
return new ConfigSculptSettingBoolean(perTool, displayInChat, defaultBoolean);
}
private static ConfigSculptSettingInt getSculptSettingInt(String name, boolean defaultPerTool, boolean defaultDisplayInChat, int defaultValue, int minValue, int maxValue,
String toolTipSecondary, String toolTipDefaultValue, String toolTipDefaultValueDefault)
{
boolean perTool = getPerTool(name, defaultPerTool, toolTipSecondary);
boolean displayInChat = getDisplayInChat(name, defaultDisplayInChat, toolTipSecondary);
int defaultInt = configFile.getInt(name, SCULPTING_DEFAULT_VALUES, defaultValue, minValue, maxValue,
getToolTipSculptSetting(toolTipDefaultValue, toolTipDefaultValueDefault));
return new ConfigSculptSettingInt(perTool, displayInChat, defaultInt);
}
private static ConfigSculptSettingInt getSculptSettingIntFromStringArray(String name, boolean defaultPerTool, boolean defaultDisplayInChat, int defaultValue, int offset,
String toolTipSecondary, String toolTipDefaultValue, String ... validValues)
{
boolean perTool = getPerTool(name, defaultPerTool, toolTipSecondary);
boolean displayInChat = getDisplayInChat(name, defaultDisplayInChat, toolTipSecondary);
String defaultInt = validValues[defaultValue];
String entry = configFile.getString(name, SCULPTING_DEFAULT_VALUES, defaultInt,
getToolTipSculptSetting(toolTipDefaultValue, defaultInt), validValues);
for (int i = 0; i < validValues.length; i++)
{
if (entry.equals(validValues[i]))
{
defaultValue = i + offset;
}
}
return new ConfigSculptSettingInt(perTool, displayInChat, defaultValue);
}
private static ConfigSculptSettingBitStack getSculptSettingItemStack(String name, boolean defaultPerTool, boolean defaultDisplayInChat, String defaultValue,
String toolTipSecondary, String toolTipDefaultValue, String toolTipDefaultValueDefault)
{
boolean perTool = getPerTool(name, defaultPerTool, toolTipSecondary);
boolean displayInChat = getDisplayInChat(name, defaultDisplayInChat, toolTipSecondary);
Block defaultBlock = null;
String blockEntry = configFile.getString(name, SCULPTING_DEFAULT_VALUES, defaultValue,
getToolTipSculptSetting(toolTipDefaultValue, toolTipDefaultValueDefault));
if (!blockEntry.isEmpty())
{
int i = blockEntry.indexOf(":");
if (i > 0)
{
int len = blockEntry.length();
if (len > 2 && StringUtils.countMatches(blockEntry, ":") == 1)
{
defaultBlock = GameRegistry.findBlock(blockEntry.substring(0, i), blockEntry.substring(i + 1, len));
}
}
}
return new ConfigSculptSettingBitStack(perTool, displayInChat, defaultBlock);
}
private static String getToolTipSculptSetting(String toolTipDefaultValue, String toolTipDefaultValueDefault)
{
return "Players and sculpting tools will initialize with this " + toolTipDefaultValue + " (default = " + toolTipDefaultValueDefault + ")";
}
private static boolean getPerTool(String name, boolean defaultPerTool, String toolTipPerTool)
{
return configFile.getBoolean(name, SCULPTING_PER_TOOL_OR_PER_PLAYER, defaultPerTool,
"If set to true, " + toolTipPerTool + " will be set/stored in each individual sculpting tool and apply only to that tool. " +
"If set to false, it will be stored in the player and will apply to all tools. Regardless of this setting, players and tools " +
"will still initialize with data, but this setting determines which is considered for use. " + getReferralString(toolTipPerTool) + " (default = " + defaultPerTool + ")");
}
private static boolean getDisplayInChat(String name, boolean defaultDisplayInChat, String toolTipDisplayInChat)
{
return configFile.getBoolean(name, SCULPTING_DISPLAY_IN_CHAT, defaultDisplayInChat,
"If set to true, whenever " + toolTipDisplayInChat + " is changed, a message will be added to chat indicating the change. " +
"This will not fill chat with messages, since any pre-existing messages from this mod will be deleted before adding the next." +
getReferralString(toolTipDisplayInChat) + " (default = " + defaultDisplayInChat + ")");
}
private static String getReferralString(String settingString)
{
return "See 'Default Value' config for a description of " + settingString + ".";
}
private static void removeCategory(String category)
{
configFile.removeCategory(configFile.getCategory(category.toLowerCase()));
}
private static String getVersion(String defaultValue)
{
return configFile.getString(VERSION, VERSION, defaultValue.toLowerCase(), "Used for cofig updating when updating mod version. Do not change.");
}
private static boolean getShapeRender(String category, boolean inner, boolean defaultValue)
{
String shape = getShape(category);
return configFile.getBoolean("Render " + (inner ? "Inner " : "Outer ") + shape, category, defaultValue,
"Causes " + getSidedShapeText(shape, inner) + " to be rendered. (default = " + defaultValue + ")");
}
private static float getShapeAlpha(String category, boolean inner, int defaultValue)
{
String shape = getShape(category);
return configFile.getInt("Alpha " + (inner ? "Inner " : "Outer ") + shape, category, defaultValue, 0, 255,
"Sets the alpha value of " + getSidedShapeText(shape, inner) + ". (default = " + defaultValue + ")") / 255F;
}
private static String getSidedShapeText(String shape, boolean inner)
{
return "the portion of the " + shape.toLowerCase() + " that is " + (inner ? "behind" : "in front of") + " other textures";
}
private static float getShapeColor(String category, int colorFlag, int defaultValue)
{
String name = COLOR_NAMES[colorFlag];
return configFile.getInt("Color - " + name, category, defaultValue, 0, 255,
"Sets the " + name.toLowerCase() + " value of the " + getShape(category).toLowerCase() + ". (default = " + defaultValue + ")") / 255F;
}
private static float getShapeLineWidth(String category, float defaultValue)
{
return configFile.getFloat("Line Width", category, defaultValue, 0, Float.MAX_VALUE,
"Sets the line width of the " + getShape(category).toLowerCase() + ". (default = " + defaultValue + ")");
}
private static String getShape(String category)
{
return category.substring(category.lastIndexOf(" ") + 1, category.length());
}
private static int getToolMaxDamage(String name, String category, int defaultValue, int min, int max, boolean perBit)
{
return configFile.getInt("Max Damage", category, defaultValue, min, max,
"The " + name + " will " + (perBit ? "be able to add/remove this many bits " : "have this many uses ")
+ "if it is configured to take damage. (default = " + defaultValue + ")");
}
private static boolean getToolTakesDamage(String name, String category, boolean defaultValue, boolean perBit)
{
return configFile.getBoolean("Takes Damage", category, defaultValue,
"Causes the " + name + " to take a point of damage " + (perBit ? " for every bit added/removed " : "")
+ "when used. (default = " + defaultValue + ")");
}
private static boolean getRecipeEnabled(String name, String category, boolean defaultValue)
{
return configFile.getBoolean("Is Enabled", category, defaultValue,
"If set to true, the " + name + " will be craftable, otherwise it will not be. (default = " + defaultValue + ")");
}
private static boolean getRecipeShaped(String name, String category, boolean defaultValue)
{
return configFile.getBoolean("Is Shaped", category, defaultValue,
"If set to true, the recipe for the " + name + " will be shaped, and thus depend on the order/number of elements." +
". If set to false, it will be shapeless and will be order-independent. (default = " + defaultValue + ")");
}
private static boolean getRecipeOreDictionary(String name, String category, boolean defaultValue)
{
return configFile.getBoolean("Use Ore Dictionary", category, defaultValue,
"If set to true, the string names given for the " + name + " recipe will be used to look up entries in the Ore Dictionary. " +
"If set to false, they will be used to look up Items by name or ID. (default = " + defaultValue + ")");
}
private static String[] getRecipeList(String name, String category, String[] defaultValue)
{
return configFile.getStringList("Recipe", category, defaultValue,
"The Ore Dictionary names or Item names/IDs of components of the crafting recipe for the " + name + ". The elements of the list " +
"correspond to the slots of the crafting grid (left to right / top to bottom). If the recipe shaped, the list must have 4 " +
"elements to be a 2x2 recipe, 9 elements to be a 3x3 recipe, etc (i.e. must make a whole grid; root n elements for an n by n " +
"grid). Inputting an incorrect number of elements will result in use of the default recipe. Empty strings denote empty slots " +
"in the recipe. If the recipe shapeless, order is not important, and duplicates or empty strings will be ignored. Whether the " +
"recipe is shaped or shapeless, strings that are not found in the Ore Dictionary or are not valid item names/IDs will be replaced " +
"with empty spaces. The default recipe will be used if none of the provided strings are found.");
}
private static double getDouble(Configuration configFile, String name, String category, double defaultValue, double minValue, double maxValue, String comment)
{
Property prop = configFile.get(category, name, Double.toString(defaultValue), name);
prop.setLanguageKey(name);
prop.comment = comment + " [range: " + minValue + " ~ " + maxValue + ", default: " + defaultValue + "]";
prop.setMinValue(minValue);
prop.setMaxValue(maxValue);
try
{
return Double.parseDouble(prop.getString()) < minValue ? minValue : (Double.parseDouble(prop.getString()) > maxValue ? maxValue : Double.parseDouble(prop.getString()));
}
catch (Exception e)
{
System.out.println("The " + Reference.MOD_NAME + " configuration '" + name
+ "' could not be parsed to a double. Default value of " + defaultValue + " was restored and used instead.");
}
return defaultValue;
}
}
|
package com.sri.ai.grinder.sgdpllt.interpreter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.grinder.helper.AssignmentsSamplingIterator;
import com.sri.ai.grinder.sgdpllt.api.Context;
import com.sri.ai.grinder.sgdpllt.group.AssociativeCommutativeGroup;
import com.sri.ai.grinder.sgdpllt.rewriter.api.Rewriter;
import com.sri.ai.grinder.sgdpllt.rewriter.api.TopRewriter;
/**
*
* @author oreilly
*
*/
public class SampleMultiIndexQuantifierEliminator extends AbstractIterativeMultiIndexQuantifierElimination {
private int sampleSizeN;
private Rewriter indicesConditionRewriter;
private Random random;
public SampleMultiIndexQuantifierEliminator(TopRewriter topRewriter, int sampleSizeN, Rewriter indicesConditionRewriter, Random random) {
super(topRewriter);
this.sampleSizeN = sampleSizeN;
this.indicesConditionRewriter = indicesConditionRewriter;
this.random = random;
}
public SampleMultiIndexQuantifierEliminator(TopRewriterUsingContextAssignments topRewriterWithBaseAssignment, int sampleSizeN, Rewriter indicesConditionRewriter, Random random) {
super(topRewriterWithBaseAssignment);
this.sampleSizeN = sampleSizeN;
this.indicesConditionRewriter = indicesConditionRewriter;
this.random = random;
}
@Override
public Iterator<Map<Expression, Expression>> makeAssignmentsIterator(List<Expression> indices, Expression indicesCondition, Context context) {
return new AssignmentsSamplingIterator(indices, sampleSizeN, indicesCondition, indicesConditionRewriter, random, context);
}
@Override
public Expression makeSummand(AssociativeCommutativeGroup group, List<Expression> indices, Expression indicesCondition, Expression body, Context context) {
// NOTE: the AssignmentsSamplingIterator takes the indicesCondition into account so no need to take it into account.
return body;
}
}
|
package rhogenwizard;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IProject;
import org.eclipse.ui.console.MessageConsoleStream;
import rhogenwizard.buildfile.AppYmlFile;
class AppLogAdapter implements ILogDevice
{
MessageConsoleStream m_consoleStream = ConsoleHelper.getConsoleAppStream();
@Override
public void log(String str)
{
if (null != m_consoleStream)
{
ConsoleHelper.showAppConsole();
m_consoleStream.println(prepareString(str));
}
}
private String prepareString(String message)
{
message = message.replaceAll("\\p{Cntrl}", " ");
return message;
}
}
public class LogFileHelper
{
class LogFileWaiter implements Runnable
{
private IProject m_project = null;
private LogFileHelper m_helper = null;
private String m_logFilePath = null;
private RunType m_type = null;
public LogFileWaiter(IProject project, LogFileHelper helper, String logFilePath, RunType type) throws Exception
{
m_project = project;
m_helper = helper;
m_logFilePath = logFilePath;
m_type = type;
}
@Override
public void run()
{
try
{
while(true)
{
if (m_logFilePath == null)
return;
File logFile = new File(m_logFilePath);
if (logFile.exists())
{
m_helper.endWaitLog(m_project, m_type);
return;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private RhodesAdapter.EPlatformType m_platformName = null;
private AsyncStreamReader m_appLogReader = null;
private InputStream m_logFileStream = null;
private StringBuffer m_logOutput = null;
private AppLogAdapter m_logAdapter = new AppLogAdapter();
@Override
protected void finalize() throws Throwable
{
stopLog();
super.finalize();
}
public void endWaitLog(IProject project, RunType type) throws Exception
{
if (type.equals(RunType.ERunType.eRhoEmulator))
{
rhoSimLog(project);
}
else
{
switch(m_platformName)
{
case eBb:
bbLog(project);
break;
}
}
}
public void startLog(RhodesAdapter.EPlatformType platformName, IProject project, RunType runType) throws Exception
{
m_platformName = platformName;
if ( runType.equals(RunType.ERunType.eRhoEmulator))
{
waitSimLog(project, runType);
}
else
{
switch(m_platformName)
{
case eWm:
wmLog(project);
break;
case eAndroid:
adnroidLog(project);
break;
case eBb:
waitBbLog(project, runType);
break;
case eIPhone:
iphoneLog(project);
break;
case eWp7:
wpLog(project);
break;
}
}
}
private void waitSimLog(IProject project, RunType type) throws Exception
{
String logFilePath = getLogFilePath(project, "run:rhosimulator:get_log");
Thread waitingLog = new Thread(new LogFileWaiter(project, this, logFilePath, type));
waitingLog.start();
}
private void waitBbLog(IProject project, RunType type) throws Exception
{
String logFilePath = getLogFilePath(project, "run:bb:get_log");
Thread waitingLog = new Thread(new LogFileWaiter(project, this, logFilePath, type));
waitingLog.start();
}
private void wpLog(IProject project) throws Exception
{
String logPath = getLogFilePath(project, "run:wp:get_log");
if (logPath != null)
{
asyncFileRead(logPath);
}
}
private void rhoSimLog(IProject project) throws Exception
{
String logPath = getLogFilePath(project, "run:rhosimulator:get_log");
if (logPath != null)
{
asyncFileRead(logPath);
}
}
private void wmLog(IProject project) throws Exception
{
String logPath = getLogFilePath(project, "run:wm:get_log");
if (logPath != null)
{
asyncFileRead(logPath);
}
}
private void iphoneLog(IProject project) throws Exception
{
String logPath = getLogFilePath(project, "run:iphone:get_log");
if (logPath != null)
{
asyncFileRead(logPath);
}
}
private void bbLog(IProject project) throws Exception
{
String logPath = getLogFilePath(project,"run:bb:get_log");
if (logPath != null)
{
asyncFileRead(logPath);
}
}
public void stopLog()
{
if (m_appLogReader != null)
{
m_appLogReader.stopReading();
}
}
private void asyncFileRead(String logFilePath) throws FileNotFoundException
{
stopLog();
File logFile = new File(logFilePath);
m_logFileStream = new FileInputStream(logFile);
m_logOutput = new StringBuffer();
m_appLogReader = new AsyncStreamReader(true, m_logFileStream, m_logOutput, m_logAdapter, "APPLOG");
m_appLogReader.start();
}
private void adnroidLog(IProject project) throws FileNotFoundException
{
AppYmlFile projectConfig = AppYmlFile.createFromProject(project);
String logFilePath = project.getLocation().toOSString() + File.separatorChar + projectConfig.getAppLog();
asyncFileRead(logFilePath);
}
private String getLogFilePath(IProject project, String taskName) throws Exception
{
RhodesAdapter rhodesExecutor = new RhodesAdapter();
String output = rhodesExecutor.runRakeTask(project.getLocation().toOSString(), taskName);
StringTokenizer st = new StringTokenizer(output, "\n");
while (st.hasMoreTokens())
{
String token = st.nextToken();
if (token.contains("log_file"))
{
String[] parts = token.split("=");
if (parts.length < 2)
return null;
String logFile = parts[1];
logFile = logFile.replaceAll("\\p{Cntrl}", "");
return logFile;
}
}
return null;
}
}
|
package io.github.mzmine.modules.io.import_rawdata_waters_raw;
import com.google.common.base.Strings;
import io.github.mzmine.datamodel.MZmineProject;
import io.github.mzmine.datamodel.RawDataFile;
import io.github.mzmine.main.MZmineCore;
import io.github.mzmine.modules.MZmineModuleCategory;
import io.github.mzmine.modules.MZmineProcessingModule;
import io.github.mzmine.parameters.ParameterSet;
import io.github.mzmine.taskcontrol.Task;
import io.github.mzmine.util.ExitCode;
import io.github.mzmine.util.MemoryMapStorage;
import io.github.mzmine.util.RawDataFileUtils;
import io.github.mzmine.util.files.FileAndPathUtil;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.jetbrains.annotations.NotNull;
/**
* Raw data import module
*/
public class WatersRawImportModule implements MZmineProcessingModule {
private static final Logger logger = Logger.getLogger(WatersRawImportModule.class.getName());
private static final String MODULE_NAME = "Waters RAW file import";
private static final String MODULE_DESCRIPTION = "This module imports raw data into the project.";
@Override
public @NotNull String getName() {
return MODULE_NAME;
}
@Override
public @NotNull String getDescription() {
return MODULE_DESCRIPTION;
}
@Override
public @NotNull MZmineModuleCategory getModuleCategory() {
return MZmineModuleCategory.RAWDATAIMPORT;
}
@Override
public @NotNull Class<? extends ParameterSet> getParameterSetClass() {
return WatersRawImportParameters.class;
}
@Override
@NotNull
public ExitCode runModule(final @NotNull MZmineProject project, @NotNull ParameterSet parameters,
@NotNull Collection<Task> tasks, @NotNull Instant moduleCallDate) {
File dir = parameters.getParameter(WatersRawImportParameters.fileNames).getValue()[0];
File fileNames[] = Arrays.stream(FileAndPathUtil.getSubDirectories(dir))
.filter(Objects::nonNull)
.filter(f -> f.isDirectory() && f.getName().toLowerCase().endsWith(".raw"))
.toArray(File[]::new);
if (fileNames.length <= 0) {
logger.warning("Select .raw folder or parent folder for waters import");
return ExitCode.ERROR;
}
if (Arrays.asList(fileNames).contains(null)) {
logger.warning("List of filenames contains null");
return ExitCode.ERROR;
}
// Find common prefix in raw file names if in GUI mode
String commonPrefix = RawDataFileUtils.askToRemoveCommonPrefix(fileNames);
// one storage for all files imported in the same task as they are typically analyzed together
final MemoryMapStorage storage = MemoryMapStorage.forRawDataFile();
for (int i = 0; i < fileNames.length; i++) {
if ((!fileNames[i].exists()) || (!fileNames[i].canRead())) {
MZmineCore.getDesktop().displayErrorMessage("Cannot read file " + fileNames[i]);
logger.warning("Cannot read file " + fileNames[i]);
return ExitCode.ERROR;
}
// Set the new name by removing the common prefix
String newName;
if (!Strings.isNullOrEmpty(commonPrefix)) {
final String regex = "^" + Pattern.quote(commonPrefix);
newName = fileNames[i].getName().replaceFirst(regex, "");
} else {
newName = fileNames[i].getName();
}
try {
RawDataFile newMZmineFile = MZmineCore.createNewFile(newName,
fileNames[i].getAbsolutePath(), storage);
Task newTask = new WatersRawImportTask(project, fileNames[i], newMZmineFile,
WatersRawImportModule.class, parameters, moduleCallDate);
tasks.add(newTask);
} catch (IOException e) {
e.printStackTrace();
MZmineCore.getDesktop().displayErrorMessage("Could not create a new temporary file " + e);
logger.log(Level.SEVERE, "Could not create a new temporary file ", e);
return ExitCode.ERROR;
}
}
return ExitCode.OK;
}
}
|
package mod._sw;
import com.sun.star.beans.NamedValue;
import util.DBTools;
import util.utils;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XNameAccess;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sdb.CommandType;
import com.sun.star.sdbc.*;
import com.sun.star.sdbcx.XRowLocate;
import com.sun.star.task.XJob;
import com.sun.star.text.MailMergeType;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
/**
* Here <code>com.sun.star.text.MailMerge</code> service is tested.<p>
* @see com.sun.star.text.MailMerge
* @see com.sun.star.task.XJob
* @see com.sun.star.text.XMailMergeBroadcaster
*/
public class SwXMailMerge extends TestCase {
public void initialize( TestParameters Param, PrintWriter log ) {
if (! Param.containsKey("uniqueSuffix")){
Param.put("uniqueSuffix", new Integer(0));
}
}
/**
* Creating a Testenvironment for the interfaces to be tested. <p>
* Creates <code>MailMerge</code> service * Object relations created :
* <ul>
* <li> <code>'executeArgs'</code> for
* {@link ifc.text._XMailMergeBroadcaster} : NamedValue[]</li>
* <li> <code>'Job'</code> for
* {@link ifc.text._XMailMergeBroadcaster} : XJob</li>
* <li> <code>'XJobArgs'</code> for
* {@link ifc.task._XJob} : Object[]</li>
* </ul>
*/
protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) {
XInterface oObj = null;
XInterface oRowSet = null;
Object oConnection = null;
XJob Job = null;
log.println(" instantiate MailMerge service");
try {
oObj = (XInterface) ( (XMultiServiceFactory) Param.getMSF()).createInstance
("com.sun.star.text.MailMerge");
} catch (Exception e) {
throw new StatusException("Can't create object environment", e) ;
}
// <set some variables>
String cTestDoc = utils.getFullTestURL("MailMerge.sxw");
//cMailMerge_DocumentURL = cTestDoc
String cOutputURL = utils.getOfficeTemp( (XMultiServiceFactory) Param.getMSF());
String cDataSourceName = "Bibliography";
String cDataCommand = "biblio";
Object[] sel = new Object[2];
sel[0] = new int[2];
sel[1] = new int[5];
Object[] myBookMarks = new Object[2];
// </set some variables>
// <create XResultSet>
log.println("create a XResultSet");
try {
oRowSet = (XInterface) ( (XMultiServiceFactory) Param.getMSF()).createInstance
("com.sun.star.sdb.RowSet");
} catch (Exception e) {
throw new StatusException("Can't create com.sun.star.sdb.RowSet", e);
}
XPropertySet oRowSetProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class, oRowSet);
XRowSet xRowSet = (XRowSet)
UnoRuntime.queryInterface(XRowSet.class, oRowSet);
try {
oRowSetProps.setPropertyValue("DataSourceName",cDataSourceName);
oRowSetProps.setPropertyValue("Command",cDataCommand);
oRowSetProps.setPropertyValue("CommandType", new Integer(CommandType.TABLE));
} catch (UnknownPropertyException e) {
throw new StatusException("Can't set properties on oRowSet", e);
} catch (PropertyVetoException e) {
throw new StatusException("Can't set properties on oRowSet", e);
} catch (IllegalArgumentException e) {
throw new StatusException("Can't set properties on oRowSet", e);
} catch (WrappedTargetException e) {
throw new StatusException("Can't set properties on oRowSet", e);
}
try {
xRowSet.execute();
} catch (SQLException e) {
throw new StatusException("Can't execute oRowSet", e);
}
XResultSet oResultSet = (XResultSet)
UnoRuntime.queryInterface(XResultSet.class, oRowSet);
// <create Bookmarks>
log.println("create bookmarks");
try {
XRowLocate oRowLocate = (XRowLocate) UnoRuntime.queryInterface(
XRowLocate.class, oResultSet);
oResultSet.first();
myBookMarks[0] = oRowLocate.getBookmark();
oResultSet.next();
myBookMarks[1] = oRowLocate.getBookmark();
} catch (SQLException e) {
throw new StatusException("Cant get Bookmarks", e);
}
// </create Bookmarks>
// <fill object with values>
log.println("fill MailMerge with default connection");
XPropertySet oObjProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class, oObj);
try {
oObjProps.setPropertyValue("ActiveConnection", getLocalXConnection(Param));
oObjProps.setPropertyValue("DataSourceName", cDataSourceName);
oObjProps.setPropertyValue("Command", cDataCommand);
oObjProps.setPropertyValue("CommandType", new Integer(CommandType.TABLE));
oObjProps.setPropertyValue("OutputType", new Short(MailMergeType.FILE));
oObjProps.setPropertyValue("DocumentURL", cTestDoc);
oObjProps.setPropertyValue("OutputURL", cOutputURL);
oObjProps.setPropertyValue("FileNamePrefix", "Author");
oObjProps.setPropertyValue("FileNameFromColumn", new Boolean(false));
oObjProps.setPropertyValue("Selection", new Object[0]);
} catch (UnknownPropertyException e) {
throw new StatusException("Can't set properties on oObj", e);
} catch (PropertyVetoException e) {
throw new StatusException("Can't set properties on oObj", e);
} catch (IllegalArgumentException e) {
throw new StatusException("Can't set properties on oObj", e);
} catch (WrappedTargetException e) {
throw new StatusException("Can't set properties on oObj", e);
}
// </fill object with values>
// <create object relations>
Object[] vXJobArgs = new Object[4];
NamedValue[] vXJobArg0 = new NamedValue[8];
NamedValue[] vXJobArg1 = new NamedValue[7];
NamedValue[] vXJobArg2 = new NamedValue[10];
NamedValue[] vXJobArg3 = new NamedValue[0];
// first Arguments
vXJobArg0[0] = new NamedValue("DataSourceName", cDataSourceName);
vXJobArg0[1] = new NamedValue("Command", cDataCommand);
vXJobArg0[2] = new NamedValue("CommandType",new Integer(CommandType.TABLE));
vXJobArg0[3] = new NamedValue("OutputType",new Short(MailMergeType.FILE));
vXJobArg0[4] = new NamedValue("DocumentURL", cTestDoc);
vXJobArg0[5] = new NamedValue("OutputURL", cOutputURL);
vXJobArg0[6] = new NamedValue("FileNamePrefix", "Identifier");
vXJobArg0[7] = new NamedValue("FileNameFromColumn", new Boolean(true));
//second Arguments
vXJobArg1[0] = new NamedValue("DataSourceName", cDataSourceName);
vXJobArg1[1] = new NamedValue("Command", cDataCommand);
vXJobArg1[2] = new NamedValue("CommandType",new Integer(CommandType.TABLE));
vXJobArg1[3] = new NamedValue("OutputType",
new Short(MailMergeType.PRINTER));
vXJobArg1[4] = new NamedValue("DocumentURL", cTestDoc);
vXJobArg1[5] = new NamedValue("FileNamePrefix", "Author");
vXJobArg1[6] = new NamedValue("FileNameFromColumn", new Boolean(true));
// third Arguments
vXJobArg2[0] = new NamedValue("ActiveConnection", getLocalXConnection(Param));
vXJobArg2[1] = new NamedValue("DataSourceName", cDataSourceName);
vXJobArg2[2] = new NamedValue("Command", cDataCommand);
vXJobArg2[3] = new NamedValue("CommandType",new Integer(CommandType.TABLE));
vXJobArg2[4] = new NamedValue("OutputType",
new Short(MailMergeType.FILE));
vXJobArg2[5] = new NamedValue("ResultSet", oResultSet);
vXJobArg2[6] = new NamedValue("OutputURL", cOutputURL);
vXJobArg2[7] = new NamedValue("FileNamePrefix", "Identifier");
vXJobArg2[8] = new NamedValue("FileNameFromColumn", new Boolean(true));
vXJobArg2[9] = new NamedValue("Selection", myBookMarks);
vXJobArgs[0] = vXJobArg0;
vXJobArgs[1] = vXJobArg1;
vXJobArgs[2] = vXJobArg2;
vXJobArgs[3] = vXJobArg3;
Job = (XJob) UnoRuntime.queryInterface(XJob.class, oObj);
try{
Job.execute(vXJobArg2);
} catch ( IllegalArgumentException e){
System.out.println(e.toString());
} catch ( Exception e){
System.out.println(e.toString());
}
// <create XResultSet>
log.println("create XResultSet");
try {
oRowSet = (XInterface) ( (XMultiServiceFactory) Param.getMSF()).createInstance
("com.sun.star.sdb.RowSet");
} catch (Exception e) {
throw new StatusException("Can't create com.sun.star.sdb.RowSet", e);
}
oRowSetProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oRowSet);
xRowSet = (XRowSet) UnoRuntime.queryInterface(XRowSet.class, oRowSet);
try {
oRowSetProps.setPropertyValue("DataSourceName",cDataSourceName);
oRowSetProps.setPropertyValue("Command",cDataCommand);
oRowSetProps.setPropertyValue("CommandType", new Integer(CommandType.TABLE));
} catch (UnknownPropertyException e) {
throw new StatusException("Can't set properties on oRowSet", e);
} catch (PropertyVetoException e) {
throw new StatusException("Can't set properties on oRowSet", e);
} catch (IllegalArgumentException e) {
throw new StatusException("Can't set properties on oRowSet", e);
} catch (WrappedTargetException e) {
throw new StatusException("Can't set properties on oRowSet", e);
}
try {
xRowSet.execute();
} catch (SQLException e) {
throw new StatusException("Can't execute oRowSet", e);
}
oResultSet = (XResultSet)
UnoRuntime.queryInterface(XResultSet.class, oRowSet);
XResultSet oMMXResultSet = null;
try {
oMMXResultSet = (XResultSet)
UnoRuntime.queryInterface(XResultSet.class,
( (XInterface)
( (XMultiServiceFactory)
Param.getMSF()).createInstance("com.sun.star.sdb.RowSet")));
} catch (Exception e) {
throw new StatusException("Can't create com.sun.star.sdb.RowSet", e);
}
// </create object relations>
TestEnvironment tEnv = new TestEnvironment(oObj) ;
// <adding object relations>
// com.sun.star.sdb.DataAccessDescriptor
tEnv.addObjRelation("DataAccessDescriptor.XResultSet", oResultSet);
tEnv.addObjRelation("DataAccessDescriptor.XConnection", getRemoteXConnection(Param));
// com.sun.star.text.MailMaerge
tEnv.addObjRelation("MailMerge.XConnection", getRemoteXConnection(Param));
tEnv.addObjRelation("MailMerge.XResultSet", oMMXResultSet);
// com.sun.star.text.XMailMergeBroadcaster
tEnv.addObjRelation( "executeArgs", vXJobArg0);
tEnv.addObjRelation( "Job", Job);
// com.sun.star.task.XJob
tEnv.addObjRelation("XJobArgs", vXJobArgs);
// </adding object relations>
return tEnv ;
}
private XConnection getRemoteXConnection(TestParameters Param){
log.println("create remote connection");
String databaseName = null ;
XDataSource oXDataSource = null;
Object oInterface = null;
XMultiServiceFactory xMSF = null ;
int uniqueSuffix = Param.getInt("uniqueSuffix");
try {
xMSF = (XMultiServiceFactory)Param.getMSF();
oInterface = xMSF.createInstance( "com.sun.star.sdb.DatabaseContext" );
// retrieving temp directory for database
String tmpDatabaseUrl = utils.getOfficeTempDir((XMultiServiceFactory)Param.getMSF());
databaseName = "NewDatabaseSource" + uniqueSuffix ;
String tmpDatabaseFile = tmpDatabaseUrl + databaseName + ".odb";
System.out.println("try to delete '"+tmpDatabaseFile+"'");
utils.deleteFile(((XMultiServiceFactory) Param.getMSF()), tmpDatabaseFile);
tmpDatabaseUrl = "sdbc:dbase:file:///" + tmpDatabaseUrl ;
// Creating new DBase data source in the TEMP directory
XInterface newSource = (XInterface) xMSF.createInstance
("com.sun.star.sdb.DataSource") ;
XPropertySet xSrcProp = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class, newSource);
xSrcProp.setPropertyValue("URL", tmpDatabaseUrl) ;
DBTools dbt = new DBTools(((XMultiServiceFactory) Param.getMSF()));
// registering source in DatabaseContext
log.println("register database '"+tmpDatabaseUrl+"' as '"+databaseName+"'" );
dbt.reRegisterDB(databaseName, newSource) ;
uniqueSuffix++;
Param.put("uniqueSuffix", new Integer(uniqueSuffix));
return dbt.connectToSource(newSource);
}
catch( Exception e ) {
uniqueSuffix++;
Param.put("uniqueSuffix", new Integer(uniqueSuffix));
log.println("could not register new database" );
e.printStackTrace();
throw new StatusException("could not register new database", e) ;
}
}
private XConnection getLocalXConnection(TestParameters Param){
log.println("create local connection");
XInterface oDataCont = null;
try {
oDataCont = (XInterface)( (XMultiServiceFactory) Param.getMSF()).createInstance
("com.sun.star.sdb.DatabaseContext");
} catch(Exception e) {
throw new StatusException("Couldn't create instance of 'com.sun.star.sdb.DatabaseContext'", e);
}
XNameAccess xNADataCont = (XNameAccess)
UnoRuntime.queryInterface(XNameAccess.class, oDataCont);
String[] dataNames = xNADataCont.getElementNames();
String dataName="";
for (int i = 0; i < dataNames.length; i++){
if (dataNames[i].startsWith("Biblio")) dataName=dataNames[i];
}
try{
Object oDataBase = xNADataCont.getByName(dataName);
XDataSource xDataSource = (XDataSource)
UnoRuntime.queryInterface(XDataSource.class, oDataBase);
return xDataSource.getConnection("","");
} catch ( NoSuchElementException e){
throw new StatusException("Couldn't get registered data base", e);
} catch ( WrappedTargetException e){
throw new StatusException("Couldn't get registered data base", e);
} catch ( SQLException e){
throw new StatusException("Couldn't get XConnection from registered data base", e);
}
}
protected void cleanup(TestParameters Param, PrintWriter log) {
log.println("closing connections...");
XMultiServiceFactory xMsf = (XMultiServiceFactory) Param.getMSF();
DBTools dbt = new DBTools(xMsf);
if (Param.containsKey("uniqueSuffix")){
int uniqueSuffix = Param.getInt("uniqueSuffix");
uniqueSuffix
String databaseName = "";
while (uniqueSuffix >= 0){
databaseName = "NewDatabaseSource" + uniqueSuffix ;
log.println("revoke '"+databaseName+"'");
try{
dbt.revokeDB(databaseName);
} catch (com.sun.star.uno.Exception e){
}
uniqueSuffix
}
}
}
}
|
package org.openlmis.referencedata.web.csv.recordhandler;
import org.openlmis.referencedata.domain.BaseEntity;
import org.openlmis.referencedata.dto.BaseDto;
/**
* AbstractPersistenceHandler is a base class used for persisting each record of the uploaded file.
*/
public abstract class AbstractPersistenceHandler<M extends BaseEntity, T extends BaseDto>
implements RecordHandler {
/**
* Persists a record based on it's transfer representation.
*/
public void execute(BaseDto currentRecord) {
M record = importDto((T)currentRecord);
execute(record);
}
/**
* Persists each record of the uploaded file.
*/
protected void execute(BaseEntity currentRecord) {
BaseEntity existing = getExisting((M)currentRecord);
if (existing != null) {
currentRecord.setId(existing.getId());
}
save((M)currentRecord);
}
/**
* Implementations should return an existing record, if there is one, based on however
* the record's identity is determined.
*
* @param record the record an implementation should use to look for an "existing" record.
* @return the record that exists that has the same identity as the given record.
*/
protected abstract BaseEntity getExisting(M record);
/**
* Implementations should return a valid entity based on data transfer object.
*
* @param record the transfer object that will be used to create an entity.
* @return the entity based on given object.
*/
protected abstract M importDto(T record);
protected abstract void save(M record);
}
|
package org.projectspinoza.twitterswissarmyknife.command;
import java.io.FileWriter;
import java.io.IOException;
import org.projectspinoza.twitterswissarmyknife.util.TsakResponse;
import twitter4j.AccountSettings;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import com.beust.jcommander.Parameters;
import com.google.gson.Gson;
@Parameters(commandNames = "dumpAccountSettings", commandDescription = "Account Setting")
public class CommandDumpAccountSettings extends BaseCommand {
@Override
public TsakResponse execute(Twitter twitter) throws TwitterException {
int remApiLimits = 0;
AccountSettings settings = twitter.getAccountSettings();
remApiLimits = settings.getRateLimitStatus().getRemaining();
TsakResponse tsakResponse = new TsakResponse(remApiLimits, settings);
tsakResponse.setCommandDetails(this.toString());
return tsakResponse;
}
@Override
public void write(TsakResponse tsakResponse, FileWriter writer) throws IOException {
String jsonSettings = new Gson().toJson(tsakResponse);
writer.append(jsonSettings);
}
@Override
public String toString() {
return "CommandDumpAccountSettings []";
}
}
|
package org.sagebionetworks.web.client.widget.entity;
import java.util.ArrayList;
import java.util.List;
import org.sagebionetworks.repo.model.AccessRequirement;
import org.sagebionetworks.repo.model.TermsOfUseAccessRequirement;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.web.client.SynapseClientAsync;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.transform.NodeModelCreator;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.utils.CallbackP;
import org.sagebionetworks.web.client.utils.GovernanceServiceHelper;
import org.sagebionetworks.web.shared.PaginatedResults;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
/**
* Widget for displaying the access requirements associated with an entity
*/
public class EntityAccessRequirementsWidget implements EntityAccessRequirementsWidgetView.Presenter {
private EntityAccessRequirementsWidgetView view;
private SynapseClientAsync synapseClient;
private AuthenticationController authenticationController;
private NodeModelCreator nodeModelCreator;
private JSONObjectAdapter jsonObjectAdapter;
private String entityId;
private CallbackP<Boolean> mainCallback;
private List<AccessRequirement> accessRequirements;
private int currentAccessRequirement;
@Inject
public EntityAccessRequirementsWidget(EntityAccessRequirementsWidgetView view,
SynapseClientAsync synapseClient,
AuthenticationController authenticationController,
NodeModelCreator nodeModelCreator,
JSONObjectAdapter jsonObjectAdapter
) {
this.view = view;
view.setPresenter(this);
this.synapseClient = synapseClient;
this.authenticationController = authenticationController;
this.nodeModelCreator = nodeModelCreator;
this.jsonObjectAdapter = jsonObjectAdapter;
}
/**
* @param entityId ask for access requirements associated with this entity id
* @param acceptedAllCallback Will callback with true if all ARs have been accepted
*/
public void showUploadAccessRequirements(String entityId, CallbackP<Boolean> acceptedAllCallback) {
this.mainCallback = acceptedAllCallback;
this.entityId = entityId;
//ask for access requirements of the specified type and show them
showAccessRequirementsStep1();
};
//first, check if logged in
public void showAccessRequirementsStep1() {
currentAccessRequirement = 0;
accessRequirements = new ArrayList<AccessRequirement>();
boolean isLoggedIn = authenticationController.isLoggedIn();
if (isLoggedIn) {
showAccessRequirementsStep2();
} else {
//not logged in
mainCallback.invoke(false);
}
}
public void showAccessRequirementsStep2() {
synapseClient.getAllEntityUploadAccessRequirements(entityId, new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
//are there access restrictions?
try{
PaginatedResults<AccessRequirement> ar = nodeModelCreator.createPaginatedResults(result, TermsOfUseAccessRequirement.class);
accessRequirements = ar.getResults();
//if there's anything to show, then show the wizard
if (accessRequirements.size() > 0)
view.showWizard();
showAccessRequirementsStep3();
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable caught) {
view.showErrorMessage(caught.getMessage());
mainCallback.invoke(false);
}
});
}
/**
* The access requirements have been set. Show them until we're finished
*/
public void showAccessRequirementsStep3() {
if (currentAccessRequirement >= accessRequirements.size()) {
//done showing access requirements
view.hideWizard();
mainCallback.invoke(true);
} else {
final AccessRequirement accessRequirement = accessRequirements.get(currentAccessRequirement);
String text = GovernanceServiceHelper.getAccessRequirementText(accessRequirement);
Callback termsOfUseCallback = new Callback() {
@Override
public void invoke() {
//agreed to terms of use.
currentAccessRequirement++;
setLicenseAccepted(accessRequirement.getId());
}
};
//pop up the requirement
view.updateWizardProgress(currentAccessRequirement, accessRequirements.size());
view.showAccessRequirement(text, termsOfUseCallback);
}
}
@Override
public void wizardCanceled() {
mainCallback.invoke(false);
}
public void setLicenseAccepted(Long arId) {
final CallbackP<Throwable> onFailure = new CallbackP<Throwable>() {
@Override
public void invoke(Throwable t) {
view.showErrorMessage(t.getMessage());
mainCallback.invoke(false);
}
};
Callback onSuccess = new Callback() {
@Override
public void invoke() {
//AR accepted, continue
showAccessRequirementsStep3();
}
};
GovernanceServiceHelper.signTermsOfUse(
authenticationController.getCurrentUserPrincipalId(),
arId,
onSuccess,
onFailure,
synapseClient,
jsonObjectAdapter);
}
public void clear() {
view.clear();
}
public Widget asWidget() {
view.setPresenter(this);
return view.asWidget();
}
}
|
package uk.co.eluinhost.ultrahardcore.features.hardcorehearts;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.events.PacketListener;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.bukkit.plugin.Plugin;
import uk.co.eluinhost.configuration.ConfigManager;
import uk.co.eluinhost.ultrahardcore.features.UHCFeature;
@Singleton
public class HardcoreHeartsFeature extends UHCFeature {
private final ProtocolManager m_manager = ProtocolLibrary.getProtocolManager();
private final PacketListener m_listner;
/**
* Shows hardcore hearts in non hardcore worlds when enabled, requires protcollib
* @param plugin the plugin
* @param configManager the config manager
*/
@Inject
public HardcoreHeartsFeature(Plugin plugin, ConfigManager configManager) {
super(plugin, configManager);
m_listner = new HardcoreHeartsListener(plugin);
}
@Override
public void enableCallback(){
m_manager.addPacketListener(m_listner);
}
@Override
public void disableCallback(){
m_manager.removePacketListener(m_listner);
}
@Override
public String getFeatureID() {
return "HardcoreHearts";
}
@Override
public String getDescription() {
return "Shows the hardcore hearts instead";
}
private static class HardcoreHeartsListener extends PacketAdapter {
/**
* listens for login packets to edit
* @param bukkitPlugin the plugin
*/
HardcoreHeartsListener(Plugin bukkitPlugin){
//listen for login packets on the normal priority
super(bukkitPlugin,ListenerPriority.NORMAL,PacketType.Play.Server.LOGIN);
}
@Override
public void onPacketSending(PacketEvent event) {
//if its a login packet write the first boolean to true (hardcore flag)
if (event.getPacketType().equals(PacketType.Play.Server.LOGIN)) {
event.getPacket().getBooleans().write(0, true);
}
}
}
}
|
package railo.runtime.op;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import railo.commons.date.JREDateTimeUtil;
import railo.commons.date.TimeZoneUtil;
import railo.commons.io.FileUtil;
import railo.commons.io.IOUtil;
import railo.commons.io.SystemUtil;
import railo.commons.io.res.Resource;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.CFTypes;
import railo.commons.lang.ClassException;
import railo.commons.lang.ClassUtil;
import railo.commons.lang.StringUtil;
import railo.commons.net.HTTPUtil;
import railo.runtime.Component;
import railo.runtime.PageContext;
import railo.runtime.coder.Base64Coder;
import railo.runtime.coder.Coder;
import railo.runtime.coder.CoderException;
import railo.runtime.config.Config;
import railo.runtime.converter.ConverterException;
import railo.runtime.converter.ScriptConverter;
import railo.runtime.engine.ThreadLocalPageContext;
import railo.runtime.exp.CasterException;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.NativeException;
import railo.runtime.exp.PageException;
import railo.runtime.exp.PageExceptionBox;
import railo.runtime.ext.function.Function;
import railo.runtime.functions.file.FileStreamWrapper;
import railo.runtime.i18n.LocaleFactory;
import railo.runtime.img.Image;
import railo.runtime.interpreter.VariableInterpreter;
import railo.runtime.java.JavaObject;
import railo.runtime.op.date.DateCaster;
import railo.runtime.op.validators.ValidateCreditCard;
import railo.runtime.reflection.Reflector;
import railo.runtime.text.xml.XMLCaster;
import railo.runtime.text.xml.XMLUtil;
import railo.runtime.text.xml.struct.XMLMultiElementArray;
import railo.runtime.text.xml.struct.XMLMultiElementStruct;
import railo.runtime.text.xml.struct.XMLStruct;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.CollectionStruct;
import railo.runtime.type.FunctionValue;
import railo.runtime.type.FunctionValueImpl;
import railo.runtime.type.Iteratorable;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.ObjectWrap;
import railo.runtime.type.Objects;
import railo.runtime.type.Query;
import railo.runtime.type.QueryColumn;
import railo.runtime.type.QueryImpl;
import railo.runtime.type.Struct;
import railo.runtime.type.StructImpl;
import railo.runtime.type.UDF;
import railo.runtime.type.dt.DateTime;
import railo.runtime.type.dt.DateTimeImpl;
import railo.runtime.type.dt.TimeSpan;
import railo.runtime.type.dt.TimeSpanImpl;
import railo.runtime.type.scope.ObjectStruct;
import railo.runtime.type.util.ArrayUtil;
import railo.runtime.type.util.ComponentUtil;
import railo.runtime.type.wrap.ArrayAsList;
import railo.runtime.type.wrap.ListAsArray;
import railo.runtime.type.wrap.MapAsStruct;
import railo.runtime.util.ArrayIterator;
import railo.runtime.util.IteratorWrapper;
/**
* This class can cast object of one type to a other by CFML rules
*/
public final class Caster {
private Caster(){
}
//static Map calendarsMap=new ReferenceMap(ReferenceMap.SOFT,ReferenceMap.SOFT);
private static final int NUMBERS_MIN=0;
private static final int NUMBERS_MAX=999;
private static final String[] NUMBERS = {
"0","1","2","3","4","5","6","7","8","9",
"10","11","12","13","14","15","16","17","18","19",
"20","21","22","23","24","25","26","27","28","29",
"30","31","32","33","34","35","36","37","38","39",
"40","41","42","43","44","45","46","47","48","49",
"50","51","52","53","54","55","56","57","58","59",
"60","61","62","63","64","65","66","67","68","69",
"70","71","72","73","74","75","76","77","78","79",
"80","81","82","83","84","85","86","87","88","89",
"90","91","92","93","94","95","96","97","98","99",
"100","101","102","103","104","105","106","107","108","109",
"110","111","112","113","114","115","116","117","118","119",
"120","121","122","123","124","125","126","127","128","129",
"130","131","132","133","134","135","136","137","138","139",
"140","141","142","143","144","145","146","147","148","149",
"150","151","152","153","154","155","156","157","158","159",
"160","161","162","163","164","165","166","167","168","169",
"170","171","172","173","174","175","176","177","178","179",
"180","181","182","183","184","185","186","187","188","189",
"190","191","192","193","194","195","196","197","198","199",
"200","201","202","203","204","205","206","207","208","209",
"210","211","212","213","214","215","216","217","218","219",
"220","221","222","223","224","225","226","227","228","229",
"230","231","232","233","234","235","236","237","238","239",
"240","241","242","243","244","245","246","247","248","249",
"250","251","252","253","254","255","256","257","258","259",
"260","261","262","263","264","265","266","267","268","269",
"270","271","272","273","274","275","276","277","278","279",
"280","281","282","283","284","285","286","287","288","289",
"290","291","292","293","294","295","296","297","298","299",
"300","301","302","303","304","305","306","307","308","309",
"310","311","312","313","314","315","316","317","318","319",
"320","321","322","323","324","325","326","327","328","329",
"330","331","332","333","334","335","336","337","338","339",
"340","341","342","343","344","345","346","347","348","349",
"350","351","352","353","354","355","356","357","358","359",
"360","361","362","363","364","365","366","367","368","369",
"370","371","372","373","374","375","376","377","378","379",
"380","381","382","383","384","385","386","387","388","389",
"390","391","392","393","394","395","396","397","398","399",
"400","401","402","403","404","405","406","407","408","409",
"410","411","412","413","414","415","416","417","418","419",
"420","421","422","423","424","425","426","427","428","429",
"430","431","432","433","434","435","436","437","438","439",
"440","441","442","443","444","445","446","447","448","449",
"450","451","452","453","454","455","456","457","458","459",
"460","461","462","463","464","465","466","467","468","469",
"470","471","472","473","474","475","476","477","478","479",
"480","481","482","483","484","485","486","487","488","489",
"490","491","492","493","494","495","496","497","498","499",
"500","501","502","503","504","505","506","507","508","509",
"510","511","512","513","514","515","516","517","518","519",
"520","521","522","523","524","525","526","527","528","529",
"530","531","532","533","534","535","536","537","538","539",
"540","541","542","543","544","545","546","547","548","549",
"550","551","552","553","554","555","556","557","558","559",
"560","561","562","563","564","565","566","567","568","569",
"570","571","572","573","574","575","576","577","578","579",
"580","581","582","583","584","585","586","587","588","589",
"590","591","592","593","594","595","596","597","598","599",
"600","601","602","603","604","605","606","607","608","609",
"610","611","612","613","614","615","616","617","618","619",
"620","621","622","623","624","625","626","627","628","629",
"630","631","632","633","634","635","636","637","638","639",
"640","641","642","643","644","645","646","647","648","649",
"650","651","652","653","654","655","656","657","658","659",
"660","661","662","663","664","665","666","667","668","669",
"670","671","672","673","674","675","676","677","678","679",
"680","681","682","683","684","685","686","687","688","689",
"690","691","692","693","694","695","696","697","698","699",
"700","701","702","703","704","705","706","707","708","709",
"710","711","712","713","714","715","716","717","718","719",
"720","721","722","723","724","725","726","727","728","729",
"730","731","732","733","734","735","736","737","738","739",
"740","741","742","743","744","745","746","747","748","749",
"750","751","752","753","754","755","756","757","758","759",
"760","761","762","763","764","765","766","767","768","769",
"770","771","772","773","774","775","776","777","778","779",
"780","781","782","783","784","785","786","787","788","789",
"790","791","792","793","794","795","796","797","798","799",
"800","801","802","803","804","805","806","807","808","809",
"810","811","812","813","814","815","816","817","818","819",
"820","821","822","823","824","825","826","827","828","829",
"830","831","832","833","834","835","836","837","838","839",
"840","841","842","843","844","845","846","847","848","849",
"850","851","852","853","854","855","856","857","858","859",
"860","861","862","863","864","865","866","867","868","869",
"870","871","872","873","874","875","876","877","878","879",
"880","881","882","883","884","885","886","887","888","889",
"890","891","892","893","894","895","896","897","898","899",
"900","901","902","903","904","905","906","907","908","909",
"910","911","912","913","914","915","916","917","918","919",
"920","921","922","923","924","925","926","927","928","929",
"930","931","932","933","934","935","936","937","938","939",
"940","941","942","943","944","945","946","947","948","949",
"950","951","952","953","954","955","956","957","958","959",
"960","961","962","963","964","965","966","967","968","969",
"970","971","972","973","974","975","976","977","978","979",
"980","981","982","983","984","985","986","987","988","989",
"990","991","992","993","994","995","996","997","998","999"
};
/**
* cast a boolean value to a boolean value (do nothing)
* @param b boolean value to cast
* @return casted boolean value
*/
public static boolean toBooleanValue(boolean b) {
return b;
}
/**
* cast a int value to a boolean value (primitive value type)
* @param i int value to cast
* @return casted boolean value
*/
public static boolean toBooleanValue(int i) {
return i!=0;
}
/**
* cast a long value to a boolean value (primitive value type)
* @param l long value to cast
* @return casted boolean value
*/
public static boolean toBooleanValue(long l) {
return l!=0;
}
/**
* cast a double value to a boolean value (primitive value type)
* @param d double value to cast
* @return casted boolean value
*/
public static boolean toBooleanValue(double d) {
return d!=0;
}
/**
* cast a double value to a boolean value (primitive value type)
* @param c char value to cast
* @return casted boolean value
*/
public static boolean toBooleanValue(char c) {
return c!=0;
}
/**
* cast a Object to a boolean value (primitive value type)
* @param o Object to cast
* @return casted boolean value
* @throws PageException
*/
public static boolean toBooleanValue(Object o) throws PageException {
if(o instanceof Boolean) return ((Boolean)o).booleanValue();
else if(o instanceof Double) return toBooleanValue(((Double)o).doubleValue());
else if(o instanceof Number) return toBooleanValue(((Number)o).doubleValue());
else if(o instanceof String) return toBooleanValue((String)o);
else if(o instanceof Castable) return ((Castable)o).castToBooleanValue();
else if(o == null) return toBooleanValue("");
else if(o instanceof ObjectWrap) return toBooleanValue(((ObjectWrap)o).getEmbededObject());
throw new CasterException(o,"boolean");
}
/**
* tranlate a Boolean object to a boolean value
* @param b
* @return
*/
public static boolean toBooleanValue(Boolean b) {
return b.booleanValue();
}
/**
* cast a Object to a boolean value (primitive value type)
* @param str String to cast
* @return casted boolean value
* @throws PageException
*/
public static boolean toBooleanValue(String str) throws PageException {
Boolean b = toBoolean(str,null);
if(b!=null) return b.booleanValue();
throw new CasterException("Can't cast String ["+str+"] to a boolean");
}
public static Boolean toBoolean(String str, Boolean defaultValue) {
if(str==null) return defaultValue;
int i=stringToBooleanValueEL(str);
if(i!=-1) return (i==1)?Boolean.TRUE:Boolean.FALSE;
double d=toDoubleValue(str,Double.NaN);
if(!Double.isNaN(d)) return toBoolean(d);
return defaultValue;
}
/**
* cast a Object to a Double Object (reference Type)
* @param f Object to cast
* @return casted Double Object
* @throws PageException
*/
public static Double toDouble(float f) {
return new Double(f);
}
public static Double toDouble(Float f) {
return new Double(f.doubleValue());
}
/**
* cast a Object to a Double Object (reference Type)
* @param o Object to cast
* @return casted Double Object
* @throws PageException
*/
public static Double toDouble(Object o) throws PageException {
if(o instanceof Double) return (Double)o;
return new Double(toDoubleValue(o));
}
/**
* cast a Object to a Double Object (reference Type)
* @param str string to cast
* @return casted Double Object
* @throws PageException
*/
public static Double toDouble(String str) throws PageException {
return new Double(toDoubleValue(str));
}
/**
* cast a Object to a Double Object (reference Type)
* @param o Object to cast
* @param defaultValue
* @return casted Double Object
*/
public static Double toDouble(Object o, Double defaultValue) {
if(o instanceof Double) return (Double)o;
double dbl = toDoubleValue(o,Double.NaN);
if(Double.isNaN(dbl)) return defaultValue;
return new Double(dbl);
}
/**
* cast a double value to a Double Object (reference Type)
* @param d double value to cast
* @return casted Double Object
*/
private static final int MAX_SMALL_DOUBLE=10000;
private static final Double[] smallDoubles=new Double[MAX_SMALL_DOUBLE];
static {
for(int i=0;i<MAX_SMALL_DOUBLE;i++) smallDoubles[i]=new Double(i);
}
public static Double toDouble(double d) {
if(d<MAX_SMALL_DOUBLE && d>=0) {
int i;
if((i=((int)d))==d) return smallDoubles[i];
}
return new Double(d);
}
/**
* cast a boolean value to a Double Object (reference Type)
* @param b boolean value to cast
* @return casted Double Object
*/
public static Double toDouble(boolean b) {
return new Double(b?1:0);
}
/**
* cast a Object to a double value (primitive value Type)
* @param o Object to cast
* @return casted double value
* @throws PageException
*/
public static double toDoubleValue(Object o) throws PageException {
if(o instanceof Number) return ((Number)o).doubleValue();
else if(o instanceof Boolean) return ((Boolean)o).booleanValue()?1:0;
else if(o instanceof String) return toDoubleValue(o.toString(),true);
//else if(o instanceof Clob) return toDoubleValue(toString(o));
else if(o instanceof Castable) return ((Castable)o).castToDoubleValue();
else if(o == null) return 0;//toDoubleValue("");
else if(o instanceof ObjectWrap) return toDoubleValue(((ObjectWrap)o).getEmbededObject());
throw new CasterException(o,"number");
}
public static double toDoubleValue(Double d) {
if(d == null) return 0;
return d.doubleValue();
}
/**
* cast a Object to a double value (primitive value Type)
* @param str String to cast
* @return casted double value
* @throws CasterException
*/
public static double toDoubleValue(String str) throws CasterException {
return toDoubleValue(str,true);
}
public static double toDoubleValue(String str, boolean alsoFromDate) throws CasterException {
if(str==null) return 0;//throw new CasterException("can't cast empty string to a number value");
str=str.trim();
double rtn_=0;
double _rtn=0;
int eCount=0;
double deep=1;
int pos=0;
int len=str.length();
if(len==0) throw new CasterException("can't cast empty string to a number value");
char curr=str.charAt(pos);
boolean isMinus=false;
if(curr=='+') {
if(len==++pos) throw new CasterException("can't cast [+] string to a number value");
}
if(curr=='-') {
if(len==++pos) throw new CasterException("can't cast [-] string to a number value");
isMinus=true;
}
boolean hasDot=false;
//boolean hasExp=false;
do {
curr=str.charAt(pos);
if(curr<'0') {
if(curr=='.') {
if(hasDot) {
if(!alsoFromDate) throw new CasterException("cannot cast ["+str+"] string to a number value");
return toDoubleValueViaDate(str);
}
hasDot=true;
}
else {
if(pos==0 && Decision.isBoolean(str)) return toBooleanValue(str,false)?1.0D:0.0D;
if(!alsoFromDate) throw new CasterException("cannot cast ["+str+"] string to a number value");
return toDoubleValueViaDate(str);
//throw new CasterException("can't cast ["+str+"] string to a number value");
}
}
else if(curr>'9') {
if(curr == 'e' || curr == 'E') {
try{
return Double.parseDouble(str);
}
catch( NumberFormatException e){
if(!alsoFromDate) throw new CasterException("cannot cast ["+str+"] string to a number value");
return toDoubleValueViaDate(str);
//throw new CasterException("can't cast ["+str+"] string to a number value");
}
}
//else {
if(pos==0 && Decision.isBoolean(str)) return toBooleanValue(str,false)?1.0D:0.0D;
if(!alsoFromDate) throw new CasterException("cannot cast ["+str+"] string to a number value");
return toDoubleValueViaDate(str);
//throw new CasterException("can't cast ["+str+"] string to a number value");
}
else if(!hasDot) {
rtn_*=10;
rtn_+=toDigit(curr);
}
/*else if(hasExp) {
eCount*=10;
eCount+=toDigit(curr);
}*/
else {
deep*=10;
_rtn*=10;
_rtn+=toDigit(curr);
//rtn_+=(toDigit(curr)/deep);
//deep*=10;
}
}
while(++pos<len);
if(deep>1) {
rtn_+=(_rtn/=deep);
}
if(isMinus)rtn_= -rtn_;
if(eCount>0)for(int i=0;i<eCount;i++)rtn_*=10;
return rtn_;
}
private static double toDoubleValueViaDate(String str) throws CasterException {
DateTime date = DateCaster.toDateSimple(str, false,false, null, null);// not advanced here, neo also only support simple
if(date==null)throw new CasterException("can't cast ["+str+"] string to a number value");
return date.castToDoubleValue(0);
}
private static double toDoubleValueViaDate(String str,double defaultValue) {
DateTime date = DateCaster.toDateSimple(str, false,false, null, null);// not advanced here, neo also only support simple
if(date==null)return defaultValue;
return date.castToDoubleValue(0);
}
/**
* cast a Object to a double value (primitive value Type)
* @param o Object to cast
* @param defaultValue if can't cast return this value
* @return casted double value
*/
public static double toDoubleValue(Object o,double defaultValue) {
if(o instanceof Number) return ((Number)o).doubleValue();
else if(o instanceof Boolean) return ((Boolean)o).booleanValue()?1:0;
else if(o instanceof String) return toDoubleValue(o.toString(),defaultValue);
else if(o instanceof Castable) {
return ((Castable)o).castToDoubleValue(defaultValue);
}
//else if(o == null) return defaultValue;
else if(o instanceof ObjectWrap) return toDoubleValue(((ObjectWrap)o).getEmbededObject(new Double(defaultValue)),defaultValue);
return defaultValue;
}
/**
* cast a Object to a double value (primitive value Type), if can't return Double.NaN
* @param str String to cast
* @param defaultValue if can't cast return this value
* @return casted double value
*/
public static double toDoubleValue(String str,double defaultValue) {
return toDoubleValue(str, true,defaultValue);
}
public static double toDoubleValue(String str,boolean alsoFromDate,double defaultValue) {
if(str==null) return defaultValue;
str=str.trim();
int len=str.length();
if(len==0) return defaultValue;
double rtn_=0;
double _rtn=0;
int eCount=0;
// double deep=10;
double deep=1;
int pos=0;
char curr=str.charAt(pos);
boolean isMinus=false;
if(curr=='+') {
if(len==++pos) return defaultValue;
}
else if(curr=='-') {
if(len==++pos) return defaultValue;
isMinus=true;
}
boolean hasDot=false;
//boolean hasExp=false;
do {
curr=str.charAt(pos);
if(curr<'0') {
if(curr=='.') {
if(hasDot) {
if(!alsoFromDate) return defaultValue;
return toDoubleValueViaDate(str,defaultValue);
}
hasDot=true;
}
else {
if(pos==0 && Decision.isBoolean(str)) return toBooleanValue(str,false)?1.0D:0.0D;
if(!alsoFromDate) return defaultValue;
return toDoubleValueViaDate(str,defaultValue);
}
}
else if(curr>'9') {
if(curr=='e' || curr=='E') {
try{
return Double.parseDouble(str);
}
catch( NumberFormatException e){
if(!alsoFromDate) return defaultValue;
return toDoubleValueViaDate(str,defaultValue);
}
}
//else {
if(pos==0 && Decision.isBoolean(str)) return toBooleanValue(str,false)?1.0D:0.0D;
if(!alsoFromDate) return defaultValue;
return toDoubleValueViaDate(str,defaultValue);
}
else if(!hasDot) {
rtn_*=10;
rtn_+=toDigit(curr);
}
/*else if(hasExp) {
eCount*=10;
eCount+=toDigit(curr);
}*/
else {
deep*=10;
_rtn*=10;
_rtn+=toDigit(curr);
}
}
while(++pos<len);
if(deep>1) {
rtn_+=(_rtn/=deep);
}
if(isMinus)rtn_= -rtn_;
if(eCount>0)for(int i=0;i<eCount;i++)rtn_*=10;
return rtn_;
}
private static int toDigit(char c) {
return c-48;
}
/**
* cast a double value to a double value (do nothing)
* @param d double value to cast
* @return casted double value
*/
public static double toDoubleValue(double d) {
return d;
}
public static double toDoubleValue(float f) {
return f;
}
public static double toDoubleValue(Float f) {
return f.doubleValue();
}
/**
* cast a boolean value to a double value (primitive value type)
* @param b boolean value to cast
* @return casted double value
*/
public static double toDoubleValue(boolean b) {
return b?1:0;
}
/**
* cast a char value to a double value (primitive value type)
* @param c char value to cast
* @return casted double value
*/
public static double toDoubleValue(char c) {
return c;
}
/**
* cast a Object to a int value (primitive value type)
* @param o Object to cast
* @return casted int value
* @throws PageException
*/
public static int toIntValue(Object o) throws PageException {
if(o instanceof Number) return ((Number)o).intValue();
else if(o instanceof Boolean) return ((Boolean)o).booleanValue()?1:0;
else if(o instanceof String) return toIntValue(o.toString().trim());
//else if(o instanceof Clob) return toIntValue(toString(o));
else if(o instanceof Castable) return (int)((Castable)o).castToDoubleValue();
else if(o instanceof Date) return (int)new DateTimeImpl((Date)o).castToDoubleValue();
if(o instanceof String)
throw new ExpressionException("Can't cast String ["+o.toString()+"] to a number");
else if(o instanceof ObjectWrap) return toIntValue(((ObjectWrap)o).getEmbededObject());
throw new CasterException(o,"number");
}
/**
* cast a Object to a int value (primitive value type)
* @param o Object to cast
* @param defaultValue
* @return casted int value
*/
public static int toIntValue(Object o, int defaultValue) {
if(o instanceof Number) return ((Number)o).intValue();
else if(o instanceof Boolean) return ((Boolean)o).booleanValue()?1:0;
else if(o instanceof String) return toIntValue(o.toString().trim(),defaultValue);
//else if(o instanceof Clob) return toIntValue(toString(o));
else if(o instanceof Castable) {
return (int)((Castable)o).castToDoubleValue(defaultValue);
}
else if(o instanceof Date) return (int)new DateTimeImpl((Date)o).castToDoubleValue();
else if(o instanceof ObjectWrap) return toIntValue(((ObjectWrap)o).getEmbededObject(Integer.valueOf(defaultValue)),defaultValue);
return defaultValue;
}
/**
* cast a String to a int value (primitive value type)
* @param str String to cast
* @return casted int value
* @throws ExpressionException
*/
public static int toIntValue(String str) throws ExpressionException {
return (int)toDoubleValue(str,false);
}
/**
* cast a Object to a double value (primitive value Type), if can't return Integer.MIN_VALUE
* @param str String to cast
* @param defaultValue
* @return casted double value
*/
public static int toIntValue(String str, int defaultValue) {
return (int)toDoubleValue(str,false,defaultValue);
}
/**
* cast a double value to a int value (primitive value type)
* @param d double value to cast
* @return casted int value
*/
public static int toIntValue(double d) {
return (int)d;
}
/**
* cast a int value to a int value (do nothing)
* @param i int value to cast
* @return casted int value
*/
public static int toIntValue(int i) {
return i;
}
/**
* cast a boolean value to a int value (primitive value type)
* @param b boolean value to cast
* @return casted int value
*/
public static int toIntValue(boolean b) {
return b?1:0;
}
/**
* cast a char value to a int value (primitive value type)
* @param c char value to cast
* @return casted int value
*/
public static int toIntValue(char c) {
return c;
}
/**
* cast a double to a decimal value (String:xx.xx)
* @param value Object to cast
* @return casted decimal value
*/
public static String toDecimal(boolean value) {
if(value) return "1.00";
return "0.00";
}
/**
* cast a double to a decimal value (String:xx.xx)
* @param value Object to cast
* @return casted decimal value
* @throws PageException
*/
public static String toDecimal(Object value) throws PageException {
return toDecimal(Caster.toDoubleValue(value));
}
/**
* cast a double to a decimal value (String:xx.xx)
* @param value Object to cast
* @return casted decimal value
* @throws PageException
*/
public static String toDecimal(String value) throws PageException {
return toDecimal(Caster.toDoubleValue(value));
}
/**
* cast a double to a decimal value (String:xx.xx)
* @param value Object to cast
* @param defaultValue
* @return casted decimal value
*/
public static String toDecimal(Object value, String defaultValue) {
double res=toDoubleValue(value,Double.NaN);
if(Double.isNaN(res)) return defaultValue;
return toDecimal(res);
}
/**
* cast a Oject to a decimal value (String:xx.xx)
* @param value Object to cast
* @return casted decimal value
*/
public static String toDecimal(double value) {
return toDecimal(value,'.',',');
}
private static String toDecimal(double value,char decDel,char thsDel) {
// TODO Caster toDecimal bessere impl.
String str=new BigDecimal((StrictMath.round(value*100)/100D)).toString();
//str=toDouble(value).toString();
String[] arr=str.split("\\.");
//right value
String rightValue;
if(arr.length==1) {
rightValue="00";
}
else {
rightValue=arr[1];
rightValue=StrictMath.round(Caster.toDoubleValue("0."+rightValue,0)*100)+"";
if(rightValue.length()<2)rightValue=0+rightValue;
}
// left value
String leftValue=arr[0];
int leftValueLen=leftValue.length();
int ends=(StringUtil.startsWith(str, '-'))?1:0;
if(leftValueLen>3) {
StringBuffer tmp=new StringBuffer();
int i;
for(i=leftValueLen-3;i>0;i-=3) {
tmp.insert(0, leftValue.substring(i,i+3));
if(i!=ends)tmp.insert(0,thsDel);
}
tmp.insert(0, leftValue.substring(0,i+3));
leftValue=tmp.toString();
}
return leftValue+decDel+rightValue;
}
/*public static void main(String[] args) {
print.out(toDecimal(12));
print.out(toDecimal(123));
print.out(toDecimal(1234));
print.out(toDecimal(12345));
print.out(toDecimal(123456));
print.out(toDecimal(-12));
print.out(toDecimal(-123));
print.out(toDecimal(-1234));
print.out(toDecimal(-12345));
print.out(toDecimal(-123456));
}*/
/**
* cast a boolean value to a Boolean Object(reference type)
* @param b boolean value to cast
* @return casted Boolean Object
*/
public static Boolean toBoolean(boolean b) {
return b?Boolean.TRUE:Boolean.FALSE;
}
/**
* cast a char value to a Boolean Object(reference type)
* @param c char value to cast
* @return casted Boolean Object
*/
public static Boolean toBoolean(char c) {
return c!=0?Boolean.TRUE:Boolean.FALSE;
}
/**
* cast a int value to a Boolean Object(reference type)
* @param i int value to cast
* @return casted Boolean Object
*/
public static Boolean toBoolean(int i) {
return i!=0?Boolean.TRUE:Boolean.FALSE;
}
/**
* cast a long value to a Boolean Object(reference type)
* @param l long value to cast
* @return casted Boolean Object
*/
public static Boolean toBoolean(long l) {
return l!=0?Boolean.TRUE:Boolean.FALSE;
}
/**
* cast a double value to a Boolean Object(reference type)
* @param d double value to cast
* @return casted Boolean Object
*/
public static Boolean toBoolean(double d) {
return d!=0?Boolean.TRUE:Boolean.FALSE;
}
/**
* cast a Object to a Boolean Object(reference type)
* @param o Object to cast
* @return casted Boolean Object
* @throws PageException
*/
public static Boolean toBoolean(Object o) throws PageException {
if(o instanceof Boolean) return (Boolean)o;
return toBooleanValue(o)?Boolean.TRUE:Boolean.FALSE;
}
/**
* cast a Object to a Boolean Object(reference type)
* @param str String to cast
* @return casted Boolean Object
* @throws PageException
*/
public static Boolean toBoolean(String str) throws PageException {
return toBooleanValue(str)?Boolean.TRUE:Boolean.FALSE;
}
/**
* cast a Object to a boolean value (primitive value type), Exception Less
* @param o Object to cast
* @param defaultValue
* @return casted boolean value
*/
public static boolean toBooleanValue(Object o, boolean defaultValue) {
if(o instanceof Boolean) return ((Boolean)o).booleanValue();
else if(o instanceof Double) return toBooleanValue(((Double)o).doubleValue());
else if(o instanceof Number) return toBooleanValue(((Number)o).doubleValue());
else if(o instanceof String) {
Boolean b = toBoolean(o.toString(),null);
if(b!=null) return b;
}
//else if(o instanceof Clob) return toBooleanValueEL(toStringEL(o));
else if(o instanceof Castable) {
return ((Castable)o).castToBoolean(Caster.toBoolean(defaultValue)).booleanValue();
}
else if(o == null) return toBooleanValue("",defaultValue);
else if(o instanceof ObjectWrap) return toBooleanValue(((ObjectWrap)o).getEmbededObject(toBoolean(defaultValue)),defaultValue);
return defaultValue;
}
/**
* cast a Object to a boolean value (refrence type), Exception Less
* @param o Object to cast
* @param defaultValue default value
* @return casted boolean reference
*/
public static Boolean toBoolean(Object o,Boolean defaultValue) {
if(o instanceof Boolean) return ((Boolean)o);
else if(o instanceof Number) return ((Number)o).intValue()==0?Boolean.FALSE:Boolean.TRUE;
else if(o instanceof String) {
int rtn=stringToBooleanValueEL(o.toString());
if(rtn==1)return Boolean.TRUE;
else if(rtn==0)return Boolean.FALSE;
else {
double dbl = toDoubleValue(o.toString(),Double.NaN);
if(!Double.isNaN(dbl)) return toBooleanValue(dbl)?Boolean.TRUE:Boolean.FALSE;
}
}
//else if(o instanceof Clob) return toBooleanValueEL(toStringEL(o));
else if(o instanceof Castable) {
return ((Castable)o).castToBoolean(defaultValue);
}
else if(o instanceof ObjectWrap) return toBoolean(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
else if(o == null) return toBoolean("",defaultValue);
return defaultValue;
}
/**
* cast a boolean value to a char value
* @param b boolean value to cast
* @return casted char value
*/
public static char toCharValue(boolean b) {
return (char)(b?1:0);
}
/**
* cast a double value to a char value (primitive value type)
* @param d double value to cast
* @return casted char value
*/
public static char toCharValue(double d) {
return (char)d;
}
/**
* cast a char value to a char value (do nothing)
* @param c char value to cast
* @return casted char value
*/
public static char toCharValue(char c) {
return c;
}
/**
* cast a Object to a char value (primitive value type)
* @param o Object to cast
* @return casted char value
* @throws PageException
*/
public static char toCharValue(Object o) throws PageException {
if(o instanceof Character) return ((Character)o).charValue();
else if(o instanceof Boolean) return (char)((((Boolean)o).booleanValue())?1:0);
else if(o instanceof Double) return (char)(((Double)o).doubleValue());
else if(o instanceof Number) return (char)(((Number)o).doubleValue());
else if(o instanceof String) {
String str = o.toString();
if(str.length()>0)return str.charAt(0);
throw new ExpressionException("can't cast empty string to a char");
}
else if(o instanceof ObjectWrap) {
return toCharValue(((ObjectWrap)o).getEmbededObject());
}
else if(o == null) return toCharValue("");
throw new CasterException(o,"char");
}
/**
* cast a Object to a char value (primitive value type)
* @param str Object to cast
* @return casted char value
* @throws PageException
*/
public static char toCharValue(String str) throws PageException {
if(str.length()>0)return str.charAt(0);
throw new ExpressionException("can't cast empty string to a char");
}
/**
* cast a Object to a char value (primitive value type)
* @param o Object to cast
* @param defaultValue
* @return casted char value
*/
public static char toCharValue(Object o, char defaultValue) {
if(o instanceof Character) return ((Character)o).charValue();
else if(o instanceof Boolean) return (char)((((Boolean)o).booleanValue())?1:0);
else if(o instanceof Double) return (char)(((Double)o).doubleValue());
else if(o instanceof Number) return (char)(((Number)o).doubleValue());
else if(o instanceof String) {
String str = o.toString();
if(str.length()>0)return str.charAt(0);
return defaultValue;
}
else if(o instanceof ObjectWrap) {
return toCharValue(((ObjectWrap)o).getEmbededObject(toCharacter(defaultValue)),defaultValue);
}
else if(o == null) return toCharValue("",defaultValue);
return defaultValue;
}
/**
* cast a boolean value to a Character Object(reference type)
* @param b boolean value to cast
* @return casted Character Object
*/
public static Character toCharacter(boolean b) {
return new Character(toCharValue(b));
}
/**
* cast a char value to a Character Object(reference type)
* @param c char value to cast
* @return casted Character Object
*/
public static Character toCharacter(char c) {
return new Character(toCharValue(c));
}
/**
* cast a double value to a Character Object(reference type)
* @param d double value to cast
* @return casted Character Object
*/
public static Character toCharacter(double d) {
return new Character(toCharValue(d));
}
/**
* cast a Object to a Character Object(reference type)
* @param o Object to cast
* @return casted Character Object
* @throws PageException
*/
public static Character toCharacter(Object o) throws PageException {
if(o instanceof Character) return (Character)o;
return new Character(toCharValue(o));
}
/**
* cast a Object to a Character Object(reference type)
* @param str Object to cast
* @return casted Character Object
* @throws PageException
*/
public static Character toCharacter(String str) throws PageException {
return new Character(toCharValue(str));
}
/**
* cast a Object to a Character Object(reference type)
* @param o Object to cast
* @param defaultValue
* @return casted Character Object
*/
public static Character toCharacter(Object o, Character defaultValue) {
if(o instanceof Character) return (Character)o;
if(defaultValue!=null)return new Character(toCharValue(o,defaultValue.charValue()));
char res = toCharValue(o,Character.MIN_VALUE);
if(res==Character.MIN_VALUE) return defaultValue;
return new Character(res);
}
/**
* cast a boolean value to a byte value
* @param b boolean value to cast
* @return casted byte value
*/
public static byte toByteValue(boolean b) {
return (byte)(b?1:0);
}
/**
* cast a double value to a byte value (primitive value type)
* @param d double value to cast
* @return casted byte value
*/
public static byte toByteValue(double d) {
return (byte)d;
}
/**
* cast a char value to a byte value (do nothing)
* @param c char value to cast
* @return casted byte value
*/
public static byte toByteValue(char c) {
return (byte)c;
}
/**
* cast a Object to a byte value (primitive value type)
* @param o Object to cast
* @return casted byte value
* @throws PageException
* @throws CasterException
*/
public static byte toByteValue(Object o) throws PageException {
if(o instanceof Byte) return ((Byte)o).byteValue();
if(o instanceof Character) return (byte)(((Character)o).charValue());
else if(o instanceof Boolean) return (byte)((((Boolean)o).booleanValue())?1:0);
else if(o instanceof Number) return (((Number)o).byteValue());
else if(o instanceof String) return (byte)toDoubleValue(o.toString());
else if(o instanceof ObjectWrap) {
return toByteValue(((ObjectWrap)o).getEmbededObject());
}
throw new CasterException(o,"byte");
}
/**
* cast a Object to a byte value (primitive value type)
* @param str Object to cast
* @return casted byte value
* @throws PageException
* @throws CasterException
*/
public static byte toByteValue(String str) throws PageException {
return (byte)toDoubleValue(str.toString());
}
/**
* cast a Object to a byte value (primitive value type)
* @param o Object to cast
* @param defaultValue
* @return casted byte value
*/
public static byte toByteValue(Object o, byte defaultValue) {
if(o instanceof Byte) return ((Byte)o).byteValue();
if(o instanceof Character) return (byte)(((Character)o).charValue());
else if(o instanceof Boolean) return (byte)((((Boolean)o).booleanValue())?1:0);
else if(o instanceof Number) return (((Number)o).byteValue());
else if(o instanceof String) return (byte)toDoubleValue(o.toString(),defaultValue);
else if(o instanceof ObjectWrap) {
return toByteValue(((ObjectWrap)o).getEmbededObject(toByte(defaultValue)),defaultValue);
}
return defaultValue;
}
/**
* cast a boolean value to a Byte Object(reference type)
* @param b boolean value to cast
* @return casted Byte Object
*/
public static Byte toByte(boolean b) {
return new Byte(toByteValue(b));
}
/**
* cast a char value to a Byte Object(reference type)
* @param c char value to cast
* @return casted Byte Object
*/
public static Byte toByte(char c) {
return new Byte(toByteValue(c));
}
/**
* cast a double value to a Byte Object(reference type)
* @param d double value to cast
* @return casted Byte Object
*/
public static Byte toByte(double d) {
return new Byte(toByteValue(d));
}
/**
* cast a Object to a Byte Object(reference type)
* @param o Object to cast
* @return casted Byte Object
* @throws PageException
*/
public static Byte toByte(Object o) throws PageException {
if(o instanceof Byte) return (Byte)o;
return new Byte(toByteValue(o));
}
/**
* cast a Object to a Byte Object(reference type)
* @param str String to cast
* @return casted Byte Object
* @throws PageException
*/
public static Byte toByte(String str) throws PageException {
return new Byte(toByteValue(str));
}
/**
* cast a Object to a Byte Object(reference type)
* @param o Object to cast
* @param defaultValue
* @return casted Byte Object
*/
public static Byte toByte(Object o, Byte defaultValue) {
if(o instanceof Byte) return (Byte)o;
if(defaultValue!=null) return new Byte(toByteValue(o,defaultValue.byteValue()));
byte res=toByteValue(o,Byte.MIN_VALUE);
if(res==Byte.MIN_VALUE) return defaultValue;
return new Byte(res);
}
/**
* cast a boolean value to a long value
* @param b boolean value to cast
* @return casted long value
*/
public static long toLongValue(boolean b) {
return (b?1L:0L);
}
/**
* cast a double value to a long value (primitive value type)
* @param d double value to cast
* @return casted long value
*/
public static long toLongValue(double d) {
return (long)d;
}
/**
* cast a char value to a long value (do nothing)
* @param c char value to cast
* @return casted long value
*/
public static long toLongValue(char c) {
return c;
}
/**
* cast a Object to a long value (primitive value type)
* @param o Object to cast
* @return casted long value
* @throws PageException
*/
public static long toLongValue(Object o) throws PageException {
if(o instanceof Character) return (((Character)o).charValue());
else if(o instanceof Boolean) return ((((Boolean)o).booleanValue())?1L:0L);
else if(o instanceof Number) return (((Number)o).longValue());
else if(o instanceof String) {
String str=(String)o;
try{
return Long.parseLong(str);
}
catch(NumberFormatException nfe){
return (long)toDoubleValue(str);
}
}
else if(o instanceof Castable) return (long)((Castable)o).castToDoubleValue();
else if(o instanceof ObjectWrap) return toLongValue(((ObjectWrap)o).getEmbededObject());
throw new CasterException(o,"long");
}
/**
* cast a Object to a long value (primitive value type)
* @param str Object to cast
* @return casted long value
* @throws PageException
*/
public static long toLongValue(String str) throws PageException {
return (long)toDoubleValue(str);
}
/**
* cast a Object to a long value (primitive value type)
* @param o Object to cast
* @param defaultValue
* @return casted long value
*/
public static long toLongValue(Object o, long defaultValue) {
if(o instanceof Character) return (((Character)o).charValue());
else if(o instanceof Boolean) return ((((Boolean)o).booleanValue())?1L:0L);
else if(o instanceof Number) return (((Number)o).longValue());
else if(o instanceof String) return (long)toDoubleValue(o.toString(),defaultValue);
else if(o instanceof Castable) {
return (long)((Castable)o).castToDoubleValue(defaultValue);
}
else if(o instanceof ObjectWrap) return toLongValue(((ObjectWrap)o).getEmbededObject(toLong(defaultValue)),defaultValue);
return defaultValue;
}
/**
* cast a boolean value to a Long Object(reference type)
* @param b boolean value to cast
* @return casted Long Object
*/
public static Long toLong(boolean b) {
return Long.valueOf(toLongValue(b));
}
/**
* cast a char value to a Long Object(reference type)
* @param c char value to cast
* @return casted Long Object
*/
public static Long toLong(char c) {
return Long.valueOf(toLongValue(c));
}
/**
* cast a double value to a Long Object(reference type)
* @param d double value to cast
* @return casted Long Object
*/
public static Long toLong(double d) {
return Long.valueOf(toLongValue(d));
}
/**
* cast a Object to a Long Object(reference type)
* @param o Object to cast
* @return casted Long Object
* @throws PageException
*/
public static Long toLong(Object o) throws PageException {
if(o instanceof Long) return (Long)o;
return Long.valueOf(toLongValue(o));
}
/**
* cast a Object to a Long Object(reference type)
* @param str Object to cast
* @return casted Long Object
* @throws PageException
*/
public static Long toLong(String str) throws PageException {
return Long.valueOf(toLongValue(str));
}
/**
* cast a long to a Long Object(reference type)
* @param l long to cast
* @return casted Long Object
*/
public static Long toLong(long l) {
return Long.valueOf(l);
}
/**
* cast a Object to a Long Object(reference type)
* @param o Object to cast
* @param defaultValue
* @return casted Long Object
*/
public static Long toLong(Object o, Long defaultValue) {
if(o instanceof Long) return (Long)o;
if(defaultValue!=null) return Long.valueOf(toLongValue(o,defaultValue.longValue()));
long res=toLongValue(o,Long.MIN_VALUE);
if(res==Long.MIN_VALUE) return defaultValue;
return Long.valueOf(res);
}
/**
* cast a boolean value to a Float Object(reference type)
* @param b boolean value to cast
* @return casted Float Object
*/
public static Float toFloat(boolean b) {
return new Float(toFloatValue(b));
}
/**
* cast a char value to a Float Object(reference type)
* @param c char value to cast
* @return casted Float Object
*/
public static Float toFloat(char c) {
return new Float(toFloatValue(c));
}
/**
* cast a double value to a Float Object(reference type)
* @param d double value to cast
* @return casted Float Object
*/
public static Float toFloat(double d) {
return new Float(toFloatValue(d));
}
/**
* cast a Object to a Float Object(reference type)
* @param o Object to cast
* @return casted Float Object
* @throws PageException
*/
public static Float toFloat(Object o) throws PageException {
if(o instanceof Float) return (Float)o;
return new Float(toFloatValue(o));
}
/**
* cast a Object to a Float Object(reference type)
* @param str Object to cast
* @return casted Float Object
* @throws PageException
*/
public static Float toFloat(String str) throws PageException {
return new Float(toFloatValue(str));
}
/**
* cast a Object to a Float Object(reference type)
* @param o Object to cast
* @param defaultValue
* @return casted Float Object
*/
public static Float toFloat(Object o, Float defaultValue) {
if(o instanceof Float) return (Float)o;
if(defaultValue!=null) return new Float(toFloatValue(o,defaultValue.floatValue()));
float res=toFloatValue(o,Float.MIN_VALUE);
if(res==Float.MIN_VALUE) return defaultValue;
return new Float(res);
}
/**
* cast a boolean value to a float value
* @param b boolean value to cast
* @return casted long value
*/
public static float toFloatValue(boolean b) {
return (b?1F:0F);
}
/**
* cast a double value to a long value (primitive value type)
* @param d double value to cast
* @return casted long value
*/
public static float toFloatValue(double d) {
return (float)d;
}
/**
* cast a char value to a long value (do nothing)
* @param c char value to cast
* @return casted long value
*/
public static float toFloatValue(char c) {
return c;
}
/**
* cast a Object to a long value (primitive value type)
* @param o Object to cast
* @return casted long value
* @throws PageException
*/
public static float toFloatValue(Object o) throws PageException {
if(o instanceof Character) return (((Character)o).charValue());
else if(o instanceof Boolean) return ((((Boolean)o).booleanValue())?1F:0F);
else if(o instanceof Number) return (((Number)o).floatValue());
else if(o instanceof String) return (float)toDoubleValue(o.toString());
else if(o instanceof Castable) return (float)((Castable)o).castToDoubleValue();
else if(o instanceof ObjectWrap) return toFloatValue(((ObjectWrap)o).getEmbededObject());
throw new CasterException(o,"float");
}
/**
* cast a Object to a long value (primitive value type)
* @param str Object to cast
* @return casted long value
* @throws PageException
*/
public static float toFloatValue(String str) throws PageException {
return (float)toDoubleValue(str);
}
/**
* cast a Object to a float value (primitive value type)
* @param o Object to cast
* @param defaultValue
* @return casted float value
*/
public static float toFloatValue(Object o, float defaultValue) {
if(o instanceof Character) return (((Character)o).charValue());
else if(o instanceof Boolean) return ((((Boolean)o).booleanValue())?1F:0F);
else if(o instanceof Number) return (((Number)o).floatValue());
else if(o instanceof String) return (float)toDoubleValue(o.toString(),defaultValue);
else if(o instanceof Castable) {
return (float)((Castable)o).castToDoubleValue(defaultValue);
}
else if(o instanceof ObjectWrap) return toFloatValue(((ObjectWrap)o).getEmbededObject(toFloat(defaultValue)),defaultValue);
return defaultValue;
}
/**
* cast a boolean value to a short value
* @param b boolean value to cast
* @return casted short value
*/
public static short toShortValue(boolean b) {
return (short)(b?1:0);
}
/**
* cast a double value to a short value (primitive value type)
* @param d double value to cast
* @return casted short value
*/
public static short toShortValue(double d) {
return (short)d;
}
/**
* cast a char value to a short value (do nothing)
* @param c char value to cast
* @return casted short value
*/
public static short toShortValue(char c) {
return (short)c;
}
/**
* cast a Object to a short value (primitive value type)
* @param o Object to cast
* @return casted short value
* @throws PageException
*/
public static short toShortValue(Object o) throws PageException {
if(o instanceof Short) return ((Short)o).shortValue();
if(o instanceof Character) return (short)(((Character)o).charValue());
else if(o instanceof Boolean) return (short)((((Boolean)o).booleanValue())?1:0);
else if(o instanceof Number) return (((Number)o).shortValue());
else if(o instanceof String) return (short)toDoubleValue(o.toString());
else if(o instanceof Castable) return (short)((Castable)o).castToDoubleValue();
else if(o instanceof ObjectWrap) return toShortValue(((ObjectWrap)o).getEmbededObject());
throw new CasterException(o,"short");
}
/**
* cast a Object to a short value (primitive value type)
* @param str Object to cast
* @return casted short value
* @throws PageException
*/
public static short toShortValue(String str) throws PageException {
return (short)toDoubleValue(str);
}
/**
* cast a Object to a short value (primitive value type)
* @param o Object to cast
* @param defaultValue
* @return casted short value
*/
public static short toShortValue(Object o, short defaultValue) {
if(o instanceof Short) return ((Short)o).shortValue();
if(o instanceof Character) return (short)(((Character)o).charValue());
else if(o instanceof Boolean) return (short)((((Boolean)o).booleanValue())?1:0);
else if(o instanceof Number) return (((Number)o).shortValue());
else if(o instanceof String) return (short)toDoubleValue(o.toString(),defaultValue);
else if(o instanceof Castable) {
return (short)((Castable)o).castToDoubleValue(defaultValue);
}
else if(o instanceof ObjectWrap) return toShortValue(((ObjectWrap)o).getEmbededObject(toShort(defaultValue)),defaultValue);
return defaultValue;
}
/**
* cast a boolean value to a Short Object(reference type)
* @param b boolean value to cast
* @return casted Short Object
*/
public static Short toShort(boolean b) {
return Short.valueOf(toShortValue(b));
}
/**
* cast a char value to a Short Object(reference type)
* @param c char value to cast
* @return casted Short Object
*/
public static Short toShort(char c) {
return Short.valueOf(toShortValue(c));
}
/**
* cast a double value to a Byte Object(reference type)
* @param d double value to cast
* @return casted Byte Object
*/
public static Short toShort(double d) {
return Short.valueOf(toShortValue(d));
}
/**
* cast a Object to a Byte Object(reference type)
* @param o Object to cast
* @return casted Byte Object
* @throws PageException
*/
public static Short toShort(Object o) throws PageException {
if(o instanceof Short) return (Short)o;
return Short.valueOf(toShortValue(o));
}
/**
* cast a Object to a Byte Object(reference type)
* @param str Object to cast
* @return casted Byte Object
* @throws PageException
*/
public static Short toShort(String str) throws PageException {
return Short.valueOf(toShortValue(str));
}
/**
* cast a Object to a Byte Object(reference type)
* @param o Object to cast
* @param defaultValue
* @return casted Byte Object
*/
public static Short toShort(Object o, Short defaultValue) {
if(o instanceof Short) return (Short)o;
if(defaultValue!=null)return Short.valueOf(toShortValue(o,defaultValue.shortValue()));
short res=toShortValue(o,Short.MIN_VALUE);
if(res==Short.MIN_VALUE) return defaultValue;
return Short.valueOf(res);
}
/**
* cast a String to a boolean value (primitive value type)
* @param str String to cast
* @return casted boolean value
* @throws ExpressionException
*/
public static boolean stringToBooleanValue(String str) throws ExpressionException {
str=StringUtil.toLowerCase(str.trim());
if(str.equals("yes") || str.equals("true")) return true;
else if(str.equals("no") || str.equals("false")) return false;
throw new CasterException("Can't cast String ["+str+"] to boolean");
}
/**
* cast a String to a boolean value (primitive value type), return 1 for true, 0 for false and -1 if can't cast to a boolean type
* @param str String to cast
* @return casted boolean value
*/
public static int stringToBooleanValueEL(String str) {
if(str.length()<2) return -1;
switch(str.charAt(0)) {
case 't':
case 'T': return str.equalsIgnoreCase("true")?1:-1;
case 'f':
case 'F': return str.equalsIgnoreCase("false")?0:-1;
case 'y':
case 'Y': return str.equalsIgnoreCase("yes")?1:-1;
case 'n':
case 'N': return str.equalsIgnoreCase("no")?0:-1;
}
return -1;
}
/**
* cast a Object to a String
* @param o Object to cast
* @return casted String
* @throws PageException
*/
public static String toString(Object o) throws PageException {
if(o instanceof String) return (String)o;
else if(o instanceof Number) return toString(((Number)o).doubleValue());
else if(o instanceof Boolean) return toString(((Boolean)o).booleanValue());
else if(o instanceof Castable) return ((Castable)o).castToString();
else if(o instanceof Date) {
if(o instanceof DateTime) return ((DateTime)o).castToString();
return new DateTimeImpl((Date)o).castToString();
}
else if(o instanceof Clob) return toString((Clob)o);
else if(o instanceof Node) return XMLCaster.toString((Node)o);
else if(o instanceof Reader) {
Reader r=null;
try {
return IOUtil.toString(r=(Reader)o);
}
catch (IOException e) {
throw Caster.toPageException(e);
}
finally {
IOUtil.closeEL(r);
}
}
else if(o instanceof InputStream) {
Config config = ThreadLocalPageContext.getConfig();
InputStream r=null;
try {
return IOUtil.toString(r=(InputStream)o,config.getWebCharset());
}
catch (IOException e) {
throw Caster.toPageException(e);
}
finally {
IOUtil.closeEL(r);
}
}
else if(o instanceof byte[]) {
Config config = ThreadLocalPageContext.getConfig();
try {
return new String((byte[])o,config.getWebCharset());
} catch (Throwable t) {
return new String((byte[])o);
}
}
else if(o instanceof char[]) return new String((char[])o);
else if(o instanceof ObjectWrap) return toString(((ObjectWrap)o).getEmbededObject());
else if(o instanceof Calendar) return toString(((Calendar)o).getTime());
else if(o == null) return "";
// INFO Collection is new of type Castable
if(o instanceof Map || o instanceof List || o instanceof Function)
throw new CasterException(o,"string");
/*if((x instanceof Query) ||
(x instanceof RowSet) ||
(x instanceof coldfusion.runtime.Array) ||
(x instanceof JavaProxy) ||
(x instanceof FileStreamWrapper))
*/
return o.toString();
}
/**
* cast a String to a String (do Nothing)
* @param str
* @return casted String
* @throws PageException
*/
public static String toString(String str) {
return str;
}
public static StringBuffer toStringBuffer(Object obj) throws PageException {
if(obj instanceof StringBuffer) return (StringBuffer) obj;
return new StringBuffer(toString(obj));
}
public static Collection.Key toKey(Object o) throws CasterException {
return KeyImpl.toKey(o);
}
public static Collection.Key toKey(Object o,Collection.Key defaultValue) {
return KeyImpl.toKey(o, defaultValue);
}
/**
* cast a Object to a String dont throw a exception, if can't cast to a string return a empty string
* @param o Object to cast
* @param defaultValue
* @return casted String
*/
public static String toString(Object o,String defaultValue) {
if(o instanceof String) return (String)o;
else if(o instanceof Boolean) return toString(((Boolean)o).booleanValue());
else if(o instanceof Number) return toString(((Number)o).doubleValue());
else if(o instanceof Castable) return ((Castable)o).castToString(defaultValue);
else if(o instanceof Date) {
if(o instanceof DateTime) {
return ((DateTime)o).castToString(defaultValue);
}
return new DateTimeImpl((Date)o).castToString(defaultValue);
}
else if(o instanceof Clob) {
try {
return toString((Clob)o);
} catch (ExpressionException e) {
return defaultValue;
}
}
else if(o instanceof Node) {
try {
return XMLCaster.toString((Node)o);
} catch (PageException e) {
return defaultValue;
}
}
else if(o instanceof Map || o instanceof List || o instanceof Function) return defaultValue;
else if(o == null) return "";
else if(o instanceof ObjectWrap) return toString(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
return o.toString();
/// TODO diese methode ist nicht gleich wie toString(Object)
}
private static String toString(Clob clob) throws ExpressionException {
try {
Reader in = clob.getCharacterStream();
StringBuffer buf = new StringBuffer();
for(int c=in.read();c != -1;c = in.read()) {
buf.append((char)c);
}
return buf.toString();
}
catch(Exception e) {
throw ExpressionException.newInstance(e);
}
}
/**
* cast a double value to a String
* @param d double value to cast
* @return casted String
*/
public static String toString3(double d) {
long l = (long)d;
if(l == d) return toString(l);
String str = Double.toString(d);
int pos;
if((pos=str.indexOf('E'))!=-1 && pos==str.length()-2){
return new StringBuffer(pos+2).
append(str.charAt(0)).
append(str.substring(2,toDigit(str.charAt(pos+1))+2)).
append('.').
append(str.substring(toDigit(str.charAt(pos+1))+2,pos)).
toString();
}
return str;
}
private static DecimalFormat df=(DecimalFormat) DecimalFormat.getInstance(Locale.US);//("
//public static int count;
static {
df.applyLocalizedPattern("
}
public static String toString(double d) {
long l = (long)d;
if(l == d) return toString(l);
if(d>l && (d-l)<0.000000000001) return toString(l);
if(l>d && (l-d)<0.000000000001) return toString(l);
return df.format(d);
}
/**
* cast a long value to a String
* @param l long value to cast
* @return casted String
*/
public static String toString(long l) {
if(l<NUMBERS_MIN || l>NUMBERS_MAX) {
return Long.toString(l, 10);
}
return NUMBERS[(int)l];
}
/**
* cast a int value to a String
* @param i int value to cast
* @return casted String
*/
public static String toString(int i) {
if(i<NUMBERS_MIN || i>NUMBERS_MAX) return Integer.toString(i, 10);
return NUMBERS[i];
}
/**
* cast a boolean value to a String
* @param b boolean value to cast
* @return casted String
*/
public static String toString(boolean b) {
return b?"true":"false";
}
public static UDF toFunction(Object o) throws PageException {
if(o instanceof UDF) return (UDF)o;
else if(o instanceof ObjectWrap) {
return toFunction(((ObjectWrap)o).getEmbededObject());
}
throw new CasterException(o,"function");
}
public static UDF toFunction(Object o, UDF defaultValue) {
if(o instanceof UDF) return (UDF)o;
else if(o instanceof ObjectWrap) {
return toFunction(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
}
return defaultValue;
}
/**
* cast a Object to a Array Object
* @param o Object to cast
* @return casted Array
* @throws PageException
*/
public static List toList(Object o) throws PageException {
return toList(o,false);
}
/**
* cast a Object to a Array Object
* @param o Object to cast
* @param defaultValue
* @return casted Array
*/
public static List toList(Object o, List defaultValue) {
return toList(o,false,defaultValue);
}
/**
* cast a Object to a Array Object
* @param o Object to cast
* @param duplicate
* @param defaultValue
* @return casted Array
*/
public static List toList(Object o, boolean duplicate, List defaultValue) {
try {
return toList(o,duplicate);
} catch (PageException e) {
return defaultValue;
}
}
/**
* cast a Object to a Array Object
* @param o Object to cast
* @param duplicate
* @return casted Array
* @throws PageException
*/
public static List toList(Object o, boolean duplicate) throws PageException {
if(o instanceof List) {
if(duplicate) {
List src=(List)o;
int size=src.size();
ArrayList trg = new ArrayList();
for(int i=0;i<size;i++) {
trg.add(i,src.get(i));
}
return trg;
}
return (List)o;
}
else if(o instanceof Object[]) {
ArrayList list=new ArrayList();
Object[] arr=(Object[])o;
for(int i=0;i<arr.length;i++)list.add(i,arr[i]);
return list;
}
else if(o instanceof Array) {
if(!duplicate)return ArrayAsList.toList((Array)o);
ArrayList list=new ArrayList();
Array arr=(Array)o;
for(int i=0;i<arr.size();i++)list.add(i,arr.get(i+1,null));
return list;
}
else if(o instanceof XMLStruct) {
XMLStruct sct=((XMLStruct)o);
if(sct instanceof XMLMultiElementStruct) return toList(new XMLMultiElementArray((XMLMultiElementStruct) o));
ArrayList list=new ArrayList();
list.add(sct);
return list;
}
else if(o instanceof ObjectWrap) {
return toList(((ObjectWrap)o).getEmbededObject());
}
else if(o instanceof Struct) {
Struct sct=(Struct) o;
ArrayList arr=new ArrayList();
Iterator<Entry<Key, Object>> it = sct.entryIterator();
Entry<Key, Object> e=null;
try {
while(it.hasNext()) {
e = it.next();
arr.add(toIntValue(e.getKey().getString()),e.getValue());
}
}
catch (ExpressionException ee) {
throw new ExpressionException("can't cast struct to a array, key ["+(e!=null?e.getKey():"")+"] is not a number");
}
return arr;
}
else if(o instanceof boolean[])return toList(ArrayUtil.toReferenceType((boolean[])o));
else if(o instanceof byte[])return toList(ArrayUtil.toReferenceType((byte[])o));
else if(o instanceof char[])return toList(ArrayUtil.toReferenceType((char[])o));
else if(o instanceof short[])return toList(ArrayUtil.toReferenceType((short[])o));
else if(o instanceof int[])return toList(ArrayUtil.toReferenceType((int[])o));
else if(o instanceof long[])return toList(ArrayUtil.toReferenceType((long[])o));
else if(o instanceof float[])return toList(ArrayUtil.toReferenceType((float[])o));
else if(o instanceof double[])return toList(ArrayUtil.toReferenceType((double[])o));
throw new CasterException(o,"List");
}
/**
* cast a Object to a Array Object
* @param o Object to cast
* @return casted Array
* @throws PageException
*/
public static Array toArray(Object o) throws PageException {
if(o instanceof Array) return (Array)o;
else if(o instanceof Object[]) {
return new ArrayImpl((Object[])o);
}
else if(o instanceof List) {
return ListAsArray.toArray((List)o);//new ArrayImpl(((List) o).toArray());
}
else if(o instanceof Set) {
return toArray(((Set)o).toArray());//new ArrayImpl(((List) o).toArray());
}
else if(o instanceof XMLStruct) {
XMLMultiElementStruct xmes;
if(o instanceof XMLMultiElementStruct) {
xmes=(XMLMultiElementStruct)o;
}
else {
XMLStruct sct=(XMLStruct) o;
Array a=new ArrayImpl();
a.append(o);
xmes=new XMLMultiElementStruct(a, sct.getCaseSensitive());
}
return new XMLMultiElementArray(xmes);
}
else if(o instanceof ObjectWrap) {
return toArray(((ObjectWrap)o).getEmbededObject());
}
else if(o instanceof Struct) {
Struct sct=(Struct) o;
Array arr=new ArrayImpl();
Iterator<Entry<Key, Object>> it = sct.entryIterator();
Entry<Key, Object> e=null;
try {
while(it.hasNext()) {
e = it.next();
arr.setE(toIntValue(e.getKey().getString()),e.getValue());
}
}
catch (ExpressionException ee) {
throw new ExpressionException("can't cast struct to a array, key ["+e.getKey().getString()+"] is not a number");
}
return arr;
}
else if(o instanceof boolean[])return new ArrayImpl(ArrayUtil.toReferenceType((boolean[])o));
else if(o instanceof byte[])return new ArrayImpl(ArrayUtil.toReferenceType((byte[])o));
else if(o instanceof char[])return new ArrayImpl(ArrayUtil.toReferenceType((char[])o));
else if(o instanceof short[])return new ArrayImpl(ArrayUtil.toReferenceType((short[])o));
else if(o instanceof int[])return new ArrayImpl(ArrayUtil.toReferenceType((int[])o));
else if(o instanceof long[])return new ArrayImpl(ArrayUtil.toReferenceType((long[])o));
else if(o instanceof float[])return new ArrayImpl(ArrayUtil.toReferenceType((float[])o));
else if(o instanceof double[])return new ArrayImpl(ArrayUtil.toReferenceType((double[])o));
throw new CasterException(o,"Array");
}
public static Object[] toNativeArray(Object o) throws PageException {
if(o instanceof Object[]) {
return (Object[])o;
}
else if(o instanceof Array) {
Array arr=(Array)o;
Object[] objs=new Object[arr.size()];
for(int i=0;i<objs.length;i++) {
objs[i]=arr.get(i+1, null);
}
return objs;
}
else if(o instanceof List) {
return ((List) o).toArray();
}
else if(o instanceof XMLStruct) {
XMLStruct sct=((XMLStruct)o);
if(sct instanceof XMLMultiElementStruct) return toNativeArray((sct));
Object[] a=new Object[1];
a[0]=sct;
return a;
}
else if(o instanceof ObjectWrap) {
return toNativeArray(((ObjectWrap)o).getEmbededObject());
}
else if(o instanceof Struct) {
Struct sct=(Struct) o;
Array arr=new ArrayImpl();
Iterator<Entry<Key, Object>> it = sct.entryIterator();
Entry<Key, Object> e=null;
try {
while(it.hasNext()) {
e=it.next();
arr.setE(toIntValue(e.getKey().getString()),e.getValue());
}
}
catch (ExpressionException ee) {
throw new ExpressionException("can't cast struct to a array, key ["+e.getKey()+"] is not a number");
}
return toNativeArray(arr);
}
else if(o instanceof boolean[])return ArrayUtil.toReferenceType((boolean[])o);
else if(o instanceof byte[])return ArrayUtil.toReferenceType((byte[])o);
else if(o instanceof char[])return ArrayUtil.toReferenceType((char[])o);
else if(o instanceof short[])return ArrayUtil.toReferenceType((short[])o);
else if(o instanceof int[])return ArrayUtil.toReferenceType((int[])o);
else if(o instanceof long[])return ArrayUtil.toReferenceType((long[])o);
else if(o instanceof float[])return ArrayUtil.toReferenceType((float[])o);
else if(o instanceof double[])return ArrayUtil.toReferenceType((double[])o);
throw new CasterException(o,"Array");
}
/**
* cast a Object to a Array Object
* @param o Object to cast
* @param defaultValue
* @return casted Array
*/
public static Array toArray(Object o, Array defaultValue) {
if(o instanceof Array) return (Array)o;
else if(o instanceof Object[]) {
return new ArrayImpl((Object[])o);
}
else if(o instanceof List) {
return new ArrayImpl(((List) o).toArray());
}
else if(o instanceof XMLStruct) {
Array arr = new ArrayImpl();
arr.appendEL(o);
return arr;
}
else if(o instanceof ObjectWrap) {
return toArray(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
//if(io!=null)return toArray(io,defaultValue);
}
else if(o instanceof Struct) {
Struct sct=(Struct) o;
Array arr=new ArrayImpl();
Iterator<Entry<Key, Object>> it = sct.entryIterator();
Entry<Key, Object> e=null;
try {
while(it.hasNext()) {
e=it.next();
arr.setEL(toIntValue(e.getKey().getString()),e.getValue());
}
}
catch (ExpressionException ee) {
return defaultValue;
}
return arr;
}
else if(o instanceof boolean[])return new ArrayImpl(ArrayUtil.toReferenceType((boolean[])o));
else if(o instanceof byte[])return new ArrayImpl(ArrayUtil.toReferenceType((byte[])o));
else if(o instanceof char[])return new ArrayImpl(ArrayUtil.toReferenceType((char[])o));
else if(o instanceof short[])return new ArrayImpl(ArrayUtil.toReferenceType((short[])o));
else if(o instanceof int[])return new ArrayImpl(ArrayUtil.toReferenceType((int[])o));
else if(o instanceof long[])return new ArrayImpl(ArrayUtil.toReferenceType((long[])o));
else if(o instanceof float[])return new ArrayImpl(ArrayUtil.toReferenceType((float[])o));
else if(o instanceof double[])return new ArrayImpl(ArrayUtil.toReferenceType((double[])o));
return defaultValue;
}
/**
* cast a Object to a Map Object
* @param o Object to cast
* @return casted Struct
* @throws PageException
*/
public static Map toMap(Object o) throws PageException {
return toMap(o,false);
}
/**
* cast a Object to a Map Object
* @param o Object to cast
* @param defaultValue
* @return casted Struct
*/
public static Map toMap(Object o, Map defaultValue) {
return toMap(o,false,defaultValue);
}
/**
* cast a Object to a Map Object
* @param o Object to cast
* @param duplicate
* @param defaultValue
* @return casted Struct
*/
public static Map toMap(Object o, boolean duplicate, Map defaultValue) {
try {
return toMap(o,duplicate);
} catch (PageException e) {
return defaultValue;
}
}
/**
* cast a Object to a Map Object
* @param o Object to cast
* @param duplicate
* @return casted Struct
* @throws PageException
*/
public static Map toMap(Object o, boolean duplicate) throws PageException {
if(o instanceof Struct) {
if(duplicate) return (Map) Duplicator.duplicate(o,false);
return ((Struct)o);
}
else if(o instanceof Map){
if(duplicate) return (Map)Duplicator.duplicate(o,false);
return (Map)o;
}
else if(o instanceof Node) {
if(duplicate) {
return toMap(XMLCaster.toXMLStruct((Node)o,false),duplicate);
}
return (XMLCaster.toXMLStruct((Node)o,false));
}
else if(o instanceof ObjectWrap) {
return toMap(((ObjectWrap)o).getEmbededObject(),duplicate);
}
throw new CasterException(o,"Map");
}
/**
* cast a Object to a Struct Object
* @param o Object to cast
* @param defaultValue
* @return casted Struct
*/
public static Struct toStruct(Object o, Struct defaultValue, boolean caseSensitive) {
if(o instanceof Struct) return (Struct)o;
else if(o instanceof Map) {
return MapAsStruct.toStruct((Map)o,caseSensitive);
}
else if(o instanceof Node)return XMLCaster.toXMLStruct((Node)o,false);
else if(o instanceof ObjectWrap) {
return toStruct(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue,caseSensitive);
}
return defaultValue;
}
/**
* cast a Object to a Struct Object
* @param o Object to cast
* @return casted Struct
*/
public static Struct toStruct(Object o) throws PageException {
return toStruct(o,true);
}
public static Struct toStruct(Object o,Struct defaultValue) {
return toStruct(o, defaultValue, true);
}
public static Struct toStruct(Object o,boolean caseSensitive) throws PageException {
if(o instanceof Struct) return (Struct)o;
else if(o instanceof Map)return MapAsStruct.toStruct((Map)o,caseSensitive);//_toStruct((Map)o,caseSensitive);
else if(o instanceof Node)return XMLCaster.toXMLStruct((Node)o,false);
else if(o instanceof ObjectWrap) {
if(o instanceof JavaObject ) {
Struct sct = toStruct(((JavaObject)o).getEmbededObject(null),null,caseSensitive);
if(sct!=null) return sct;
JavaObject jo = (JavaObject)o;
return new ObjectStruct(jo);
}
return toStruct(((ObjectWrap)o).getEmbededObject(),caseSensitive);
}
if(Decision.isSimpleValue(o) || Decision.isArray(o))
throw new CasterException(o,"Struct");
if(o instanceof Collection) return new CollectionStruct((Collection)o);
if ( o == null )
throw new CasterException( "null can not be casted to a Struct" );
return new ObjectStruct(o);
}
/*private static Struct _toStruct(Map map) {
Struct sct = new StructImpl();
Iterator it=map.keySet().iterator();
while(it.hasNext()) {
Object key=it.next();
sct.set(StringUtil.toLowerCase(Caster.toString(key)),map.get(key));
}
return sct;
}*/
/**
* cast a Object to a Binary
* @param o Object to cast
* @return casted Binary
* @throws PageException
*/
public static byte[] toBinary(Object o) throws PageException {
if(o instanceof byte[]) return (byte[])o;
else if(o instanceof ObjectWrap) return toBinary(((ObjectWrap)o).getEmbededObject(""));
else if(o instanceof InputStream) {
ByteArrayOutputStream barr = new ByteArrayOutputStream();
try {
IOUtil.copy((InputStream)o,barr,false,true);
} catch (IOException e) {
throw ExpressionException.newInstance(e);
}
return barr.toByteArray();
}
else if(o instanceof Image) {
return ((Image)o).getImageBytes(null);
}
else if(o instanceof BufferedImage) {
return new Image(((BufferedImage)o)).getImageBytes("png");
}
else if(o instanceof ByteArrayOutputStream) {
return ((ByteArrayOutputStream)o).toByteArray();
}
else if(o instanceof Blob) {
InputStream is=null;
try {
is=((Blob)o).getBinaryStream();
return IOUtil.toBytes(is);
}
catch (Exception e) {
throw new ExpressionException(e.getMessage());
}
finally {
IOUtil.closeEL(is);
}
}
try {
return Coder.decode(Coder.ENCODING_BASE64,toString(o));
}
catch (CoderException e) {
throw new CasterException(e.getMessage(),"binary");
}
catch (PageException e) {
throw new CasterException(o,"binary");
}
}
/**
* cast a Object to a Binary
* @param o Object to cast
* @param defaultValue
* @return casted Binary
*/
public static byte[] toBinary(Object o, byte[] defaultValue) {
try {
return toBinary(o);
}
catch (PageException e) {
return defaultValue;
}
}
public static Object toCreditCard(Object o) throws PageException {
return ValidateCreditCard.toCreditcard(toString(o));
}
public static Object toCreditCard(Object o, String defaultValue) {
//print.out("enter");
String str=toString(o,null);
if(str==null)return defaultValue;
//print.out("enter:"+str+":"+ValidateCreditCard.toCreditcard(str,defaultValue));
return ValidateCreditCard.toCreditcard(str,defaultValue);
}
/**
* cast a Object to a Base64 value
* @param o Object to cast
* @return to Base64 String
* @throws PageException
*/
public static String toBase64(Object o,String charset) throws PageException {
String str=toBase64(o,charset,null);
if(str==null) throw new CasterException(o,"base 64");
return str;
}
/**
* cast a Object to a Base64 value
* @param o Object to cast
* @param defaultValue
* @return to Base64 String
*/
public static String toBase64(Object o,String charset,String defaultValue) {
byte[] b;
if(o instanceof byte[])b=(byte[]) o;
else if(o instanceof String)return toB64((String)o, charset,defaultValue);
else if(o instanceof ObjectWrap) {
return toBase64(((ObjectWrap)o).getEmbededObject(defaultValue),charset,defaultValue);
}
else if(o == null) return toBase64("",charset,defaultValue);
else {
String str = toString(o,null);
if(str!=null)return toBase64(str,charset,defaultValue);
b=toBinary(o,null);
if(b==null)return defaultValue;
}
return toB64(b,defaultValue);
}
public static String toB64(String str,String charset) throws UnsupportedEncodingException {
return toB64(str.getBytes(charset));
}
public static String toB64(byte[] b) {
return Base64Coder.encode(b);
}
public static String toB64(String str,String charset, String defaultValue) {
if(StringUtil.isEmpty(charset,true))charset="UTF-8";
try {
return Base64Coder.encodeFromString(str,charset);
} catch (Throwable t) {
return defaultValue;
}
}
public static String toB64(byte[] b, String defaultValue) {
try {
return Base64Coder.encode(b);
} catch (Throwable t) {
return defaultValue;
}
}
/**
* cast a boolean to a DateTime Object
* @param b boolean to cast
* @param tz
* @return casted DateTime Object
*/
public static DateTime toDate(boolean b, TimeZone tz) {
return DateCaster.toDateSimple(b,tz);
}
/**
* cast a char to a DateTime Object
* @param c char to cast
* @param tz
* @return casted DateTime Object
*/
public static DateTime toDate(char c, TimeZone tz) {
return DateCaster.toDateSimple(c,tz);
}
/**
* cast a double to a DateTime Object
* @param d double to cast
* @param tz
* @return casted DateTime Object
*/
public static DateTime toDate(double d, TimeZone tz) {
return DateCaster.toDateSimple(d,tz);
}
/**
* cast a Object to a DateTime Object
* @param o Object to cast
* @param tz
* @return casted DateTime Object
* @throws PageException
*/
public static DateTime toDate(Object o, TimeZone tz) throws PageException {
return DateCaster.toDateAdvanced(o,tz);
}
/**
* cast a Object to a DateTime Object
* @param str String to cast
* @param tz
* @return casted DateTime Object
* @throws PageException
*/
public static DateTime toDate(String str, TimeZone tz) throws PageException {
return DateCaster.toDateAdvanced(str,tz);
}
/**
* cast a Object to a DateTime Object
* @param o Object to cast
* @param alsoNumbers define if also numbers will casted to a datetime value
* @param tz
* @return casted DateTime Object
* @throws PageException
*/
public static DateTime toDate(Object o,boolean alsoNumbers, TimeZone tz) throws PageException {
return DateCaster.toDateAdvanced(o,alsoNumbers,tz);
}
/**
* cast a Object to a DateTime Object
* @param o Object to cast
* @param alsoNumbers define if also numbers will casted to a datetime value
* @param tz
* @param defaultValue
* @return casted DateTime Object
*/
public static DateTime toDate(Object o,boolean alsoNumbers, TimeZone tz, DateTime defaultValue) {
return DateCaster.toDateAdvanced(o,alsoNumbers,tz,defaultValue);
}
/**
* cast a Object to a DateTime Object
* @param str String to cast
* @param alsoNumbers define if also numbers will casted to a datetime value
* @param tz
* @param defaultValue
* @return casted DateTime Object
*/
public static DateTime toDate(String str,boolean alsoNumbers, TimeZone tz, DateTime defaultValue) {
return DateCaster.toDateAdvanced(str,alsoNumbers,tz,defaultValue);
}
/**
* cast a Object to a DateTime Object
* @param o Object to cast
* @param tz
* @return casted DateTime Object
* @throws PageException
*/
public static DateTime toDateTime(Object o, TimeZone tz) throws PageException {
return DateCaster.toDateAdvanced(o,tz);
}
/**
* cast a Object to a DateTime Object (alias for toDateTime)
* @param o Object to cast
* @param tz
* @return casted DateTime Object
* @throws PageException
*/
public static DateTime toDatetime(Object o, TimeZone tz) throws PageException {
return DateCaster.toDateAdvanced(o,tz);
}
/**
* cast a Object to a Query Object
* @param o Object to cast
* @return casted Query Object
* @throws PageException
*/
public static Query toQuery(Object o) throws PageException {
if(o instanceof Query) return (Query)o;
if(o instanceof ObjectWrap) {
return toQuery(((ObjectWrap)o).getEmbededObject());
}
if(o instanceof ResultSet) return new QueryImpl((ResultSet)o,"query", ThreadLocalPageContext.getTimeZone());
throw new CasterException(o,"query");
}
/**
* converts a object to a QueryColumn, if possible
* @param o
* @return
* @throws PageException
*/
public static QueryColumn toQueryColumn(Object o) throws PageException {
if(o instanceof QueryColumn) return (QueryColumn)o;
throw new CasterException(o,"querycolumn");
}
/**
* converts a object to a QueryColumn, if possible, also variable declarations are allowed.
* this method is used within the generated bytecode
* @param o
* @return
* @throws PageException
* @info used in bytecode generation
*/
public static QueryColumn toQueryColumn(Object o, PageContext pc) throws PageException {
if(o instanceof QueryColumn) return (QueryColumn)o;
if(o instanceof String) {
o=VariableInterpreter.getVariableAsCollection(pc, (String)o);
if(o instanceof QueryColumn) return (QueryColumn) o;
}
throw new CasterException(o,"querycolumn");
}
/**
* cast a Object to a Query Object
* @param o Object to cast
* @param defaultValue
* @return casted Query Object
*/
public static Query toQuery(Object o, Query defaultValue) {
if(o instanceof Query) return (Query)o;
else if(o instanceof ObjectWrap) {
return toQuery(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
}
return defaultValue;
}
/**
* cast a Object to a Query Object
* @param o Object to cast
* @param duplicate duplicate the object or not
* @param defaultValue
* @return casted Query Object
*/
public static Query toQuery(Object o, boolean duplicate, Query defaultValue) {
try {
return toQuery(o,duplicate);
} catch (PageException e) {
return defaultValue;
}
}
/**
* cast a Object to a Query Object
* @param o Object to cast
* @param duplicate duplicate the object or not
* @return casted Query Object
* @throws PageException
*/
public static Query toQuery(Object o, boolean duplicate) throws PageException {
if(o instanceof Query) {
if(duplicate) {
Query src = (Query)o;
Query trg=new QueryImpl(src.getColumnNames(),src.getRowCount(),"query");
Collection.Key[] keys=src.getColumnNames();
QueryColumn[] columnsSrc=new QueryColumn[keys.length];
for(int i=0;i<columnsSrc.length;i++) {
columnsSrc[i]=src.getColumn(keys[i]);
}
keys=trg.getColumnNames();
QueryColumn[] columnsTrg=new QueryColumn[keys.length];
for(int i=0;i<columnsTrg.length;i++) {
columnsTrg[i]=trg.getColumn(keys[i]);
}
int i;
for(int row=trg.getRecordcount();row>0;row
for(i=0;i<columnsTrg.length;i++) {
columnsTrg[i].set(row,columnsSrc[i].get(row,null));
}
}
return trg;
}
return (Query)o;
}
else if(o instanceof ObjectWrap) {
return toQuery(((ObjectWrap)o).getEmbededObject(),duplicate);
}
throw new CasterException(o,"query");
}
/**
* cast a Object to a UUID
* @param o Object to cast
* @return casted Query Object
* @throws PageException
*/
public static Object toUUId(Object o) throws PageException {
String str=toString(o);
if(!Decision.isUUId(str))
throw new ExpressionException("can't cast ["+str+"] to uuid value");
return str;
}
/**
* cast a Object to a UUID
* @param o Object to cast
* @param defaultValue
* @return casted Query Object
*/
public static Object toUUId(Object o, Object defaultValue) {
String str=toString(o,null);
if(str==null) return defaultValue;
if(!Decision.isUUId(str)) return defaultValue;
return str;
}
/**
* cast a Object to a GUID
* @param o Object to cast
* @return casted Query Object
* @throws PageException
*/
public static Object toGUId(Object o) throws PageException {
String str=toString(o);
if(!Decision.isGUId(str))
throw new ExpressionException("can't cast ["+str+"] to guid value");
return str;
}
/**
* cast a Object to a GUID
* @param o Object to cast
* @param defaultValue
* @return casted Query Object
*/
public static Object toGUId(Object o, Object defaultValue) {
String str=toString(o,null);
if(str==null) return defaultValue;
if(!Decision.isGUId(str)) return defaultValue;
return str;
}
/**
* cast a Object to a Variable Name
* @param o Object to cast
* @return casted Variable Name
* @throws PageException
*/
public static String toVariableName(Object o) throws PageException {
String str=toString(o);
if(!Decision.isVariableName(str))
throw new ExpressionException("can't cast ["+str+"] to variable name value");
return str;
}
/**
* cast a Object to a Variable Name
* @param o Object to cast
* @param defaultValue
* @return casted Variable Name
*/
public static Object toVariableName(Object o, Object defaultValue) {
String str=toString(o,null);
if(str==null || !Decision.isVariableName(str))
return defaultValue;
return str;
}
/**
* cast a Object to a TimeSpan Object
* @param o Object to cast
* @return casted TimeSpan Object
* @throws PageException
*/
public static TimeSpan toTimeSpan(Object o) throws PageException {
return toTimespan(o);
}
/**
* cast a Object to a TimeSpan Object (alias for toTimeSpan)
* @param o Object to cast
* @param defaultValue
* @return casted TimeSpan Object
*/
public static TimeSpan toTimespan(Object o, TimeSpan defaultValue) {
try {
return toTimespan(o);
} catch (PageException e) {
return defaultValue;
}
}
/**
* cast a Object to a TimeSpan Object (alias for toTimeSpan)
* @param o Object to cast
* @return casted TimeSpan Object
* @throws PageException
*/
public static TimeSpan toTimespan(Object o) throws PageException {
if(o instanceof TimeSpan) return (TimeSpan)o;
else if(o instanceof String) {
String[] arr=o.toString().split(",");
if(arr.length==4) {
int[] values=new int[4];
try {
for(int i=0;i<arr.length;i++) {
values[i]=toIntValue(arr[i]);
}
return new TimeSpanImpl(values[0],values[1],values[2],values[3]);
}
catch(ExpressionException e) {}
}
}
else if(o instanceof ObjectWrap) {
return toTimespan(((ObjectWrap)o).getEmbededObject());
}
double dbl = toDoubleValue(o,Double.NaN);
if(!Double.isNaN(dbl))return TimeSpanImpl.fromDays(dbl);
throw new CasterException(o,"timespan");
}
/**
* cast a Throwable Object to a PageException Object
* @param t Throwable to cast
* @return casted PageException Object
*/
public static PageException toPageException(Throwable t) {
if(t instanceof PageException)
return (PageException)t;
else if(t instanceof PageExceptionBox)
return ((PageExceptionBox)t).getPageException();
else if(t instanceof InvocationTargetException){
return toPageException(((InvocationTargetException)t).getTargetException());
}
else if(t instanceof ExceptionInInitializerError){
return toPageException(((ExceptionInInitializerError)t).getCause());
}
else if(t instanceof ExecutionException){
return toPageException(((ExecutionException)t).getCause());
}
else {
//Throwable cause = t.getCause();
//if(cause!=null && cause!=t) return toPageException(cause);
return new NativeException(t);
}
}
/**
* return the type name of a object (string, boolean, int aso.), type is not same like class name
* @param o Object to get type from
* @return type of the object
*/
public static String toTypeName(Object o) {
if(o == null) return "null";
else if(o instanceof String) return "string";
else if(o instanceof Boolean) return "boolean";
else if(o instanceof Number) return "int";
else if(o instanceof Array) return "array";
else if(o instanceof Component) return "component";
else if(o instanceof Struct) return "struct";
else if(o instanceof Query) return "query";
else if(o instanceof DateTime) return "datetime";
else if(o instanceof byte[]) return "binary";
else if(o instanceof ObjectWrap) {
return toTypeName(((ObjectWrap)o).getEmbededObject(null));
}
Class clazz=o.getClass();
String className=clazz.getName();
if(className.startsWith("java.lang.")) {
return className.substring(10);
}
return toClassName(clazz);
}
public static String toTypeName(Class clazz) {
if(Reflector.isInstaneOf(clazz,String.class)) return "string";
if(Reflector.isInstaneOf(clazz,Boolean.class)) return "boolean";
if(Reflector.isInstaneOf(clazz,Number.class)) return "numeric";
if(Reflector.isInstaneOf(clazz,Array.class)) return "array";
if(Reflector.isInstaneOf(clazz,Struct.class)) return "struct";
if(Reflector.isInstaneOf(clazz,Query.class)) return "query";
if(Reflector.isInstaneOf(clazz,DateTime.class)) return "datetime";
if(Reflector.isInstaneOf(clazz,byte[].class)) return "binary";
String className=clazz.getName();
if(className.startsWith("java.lang.")) {
return className.substring(10);
}
return toClassName(clazz);
}
public static String toClassName(Object o) {
if(o==null)return "null";
return toClassName(o.getClass());
}
public static String toClassName(Class clazz) {
if(clazz.isArray()){
return toClassName(clazz.getComponentType())+"[]";
}
return clazz.getName();
}
public static Class cfTypeToClass(String type) throws PageException {
// TODO weitere typen siehe bytecode.cast.Cast
type=type.trim();
String lcType=StringUtil.toLowerCase(type);
if(lcType.length()>2) {
char first=lcType.charAt(0);
switch(first) {
case 'a':
if(lcType.equals("any")) {
return Object.class;
}
else if(lcType.equals("array")) {
return Array.class;
}
break;
case 'b':
if(lcType.equals("boolean") || lcType.equals("bool")) {
return Boolean.class;
}
else if(lcType.equals("binary")) {
return byte[].class;
}
else if(lcType.equals("base64")) {
return String.class;
}
else if(lcType.equals("byte")) {
return Byte.class;
}
break;
case 'c':
if(lcType.equals("creditcard")) {
return String.class;
}
else if(lcType.equals("component")) {
return Component.class;
}
break;
case 'd':
if(lcType.equals("date")) {
return Date.class;
}
else if(lcType.equals("datetime")) {
return Date.class;
}
break;
case 'g':
if(lcType.equals("guid")) {
return Object.class;
}
break;
case 'n':
if(lcType.equals("numeric")) {
return Double.class;
}
else if(lcType.equals("number")) {
return Double.class;
}
else if(lcType.equals("node")) {
return Node.class;
}
break;
case 'o':
if(lcType.equals("object")) {
return Object.class;
}
break;
case 'q':
if(lcType.equals("query")) {
return Query.class;
}
break;
case 's':
if(lcType.equals("string")) {
return String.class;
}
else if(lcType.equals("struct")) {
return Struct.class;
}
break;
case 't':
if(lcType.equals("timespan")) {
return TimeSpan.class;
}
break;
case 'u':
if(lcType.equals("uuid")) {
return Object.class;
}
break;
case 'v':
if(lcType.equals("variablename")) {
return Object.class;
}
if(lcType.equals("void")) {
return Object.class;
}
break;
case 'x':
if(lcType.equals("xml")) {
return Node.class;
}
break;
}
}
// array
if(type.endsWith("[]")) {
Class clazz = cfTypeToClass(type.substring(0,type.length()-2));
clazz=ClassUtil.toArrayClass(clazz);
return clazz;
}
// check for argument
Class<?> clazz;
try {
clazz = otherTypeToClass(type);
}
catch (ClassException e) {
throw Caster.toPageException(e);
}
return clazz;
}
private static Class<?> otherTypeToClass(String type) throws PageException, ClassException{
PageContext pc = ThreadLocalPageContext.get();
PageException pe=null;
// try to load as cfc
if(pc!=null) {
try {
Component c = pc.loadComponent(type);
return ComponentUtil.getServerComponentPropertiesClass(pc,c);
}
catch (PageException e) {
pe=e;
}
}
// try to load as class
try {
return ClassUtil.loadClass(type);
}
catch (ClassException ce) {
if(pe!=null) throw pe;
throw ce;
}
}
/**
* cast a value to a value defined by type argument
* @param pc
* @param type type of the returning Value
* @param o Object to cast
* @return casted Value
* @throws PageException
*/
public static Object castTo(PageContext pc,String type, Object o, boolean alsoPattern) throws PageException {
type=StringUtil.toLowerCase(type).trim();
if(type.length()>2) {
char first=type.charAt(0);
switch(first) {
case 'a':
if(type.equals("any")) {
return o;
}
else if(type.equals("array")) {
return toArray(o);
}
break;
case 'b':
if(type.equals("boolean") || type.equals("bool")) {
return toBoolean(o);
}
else if(type.equals("binary")) {
return toBinary(o);
}
else if(type.equals("base64")) {
return toBase64(o,null);
}
break;
case 'c':
if(alsoPattern && type.equals("creditcard")) {
return toCreditCard(o);
}
break;
case 'd':
if(type.equals("date")) {
return DateCaster.toDateAdvanced(o,pc.getTimeZone());
}
else if(type.equals("datetime")) {
return DateCaster.toDateAdvanced(o,pc.getTimeZone());
}
else if(type.equals("double")) {
return toDouble(o);
}
else if(type.equals("decimal")) {
return toDecimal(o);
}
break;
case 'e':
if(type.equals("eurodate")) {
return DateCaster.toEuroDate(o,pc.getTimeZone());
}
else if(alsoPattern && type.equals("email")) {
return toEmail(o);
}
break;
case 'f':
if(type.equals("float")) {
return toDouble(o);
}
break;
case 'g':
if(type.equals("guid")) {
return toGUId(o);
}
break;
case 'i':
if(type.equals("integer") || type.equals("int")) {
return toInteger(o);
}
break;
case 'l':
if(type.equals("long")) {
return toLong(o);
}
break;
case 'n':
if(type.equals("numeric")) {
return toDouble(o);
}
else if(type.equals("number")) {
return toDouble(o);
}
else if(type.equals("node")) {
return toXML(o);
}
break;
case 'o':
if(type.equals("object")) {
return o;
}
else if(type.equals("other")) {
return o;
}
break;
case 'p':
if(alsoPattern && type.equals("phone")) {
return toPhone(o);
}
break;
case 'q':
if(type.equals("query")) {
return toQuery(o);
}
break;
case 's':
if(type.equals("string")) {
return toString(o);
}
else if(type.equals("struct")) {
return toStruct(o);
}
else if(type.equals("short")) {
return toShort(o);
}
else if(alsoPattern && (type.equals("ssn") ||type.equals("social_security_number"))) {
return toSSN(o);
}
break;
case 't':
if(type.equals("timespan")) {
return toTimespan(o);
}
if(type.equals("time")) {
return DateCaster.toDateAdvanced(o,pc.getTimeZone());
}
if(alsoPattern && type.equals("telephone")) {
return toPhone(o);
}
break;
case 'u':
if(type.equals("uuid")) {
return toUUId(o);
}
if(alsoPattern && type.equals("url")) {
return toURL(o);
}
if(type.equals("usdate")) {
return DateCaster.toUSDate(o,pc.getTimeZone());
//return DateCaster.toDate(o,pc.getTimeZone());
}
break;
case 'v':
if(type.equals("variablename")) {
return toVariableName(o);
}
else if(type.equals("void")) {
return toVoid(o);
}
else if(type.equals("variable_name")) {
return toVariableName(o);
}
else if(type.equals("variable-name")) {
return toVariableName(o);
}
break;
case 'x':
if(type.equals("xml")) {
return toXML(o);
}
case 'z':
if(alsoPattern && (type.equals("zip") || type.equals("zipcode"))) {
return toZip(o);
}
break;
}
}
// <type>[]
if(type.endsWith("[]")){
String componentType = type.substring(0,type.length()-2);
Object[] src = toNativeArray(o);
Array trg=new ArrayImpl();
for(int i=0;i<src.length;i++){
if(src[i]==null){
continue;
}
trg.setE(i+1,castTo(pc, componentType, src[i],alsoPattern));
}
return trg;
}
if(o instanceof Component) {
Component comp=((Component)o);
if(comp.instanceOf(type)) return o;
// neo batch
throw new ExpressionException("can't cast Component of Type ["+comp.getAbsName()+"] to ["+type+"]");
}
throw new CasterException(o,type);
}
public static String toZip(Object o) throws PageException {
String str=toString(o);
if(Decision.isZipCode(str)) return str;
throw new ExpressionException("can't cast value ["+str+"] to a zip code");
}
public static String toZip(Object o, String defaultValue) {
String str=toString(o,null);
if(str==null) return defaultValue;
if(Decision.isZipCode(str)) return str;
return defaultValue;
}
public static String toURL(Object o) throws PageException {
String str=toString(o);
if(Decision.isURL(str)) return str;
try {
return HTTPUtil.toURL(str).toExternalForm();
}
catch (MalformedURLException e) {
throw new ExpressionException("can't cast value ["+str+"] to a URL",e.getMessage());
}
}
public static String toURL(Object o, String defaultValue) {
String str=toString(o,null);
if(str==null) return defaultValue;
if(Decision.isURL(str)) return str;
try {
return HTTPUtil.toURL(str).toExternalForm();
}
catch (MalformedURLException e) {
return defaultValue;
}
}
public static String toPhone(Object o) throws PageException {
String str=toString(o);
if(Decision.isPhone(str)) return str;
throw new ExpressionException("can't cast value ["+str+"] to a telephone number");
}
public static String toPhone(Object o, String defaultValue) {
String str=toString(o,null);
if(str==null) return defaultValue;
if(Decision.isPhone(str)) return str;
return defaultValue;
}
public static String toSSN(Object o) throws PageException {
String str=toString(o);
if(Decision.isSSN(str)) return str;
throw new ExpressionException("can't cast value ["+str+"] to a U.S. social security number");
}
public static String toSSN(Object o, String defaultValue) {
String str=toString(o,null);
if(str==null) return defaultValue;
if(Decision.isSSN(str)) return str;
return defaultValue;
}
public static String toEmail(Object o) throws PageException {
String str=toString(o);
if(Decision.isEmail(str)) return str;
throw new ExpressionException("can't cast value ["+str+"] to a E-Mail Address");
}
public static String toEmail(Object o, String defaultValue) {
String str=toString(o,null);
if(str==null) return defaultValue;
if(Decision.isEmail(str)) return str;
return defaultValue;
}
/**
* cast a value to a value defined by type argument
* @param pc
* @param type type of the returning Value
* @param strType type as String
* @param o Object to cast
* @return casted Value
* @throws PageException
*/
public static Object castTo(PageContext pc, short type, String strType, Object o) throws PageException {
// TODO weitere typen siehe bytecode.cast.Cast
if(type==CFTypes.TYPE_ANY) return o;
else if(type==CFTypes.TYPE_ARRAY) return toArray(o);
else if(type==CFTypes.TYPE_BOOLEAN) return toBoolean(o);
else if(type==CFTypes.TYPE_BINARY) return toBinary(o);
else if(type==CFTypes.TYPE_DATETIME) return DateCaster.toDateAdvanced(o,pc.getTimeZone());
else if(type==CFTypes.TYPE_NUMERIC) return toDouble(o);
else if(type==CFTypes.TYPE_QUERY) return toQuery(o);
else if(type==CFTypes.TYPE_QUERY_COLUMN) return toQueryColumn(o);
else if(type==CFTypes.TYPE_STRING) return toString(o);
else if(type==CFTypes.TYPE_STRUCT) return toStruct(o);
else if(type==CFTypes.TYPE_TIMESPAN) return toTimespan(o);
else if(type==CFTypes.TYPE_UUID) return toUUId(o);
else if(type==CFTypes.TYPE_GUID) return toGUId(o);
else if(type==CFTypes.TYPE_VARIABLE_NAME) return toVariableName(o);
else if(type==CFTypes.TYPE_VOID) return toVoid(o);
else if(type==CFTypes.TYPE_XML) return toXML(o);
else if(type==CFTypes.TYPE_FUNCTION) return toFunction(o);
if(o instanceof Component) {
Component comp=((Component)o);
if(comp.instanceOf(strType)) return o;
throw new ExpressionException("can't cast Component of Type ["+comp.getAbsName()+"] to ["+strType+"]");
}
throw new CasterException(o,strType);
}
/**
* cast a value to a value defined by type argument
* @param pc
* @param type type of the returning Value
* @param o Object to cast
* @return casted Value
* @throws PageException
*/
public static Object castTo(PageContext pc, short type, Object o) throws PageException {
if(type==CFTypes.TYPE_ANY) return o;
else if(type==CFTypes.TYPE_ARRAY) return toArray(o);
else if(type==CFTypes.TYPE_BOOLEAN) return toBoolean(o);
else if(type==CFTypes.TYPE_BINARY) return toBinary(o);
else if(type==CFTypes.TYPE_DATETIME) return DateCaster.toDateAdvanced(o,pc.getTimeZone());
else if(type==CFTypes.TYPE_NUMERIC) return toDouble(o);
else if(type==CFTypes.TYPE_QUERY) return toQuery(o);
else if(type==CFTypes.TYPE_QUERY_COLUMN) return toQueryColumn(o);
else if(type==CFTypes.TYPE_STRING) return toString(o);
else if(type==CFTypes.TYPE_STRUCT) return toStruct(o);
else if(type==CFTypes.TYPE_TIMESPAN) return toTimespan(o);
else if(type==CFTypes.TYPE_UUID) return toGUId(o);
else if(type==CFTypes.TYPE_UUID) return toUUId(o);
else if(type==CFTypes.TYPE_VARIABLE_NAME) return toVariableName(o);
else if(type==CFTypes.TYPE_VOID) return toVoid(o);
else if(type==CFTypes.TYPE_FUNCTION) return toFunction(o);
else if(type==CFTypes.TYPE_XML) return toXML(o);
if(type==CFTypes.TYPE_UNDEFINED)
throw new ExpressionException("type isn't defined (TYPE_UNDEFINED)");
throw new ExpressionException("invalid type ["+type+"]");
}
/**
* cast a value to void (Empty String)
* @param o
* @return void value
* @throws ExpressionException
*/
public static Object toVoid(Object o) throws ExpressionException {
if(o==null)return null;
else if(o instanceof String && o.toString().length()==0)return null;
else if(o instanceof Number && ((Number)o).intValue()==0 ) return null;
else if(o instanceof Boolean && ((Boolean)o).booleanValue()==false ) return null;
else if(o instanceof ObjectWrap) return toVoid(((ObjectWrap)o).getEmbededObject(null));
throw new CasterException(o,"void");
}
/**
* cast a value to void (Empty String)
* @param o
* @param defaultValue
* @return void value
*/
public static Object toVoid(Object o, Object defaultValue) {
if(o==null)return null;
else if(o instanceof String && o.toString().length()==0)return null;
else if(o instanceof Number && ((Number)o).intValue()==0 ) return null;
else if(o instanceof Boolean && ((Boolean)o).booleanValue()==false ) return null;
else if(o instanceof ObjectWrap) return toVoid(((ObjectWrap)o).getEmbededObject((defaultValue)),defaultValue);
return defaultValue;
}
/**
* cast a Object to a reference type (Object), in that case this method to nothing, because a Object is already a reference type
* @param o Object to cast
* @return casted Object
*/
public static Object toRef(Object o) {
return o;
}
/**
* cast a String to a reference type (Object), in that case this method to nothing, because a String is already a reference type
* @param o Object to cast
* @return casted Object
*/
public static String toRef(String o) {
return o;
}
/**
* cast a Collection to a reference type (Object), in that case this method to nothing, because a Collection is already a reference type
* @param o Collection to cast
* @return casted Object
*/
public static Collection toRef(Collection o) {
return o;
}
/**
* cast a char value to his (CFML) reference type String
* @param c char to cast
* @return casted String
*/
public static String toRef(char c) {
return ""+c;
}
/**
* cast a boolean value to his (CFML) reference type Boolean
* @param b boolean to cast
* @return casted Boolean
*/
public static Boolean toRef(boolean b) {
return b?Boolean.TRUE:Boolean.FALSE;
}
/**
* cast a byte value to his (CFML) reference type Integer
* @param b byte to cast
* @return casted Integer
*/
public static Byte toRef(byte b) {
return new Byte(b);
}
/**
* cast a int value to his (CFML) reference type Integer
* @param i int to cast
* @return casted Integer
*/
public static Integer toRef(int i) {
return Integer.valueOf(i);
}
/**
* cast a float value to his (CFML) reference type Float
* @param f float to cast
* @return casted Float
*/
public static Float toRef(float f) {
return new Float(f);
}
/**
* cast a long value to his (CFML) reference type Long
* @param l long to cast
* @return casted Long
*/
public static Long toRef(long l) {
return Long.valueOf(l);
}
/**
* cast a double value to his (CFML) reference type Double
* @param d doble to cast
* @return casted Double
*/
public static Double toRef(double d) {
return new Double(d);
}
/**
* cast a double value to his (CFML) reference type Double
* @param s short to cast
* @return casted Short
*/
public static Short toRef(short s) {
return Short.valueOf(s);
}
/**
* cast a Object to a Iterator or get Iterator from Object
* @param o Object to cast
* @return casted Collection
* @throws PageException
*/
public static Iterator toIterator(Object o) throws PageException {
if(o instanceof Iterator) return (Iterator)o;
else if(o instanceof Iteratorable) return ((Iteratorable)o).keysAsStringIterator();
else if(o instanceof Enumeration) return new IteratorWrapper((Enumeration)o);
else if(o instanceof JavaObject) {
String[] names = ClassUtil.getFieldNames(((JavaObject)o).getClazz());
return new ArrayIterator(names);
}
else if(o instanceof ObjectWrap) return toIterator(((ObjectWrap)o).getEmbededObject());
return toIterator(toCollection(o));
}
/**
* cast a Object to a Collection
* @param o Object to cast
* @return casted Collection
* @throws PageException
*/
public static Collection toCollection(Object o) throws PageException {
if(o instanceof Collection) return (Collection)o;
else if(o instanceof Node)return XMLCaster.toXMLStruct((Node)o,false);
else if(o instanceof Map) {
return MapAsStruct.toStruct((Map)o,true);//StructImpl((Map)o);
}
else if(o instanceof ObjectWrap) {
return toCollection(((ObjectWrap)o).getEmbededObject());
}
else if(Decision.isArray(o)) {
return toArray(o);
}
throw new CasterException(o,"collection");
}
public static java.util.Collection toJavaCollection(Object o) throws PageException {
if(o instanceof java.util.Collection) return (java.util.Collection) o;
return toList(o);
}
/**
* cast a Object to a Component
* @param o Object to cast
* @return casted Component
* @throws PageException
*/
public static Component toComponent(Object o ) throws PageException {
if(o instanceof Component) return (Component)o;
else if(o instanceof ObjectWrap) {
return toComponent(((ObjectWrap)o).getEmbededObject());
}
throw new CasterException(o,"Component");
}
public static Component toComponent(Object o , Component defaultValue) {
if(o instanceof Component) return (Component)o;
else if(o instanceof ObjectWrap) {
return toComponent(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
}
return defaultValue;
}
/**
* cast a Object to a Collection, if not returns null
* @param o Object to cast
* @param defaultValue
* @return casted Collection
*/
public static Collection toCollection(Object o, Collection defaultValue) {
if(o instanceof Collection) return (Collection)o;
else if(o instanceof Node)return XMLCaster.toXMLStruct((Node)o,false);
else if(o instanceof Map) {
return MapAsStruct.toStruct((Map)o,true);
}
else if(o instanceof ObjectWrap) {
return toCollection(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
}
else if(Decision.isArray(o)) {
try {
return toArray(o);
} catch (PageException e) {
return defaultValue;
}
}
return defaultValue;
}
/**
* convert a object to a File
* @param obj
* @return File
* @throws PageException
*/
public static File toFile(Object obj) throws PageException {
if(obj instanceof File) return (File)obj;
return FileUtil.toFile(Caster.toString(obj));
}
/**
* convert a object to a File
* @param obj
* @param defaultValue
* @return File
*/
public static File toFile(Object obj, File defaultValue) {
if(obj instanceof File) return (File)obj;
String str=Caster.toString(obj,null);
if(str==null) return defaultValue;
return FileUtil.toFile(str);
}
/**
* convert a object array to a HashMap filled with Function value Objects
* @param args Object array to convert
* @return hashmap containing Function values
* @throws ExpressionException
*/
public static Struct toFunctionValues(Object[] args) throws ExpressionException {
return toFunctionValues(args, 0, args.length);
}
public static Struct toFunctionValues(Object[] args, int offset, int len) throws ExpressionException {
// TODO nicht sehr optimal
Struct sct=new StructImpl(StructImpl.TYPE_LINKED);
for(int i=offset;i<offset+len;i++) {
if(args[i] instanceof FunctionValueImpl){
FunctionValueImpl value = (FunctionValueImpl) args[i];
sct.setEL(value.getNameAsKey(),value.getValue());
}
else throw new ExpressionException("Missing argument name, when using named parameters to a function, every parameter must have a name ["+i+":"+args[i].getClass().getName()+"].");
}
return sct;
}
public static Object[] toFunctionValues(Struct args) {
// TODO nicht sehr optimal
Iterator<Entry<Key, Object>> it = args.entryIterator();
Entry<Key, Object> e;
List<FunctionValue> fvalues=new ArrayList<FunctionValue>();
while(it.hasNext()) {
e=it.next();
fvalues.add(new FunctionValueImpl(e.getKey().getString(),e.getValue()));
}
return fvalues.toArray(new FunctionValue[fvalues.size()]);
}
/**
* casts a string to a Locale
* @param strLocale
* @return Locale from String
* @throws ExpressionException
*/
public static Locale toLocale(String strLocale) throws ExpressionException {
return LocaleFactory.getLocale(strLocale);
}
/**
* casts a string to a Locale
* @param strLocale
* @param defaultValue
* @return Locale from String
*/
public static Locale toLocale(String strLocale, Locale defaultValue) {
return LocaleFactory.getLocale(strLocale,defaultValue);
}
/**
* casts a string to a TimeZone
* @param strTimeZone
* @return TimeZone from String
* @throws ExpressionException
*/
public static TimeZone toTimeZone(String strTimeZone) throws ExpressionException {
return TimeZoneUtil.toTimeZone(strTimeZone);
}
/**
* casts a string to a TimeZone
* @param strTimeZone
* @param defaultValue
* @return TimeZone from String
*/
public static TimeZone toTimeZone(String strTimeZone, TimeZone defaultValue) {
return TimeZoneUtil.toTimeZone(strTimeZone,defaultValue);
}
public static TimeZone toTimeZone(Object oTimeZone, TimeZone defaultValue) {
if(oTimeZone instanceof TimeZone) return (TimeZone) oTimeZone;
return TimeZoneUtil.toTimeZone(Caster.toString(oTimeZone,null),defaultValue);
}
/**
* casts a Object to a Node List
* @param o Object to Cast
* @return NodeList from Object
* @throws PageException
*/
public static NodeList toNodeList(Object o) throws PageException {
//print.ln("nodeList:"+o);
if(o instanceof NodeList) {
return (NodeList)o;
}
else if(o instanceof ObjectWrap) {
return toNodeList(((ObjectWrap)o).getEmbededObject());
}
throw new CasterException(o,"NodeList");
}
/**
* casts a Object to a Node List
* @param o Object to Cast
* @param defaultValue
* @return NodeList from Object
*/
public static NodeList toNodeList(Object o, NodeList defaultValue) {
//print.ln("nodeList:"+o);
if(o instanceof NodeList) {
return (NodeList)o;
}
else if(o instanceof ObjectWrap) {
return toNodeList(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
}
return defaultValue;
}
/**
* casts a Object to a XML Node
* @param o Object to Cast
* @return Node from Object
* @throws PageException
*/
public static Node toNode(Object o) throws PageException {
return toXML(o);
/*if(o instanceof Node)return (Node)o;
else if(o instanceof String) {
try {
return XMLCaster.toXMLStruct(XMLUtil.parse(o.toString(),false),false);
} catch (Exception e) {
throw Caster.toPageException(e);
}
}
else if(o instanceof ObjectWrap) {
return toNode(((ObjectWrap)o).getEmbededObject());
}
throw new CasterException(o,"Node");*/
}
/**
* casts a Object to a XML Node
* @param o Object to Cast
* @param defaultValue
* @return Node from Object
*/
public static Node toNode(Object o, Node defaultValue) {
return toXML(o,defaultValue);
/*if(o instanceof Node)return (Node)o;
else if(o instanceof String) {
try {
return XMLCaster.toXMLStruct(XMLUtil.parse(o.toString(),false),false);
} catch (Exception e) {
return defaultValue;
}
}
else if(o instanceof ObjectWrap) {
return toNode(((ObjectWrap)o).getEmbededObject(defaultValue),defaultValue);
}
return defaultValue;*/
}
/**
* casts a boolean to a Integer
* @param b
* @return Integer from boolean
*/
public static Integer toInteger(boolean b) {
return b?Constants.INTEGER_1:Constants.INTEGER_0;
}
/**
* casts a char to a Integer
* @param c
* @return Integer from char
*/
public static Integer toInteger(char c) {
return Integer.valueOf(c);
}
/**
* casts a double to a Integer
* @param d
* @return Integer from double
*/
public static Integer toInteger(double d) {
return Integer.valueOf((int)d);
}
/**
* casts a Object to a Integer
* @param o Object to cast to Integer
* @return Integer from Object
* @throws PageException
*/
public static Integer toInteger(Object o) throws PageException {
return Integer.valueOf(toIntValue(o));
}
/**
* casts a Object to a Integer
* @param str Object to cast to Integer
* @return Integer from Object
* @throws PageException
*/
public static Integer toInteger(String str) throws PageException {
return Integer.valueOf(toIntValue(str));
}
// used in bytecode genrator
public static Integer toInteger(int i) {
return Integer.valueOf(i);
}
/**
* casts a Object to a Integer
* @param o Object to cast to Integer
* @param defaultValue
* @return Integer from Object
*/
public static Integer toInteger(Object o, Integer defaultValue) {
if(defaultValue!=null) return Integer.valueOf(toIntValue(o,defaultValue.intValue()));
int res=toIntValue(o,Integer.MIN_VALUE);
if(res==Integer.MIN_VALUE) return defaultValue;
return Integer.valueOf(res);
}
/**
* casts a Object to null
* @param value
* @return to null from Object
* @throws PageException
*/
public static Object toNull(Object value) throws PageException {
if(value==null)return null;
if(value instanceof String && Caster.toString(value).trim().length()==0) return null;
if(value instanceof Number && ((Number)value).intValue()==0) return null;
throw new CasterException(value,"null");
}
/**
* casts a Object to null
* @param value
* @param defaultValue
* @return to null from Object
*/
public static Object toNull(Object value, Object defaultValue){
if(value==null)return null;
if(value instanceof String && Caster.toString(value,"").trim().length()==0) return null;
if(value instanceof Number && ((Number)value).intValue()==0) return null;
return defaultValue;
}
/**
* cast Object to a XML Node
* @param value
* @param defaultValue
* @return XML Node
*/
public static Node toXML(Object value, Node defaultValue) {
try {
return toXML(value);
} catch (PageException e) {
return defaultValue;
}
}
/**
* cast Object to a XML Node
* @param value
* @return XML Node
* @throws PageException
*/
public static Node toXML(Object value) throws PageException {
if(value instanceof Node) return XMLCaster.toXMLStruct((Node)value,false);
if(value instanceof ObjectWrap) {
return toXML(((ObjectWrap)value).getEmbededObject());
}
try {
return XMLCaster.toXMLStruct(XMLUtil.parse(XMLUtil.toInputSource(null, value),null,false),false);
}
catch(Exception outer) {
throw Caster.toPageException(outer);
}
}
public static String toStringForce(Object value, String defaultValue) {
String rtn=toString(value,null);
if(rtn!=null)return rtn;
try {
if(value instanceof Struct) {
return new ScriptConverter().serialize(value);
}
else if(value instanceof Array) {
return new ScriptConverter().serialize(value);
}
}
catch (ConverterException e) {}
return defaultValue;
}
public static Resource toResource(PageContext pc,Object src, boolean existing) throws ExpressionException {
return toResource(pc,src,existing,pc.getConfig().allowRealPath());
}
public static Resource toResource(PageContext pc,Object src, boolean existing,boolean allowRealpath) throws ExpressionException {
if(src instanceof Resource) return (Resource) src;
if(src instanceof File) src=src.toString();
if(src instanceof String) {
if(existing)
return ResourceUtil.toResourceExisting(pc, (String)src,allowRealpath);
return ResourceUtil.toResourceNotExisting(pc, (String)src,allowRealpath);
}
if(src instanceof FileStreamWrapper) return ((FileStreamWrapper)src).getResource();
throw new CasterException(src,"Resource");
}
public static Resource toResource(Config config,Object src, boolean existing) throws ExpressionException {
if(src instanceof Resource) return (Resource) src;
if(src instanceof File) src=src.toString();
if(src instanceof String) {
if(existing)
return ResourceUtil.toResourceExisting(config, (String)src);
return ResourceUtil.toResourceNotExisting(config, (String)src);
}
if(src instanceof FileStreamWrapper) return ((FileStreamWrapper)src).getResource();
throw new CasterException(src,"Resource");
}
public static Hashtable toHashtable(Object obj) throws PageException {
if(obj instanceof Hashtable) return (Hashtable) obj;
return (Hashtable) Duplicator.duplicateMap(toMap(obj,false), new Hashtable(), false);
}
public static Vector toVetor(Object obj) throws PageException {
if(obj instanceof Vector) return (Vector) obj;
return (Vector) Duplicator.duplicateList(toList(obj,false),new Vector(), false);
}
public static Calendar toCalendar(Date date, TimeZone tz) {
tz=ThreadLocalPageContext.getTimeZone(tz);
Calendar c = tz==null?JREDateTimeUtil.newInstance():JREDateTimeUtil.newInstance(tz);
c.setTime(date);
return c;
}
public static Calendar toCalendar(long time, TimeZone tz) {
tz=ThreadLocalPageContext.getTimeZone(tz);
Calendar c = tz==null?JREDateTimeUtil.newInstance():JREDateTimeUtil.newInstance(tz);
c.setTimeInMillis(time);
return c;
}
public static Serializable toSerializable(Object object) throws CasterException {
if(object instanceof Serializable)return (Serializable)object;
throw new CasterException(object,"Serializable");
}
public static Serializable toSerializable(Object object, Serializable defaultValue) {
if(object instanceof Serializable)return (Serializable)object;
return defaultValue;
}
public static byte[] toBytes(Object obj,Charset charset) throws PageException {
try {
if(obj instanceof byte[]) return (byte[]) obj;
if(obj instanceof InputStream)return IOUtil.toBytes((InputStream)obj);
if(obj instanceof Resource)return IOUtil.toBytes((Resource)obj);
if(obj instanceof File)return IOUtil.toBytes((File)obj);
if(obj instanceof String) return ((String)obj).getBytes(charset==null?SystemUtil.getCharset():charset);
if(obj instanceof Blob) {
InputStream is=null;
try {
is=((Blob)obj).getBinaryStream();
return IOUtil.toBytes(is);
}
finally {
IOUtil.closeEL(is);
}
}
}
catch(IOException ioe) {
throw toPageException(ioe);
}
catch(SQLException ioe) {
throw toPageException(ioe);
}
throw new CasterException(obj,byte[].class);
}
public static InputStream toInputStream(Object obj,Charset charset) throws PageException {
try {
if(obj instanceof InputStream)return (InputStream)obj;
if(obj instanceof byte[]) return new ByteArrayInputStream((byte[]) obj);
if(obj instanceof Resource)return ((Resource)obj).getInputStream();
if(obj instanceof File)return new FileInputStream((File)obj);
if(obj instanceof String) return new ByteArrayInputStream(((String)obj).getBytes(charset==null?SystemUtil.getCharset():charset));
if(obj instanceof Blob) return ((Blob)obj).getBinaryStream();
}
catch(IOException ioe) {
throw toPageException(ioe);
}
catch(SQLException ioe) {
throw toPageException(ioe);
}
throw new CasterException(obj,InputStream.class);
}
public static OutputStream toOutputStream(Object obj) throws PageException {
if(obj instanceof OutputStream)return (OutputStream)obj;
throw new CasterException(obj,OutputStream.class);
}
public static Object castTo(PageContext pc, Class trgClass, Object obj) throws PageException {
if(trgClass==null)return Caster.toNull(obj);
else if(obj.getClass()==trgClass) return obj;
else if(trgClass==boolean.class)return Caster.toBoolean(obj);
else if(trgClass==byte.class)return Caster.toByte(obj);
else if(trgClass==short.class)return Caster.toShort(obj);
else if(trgClass==int.class)return Integer.valueOf(Caster.toDouble(obj).intValue());
else if(trgClass==long.class)return Caster.toLong(obj);
else if(trgClass==float.class)return new Float(Caster.toDouble(obj).floatValue());
else if(trgClass==double.class)return Caster.toDouble(obj);
else if(trgClass==char.class)return Caster.toCharacter(obj);
else if(trgClass==Boolean.class)return Caster.toBoolean(obj);
else if(trgClass==Byte.class)return Caster.toByte(obj);
else if(trgClass==Short.class)return Caster.toShort(obj);
else if(trgClass==Integer.class)return Integer.valueOf(Caster.toDouble(obj).intValue());
else if(trgClass==Long.class)return Caster.toLong(obj);
else if(trgClass==Float.class)return new Float(Caster.toDouble(obj).floatValue());
else if(trgClass==Double.class)return Caster.toDouble(obj);
else if(trgClass==Character.class)return Caster.toCharacter(obj);
else if(trgClass==Object.class)return obj;
else if(trgClass==String.class)return Caster.toString(obj);
if(Reflector.isInstaneOf(obj.getClass(), trgClass)) return obj;
return Caster.castTo(pc, trgClass.getName(), obj,false);
}
public static Objects toObjects(PageContext pc,Object obj) throws PageException {
if(obj instanceof Objects) return (Objects) obj;
if(obj instanceof ObjectWrap) return toObjects(pc,((ObjectWrap)obj).getEmbededObject());
return new JavaObject(pc.getVariableUtil(), obj);
}
public static BigDecimal toBigDecimal(Object o) throws PageException {
if(o instanceof BigDecimal) return (BigDecimal) o;
if(o instanceof Number) return new BigDecimal(((Number)o).doubleValue());
else if(o instanceof Boolean) return new BigDecimal(((Boolean)o).booleanValue()?1:0);
else if(o instanceof String) return new BigDecimal(o.toString());
else if(o instanceof Castable) return new BigDecimal(((Castable)o).castToDoubleValue());
else if(o == null) return BigDecimal.ZERO;
else if(o instanceof ObjectWrap) return toBigDecimal(((ObjectWrap)o).getEmbededObject());
throw new CasterException(o,"number");
}
public static Object unwrap(Object value) throws PageException {
if(value==null) return null;
if(value instanceof ObjectWrap) {
return ((ObjectWrap)value).getEmbededObject();
}
return value;
}
public static Object unwrap(Object value,Object defaultValue) {
if(value==null) return null;
if(value instanceof ObjectWrap) {
return ((ObjectWrap)value).getEmbededObject(defaultValue);
}
return value;
}
public static CharSequence toCharSequence(Object obj) throws PageException {
if(obj instanceof CharSequence) return (CharSequence) obj;
return Caster.toString(obj);
}
public static CharSequence toCharSequence(Object obj, CharSequence defaultValue) {
if(obj instanceof CharSequence) return (CharSequence) obj;
String str = Caster.toString(obj,null);
if(str==null) return defaultValue;
return str;
}
}
|
package org.broadinstitute.hellbender.engine;
import org.broadinstitute.hellbender.CommandLineProgramTest;
import org.broadinstitute.hellbender.tools.walkers.variantutils.SelectVariants;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import org.broadinstitute.hellbender.utils.test.IntegrationTestSpec;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Tests to prove that we can access and query inputs on Google Cloud Storage (GCS) in VariantWalkers.
*/
public class VariantWalkerGCSSupportIntegrationTest extends CommandLineProgramTest {
private static final String TEST_VCF_ON_GCS = "org/broadinstitute/hellbender/engine/dbsnp_138.b37.20.10000000-10010000.vcf";
private static final String TEST_BGZIPPED_VCF_ON_GCS = "org/broadinstitute/hellbender/engine/dbsnp_138.b37.20.10000000-10010000.vcf.block.gz";
private static final String EXPECTED_OUTPUT_DIR = publicTestDir + "org/broadinstitute/hellbender/engine/GCSTests/";
@Override
public String getTestedToolName() {
return SelectVariants.class.getSimpleName();
}
@DataProvider(name = "GCSTestCases")
public Object[][] getGCSTestCases() {
final SimpleInterval singleInterval = new SimpleInterval("20", 10004000, 10006000);
final List<SimpleInterval> multipleIntervals = Arrays.asList(singleInterval, new SimpleInterval("20", 10008000, 10009000));
final String EXPECTED_WHOLE_FILE_RESULTS = EXPECTED_OUTPUT_DIR + "expected_VariantWalkerGCSSupportIntegrationTest_vcf_wholefile.vcf";
final String EXPECTED_SINGLE_INTERVAL_RESULTS = EXPECTED_OUTPUT_DIR + "expected_VariantWalkerGCSSupportIntegrationTest_vcf_single_interval.vcf";
final String EXPECTED_MULTIPLE_INTERVALS_RESULTS = EXPECTED_OUTPUT_DIR + "expected_VariantWalkerGCSSupportIntegrationTest_vcf_multiple_intervals.vcf";
return new Object[][] {
{ TEST_VCF_ON_GCS, null, EXPECTED_WHOLE_FILE_RESULTS },
{ TEST_BGZIPPED_VCF_ON_GCS, null, EXPECTED_WHOLE_FILE_RESULTS },
{ TEST_VCF_ON_GCS, Collections.singletonList(singleInterval), EXPECTED_SINGLE_INTERVAL_RESULTS },
{ TEST_BGZIPPED_VCF_ON_GCS, Collections.singletonList(singleInterval), EXPECTED_SINGLE_INTERVAL_RESULTS },
{ TEST_VCF_ON_GCS, multipleIntervals, EXPECTED_MULTIPLE_INTERVALS_RESULTS },
{ TEST_BGZIPPED_VCF_ON_GCS, multipleIntervals, EXPECTED_MULTIPLE_INTERVALS_RESULTS }
};
}
@Test(dataProvider = "GCSTestCases", groups = {"bucket"})
public void testReadVCFOnGCS( final String vcf, final List<SimpleInterval> intervals, final String expectedOutput ) throws IOException {
String intervalArg = "";
if ( intervals != null ) {
final StringBuilder intervalArgBuilder = new StringBuilder();
for ( final SimpleInterval interval : intervals ) {
intervalArgBuilder.append(" -L ");
intervalArgBuilder.append(interval.toString());
}
intervalArg = intervalArgBuilder.toString();
}
final IntegrationTestSpec testSpec = new IntegrationTestSpec(
" -V " + getGCPTestInputPath() + vcf +
intervalArg +
" -O %s",
Collections.singletonList(expectedOutput)
);
testSpec.executeTest("testReadVCFOnGCS", this);
}
}
|
package com.splicemachine.derby.test.framework;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.commons.dbutils.DbUtils;
import org.apache.log4j.Logger;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class SpliceSchemaWatcher extends TestWatcher {
private static final Logger LOG = Logger.getLogger(SpliceSchemaWatcher.class);
public String schemaName;
public SpliceSchemaWatcher(String schemaName) {
this.schemaName = schemaName.toUpperCase();
}
@Override
protected void starting(Description description) {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
connection = SpliceNetConnection.getConnection();
rs = connection.getMetaData().getSchemas(null, schemaName);
if (rs.next())
executeDrop(schemaName);
connection.commit();
statement = connection.createStatement();
statement.execute("create schema " + schemaName);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(statement);
DbUtils.commitAndCloseQuietly(connection);
}
super.starting(description);
}
@Override
protected void finished(Description description) {
LOG.trace("Finished");
executeDrop(schemaName);
}
public static void executeDrop(String schemaName) {
LOG.trace("ExecuteDrop");
Connection connection = null;
Statement statement = null;
try {
connection = SpliceNetConnection.getConnection();
ResultSet resultSet = connection.getMetaData().getTables(null, schemaName.toUpperCase(), null, null);
while (resultSet.next()) {
SpliceTableWatcher.executeDrop(schemaName, resultSet.getString("TABLE_NAME"));
}
statement = connection.createStatement();
resultSet = connection.getMetaData().getSchemas(null, schemaName.toUpperCase());
while (resultSet.next()) {
statement.execute("drop schema " + schemaName + " RESTRICT");
}
connection.commit();
} catch (Exception e) {
LOG.error("error Dropping " + e.getMessage());
e.printStackTrace();
throw new RuntimeException(e);
} finally {
DbUtils.closeQuietly(statement);
DbUtils.commitAndCloseQuietly(connection);
}
}
}
|
package org.openlmis.functional;
import org.openlmis.UiUtils.HttpClient;
import org.openlmis.UiUtils.ResponseEntity;
import org.openlmis.restapi.domain.Report;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.IOException;
import java.sql.SQLException;
import static com.thoughtworks.selenium.SeleneseTestBase.assertEquals;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
public class ApproveRequisitionTest extends JsonUtility {
public static final String FULL_JSON_APPROVE_TXT_FILE_NAME = "ReportJsonApprove.txt";
public static final String FULL_JSON_MULTIPLE_PRODUCTS_APPROVE_TXT_FILE_NAME = "ReportJsonMultipleProductsApprove.txt";
@BeforeMethod(groups = {"webservice"})
public void setUp() throws Exception {
super.setup();
super.setupTestData(false);
super.setupDataRequisitionApprover();
}
@AfterMethod(groups = {"webservice"})
public void tearDown() throws IOException, SQLException {
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
@Test(groups = {"webservice"})
public void testApproveRequisitionValidRnR() throws Exception {
HttpClient client = new HttpClient();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
client.createContext();
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED", "commTrack", "HIV");
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack1");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity =
client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(200, responseEntity.getStatus());
assertTrue(response.contains("{\"success\":"));
assertEquals("APPROVED", dbWrapper.getRequisitionStatus(id));
ResponseEntity responseEntity1 = client.SendJSON("", "http://localhost:9091/feeds/requisition-status/recent", "GET", "", "");
assertTrue(responseEntity1.getResponse().contains("{\"requisitionId\":" + id + ",\"requisitionStatus\":\"APPROVED\",\"emergency\":false,\"startDate\":"));
assertTrue(responseEntity1.getResponse().contains(",\"endDate\":"));
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionUnauthorizedAccess() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setRequisitionId(id);
reportFromJson.setUserName("commTrack100");
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity = client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve", "PUT",
"commTrack100", "Admin123");
client.SendJSON("", "http://localhost:9091/", "GET", "", "");
assertEquals(401, responseEntity.getStatus());
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionProductNotAvailableInSystem() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P1000");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity =
client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(400, responseEntity.getStatus());
assertEquals("{\"error\":\"Invalid product codes [P1000]\"}", response);
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionProductNotAvailableInRnR() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P11");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity =
client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(400, responseEntity.getStatus());
assertEquals("{\"error\":\"Invalid product codes [P11]\"}", response);
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionProgramProductsInactive() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
dbWrapper.updateActiveStatusOfProgramProduct("P10","HIV","False");
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity = client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(200, responseEntity.getStatus());
assertTrue(response.contains("{\"success\":"));
assertEquals("APPROVED", dbWrapper.getRequisitionStatus(id));
dbWrapper.updateActiveStatusOfProgramProduct("P10","HIV","True");
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionProgramInactive() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
dbWrapper.updateActiveStatusOfProgram("HIV",false);
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity = client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(200, responseEntity.getStatus());
assertTrue(response.contains("{\"success\":"));
assertEquals("APPROVED", dbWrapper.getRequisitionStatus(id));
dbWrapper.updateActiveStatusOfProgram("HIV",true);
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionProductInactive() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
dbWrapper.updateActiveStatusOfProduct("P10","False");
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity = client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(200, responseEntity.getStatus());
assertTrue(response.contains("{\"success\":"));
assertEquals("APPROVED", dbWrapper.getRequisitionStatus(id));
dbWrapper.updateActiveStatusOfProduct("P10","True");
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionNotVirtualFacility() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity = client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(400, responseEntity.getStatus());
assertEquals("{\"error\":\"Approval not allowed\"}", response);
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionInvalidRequisitionId() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
submitRequisition("commTrack1","HIV");
Long id = 999999L;
Long id2 = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
Report reportFromJson = readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setRequisitionId(id2);
reportFromJson.setUserName("commTrack");
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity = client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve", "PUT",
"commTrack", "Admin123");
String response = responseEntity.getResponse();
client.SendJSON("", "http://localhost:9091/", "GET", "", "");
assertEquals(400, responseEntity.getStatus());
assertEquals("{\"error\":\"Invalid RequisitionID\"}", response);
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionBlankQuantityApproved() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED","commTrack","HIV");
Report reportFromJson = readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setRequisitionId(id);
reportFromJson.setUserName("commTrack1");
reportFromJson.getProducts().get(0).setProductCode("P10");
ResponseEntity responseEntity =
client.SendJSON(
getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
client.SendJSON("", "http://localhost:9091/", "GET", "", "");
assertEquals(400, responseEntity.getStatus());
assertEquals("{\"error\":\"Missing mandatory fields\"}", response);
}
@Test(groups = {"webservice"}, dependsOnMethods = {"testApproveRequisitionValidRnR"})
public void testApproveRequisitionOnIncorrectRequisitionStatus() throws Exception {
HttpClient client = new HttpClient();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
client.createContext();
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack1");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
ResponseEntity responseEntity =
client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(400, responseEntity.getStatus());
assertTrue(response.contains("{\"error\":\"Approval not allowed\"}"));
}
@Test(groups = {"webservice"})
public void testApproveRequisitionProductCountMismatch() throws Exception {
HttpClient client = new HttpClient();
dbWrapper.updateVirtualPropertyOfFacility("F10", "true");
client.createContext();
submitRequisition("commTrack1","HIV");
Long id = (long)dbWrapper.getMaxRnrID();
dbWrapper.updateRequisitionStatus("AUTHORIZED", "commTrack", "HIV");
Report reportFromJson = JsonUtility.readObjectFromFile(FULL_JSON_MULTIPLE_PRODUCTS_APPROVE_TXT_FILE_NAME, Report.class);
reportFromJson.setUserName("commTrack1");
reportFromJson.setRequisitionId(id);
reportFromJson.getProducts().get(0).setProductCode("P10");
reportFromJson.getProducts().get(0).setQuantityApproved(65);
reportFromJson.getProducts().get(1).setProductCode("P11");
reportFromJson.getProducts().get(1).setQuantityApproved(65);
ResponseEntity responseEntity =
client.SendJSON(getJsonStringFor(reportFromJson),
"http://localhost:9091/rest-api/requisitions/" + id + "/approve",
"PUT",
"commTrack",
"Admin123");
String response = responseEntity.getResponse();
assertEquals(400, responseEntity.getStatus());
assertTrue(response.contains("{\"error\":\"Products do not match with requisition\"}"));
assertEquals("AUTHORIZED", dbWrapper.getRequisitionStatus(id));
}
}
|
package nl.mvdr.tinustris.controller;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import nl.mvdr.tinustris.gui.ConfigurationScreen;
/**
* Controller for the netplay configuration screen.
*
* @author Martijn van de Rijdt
*/
@Slf4j
public class NetplayConfigurationScreenController {
/** Radio button for an offline game. */
@FXML
private RadioButton offlineRadioButton;
/** Radio button for hosting a netplay game. */
@FXML
private RadioButton hostRadioButton;
/** Radio button for joining a netplay game. */
@FXML
private RadioButton joinRadioButton;
/**
* Handles the player activating the "next" button.
*
* @param event event leading to this method call; its source should be a component in the configuration screen stage
* @throws Exception unexpected exception on loading the next screen
*/
@FXML
private void next(ActionEvent event) throws Exception {
log.info("Next button activated.");
Application nextScreen = createNextScreen();
Node source = (Node)event.getSource();
Stage stage = (Stage)source.getScene().getWindow();
log.info("Starting the next screen: " + nextScreen);
nextScreen.start(stage);
}
/**
* Creates an application for the next screen, depending on the player's selected radio button.
*
* @return application
*/
private Application createNextScreen() {
Application result;
Toggle selectedRadioButton = offlineRadioButton.getToggleGroup().getSelectedToggle();
if (selectedRadioButton == offlineRadioButton) {
result = new ConfigurationScreen();
} else if (selectedRadioButton == hostRadioButton) {
throw new UnsupportedOperationException(); // TODO
} else if (selectedRadioButton == joinRadioButton) {
throw new UnsupportedOperationException(); // TODO
} else {
// Should not occur; there is a default radio button selection and there is no way to deselect.
throw new IllegalStateException("Unexpected selection: " + selectedRadioButton);
}
return result;
}
}
|
package de.danielnaber.languagetool.rules;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Pattern;
import de.danielnaber.languagetool.AnalyzedSentence;
import de.danielnaber.languagetool.AnalyzedTokenReadings;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.tools.UnsyncStack;
public class UnpairedQuotesBracketsRule extends Rule {
/**
* Note that there must be equal length of both arrays, and the sequence of
* starting symbols must match exactly the sequence of ending symbols.
*/
private static final String[] START_SYMBOLS = { "[", "(", "{", "\"", "'" };
private static final String[] END_SYMBOLS = { "]", ")", "}", "\"", "'" };
private final String[] startSymbols;
private final String[] endSymbols;
private static final String[] EN_START_SYMBOLS = { "[", "(", "{", "“", "\"",
"'" };
private static final String[] EN_END_SYMBOLS = { "]", ")", "}", "”", "\"",
"'" };
private static final String[] PL_START_SYMBOLS = { "[", "(", "{", "„", "»",
"\"" };
private static final String[] PL_END_SYMBOLS = { "]", ")", "}", "”", "«",
"\"" };
private static final String[] SK_START_SYMBOLS = { "[", "(", "{", "„", "»",
"\"" };
private static final String[] SK_END_SYMBOLS = { "]", ")", "}", "“", "«",
"\"" };
private static final String[] RO_START_SYMBOLS = { "[", "(", "{", "„", "«" };
private static final String[] RO_END_SYMBOLS = { "]", ")", "}", "”", "»" };
private static final String[] FR_START_SYMBOLS = { "[", "(", "{", "»", "‘" };
private static final String[] FR_END_SYMBOLS = { "]", ")", "}", "«", "’" };
private static final String[] DE_START_SYMBOLS = { "[", "(", "{", "„", "»",
"‘" };
private static final String[] DE_END_SYMBOLS = { "]", ")", "}", "“", "«", "’" };
private static final String[] ES_START_SYMBOLS = { "[", "(", "{", "“", "«",
"¿", "¡" };
private static final String[] ES_END_SYMBOLS = { "]", ")", "}", "”", "»",
"?", "!" };
private static final String[] UK_START_SYMBOLS = { "[", "(", "{", "„", "«" };
private static final String[] UK_END_SYMBOLS = { "]", ")", "}", "“", "»" };
private static final String[] RU_START_SYMBOLS = { "[", "(", "{", "„", "«",
"\"", "'" };
private static final String[] RU_END_SYMBOLS = { "]", ")", "}", "“", "»",
"\"", "'" };
private static final String[] NL_START_SYMBOLS = { "[", "(", "{", "„", "“",
"‘" };
private static final String[] NL_END_SYMBOLS = { "]", ")", "}", "”", "”", "’" };
private static final String[] IT_START_SYMBOLS = { "[", "(", "{", "»", "‘" };
private static final String[] IT_END_SYMBOLS = { "]", ")", "}", "«", "’" };
/**
* The stack for pairing symbols.
*/
private final UnsyncStack<SymbolLocator> symbolStack = new UnsyncStack<SymbolLocator>();
/**
* Stack of rule matches.
*/
private final UnsyncStack<RuleMatchLocator> ruleMatchStack = new UnsyncStack<RuleMatchLocator>();
private boolean endOfParagraph;
private final Language ruleLang;
private static final Pattern PUNCTUATION = Pattern.compile("\\p{Punct}");
private static final Pattern PUNCTUATION_NO_DOT = Pattern
.compile("[\\p{Punct}&&[^\\.]]");
private static final Pattern NUMBER = Pattern.compile("\\d+");
private static final Pattern NUMERALS = Pattern
.compile("(?i)\\d{1,2}?[a-z']*|M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$");
private int ruleMatchIndex;
private List<RuleMatch> ruleMatches;
public UnpairedQuotesBracketsRule(final ResourceBundle messages,
final Language language) {
super(messages);
super.setCategory(new Category(messages.getString("category_misc")));
setParagraphBackTrack(true);
if (language.equals(Language.POLISH)) {
startSymbols = PL_START_SYMBOLS;
endSymbols = PL_END_SYMBOLS;
} else if (language.equals(Language.SLOVAK)) {
startSymbols = SK_START_SYMBOLS;
endSymbols = SK_END_SYMBOLS;
} else if (language.equals(Language.FRENCH)) {
startSymbols = FR_START_SYMBOLS;
endSymbols = FR_END_SYMBOLS;
} else if (language.equals(Language.ENGLISH)) {
startSymbols = EN_START_SYMBOLS;
endSymbols = EN_END_SYMBOLS;
} else if (language.equals(Language.GERMAN)) {
startSymbols = DE_START_SYMBOLS;
endSymbols = DE_END_SYMBOLS;
} else if (language.equals(Language.DUTCH)) {
startSymbols = NL_START_SYMBOLS;
endSymbols = NL_END_SYMBOLS;
} else if (language.equals(Language.SPANISH)) {
startSymbols = ES_START_SYMBOLS;
endSymbols = ES_END_SYMBOLS;
} else if (language.equals(Language.UKRAINIAN)) {
startSymbols = UK_START_SYMBOLS;
endSymbols = UK_END_SYMBOLS;
} else if (language.equals(Language.RUSSIAN)) {
startSymbols = RU_START_SYMBOLS;
endSymbols = RU_END_SYMBOLS;
} else if (language.equals(Language.ITALIAN)) {
startSymbols = IT_START_SYMBOLS;
endSymbols = IT_END_SYMBOLS;
} else if (language.equals(Language.ROMANIAN)) {
startSymbols = RO_START_SYMBOLS;
endSymbols = RO_END_SYMBOLS;
} else {
startSymbols = START_SYMBOLS;
endSymbols = END_SYMBOLS;
}
ruleLang = language;
}
public final String getId() {
return "UNPAIRED_BRACKETS";
}
public final String getDescription() {
return messages.getString("desc_unpaired_brackets");
}
// TODO: make this a generic rule, and extend for every language
//find a way to easily specify exceptions (abstract method similar
// to isEnglishException?)
public final RuleMatch[] match(final AnalyzedSentence text) {
ruleMatches = new ArrayList<RuleMatch>();
final AnalyzedTokenReadings[] tokens = text.getTokensWithoutWhitespace();
if (endOfParagraph) {
reset();
}
ruleMatchIndex = getMatchesIndex();
for (int i = 1; i < tokens.length; i++) {
for (int j = 0; j < startSymbols.length; j++) {
final String token = tokens[i].getToken();
if (token.equals(startSymbols[j]) || token.equals(endSymbols[j])) {
boolean precededByWhitespace = true;
if (startSymbols[j].equals(endSymbols[j])) {
precededByWhitespace = tokens[i - 1].isSentStart()
|| tokens[i].isWhitespaceBefore()
|| PUNCTUATION_NO_DOT.matcher(tokens[i - 1].getToken())
.matches();
}
boolean followedByWhitespace = true;
if (i < tokens.length - 1 && startSymbols[j].equals(endSymbols[j])) {
followedByWhitespace = tokens[i + 1].isWhitespaceBefore()
|| PUNCTUATION.matcher(tokens[i + 1].getToken()).matches();
}
if (followedByWhitespace && precededByWhitespace) {
if (i == tokens.length) {
precededByWhitespace = false;
} else if (startSymbols[j].equals(endSymbols[j])) {
if (symbolStack.empty()) {
followedByWhitespace = false;
} else {
precededByWhitespace = false;
}
}
}
boolean noException = true;
if (ruleLang.equals(Language.ENGLISH) && i > 1) {
noException = isEnglishException(token, tokens, i,
precededByWhitespace, followedByWhitespace);
}
if (noException && precededByWhitespace
&& token.equals(startSymbols[j])) {
symbolStack.push(new SymbolLocator(startSymbols[j], i));
} else if (noException && followedByWhitespace
&& token.equals(endSymbols[j])) {
if (i > 1 && endSymbols[j].equals(")")) {
// exception for bullets: 1), 2), 3)...,
// II), 2') and 1a).
if ((NUMERALS.matcher(tokens[i - 1].getToken()).matches() && !(!symbolStack
.empty() && "(".equals(symbolStack.peek().symbol)))) {
noException = false;
}
}
if (noException)
if (symbolStack.isEmpty()) {
symbolStack.push(new SymbolLocator(endSymbols[j], i));
} else {
if (symbolStack.peek().symbol.equals(startSymbols[j])) {
symbolStack.pop();
} else {
symbolStack.push(new SymbolLocator(endSymbols[j], i));
}
}
}
}
}
}
for (final SymbolLocator sLoc : symbolStack) {
final RuleMatch rMatch = createMatch(tokens[sLoc.index].getStartPos(),
sLoc.symbol);
if (rMatch != null) {
ruleMatches.add(rMatch);
}
}
symbolStack.clear();
if (tokens[tokens.length - 1].isParaEnd()) {
endOfParagraph = true;
}
return toRuleMatchArray(ruleMatches);
}
private boolean isEnglishException(final String token,
final AnalyzedTokenReadings[] tokens, final int i, final boolean precSpace,
final boolean follSpace) {
//TODO: add an', o', 'till, 'tain't, 'cept, 'fore in the disambiguator
//and mark up as contractions somehow
// add exception for dates like '52
if (!precSpace && follSpace) {
// exception for English inches, e.g., 20"
if ("\"".equals(token)
&& NUMBER.matcher(tokens[i - 1].getToken()).matches()) {
return false;
}
// Exception for English plural Saxon genetive
// current disambiguation scheme is a bit too greedy
// for adjectives
if ("'".equals(token) && tokens[i].hasPosTag("POS")) {
return false;
}
// puttin' on the Ritz
if ("'".equals(token) && tokens[i - 1].hasPosTag("VBG")
&& tokens[i - 1].getToken().endsWith("in")) {
return false;
}
}
if (precSpace && !follSpace) {
// hold 'em!
if ("'".equals(token) && i < tokens.length
&& "em".equals(tokens[i + 1].getToken())) {
return false;
}
}
return true;
}
private RuleMatch createMatch(final int startPos, final String symbol) {
if (!ruleMatchStack.empty()) {
final int index = findSymbolNum(symbol);
if (index >= 0) {
final RuleMatchLocator rLoc = ruleMatchStack.peek();
if (rLoc.symbol.equals(startSymbols[index])) {
if (ruleMatches.size() > rLoc.myIndex) {
ruleMatches.remove(rLoc.myIndex);
ruleMatchStack.pop();
return null;
// if (ruleMatches.get(rLoc.myIndex).getFromPos())
}
if (isInMatches(rLoc.index)) {
setAsDeleted(rLoc.index);
ruleMatchStack.pop();
return null;
}
}
}
}
ruleMatchStack.push(new RuleMatchLocator(symbol, ruleMatchIndex,
ruleMatches.size()));
ruleMatchIndex++;
return new RuleMatch(this, startPos, startPos + symbol.length(), messages
.getString("unpaired_brackets"));
}
private int findSymbolNum(final String ch) {
for (int i = 0; i < endSymbols.length; i++) {
if (ch.equals(endSymbols[i])) {
return i;
}
}
return -1;
}
/**
* Reset the state information for the rule, including paragraph-level
* information.
*/
public final void reset() {
ruleMatchStack.clear();
symbolStack.clear();
if (!endOfParagraph) {
clearMatches();
}
endOfParagraph = false;
}
}
class SymbolLocator {
public String symbol;
public int index;
SymbolLocator(final String sym, final int ind) {
symbol = sym;
index = ind;
}
}
class RuleMatchLocator extends SymbolLocator {
public int myIndex;
RuleMatchLocator(final String sym, final int ind, final int myInd) {
super(sym, ind);
myIndex = myInd;
}
}
|
package info.bitrich.xchangestream.serum;
import static info.bitrich.xchangestream.serum.SerumEventType.subscribe;
import static info.bitrich.xchangestream.serum.SerumEventType.unknown;
import static info.bitrich.xchangestream.serum.SerumEventType.unsubscribe;
import com.fasterxml.jackson.databind.JsonNode;
import com.knowm.xchange.serum.SerumAdapters;
import com.knowm.xchange.serum.SerumConfigs.Commitment;
import com.knowm.xchange.serum.SerumConfigs.SubscriptionType;
import info.bitrich.xchangestream.serum.dto.SerumWsSubscriptionMessage;
import info.bitrich.xchangestream.service.netty.JsonNettyStreamingService;
import java.io.IOException;
import java.time.Duration;
import org.knowm.xchange.currency.CurrencyPair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SerumStreamingService extends JsonNettyStreamingService {
private static final Logger LOG = LoggerFactory.getLogger(SerumStreamingService.class);
private final SerumSubscriptionManager subscriptionManager = new SerumSubscriptionManager();
private final String RESULT = "result";
private final String SUBSCRIPTION = "subscription";
private final String PARAMS = "params";
private final String ID = "id";
public SerumStreamingService(String apiUrl) {
super(apiUrl);
}
public SerumStreamingService(
String apiUrl,
int maxFramePayloadLength,
Duration connectionTimeout,
Duration retryDuration,
int idleTimeoutSeconds) {
super(apiUrl, maxFramePayloadLength, connectionTimeout, retryDuration, idleTimeoutSeconds);
}
/**
* Channel name is mapped from the subscription id
*
* @param message to extract it from
*/
@Override
protected String getChannelNameFromMessage(JsonNode message) {
if (message.has(PARAMS) && message.get(PARAMS).has(SUBSCRIPTION)) {
final int subID = message.get(PARAMS).get(SUBSCRIPTION).intValue();
return subscriptionManager.getChannelName(subID);
}
return null;
}
private SerumEventType getMessageEvent(final JsonNode message) {
if (message.has(RESULT)) {
if (message.get(RESULT).isBoolean()) {
return unsubscribe;
}
if (message.get(RESULT).isInt()) {
return subscribe;
}
}
return unknown;
}
@Override
protected void handleMessage(final JsonNode message) {
try {
if (!message.has(ID)) {
super.handleMessage(message);
return;
}
final int reqID = message.get(ID).intValue();
switch (getMessageEvent(message)) {
case subscribe:
final int subID = message.get(RESULT).intValue();
subscriptionManager.newSubscription(reqID, subID);
break;
case unsubscribe:
boolean status = message.get(RESULT).asBoolean();
subscriptionManager.removedSubscription(reqID, status);
break;
case unknown:
default:
LOG.error("Unknown message type on msg {}", message);
}
} catch (Exception e) {
LOG.error("Issue processing message {}", message, e);
}
}
@Override
public String getSubscribeMessage(String channelName, Object... args) throws IOException {
if (args.length < 2) {
throw new IllegalArgumentException("Not enough args");
}
if (!(args[0] instanceof CurrencyPair)) {
throw new IllegalArgumentException("arg[0] must be the currency pairs");
}
if (!(args[1] instanceof SubscriptionType)) {
throw new IllegalArgumentException("arg[1] must be the subscription type");
}
final String account = SerumAdapters.toSolanaAddress((CurrencyPair) args[0]);
final SubscriptionType subscriptionType = (SubscriptionType) args[1];
final Commitment commitment =
args.length > 2 && args[2] != null && args[2] instanceof Commitment ? (Commitment) args[2] : Commitment.max;
int reqID = subscriptionManager.generateNewInflightRequest(channelName);
return new SerumWsSubscriptionMessage(commitment, subscriptionType, account, reqID).buildMsg();
}
@Override
public String getUnsubscribeMessage(String channelName) throws IOException {
return null;
}
public String buildChannelName(final SubscriptionType subscriptionType, final CurrencyPair pair) {
return subscriptionType.name() + "_" + pair.base.toString() + "-" + pair.counter.toString();
}
}
|
package de.fu_berlin.cdv.chasingpictures.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* This is largely copied from Mapbox' {@link com.mapbox.mapboxsdk.overlay.GpsLocationProvider GpsLocationProvider}.
*
* @author Simon Kalt
*/
public class LocationHelper {
/**
* The default minimum time interval for location updates (5 seconds).
*/
public static final int DEFAULT_MIN_TIME = 5000;
/**
* The default minimum distance for location updates (5 meters).
*/
public static final int DEFAULT_MIN_DISTANCE = 5;
private final Map<LocationListener, ListenerInfo> listeners = new HashMap<>();
private LocationManager mLocationManager;
/**
* Constructs a new location helper.
*
* @param context The current context
*/
public LocationHelper(@NonNull Context context) {
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
/**
* Returns the last known location with the highest available accuracy.
* <p/>
* TODO: Only update in specified interval?
*/
@Nullable
public Location getLastKnownLocation() {
return getLocation(false);
}
private Location getLocation(boolean registerListeners) {
Location location = null;
for (final String provider : mLocationManager.getProviders(true)) {
if (LocationManager.GPS_PROVIDER.equals(provider)
|| LocationManager.PASSIVE_PROVIDER.equals(provider)
|| LocationManager.NETWORK_PROVIDER.equals(provider)) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider);
if (location == null)
location = lastKnownLocation;
else if (lastKnownLocation != null && lastKnownLocation.getAccuracy() > location.getAccuracy())
location = lastKnownLocation;
if (registerListeners) {
for (Map.Entry<LocationListener, ListenerInfo> entry : listeners.entrySet()) {
ListenerInfo info = entry.getValue();
LocationListener listener = entry.getKey();
if (location != null)
listener.onLocationChanged(location);
if (!info.updatesStarted) {
mLocationManager.requestLocationUpdates(provider, info.minTime, info.minDistance, listener);
info.updatesStarted = true;
}
}
}
}
}
return location;
}
//region Starting and stopping location updates
/**
* Start location updates for the given listener.
*
* @param newListener
* @param minTime
* @param minDistance
* @return
*/
public LocationHelper startLocationUpdates(@NonNull LocationListener newListener, long minTime, float minDistance) {
if (!listeners.containsKey(newListener)) {
addListener(newListener, minTime, minDistance);
getLocation(true);
}
return this;
}
/**
* Stop location updates on all registered listeners.
*/
public void stopAllLocationUpdates() {
for (Map.Entry<LocationListener, ListenerInfo> entry : listeners.entrySet()) {
mLocationManager.removeUpdates(entry.getKey());
}
listeners.clear();
}
/**
* Stop location updates on the given listener.
*
* @param listener Listener to stop location updates for
*/
public void stopLocationUpdates(LocationListener listener) {
mLocationManager.removeUpdates(listener);
listeners.remove(listener);
}
//endregion
//region Internals
/**
* Add a listener to the local reference of listeners.
*
* @param listener Listener to add
*/
private void addListener(LocationListener listener, long minTime, float minDistance) {
listeners.put(listener, new ListenerInfo(minTime, minDistance));
}
/**
* Remove a listener from the local reference of listeners.
*
* @param listener Listener to removeg
*/
private void removeListener(LocationListener listener) {
if (listener != null)
listeners.remove(listener);
}
/**
* Info about location listeners.
*/
private static class ListenerInfo {
public final long minTime;
public final float minDistance;
public boolean updatesStarted;
private ListenerInfo(long minTime, float minDistance) {
this.minTime = minTime;
this.minDistance = minDistance;
}
}
//endregion
}
|
package co.com.sura.webTest;
import java.util.List;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.Format;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.CandidateSteps;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.jbehave.core.steps.SilentStepMonitor;
import org.jbehave.web.selenium.ContextView;
import org.jbehave.web.selenium.LocalFrameContextView;
import org.jbehave.web.selenium.PerStoriesWebDriverSteps;
import org.jbehave.web.selenium.SeleniumConfiguration;
import org.jbehave.web.selenium.SeleniumContext;
import org.jbehave.web.selenium.SeleniumStepMonitor;
import org.jbehave.web.selenium.WebDriverProvider;
import org.jbehave.web.selenium.WebDriverSteps;
import com.google.common.util.concurrent.MoreExecutors;
public abstract class PhantomJSConfig extends JUnitStories{
protected WebDriverProvider driverProvider = getWebDriver();
protected WebDriverSteps lifecycleSteps = new PerStoriesWebDriverSteps(driverProvider);
private SeleniumContext context = new SeleniumContext();
private ContextView contextView = new LocalFrameContextView().sized(500,100);
protected Configuration configuration = configuration();
public PhantomJSConfig() {
configuredEmbedder().useExecutorService(MoreExecutors.sameThreadExecutor());
}
protected WebDriverProvider getWebDriver()
{
return PhantomJSDelegateWebDriverProvider.getDriverWithJsDirverOnPath();
}
protected abstract List<Object> getWebSteps();
@Override
public List<CandidateSteps> candidateSteps() {
List<Object> steps = getWebSteps();
steps.add(lifecycleSteps);
steps.add(configuration.storyReporterBuilder());
InstanceStepsFactory instanceStepFactory = new InstanceStepsFactory(configuration(), steps.toArray(new Object[steps.size()]));
return instanceStepFactory.createCandidateSteps();
}
@Override
public List<String> storyPaths() {
return new StoryFinder().findPaths(
CodeLocations.codeLocationFromPath("src/test/resources"),
"**/*.story", "");
}
@Override
public Configuration configuration() {
if (configuration == null) {
Class<?> embeddableClass = this.getClass();
return new SeleniumConfiguration()
.useSeleniumContext(context)
.useWebDriverProvider(driverProvider)
.useStepMonitor(
new SeleniumStepMonitor(contextView, context,
new SilentStepMonitor()))
.useStoryLoader(new LoadFromClasspath(embeddableClass))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withCodeLocation(
CodeLocations
.codeLocationFromClass(embeddableClass))
.withDefaultFormats()
.withFormats(Format.CONSOLE, Format.TXT,
Format.HTML, Format.XML));
} else {
return configuration;
}
}
}
|
package WTSpec4M.presentation;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.ui.ViewerPane;
import org.eclipse.emf.common.ui.dialogs.ResourceDialog;
import org.eclipse.emf.common.ui.editor.ProblemEditorPart;
import org.eclipse.emf.common.ui.viewer.IViewerProvider;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.command.AddCommand;
import org.eclipse.emf.edit.command.CreateChildCommand;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
import org.eclipse.emf.edit.ui.celleditor.AdapterFactoryTreeEditor;
import org.eclipse.emf.edit.ui.dnd.EditingDomainViewerDropAdapter;
import org.eclipse.emf.edit.ui.dnd.LocalTransfer;
import org.eclipse.emf.edit.ui.dnd.ViewerDragAdapter;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.edit.ui.provider.UnwrappingSelectionProvider;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.PropertySheetPage;
import org.mondo.collaboration.online.core.LensSessionManager;
import org.mondo.collaboration.online.core.OnlineLeg;
import org.mondo.collaboration.online.core.OnlineLeg.CreateCommand;
import org.mondo.collaboration.online.core.OnlineLeg.LegCommand;
import org.mondo.collaboration.online.core.StorageAccess;
import org.mondo.collaboration.online.rap.UINotifierManager;
import org.mondo.collaboration.online.rap.UISessionManager;
import org.mondo.collaboration.online.rap.widgets.CommitMessageDialog;
import org.mondo.collaboration.online.rap.widgets.ModelExplorer;
import org.mondo.collaboration.online.rap.widgets.ModelLogView;
import org.mondo.collaboration.security.lens.bx.AbortReason.DenialReason;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.FutureCallback;
import WTSpec4M.provider.WTSpec4MItemProviderAdapterFactory;
/**
* This is an example of a WTSpec4M model editor. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
public class WTSpec4MEditor extends MultiPageEditorPart
implements IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider {
private static final String DENIED_MODIFICATION_ON_MODEL = "Denied Modification on Model";
/**
* The filters for file extensions supported by the editor. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public static final List<String> FILE_EXTENSION_FILTERS = prefixExtensions(WTSpec4MModelWizard.FILE_EXTENSIONS,
"*.");
/**
* Returns a new unmodifiable list containing prefixed versions of the
* extensions in the given list. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
private static List<String> prefixExtensions(List<String> extensions, String prefix) {
List<String> result = new ArrayList<String>();
for (String extension : extensions) {
result.add(prefix + extension);
}
return Collections.unmodifiableList(result);
}
/**
* This keeps track of the editing domain that is used to track all changes
* to the model. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected AdapterFactoryEditingDomain editingDomain;
/**
* This is the one adapter factory used for providing views of the model.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected AdapterFactory adapterFactory;
/**
* This is the content outline page. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected IContentOutlinePage contentOutlinePage;
/**
* This is a kludge... <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected IStatusLineManager contentOutlineStatusLineManager;
/**
* This is the content outline page's viewer. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected TreeViewer contentOutlineViewer;
/**
* This is the property sheet page. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected List<PropertySheetPage> propertySheetPages = new ArrayList<PropertySheetPage>();
/**
* This is the viewer that shadows the selection in the content outline. The
* parent relation must be correctly defined for this to work. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer selectionViewer;
/**
* This inverts the roll of parent and child in the content provider and
* show parents as a tree. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer parentViewer;
/**
* This shows how a tree view works. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected TreeViewer treeViewer;
/**
* This shows how a list view works. A list viewer doesn't support icons.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ListViewer listViewer;
/**
* This shows how a table view works. A table can be used as a list with
* icons. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TableViewer tableViewer;
/**
* This shows how a tree view with columns works. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer treeViewerWithColumns;
/**
* This keeps track of the active viewer pane, in the book. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ViewerPane currentViewerPane;
/**
* This keeps track of the active content viewer, which may be either one of
* the viewers in the pages or the content outline viewer. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Viewer currentViewer;
/**
* This listens to which ever viewer is active. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected ISelectionChangedListener selectionChangedListener;
/**
* This keeps track of all the
* {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are
* listening to this editor. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>();
/**
* This keeps track of the selection of the editor as a whole. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ISelection editorSelection = StructuredSelection.EMPTY;
/**
* This listens for when the outline becomes active <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected IPartListener partListener = new IPartListener() {
public void partActivated(IWorkbenchPart p) {
if (p instanceof ContentOutline) {
if (((ContentOutline) p).getCurrentPage() == contentOutlinePage) {
getActionBarContributor().setActiveEditor(WTSpec4MEditor.this);
setCurrentViewer(contentOutlineViewer);
}
} else if (p instanceof PropertySheet) {
if (propertySheetPages.contains(((PropertySheet) p).getCurrentPage())) {
getActionBarContributor().setActiveEditor(WTSpec4MEditor.this);
handleActivate();
}
} else if (p == WTSpec4MEditor.this) {
handleActivate();
}
}
public void partBroughtToTop(IWorkbenchPart p) {
// Ignore.
}
public void partClosed(IWorkbenchPart p) {
// TODO dispose leg only when it was the last open front model editor for the current user
if(leg != null){
String userName = ModelExplorer.getCurrentStorageAccess().getUsername();
if(legsForUser.get(userName)==1){
leg.dispose();
}
legsForUser.put(userName, legsForUser.get(userName)-1);
}
}
public void partDeactivated(IWorkbenchPart p) {
// Ignore.
}
public void partOpened(IWorkbenchPart p) {
// Ignore.
}
};
/**
* Resources that have been removed since last activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<Resource> removedResources = new ArrayList<Resource>();
/**
* Resources that have been changed since last activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<Resource> changedResources = new ArrayList<Resource>();
/**
* Resources that have been saved. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
protected Collection<Resource> savedResources = new ArrayList<Resource>();
/**
* Map to store the diagnostic associated with a resource. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>();
/**
* Controls whether the problem indication should be updated. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean updateProblemIndication = true;
/**
* Adapter used to update the problem indication when resources are demanded
* loaded. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected EContentAdapter problemIndicationAdapter = new EContentAdapter() {
@Override
public void notifyChanged(Notification notification) {
if (notification.getNotifier() instanceof Resource) {
switch (notification.getFeatureID(Resource.class)) {
case Resource.RESOURCE__IS_LOADED:
case Resource.RESOURCE__ERRORS:
case Resource.RESOURCE__WARNINGS: {
Resource resource = (Resource) notification.getNotifier();
Diagnostic diagnostic = analyzeResourceProblems(resource, null);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, diagnostic);
} else {
resourceToDiagnosticMap.remove(resource);
}
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
break;
}
}
} else {
super.notifyChanged(notification);
}
}
@Override
protected void setTarget(Resource target) {
basicSetTarget(target);
}
@Override
protected void unsetTarget(Resource target) {
basicUnsetTarget(target);
resourceToDiagnosticMap.remove(target);
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
}
};
private OnlineLeg leg;
private boolean isItMe;
private static Map<String, Integer> legsForUser = Maps.newHashMap();
private CommandStack commandStack;
private CommandStackListener refreshListener;
private CommandStackListener editorActionListener;
/**
* Handles activation of the editor or it's associated views. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleActivate() {
// Recompute the read only state.
if (editingDomain.getResourceToReadOnlyMap() != null) {
editingDomain.getResourceToReadOnlyMap().clear();
// Refresh any actions that may become enabled or disabled.
setSelection(getSelection());
}
if (!removedResources.isEmpty()) {
if (handleDirtyConflict()) {
getSite().getPage().closeEditor(WTSpec4MEditor.this, false);
} else {
removedResources.clear();
changedResources.clear();
savedResources.clear();
}
} else if (!changedResources.isEmpty()) {
changedResources.removeAll(savedResources);
handleChangedResources();
changedResources.clear();
savedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleChangedResources() {
if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
if (isDirty()) {
changedResources.addAll(editingDomain.getResourceSet().getResources());
}
editingDomain.getCommandStack().flush();
updateProblemIndication = false;
for (Resource resource : changedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
} catch (IOException exception) {
if (!resourceToDiagnosticMap.containsKey(resource)) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
}
}
}
if (AdapterFactoryEditingDomain.isStale(editorSelection)) {
setSelection(StructuredSelection.EMPTY);
}
updateProblemIndication = true;
updateProblemIndication();
}
}
/**
* Updates the problems indication with the information described in the
* specified diagnostic. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void updateProblemIndication() {
if (updateProblemIndication) {
BasicDiagnostic diagnostic = new BasicDiagnostic(Diagnostic.OK, "org.mondo.wt.cstudy.metamodel.editor", 0,
null, new Object[] { editingDomain.getResourceSet() });
for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) {
if (childDiagnostic.getSeverity() != Diagnostic.OK) {
diagnostic.add(childDiagnostic);
}
}
int lastEditorPage = getPageCount() - 1;
if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
((ProblemEditorPart) getEditor(lastEditorPage)).setDiagnostic(diagnostic);
if (diagnostic.getSeverity() != Diagnostic.OK) {
setActivePage(lastEditorPage);
}
} else if (diagnostic.getSeverity() != Diagnostic.OK) {
ProblemEditorPart problemEditorPart = new ProblemEditorPart();
problemEditorPart.setDiagnostic(diagnostic);
try {
addPage(++lastEditorPage, problemEditorPart, getEditorInput());
setPageText(lastEditorPage, problemEditorPart.getPartName());
setActivePage(lastEditorPage);
showTabs();
} catch (PartInitException exception) {
WTSpec4MEditorPlugin.INSTANCE.log(exception);
}
}
}
}
/**
* Shows a dialog that asks if conflicting changes should be discarded. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean handleDirtyConflict() {
return MessageDialog.openQuestion(getSite().getShell(), getString("_UI_FileConflict_label"),
getString("_WARN_FileConflict"));
}
/**
* This creates a model editor. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
public WTSpec4MEditor() {
super();
initializeEditingDomain();
}
/**
* This sets up the editing domain for the model editor. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated NOT
*/
protected void initializeEditingDomain() {
// Create an adapter factory that yields item providers.
ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new WTSpec4MItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
this.adapterFactory = adapterFactory;
commandStack = new BasicCommandStack();
// Add a listener to set the most recent command's affected objects to
// be the selection of the viewer with focus.
refreshListener = new CommandStackListener() {
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec(new Runnable() {
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
// Try to select the affected objects.
Command mostRecentCommand = ((CommandStack) event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
setSelectionToViewer(mostRecentCommand.getAffectedObjects());
}
for (Iterator<PropertySheetPage> i = propertySheetPages.iterator(); i.hasNext();) {
PropertySheetPage propertySheetPage = i.next();
if (propertySheetPage.getControl().isDisposed()) {
i.remove();
} else {
propertySheetPage.refresh();
}
}
}
});
}
};
commandStack.addCommandStackListener(refreshListener);
// Create the editing domain with a special command stack.
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack, new HashMap<Resource, Boolean>());
}
protected void initializeEditingDomain(AdapterFactoryEditingDomain editingDomain) {
this.editingDomain = editingDomain;
this.adapterFactory = editingDomain.getAdapterFactory();
refreshListener = new CommandStackListener() {
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec(new Runnable() {
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
// Try to select the affected objects.
Command mostRecentCommand = ((CommandStack) event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
setSelectionToViewer(mostRecentCommand.getAffectedObjects());
}
for (Iterator<PropertySheetPage> i = propertySheetPages.iterator(); i.hasNext();) {
PropertySheetPage propertySheetPage = i.next();
if (propertySheetPage.getControl().isDisposed()) {
i.remove();
} else {
propertySheetPage.refresh();
}
}
}
});
}
};
editingDomain.getCommandStack().addCommandStackListener(refreshListener);
}
/**
* This is here for the listener to be able to call it. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected void firePropertyChange(int action) {
super.firePropertyChange(action);
}
/**
* This sets the selection into whichever viewer is active. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSelectionToViewer(Collection<?> collection) {
final Collection<?> theSelection = collection;
// Make sure it's okay.
if (theSelection != null && !theSelection.isEmpty()) {
Runnable runnable = new Runnable() {
public void run() {
// Try to select the items in the current content viewer of
// the editor.
if (currentViewer != null) {
currentViewer.setSelection(new StructuredSelection(theSelection.toArray()), true);
}
}
};
getSite().getShell().getDisplay().asyncExec(runnable);
}
}
/**
* This returns the editing domain as required by the
* {@link IEditingDomainProvider} interface. This is important for
* implementing the static methods of {@link AdapterFactoryEditingDomain}
* and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public EditingDomain getEditingDomain() {
return editingDomain;
}
private final class UpdateOnModification implements FutureCallback<Object> {
@Override
public void onFailure(Throwable arg0) {
}
@Override
public void onSuccess(Object obj) {
if(!isItMe) {
System.out.println("other user");
selectionViewer.getControl().getDisplay().asyncExec( new Runnable() {
public void run() {
System.out.println("executing on ui thread");
if(selectionViewer != null)
selectionViewer.refresh();
System.out.println("finished");
}
});
}
}
}
private final class UpdateOnSave implements FutureCallback<Object> {
@Override
public void onFailure(Throwable arg0) {
}
@Override
public void onSuccess(Object obj) {
getContainer().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
}
});
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object[] getElements(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object[] getChildren(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean hasChildren(Object object) {
Object parent = super.getParent(object);
return parent != null;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object getParent(Object object) {
return null;
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setCurrentViewerPane(ViewerPane viewerPane) {
if (currentViewerPane != viewerPane) {
if (currentViewerPane != null) {
currentViewerPane.showFocus(false);
}
currentViewerPane = viewerPane;
}
setCurrentViewer(currentViewerPane.getViewer());
}
/**
* This makes sure that one content viewer, either for the current page or
* the outline view, if it has focus, is the current one. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setCurrentViewer(Viewer viewer) {
// If it is changing...
if (currentViewer != viewer) {
if (selectionChangedListener == null) {
// Create the listener on demand.
selectionChangedListener = new ISelectionChangedListener() {
// This just notifies those things that are affected by the
// section.
public void selectionChanged(SelectionChangedEvent selectionChangedEvent) {
setSelection(selectionChangedEvent.getSelection());
}
};
}
// Stop listening to the old one.
if (currentViewer != null) {
currentViewer.removeSelectionChangedListener(selectionChangedListener);
}
// Start listening to the new one.
if (viewer != null) {
viewer.addSelectionChangedListener(selectionChangedListener);
}
// Remember it.
currentViewer = viewer;
// Set the editors selection based on the current viewer's
// selection.
setSelection(currentViewer == null ? StructuredSelection.EMPTY : currentViewer.getSelection());
}
}
/**
* This returns the viewer as required by the {@link IViewerProvider}
* interface. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public Viewer getViewer() {
return currentViewer;
}
/**
* This creates a context menu for the viewer and adds a listener as well
* registering the menu for extension. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected void createContextMenuFor(StructuredViewer viewer) {
MenuManager contextMenu = new MenuManager("#PopUp");
contextMenu.add(new Separator("additions"));
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(this);
Menu menu = contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer));
int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers = new Transfer[] { LocalTransfer.getInstance(), LocalSelectionTransfer.getTransfer(),
FileTransfer.getInstance() };
viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer));
viewer.addDropSupport(dndOperations, transfers, new EditingDomainViewerDropAdapter(editingDomain, viewer));
}
/**
* This is the method called to load a resource into the editing domain's
* resource set based on the editor's input. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated NOT
*/
public void createModel() {
URI resourceURI = EditUIUtil.getURI(getEditorInput());
Exception exception = null;
Resource resource = null;
String userName = ModelExplorer.getCurrentStorageAccess().getUsername();
leg = LensSessionManager.getExistingLeg(userName, RWT.getUISession().getHttpSession(), resourceURI);
boolean isNewUser = false;
if(leg == null) {
initializeEditingDomain();
leg = LensSessionManager.createLeg(resourceURI, ModelExplorer.getCurrentStorageAccess(), editingDomain, RWT.getUISession().getHttpSession());
legsForUser.put(userName,1);
isNewUser = true;
} else {
initializeEditingDomain(leg.getEditingDomain());
legsForUser.put(userName, legsForUser.get(userName)+1);
}
UISessionManager.register(resourceURI, ModelExplorer.getCurrentStorageAccess().getUsername(), RWT.getUISession());
UINotifierManager.register(OnlineLeg.EVENT_UPDATE, RWT.getUISession(), new UpdateOnModification());
UINotifierManager.register(OnlineLeg.EVENT_SAVE, RWT.getUISession(), new UpdateOnSave());
resource = leg.getFrontResourceSet().getResources().get(0);
Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
// Submit changes for lens
if(isNewUser){
editorActionListener = new CommandStackListener() {
boolean isAborted = false;
@SuppressWarnings("unchecked")
@Override
public void commandStackChanged(EventObject event) {
if(isAborted)
return;
Command mostRecentCommand = editingDomain.getCommandStack().getMostRecentCommand();
//We have to change the create command to a customized one that set the ID attribute of the child
if(mostRecentCommand instanceof CreateChildCommand && !(mostRecentCommand instanceof OnlineLeg.CreateCommand)) {
CreateChildCommand commandDelegate = (CreateChildCommand) mostRecentCommand;
Collection<?> affectedObjects = commandDelegate.getAffectedObjects();
Command command = commandDelegate.getCommand();
EditingDomain domain = null;
EStructuralFeature feature = null;
EObject owner = null;
EObject child = null;
if(command instanceof AddCommand) {
AddCommand addCommand = (AddCommand) command;
domain = addCommand.getDomain();
feature = addCommand.getFeature();
owner = addCommand.getOwner();
child = (EObject) addCommand.getCollection().iterator().next();
}
if(command instanceof SetCommand) {
SetCommand setCommand = (SetCommand) command;
domain = setCommand.getDomain();
feature = setCommand.getFeature();
owner = setCommand.getOwner();
child = (EObject) owner.eGet(feature);
}
commandDelegate.undo();
Command createWithIDCommand = leg.new CreateCommand(domain, owner, feature, child, affectedObjects, leg);
editingDomain.getCommandStack().execute(createWithIDCommand);
return;
}
if(!(mostRecentCommand instanceof LegCommand)){
DenialReason result = leg.trySubmitModification();
if(result != null) {
MessageBox messageBox = new MessageBox(getSite().getShell(), SWT.ABORT | SWT.ICON_WARNING);
messageBox.setMessage(result.prettyPrintProblem());
messageBox.setText(DENIED_MODIFICATION_ON_MODEL);
messageBox.open();
isAborted = true;
editingDomain.getCommandStack().undo();
isAborted = false;
return;
}
// Log the event
Date now = new Date();
String strDate = ModelExplorer.DATE_FORMAT.format(now);
String commandLabel = mostRecentCommand.getLabel();
String logMessage = commandLabel;
if ("Delete".equals(commandLabel)) {
Collection<?> commandResult = mostRecentCommand.getResult();
String affectedObjectLabels = "";
for (Object object : commandResult) {
// TODO collect more details here about the executed
// command
if(treeViewer.getLabelProvider() instanceof LabelProvider){
affectedObjectLabels += ((LabelProvider) treeViewer.getLabelProvider()).getText(object);
} else {
affectedObjectLabels += ((AdapterFactoryLabelProvider) treeViewer.getLabelProvider()).getText(object);
}
}
logMessage = logMessage + ". " + "Deleted object(s): " + affectedObjectLabels;
} else {
Collection<?> affectedObjects = mostRecentCommand.getAffectedObjects();
String affectedObjectLabels = "";
for (Object object : affectedObjects) {
// TODO collect more details here about the executed
// command
if(treeViewer.getLabelProvider() instanceof LabelProvider){
affectedObjectLabels += ((LabelProvider) treeViewer.getLabelProvider()).getText(object);
} else {
affectedObjectLabels += ((AdapterFactoryLabelProvider) treeViewer.getLabelProvider()).getText(object);
}
// affectedObjectLabels += ((AdapterFactoryLabelProvider) treeViewer.getLabelProvider()).getText(object);
}
logMessage = logMessage + ". " + "Affected object(s): " + affectedObjectLabels;
}
logMessage= strDate + " " + userName + ": " + logMessage;
// ModelLogView logView = null;
// IViewReference viewReferences[] = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
// .getActivePage().getViewReferences();
// for (int i = 0; i < viewReferences.length; i++) {
// if (ModelLogView.ID.equals(viewReferences[i].getId())) {
// logView = (ModelLogView) viewReferences[i].getView(false);
ModelLogView.addMessage(logMessage, leg.getOnlineCollaborationSession().getGoldConfinementURI());
}
}
};
editingDomain.getCommandStack().addCommandStackListener(editorActionListener);
}
}
/**
* Returns a diagnostic describing the errors and warnings listed in the
* resource and the specified exception (if any). <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public Diagnostic analyzeResourceProblems(Resource resource, Exception exception) {
boolean hasErrors = !resource.getErrors().isEmpty();
if (hasErrors || !resource.getWarnings().isEmpty()) {
BasicDiagnostic basicDiagnostic = new BasicDiagnostic(hasErrors ? Diagnostic.ERROR : Diagnostic.WARNING,
"org.mondo.wt.cstudy.metamodel.editor", 0,
getString("_UI_CreateModelError_message", resource.getURI()),
new Object[] { exception == null ? (Object) resource : exception });
basicDiagnostic.merge(EcoreUtil.computeDiagnostic(resource, true));
return basicDiagnostic;
} else if (exception != null) {
return new BasicDiagnostic(Diagnostic.ERROR, "org.mondo.wt.cstudy.metamodel.editor", 0,
getString("_UI_CreateModelError_message", resource.getURI()), new Object[] { exception });
} else {
return Diagnostic.OK_INSTANCE;
}
}
/**
* This is the method used by the framework to install your own controls.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void createPages() {
// Creates the model from the editor input
createModel();
// Only creates the other pages if there is something that can be edited
if (!getEditingDomain().getResourceSet().getResources().isEmpty()) {
// Create a page for the selection tree view.
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
selectionViewer = (TreeViewer) viewerPane.getViewer();
selectionViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
selectionViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
selectionViewer.setInput(editingDomain.getResourceSet());
selectionViewer.setSelection(
new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
viewerPane.setTitle(editingDomain.getResourceSet());
new AdapterFactoryTreeEditor(selectionViewer.getTree(), adapterFactory);
createContextMenuFor(selectionViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_SelectionPage_label"));
}
// Create a page for the parent tree view.
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
parentViewer = (TreeViewer) viewerPane.getViewer();
parentViewer.setAutoExpandLevel(30);
parentViewer.setContentProvider(new ReverseAdapterFactoryContentProvider(adapterFactory));
parentViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(parentViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ParentPage_label"));
}
// This is the page for the list viewer
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new ListViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
listViewer = (ListViewer) viewerPane.getViewer();
listViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
listViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(listViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ListPage_label"));
}
// This is the page for the tree viewer
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewer = (TreeViewer) viewerPane.getViewer();
treeViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
new AdapterFactoryTreeEditor(treeViewer.getTree(), adapterFactory);
createContextMenuFor(treeViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreePage_label"));
}
// This is the page for the table viewer.
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TableViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
tableViewer = (TableViewer) viewerPane.getViewer();
Table table = tableViewer.getTable();
TableLayout layout = new TableLayout();
table.setLayout(layout);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn objectColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(3, 100, true));
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
TableColumn selfColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(2, 100, true));
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
tableViewer.setColumnProperties(new String[] { "a", "b" });
tableViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
tableViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(tableViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TablePage_label"));
}
// This is the page for the table tree viewer.
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewerWithColumns = (TreeViewer) viewerPane.getViewer();
Tree tree = treeViewerWithColumns.getTree();
tree.setLayoutData(new FillLayout());
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
TreeColumn objectColumn = new TreeColumn(tree, SWT.NONE);
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
objectColumn.setWidth(250);
TreeColumn selfColumn = new TreeColumn(tree, SWT.NONE);
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
selfColumn.setWidth(200);
treeViewerWithColumns.setColumnProperties(new String[] { "a", "b" });
treeViewerWithColumns.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewerWithColumns.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(treeViewerWithColumns);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreeWithColumnsPage_label"));
}
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
setActivePage(0);
}
});
}
// Ensures that this editor will only display the page's tab
// area if there are more than one page
getContainer().addControlListener(new ControlAdapter() {
boolean guard = false;
@Override
public void controlResized(ControlEvent event) {
if (!guard) {
guard = true;
hideTabs();
guard = false;
}
}
});
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
/**
* If there is just one page in the multi-page editor part, this hides the
* single tab at the bottom. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void hideTabs() {
if (getPageCount() <= 1) {
setPageText(0, "");
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(1);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y + 6);
}
}
}
/**
* If there is more than one page in the multi-page editor part, this shows
* the tabs at the bottom. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void showTabs() {
if (getPageCount() > 1) {
setPageText(0, getString("_UI_SelectionPage_label"));
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(SWT.DEFAULT);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y - 6);
}
}
}
/**
* This is used to track the active viewer. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
@Override
protected void pageChange(int pageIndex) {
super.pageChange(pageIndex);
if (contentOutlinePage != null) {
handleContentOutlineSelection(contentOutlinePage.getSelection());
}
}
/**
* This is how the framework determines which interfaces we implement. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
if (key.equals(IContentOutlinePage.class)) {
return showOutlineView() ? getContentOutlinePage() : null;
} else if (key.equals(IPropertySheetPage.class)) {
return getPropertySheetPage();
} else {
return super.getAdapter(key);
}
}
/**
* This accesses a cached version of the content outliner. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IContentOutlinePage getContentOutlinePage() {
if (contentOutlinePage == null) {
// The content outline is just a tree.
class MyContentOutlinePage extends ContentOutlinePage {
@Override
public void createControl(Composite parent) {
super.createControl(parent);
contentOutlineViewer = getTreeViewer();
contentOutlineViewer.addSelectionChangedListener(this);
// Set up the tree viewer.
contentOutlineViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
contentOutlineViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
contentOutlineViewer.setInput(editingDomain.getResourceSet());
// Make sure our popups work.
createContextMenuFor(contentOutlineViewer);
if (!editingDomain.getResourceSet().getResources().isEmpty()) {
// Select the root object in the view.
contentOutlineViewer.setSelection(
new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
}
}
@Override
public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager,
IStatusLineManager statusLineManager) {
super.makeContributions(menuManager, toolBarManager, statusLineManager);
contentOutlineStatusLineManager = statusLineManager;
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
}
contentOutlinePage = new MyContentOutlinePage();
// Listen to selection so that we can handle it is a special way.
contentOutlinePage.addSelectionChangedListener(new ISelectionChangedListener() {
// This ensures that we handle selections correctly.
public void selectionChanged(SelectionChangedEvent event) {
handleContentOutlineSelection(event.getSelection());
}
});
}
return contentOutlinePage;
}
/**
* This accesses a cached version of the property sheet. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
public IPropertySheetPage getPropertySheetPage() {
PropertySheetPage propertySheetPage = new ExtendedPropertySheetPage(editingDomain) {
@Override
public void setSelectionToViewer(List<?> selection) {
WTSpec4MEditor.this.setSelectionToViewer(selection);
WTSpec4MEditor.this.setFocus();
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
};
propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory));
propertySheetPages.add(propertySheetPage);
return propertySheetPage;
}
/**
* This deals with how we want selection in the outliner to affect the other
* views. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void handleContentOutlineSelection(ISelection selection) {
if (currentViewerPane != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
Iterator<?> selectedElements = ((IStructuredSelection) selection).iterator();
if (selectedElements.hasNext()) {
// Get the first selected element.
Object selectedElement = selectedElements.next();
// If it's the selection viewer, then we want it to select the
// same selection as this selection.
if (currentViewerPane.getViewer() == selectionViewer) {
ArrayList<Object> selectionList = new ArrayList<Object>();
selectionList.add(selectedElement);
while (selectedElements.hasNext()) {
selectionList.add(selectedElements.next());
}
// Set the selection to the widget.
selectionViewer.setSelection(new StructuredSelection(selectionList));
} else {
// Set the input to the widget.
if (currentViewerPane.getViewer().getInput() != selectedElement) {
currentViewerPane.getViewer().setInput(selectedElement);
currentViewerPane.setTitle(selectedElement);
}
}
}
}
}
/**
* This is for implementing {@link IEditorPart} and simply tests the command
* stack. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isDirty() {
return ((BasicCommandStack) editingDomain.getCommandStack()).isSaveNeeded();
}
/**
* This is for implementing {@link IEditorPart} and simply saves the model
* file. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void doSave(IProgressMonitor progressMonitor) {
// Not needed, because it is checked on the fly
// leg.trySubmitModification();
CommitMessageDialog dialog = new CommitMessageDialog(Display.getCurrent().getActiveShell());
dialog.create();
if (dialog.open() == Window.OK) {
String commitMessage = dialog.getCommitMessage();
StorageAccess currentStorageAccess = ModelExplorer.getCurrentStorageAccess();
URIEditorInput editorInput = (URIEditorInput) getEditorInput();
// TODO make sure that the expected uri is correct
currentStorageAccess.commit(editorInput.getURI().toString(), commitMessage);
} else {
return;
}
// Save only resources that have actually changed.
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
// Do the work within an operation because this is a long running
// activity that modifies the workbench.
IRunnableWithProgress operation = new IRunnableWithProgress() {
// This is the method that gets invoked when the operation runs.
public void run(IProgressMonitor monitor) {
// Save the resources to the file system.
boolean first = true;
for (Resource resource : leg.getGoldResourceSet().getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource))) {
try {
long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
savedResources.add(resource);
}
} catch (Exception exception) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
first = false;
}
}
// for (Leg l : leg.getOnlineCollaborationSession().getLegs()) {
// if(l instanceof OnlineLeg) {
// OnlineLeg onlineLeg = (OnlineLeg) l;
// onlineLeg.saveExecuted();
}
};
updateProblemIndication = false;
try {
// This runs the options, and shows progress.
new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation);
// Refresh the necessary state.
((BasicCommandStack) editingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
} catch (Exception exception) {
// Something went wrong that shouldn't.
WTSpec4MEditorPlugin.INSTANCE.log(exception);
}
updateProblemIndication = true;
updateProblemIndication();
}
/**
* This returns whether something has been persisted to the URI of the
* specified resource. The implementation uses the URI converter from the
* editor's resource set to try to open an input stream. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean isPersisted(Resource resource) {
boolean result = false;
try {
InputStream stream = editingDomain.getResourceSet().getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
} catch (IOException e) {
// Ignore
}
return result;
}
/**
* This always returns true because it is not currently supported. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* This also changes the editor's input. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
@Override
public void doSaveAs() {
new ResourceDialog(getSite().getShell(), null, SWT.NONE) {
@Override
protected boolean isSave() {
return true;
}
@Override
protected boolean processResources() {
List<URI> uris = getURIs();
if (uris.size() > 0) {
URI uri = uris.get(0);
doSaveAs(uri, new URIEditorInput(uri));
return true;
} else {
return false;
}
}
}.open();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void doSaveAs(URI uri, IEditorInput editorInput) {
(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
IProgressMonitor progressMonitor = getActionBars().getStatusLineManager() != null
? getActionBars().getStatusLineManager().getProgressMonitor() : new NullProgressMonitor();
doSave(progressMonitor);
}
/**
* This is called during startup. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
@Override
public void init(IEditorSite site, IEditorInput editorInput) {
setSite(site);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
site.setSelectionProvider(this);
site.getPage().addPartListener(partListener);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setFocus() {
if (currentViewerPane != null) {
currentViewerPane.setFocus();
} else {
getControl(getActivePage()).setFocus();
}
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to
* return this editor's overall selection. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
public ISelection getSelection() {
return editorSelection;
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to
* set this editor's overall selection. Calling this result will notify the
* listeners. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSelection(ISelection selection) {
editorSelection = selection;
for (ISelectionChangedListener listener : selectionChangedListeners) {
listener.selectionChanged(new SelectionChangedEvent(this, selection));
}
setStatusLineManager(selection);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setStatusLineManager(ISelection selection) {
IStatusLineManager statusLineManager = currentViewer != null && currentViewer == contentOutlineViewer
? contentOutlineStatusLineManager : getActionBars().getStatusLineManager();
if (statusLineManager != null) {
if (selection instanceof IStructuredSelection) {
Collection<?> collection = ((IStructuredSelection) selection).toList();
switch (collection.size()) {
case 0: {
statusLineManager.setMessage(getString("_UI_NoObjectSelected"));
break;
}
case 1: {
String text = new AdapterFactoryItemDelegator(adapterFactory).getText(collection.iterator().next());
statusLineManager.setMessage(getString("_UI_SingleObjectSelected", text));
break;
}
default: {
statusLineManager
.setMessage(getString("_UI_MultiObjectSelected", Integer.toString(collection.size())));
break;
}
}
} else {
statusLineManager.setMessage("");
}
}
}
/**
* This looks up a string in the plugin's plugin.properties file. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static String getString(String key) {
return WTSpec4MEditorPlugin.INSTANCE.getString(key);
}
/**
* This looks up a string in plugin.properties, making a substitution. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static String getString(String key, Object s1) {
return WTSpec4MEditorPlugin.INSTANCE.getString(key, new Object[] { s1 });
}
/**
* This implements {@link org.eclipse.jface.action.IMenuListener} to help
* fill the context menus with contributions from the Edit menu. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void menuAboutToShow(IMenuManager menuManager) {
((IMenuListener) getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public EditingDomainActionBarContributor getActionBarContributor() {
return (EditingDomainActionBarContributor) getEditorSite().getActionBarContributor();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IActionBars getActionBars() {
return getActionBarContributor().getActionBars();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public AdapterFactory getAdapterFactory() {
return adapterFactory;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void dispose() {
updateProblemIndication = false;
editingDomain.getCommandStack().removeCommandStackListener(refreshListener);
// editingDomain.getCommandStack().removeCommandStackListener(editorActionListener);
getSite().getPage().removePartListener(partListener);
// adapterFactory.dispose();
if (getActionBarContributor().getActiveEditor() == this) {
getActionBarContributor().setActiveEditor(null);
}
for (PropertySheetPage propertySheetPage : propertySheetPages) {
propertySheetPage.dispose();
}
if (contentOutlinePage != null) {
contentOutlinePage.dispose();
}
URI resourceURI = EditUIUtil.getURI(getEditorInput());
// leg
// if(LensSessionManager.getUsersForURI(resourceURI))
UISessionManager.remove(resourceURI, ModelExplorer.getCurrentStorageAccess().getUsername(), RWT.getUISession());
super.dispose();
}
/**
* Returns whether the outline view should be presented to the user. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean showOutlineView() {
return true;
}
}
|
package WTSpec4M.presentation;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.ui.ViewerPane;
import org.eclipse.emf.common.ui.dialogs.ResourceDialog;
import org.eclipse.emf.common.ui.editor.ProblemEditorPart;
import org.eclipse.emf.common.ui.viewer.IViewerProvider;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
import org.eclipse.emf.edit.ui.celleditor.AdapterFactoryTreeEditor;
import org.eclipse.emf.edit.ui.dnd.EditingDomainViewerDropAdapter;
import org.eclipse.emf.edit.ui.dnd.LocalTransfer;
import org.eclipse.emf.edit.ui.dnd.ViewerDragAdapter;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.edit.ui.provider.UnwrappingSelectionProvider;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.PropertySheetPage;
import org.mondo.collaboration.online.core.LensActivator;
import org.mondo.collaboration.online.core.LensSessionManager;
import org.mondo.collaboration.online.core.OnlineLeg;
import org.mondo.collaboration.online.core.OnlineLeg.LegCommand;
import org.mondo.collaboration.online.rap.widgets.ModelExplorer;
import org.mondo.collaboration.online.rap.widgets.ModelLogView;
import org.mondo.collaboration.online.rap.widgets.UINotifierManager;
import org.mondo.collaboration.security.lens.bx.online.OnlineCollaborationSession;
import org.mondo.collaboration.security.lens.bx.online.OnlineCollaborationSession.Leg;
import com.google.common.util.concurrent.FutureCallback;
import WTSpec4M.provider.WTSpec4MItemProviderAdapterFactory;
/**
* This is an example of a WTSpec4M model editor. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
public class WTSpec4MEditor extends MultiPageEditorPart
implements IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider {
/**
* The filters for file extensions supported by the editor. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public static final List<String> FILE_EXTENSION_FILTERS = prefixExtensions(WTSpec4MModelWizard.FILE_EXTENSIONS,
"*.");
/**
* Returns a new unmodifiable list containing prefixed versions of the
* extensions in the given list. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
private static List<String> prefixExtensions(List<String> extensions, String prefix) {
List<String> result = new ArrayList<String>();
for (String extension : extensions) {
result.add(prefix + extension);
}
return Collections.unmodifiableList(result);
}
/**
* This keeps track of the editing domain that is used to track all changes
* to the model. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected AdapterFactoryEditingDomain editingDomain;
/**
* This is the one adapter factory used for providing views of the model.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected AdapterFactory adapterFactory;
/**
* This is the content outline page. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected IContentOutlinePage contentOutlinePage;
/**
* This is a kludge... <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected IStatusLineManager contentOutlineStatusLineManager;
/**
* This is the content outline page's viewer. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected TreeViewer contentOutlineViewer;
/**
* This is the property sheet page. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected List<PropertySheetPage> propertySheetPages = new ArrayList<PropertySheetPage>();
/**
* This is the viewer that shadows the selection in the content outline. The
* parent relation must be correctly defined for this to work. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer selectionViewer;
/**
* This inverts the roll of parent and child in the content provider and
* show parents as a tree. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer parentViewer;
/**
* This shows how a tree view works. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected TreeViewer treeViewer;
/**
* This shows how a list view works. A list viewer doesn't support icons.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ListViewer listViewer;
/**
* This shows how a table view works. A table can be used as a list with
* icons. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TableViewer tableViewer;
/**
* This shows how a tree view with columns works. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer treeViewerWithColumns;
/**
* This keeps track of the active viewer pane, in the book. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ViewerPane currentViewerPane;
/**
* This keeps track of the active content viewer, which may be either one of
* the viewers in the pages or the content outline viewer. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Viewer currentViewer;
/**
* This listens to which ever viewer is active. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected ISelectionChangedListener selectionChangedListener;
/**
* This keeps track of all the
* {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are
* listening to this editor. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>();
/**
* This keeps track of the selection of the editor as a whole. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ISelection editorSelection = StructuredSelection.EMPTY;
/**
* This listens for when the outline becomes active <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected IPartListener partListener = new IPartListener() {
public void partActivated(IWorkbenchPart p) {
if (p instanceof ContentOutline) {
if (((ContentOutline) p).getCurrentPage() == contentOutlinePage) {
getActionBarContributor().setActiveEditor(WTSpec4MEditor.this);
setCurrentViewer(contentOutlineViewer);
}
} else if (p instanceof PropertySheet) {
if (propertySheetPages.contains(((PropertySheet) p).getCurrentPage())) {
getActionBarContributor().setActiveEditor(WTSpec4MEditor.this);
handleActivate();
}
} else if (p == WTSpec4MEditor.this) {
handleActivate();
}
}
public void partBroughtToTop(IWorkbenchPart p) {
// Ignore.
}
public void partClosed(IWorkbenchPart p) {
if(leg != null){
leg.dispose();
}
}
public void partDeactivated(IWorkbenchPart p) {
// Ignore.
}
public void partOpened(IWorkbenchPart p) {
// Ignore.
}
};
/**
* Resources that have been removed since last activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<Resource> removedResources = new ArrayList<Resource>();
/**
* Resources that have been changed since last activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<Resource> changedResources = new ArrayList<Resource>();
/**
* Resources that have been saved. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
protected Collection<Resource> savedResources = new ArrayList<Resource>();
/**
* Map to store the diagnostic associated with a resource. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>();
/**
* Controls whether the problem indication should be updated. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean updateProblemIndication = true;
/**
* Adapter used to update the problem indication when resources are demanded
* loaded. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected EContentAdapter problemIndicationAdapter = new EContentAdapter() {
@Override
public void notifyChanged(Notification notification) {
if (notification.getNotifier() instanceof Resource) {
switch (notification.getFeatureID(Resource.class)) {
case Resource.RESOURCE__IS_LOADED:
case Resource.RESOURCE__ERRORS:
case Resource.RESOURCE__WARNINGS: {
Resource resource = (Resource) notification.getNotifier();
Diagnostic diagnostic = analyzeResourceProblems(resource, null);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, diagnostic);
} else {
resourceToDiagnosticMap.remove(resource);
}
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
break;
}
}
} else {
super.notifyChanged(notification);
}
}
@Override
protected void setTarget(Resource target) {
basicSetTarget(target);
}
@Override
protected void unsetTarget(Resource target) {
basicUnsetTarget(target);
resourceToDiagnosticMap.remove(target);
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
}
};
private OnlineLeg leg;
private boolean isItMe;
/**
* Handles activation of the editor or it's associated views. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleActivate() {
// Recompute the read only state.
if (editingDomain.getResourceToReadOnlyMap() != null) {
editingDomain.getResourceToReadOnlyMap().clear();
// Refresh any actions that may become enabled or disabled.
setSelection(getSelection());
}
if (!removedResources.isEmpty()) {
if (handleDirtyConflict()) {
getSite().getPage().closeEditor(WTSpec4MEditor.this, false);
} else {
removedResources.clear();
changedResources.clear();
savedResources.clear();
}
} else if (!changedResources.isEmpty()) {
changedResources.removeAll(savedResources);
handleChangedResources();
changedResources.clear();
savedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleChangedResources() {
if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
if (isDirty()) {
changedResources.addAll(editingDomain.getResourceSet().getResources());
}
editingDomain.getCommandStack().flush();
updateProblemIndication = false;
for (Resource resource : changedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
} catch (IOException exception) {
if (!resourceToDiagnosticMap.containsKey(resource)) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
}
}
}
if (AdapterFactoryEditingDomain.isStale(editorSelection)) {
setSelection(StructuredSelection.EMPTY);
}
updateProblemIndication = true;
updateProblemIndication();
}
}
/**
* Updates the problems indication with the information described in the
* specified diagnostic. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void updateProblemIndication() {
if (updateProblemIndication) {
BasicDiagnostic diagnostic = new BasicDiagnostic(Diagnostic.OK, "org.mondo.wt.cstudy.metamodel.editor", 0,
null, new Object[] { editingDomain.getResourceSet() });
for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) {
if (childDiagnostic.getSeverity() != Diagnostic.OK) {
diagnostic.add(childDiagnostic);
}
}
int lastEditorPage = getPageCount() - 1;
if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
((ProblemEditorPart) getEditor(lastEditorPage)).setDiagnostic(diagnostic);
if (diagnostic.getSeverity() != Diagnostic.OK) {
setActivePage(lastEditorPage);
}
} else if (diagnostic.getSeverity() != Diagnostic.OK) {
ProblemEditorPart problemEditorPart = new ProblemEditorPart();
problemEditorPart.setDiagnostic(diagnostic);
try {
addPage(++lastEditorPage, problemEditorPart, getEditorInput());
setPageText(lastEditorPage, problemEditorPart.getPartName());
setActivePage(lastEditorPage);
showTabs();
} catch (PartInitException exception) {
WTSpec4MEditorPlugin.INSTANCE.log(exception);
}
}
}
}
/**
* Shows a dialog that asks if conflicting changes should be discarded. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean handleDirtyConflict() {
return MessageDialog.openQuestion(getSite().getShell(), getString("_UI_FileConflict_label"),
getString("_WARN_FileConflict"));
}
/**
* This creates a model editor. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
public WTSpec4MEditor() {
super();
initializeEditingDomain();
}
/**
* This sets up the editing domain for the model editor. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated NOT
*/
protected void initializeEditingDomain() {
// Create an adapter factory that yields item providers.
ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new WTSpec4MItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
this.adapterFactory = adapterFactory;
// Create the command stack that will notify this editor as commands are
// executed.
BasicCommandStack commandStack = new BasicCommandStack();
// Add a listener to set the most recent command's affected objects to
// be the selection of the viewer with focus.
commandStack.addCommandStackListener(new CommandStackListener() {
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec(new Runnable() {
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
// Try to select the affected objects.
Command mostRecentCommand = ((CommandStack) event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
setSelectionToViewer(mostRecentCommand.getAffectedObjects());
}
for (Iterator<PropertySheetPage> i = propertySheetPages.iterator(); i.hasNext();) {
PropertySheetPage propertySheetPage = i.next();
if (propertySheetPage.getControl().isDisposed()) {
i.remove();
} else {
propertySheetPage.refresh();
}
}
}
});
}
});
// Create the editing domain with a special command stack.
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack, new HashMap<Resource, Boolean>());
}
protected void initializeEditingDomain(AdapterFactoryEditingDomain editingDomain) {
this.editingDomain = editingDomain;
this.adapterFactory = editingDomain.getAdapterFactory();
editingDomain.getCommandStack().addCommandStackListener(new CommandStackListener() {
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec(new Runnable() {
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
// Try to select the affected objects.
Command mostRecentCommand = ((CommandStack) event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
setSelectionToViewer(mostRecentCommand.getAffectedObjects());
}
for (Iterator<PropertySheetPage> i = propertySheetPages.iterator(); i.hasNext();) {
PropertySheetPage propertySheetPage = i.next();
if (propertySheetPage.getControl().isDisposed()) {
i.remove();
} else {
propertySheetPage.refresh();
}
}
}
});
}
});
}
/**
* This is here for the listener to be able to call it. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected void firePropertyChange(int action) {
super.firePropertyChange(action);
}
/**
* This sets the selection into whichever viewer is active. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSelectionToViewer(Collection<?> collection) {
final Collection<?> theSelection = collection;
// Make sure it's okay.
if (theSelection != null && !theSelection.isEmpty()) {
Runnable runnable = new Runnable() {
public void run() {
// Try to select the items in the current content viewer of
// the editor.
if (currentViewer != null) {
currentViewer.setSelection(new StructuredSelection(theSelection.toArray()), true);
}
}
};
getSite().getShell().getDisplay().asyncExec(runnable);
}
}
/**
* This returns the editing domain as required by the
* {@link IEditingDomainProvider} interface. This is important for
* implementing the static methods of {@link AdapterFactoryEditingDomain}
* and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public EditingDomain getEditingDomain() {
return editingDomain;
}
private final class UpdateOnModification implements FutureCallback<Object> {
@Override
public void onFailure(Throwable arg0) {
}
@Override
public void onSuccess(Object obj) {
if(!isItMe) {
System.out.println("other user");
selectionViewer.getControl().getDisplay().asyncExec( new Runnable() {
public void run() {
System.out.println("executing on ui thread");
if(selectionViewer != null)
selectionViewer.refresh();
System.out.println("finished");
}
});
}
}
}
private final class UpdateOnSave implements FutureCallback<Object> {
@Override
public void onFailure(Throwable arg0) {
}
@Override
public void onSuccess(Object obj) {
ModelExplorer.update((String) obj);
getContainer().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
}
});
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object[] getElements(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object[] getChildren(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean hasChildren(Object object) {
Object parent = super.getParent(object);
return parent != null;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object getParent(Object object) {
return null;
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setCurrentViewerPane(ViewerPane viewerPane) {
if (currentViewerPane != viewerPane) {
if (currentViewerPane != null) {
currentViewerPane.showFocus(false);
}
currentViewerPane = viewerPane;
}
setCurrentViewer(currentViewerPane.getViewer());
}
/**
* This makes sure that one content viewer, either for the current page or
* the outline view, if it has focus, is the current one. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setCurrentViewer(Viewer viewer) {
// If it is changing...
if (currentViewer != viewer) {
if (selectionChangedListener == null) {
// Create the listener on demand.
selectionChangedListener = new ISelectionChangedListener() {
// This just notifies those things that are affected by the
// section.
public void selectionChanged(SelectionChangedEvent selectionChangedEvent) {
setSelection(selectionChangedEvent.getSelection());
}
};
}
// Stop listening to the old one.
if (currentViewer != null) {
currentViewer.removeSelectionChangedListener(selectionChangedListener);
}
// Start listening to the new one.
if (viewer != null) {
viewer.addSelectionChangedListener(selectionChangedListener);
}
// Remember it.
currentViewer = viewer;
// Set the editors selection based on the current viewer's
// selection.
setSelection(currentViewer == null ? StructuredSelection.EMPTY : currentViewer.getSelection());
}
}
/**
* This returns the viewer as required by the {@link IViewerProvider}
* interface. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public Viewer getViewer() {
return currentViewer;
}
/**
* This creates a context menu for the viewer and adds a listener as well
* registering the menu for extension. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected void createContextMenuFor(StructuredViewer viewer) {
MenuManager contextMenu = new MenuManager("#PopUp");
contextMenu.add(new Separator("additions"));
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(this);
Menu menu = contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer));
int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers = new Transfer[] { LocalTransfer.getInstance(), LocalSelectionTransfer.getTransfer(),
FileTransfer.getInstance() };
viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer));
viewer.addDropSupport(dndOperations, transfers, new EditingDomainViewerDropAdapter(editingDomain, viewer));
}
/**
* This is the method called to load a resource into the editing domain's
* resource set based on the editor's input. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated NOT
*/
public void createModel() {
URI resourceURI = EditUIUtil.getURI(getEditorInput());
Exception exception = null;
Resource resource = null;
leg = LensSessionManager.getExistingLeg(ModelExplorer.getCurrentStorageAccess().getUsername(), RWT.getUISession().getHttpSession(), resourceURI);
if(leg == null) {
initializeEditingDomain();
leg = LensSessionManager.createLeg(resourceURI, ModelExplorer.getCurrentStorageAccess(), editingDomain, RWT.getUISession().getHttpSession());
} else {
initializeEditingDomain(leg.getEditingDomain());
}
UINotifierManager.register(OnlineLeg.EVENT_UPDATE, RWT.getUISession(), new UpdateOnModification());
UINotifierManager.register(OnlineLeg.EVENT_SAVE, RWT.getUISession(), new UpdateOnSave());
resource = leg.getFrontResourceSet().getResources().get(0);
Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
// Submit changes for lens
editingDomain.getCommandStack().addCommandStackListener(new CommandStackListener() {
@Override
public void commandStackChanged(EventObject event) {
Command mostRecentCommand = editingDomain.getCommandStack().getMostRecentCommand();
if(!(mostRecentCommand instanceof LegCommand)){
leg.trySubmitModification();
// Log the event
IViewReference[] viewReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViewReferences();
ModelLogView logView = ModelLogView.getCurrentLogView(viewReferences);
String username = ModelExplorer.getCurrentStorageAccess().getUsername();
Date now = new Date();
String strDate = sdf.format(now);
String commandLabel = mostRecentCommand.getLabel();
String logString = logView.getLogString();
Collection<?> affectedObjects = mostRecentCommand.getAffectedObjects();
String affectedObjectETypes = "";
for (Object object : affectedObjects) {
// TODO collect more details here
affectedObjectETypes += (((EObject) object).eClass().getName()+ " ");
}
logString= strDate + " " + commandLabel + " by " + username + ". Affeted object type: " + affectedObjectETypes + logView.getLineDelimiter() + logString; //" (Details: " + commandDescription + ") " + logView.getLineDelimiter() + logString ;
logView.setLogString(logString);
logView.refresh();
}
}
});
}
/**
* Returns a diagnostic describing the errors and warnings listed in the
* resource and the specified exception (if any). <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public Diagnostic analyzeResourceProblems(Resource resource, Exception exception) {
boolean hasErrors = !resource.getErrors().isEmpty();
if (hasErrors || !resource.getWarnings().isEmpty()) {
BasicDiagnostic basicDiagnostic = new BasicDiagnostic(hasErrors ? Diagnostic.ERROR : Diagnostic.WARNING,
"org.mondo.wt.cstudy.metamodel.editor", 0,
getString("_UI_CreateModelError_message", resource.getURI()),
new Object[] { exception == null ? (Object) resource : exception });
basicDiagnostic.merge(EcoreUtil.computeDiagnostic(resource, true));
return basicDiagnostic;
} else if (exception != null) {
return new BasicDiagnostic(Diagnostic.ERROR, "org.mondo.wt.cstudy.metamodel.editor", 0,
getString("_UI_CreateModelError_message", resource.getURI()), new Object[] { exception });
} else {
return Diagnostic.OK_INSTANCE;
}
}
/**
* This is the method used by the framework to install your own controls.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void createPages() {
// Creates the model from the editor input
createModel();
// Only creates the other pages if there is something that can be edited
if (!getEditingDomain().getResourceSet().getResources().isEmpty()) {
// Create a page for the selection tree view.
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
selectionViewer = (TreeViewer) viewerPane.getViewer();
selectionViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
selectionViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
selectionViewer.setInput(editingDomain.getResourceSet());
selectionViewer.setSelection(
new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
viewerPane.setTitle(editingDomain.getResourceSet());
new AdapterFactoryTreeEditor(selectionViewer.getTree(), adapterFactory);
createContextMenuFor(selectionViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_SelectionPage_label"));
}
// Create a page for the parent tree view.
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
parentViewer = (TreeViewer) viewerPane.getViewer();
parentViewer.setAutoExpandLevel(30);
parentViewer.setContentProvider(new ReverseAdapterFactoryContentProvider(adapterFactory));
parentViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(parentViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ParentPage_label"));
}
// This is the page for the list viewer
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new ListViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
listViewer = (ListViewer) viewerPane.getViewer();
listViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
listViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(listViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ListPage_label"));
}
// This is the page for the tree viewer
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewer = (TreeViewer) viewerPane.getViewer();
treeViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
new AdapterFactoryTreeEditor(treeViewer.getTree(), adapterFactory);
createContextMenuFor(treeViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreePage_label"));
}
// This is the page for the table viewer.
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TableViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
tableViewer = (TableViewer) viewerPane.getViewer();
Table table = tableViewer.getTable();
TableLayout layout = new TableLayout();
table.setLayout(layout);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn objectColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(3, 100, true));
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
TableColumn selfColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(2, 100, true));
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
tableViewer.setColumnProperties(new String[] { "a", "b" });
tableViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
tableViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(tableViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TablePage_label"));
}
// This is the page for the table tree viewer.
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewerWithColumns = (TreeViewer) viewerPane.getViewer();
Tree tree = treeViewerWithColumns.getTree();
tree.setLayoutData(new FillLayout());
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
TreeColumn objectColumn = new TreeColumn(tree, SWT.NONE);
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
objectColumn.setWidth(250);
TreeColumn selfColumn = new TreeColumn(tree, SWT.NONE);
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
selfColumn.setWidth(200);
treeViewerWithColumns.setColumnProperties(new String[] { "a", "b" });
treeViewerWithColumns.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewerWithColumns.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(treeViewerWithColumns);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreeWithColumnsPage_label"));
}
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
setActivePage(0);
}
});
}
// Ensures that this editor will only display the page's tab
// area if there are more than one page
getContainer().addControlListener(new ControlAdapter() {
boolean guard = false;
@Override
public void controlResized(ControlEvent event) {
if (!guard) {
guard = true;
hideTabs();
guard = false;
}
}
});
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
/**
* If there is just one page in the multi-page editor part, this hides the
* single tab at the bottom. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void hideTabs() {
if (getPageCount() <= 1) {
setPageText(0, "");
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(1);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y + 6);
}
}
}
/**
* If there is more than one page in the multi-page editor part, this shows
* the tabs at the bottom. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void showTabs() {
if (getPageCount() > 1) {
setPageText(0, getString("_UI_SelectionPage_label"));
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(SWT.DEFAULT);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y - 6);
}
}
}
/**
* This is used to track the active viewer. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
@Override
protected void pageChange(int pageIndex) {
super.pageChange(pageIndex);
if (contentOutlinePage != null) {
handleContentOutlineSelection(contentOutlinePage.getSelection());
}
}
/**
* This is how the framework determines which interfaces we implement. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
if (key.equals(IContentOutlinePage.class)) {
return showOutlineView() ? getContentOutlinePage() : null;
} else if (key.equals(IPropertySheetPage.class)) {
return getPropertySheetPage();
} else {
return super.getAdapter(key);
}
}
/**
* This accesses a cached version of the content outliner. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IContentOutlinePage getContentOutlinePage() {
if (contentOutlinePage == null) {
// The content outline is just a tree.
class MyContentOutlinePage extends ContentOutlinePage {
@Override
public void createControl(Composite parent) {
super.createControl(parent);
contentOutlineViewer = getTreeViewer();
contentOutlineViewer.addSelectionChangedListener(this);
// Set up the tree viewer.
contentOutlineViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
contentOutlineViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
contentOutlineViewer.setInput(editingDomain.getResourceSet());
// Make sure our popups work.
createContextMenuFor(contentOutlineViewer);
if (!editingDomain.getResourceSet().getResources().isEmpty()) {
// Select the root object in the view.
contentOutlineViewer.setSelection(
new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
}
}
@Override
public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager,
IStatusLineManager statusLineManager) {
super.makeContributions(menuManager, toolBarManager, statusLineManager);
contentOutlineStatusLineManager = statusLineManager;
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
}
contentOutlinePage = new MyContentOutlinePage();
// Listen to selection so that we can handle it is a special way.
contentOutlinePage.addSelectionChangedListener(new ISelectionChangedListener() {
// This ensures that we handle selections correctly.
public void selectionChanged(SelectionChangedEvent event) {
handleContentOutlineSelection(event.getSelection());
}
});
}
return contentOutlinePage;
}
/**
* This accesses a cached version of the property sheet. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
public IPropertySheetPage getPropertySheetPage() {
PropertySheetPage propertySheetPage = new ExtendedPropertySheetPage(editingDomain) {
@Override
public void setSelectionToViewer(List<?> selection) {
WTSpec4MEditor.this.setSelectionToViewer(selection);
WTSpec4MEditor.this.setFocus();
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
};
propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory));
propertySheetPages.add(propertySheetPage);
return propertySheetPage;
}
/**
* This deals with how we want selection in the outliner to affect the other
* views. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void handleContentOutlineSelection(ISelection selection) {
if (currentViewerPane != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
Iterator<?> selectedElements = ((IStructuredSelection) selection).iterator();
if (selectedElements.hasNext()) {
// Get the first selected element.
Object selectedElement = selectedElements.next();
// If it's the selection viewer, then we want it to select the
// same selection as this selection.
if (currentViewerPane.getViewer() == selectionViewer) {
ArrayList<Object> selectionList = new ArrayList<Object>();
selectionList.add(selectedElement);
while (selectedElements.hasNext()) {
selectionList.add(selectedElements.next());
}
// Set the selection to the widget.
selectionViewer.setSelection(new StructuredSelection(selectionList));
} else {
// Set the input to the widget.
if (currentViewerPane.getViewer().getInput() != selectedElement) {
currentViewerPane.getViewer().setInput(selectedElement);
currentViewerPane.setTitle(selectedElement);
}
}
}
}
}
/**
* This is for implementing {@link IEditorPart} and simply tests the command
* stack. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isDirty() {
return ((BasicCommandStack) editingDomain.getCommandStack()).isSaveNeeded();
}
/**
* This is for implementing {@link IEditorPart} and simply saves the model
* file. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void doSave(IProgressMonitor progressMonitor) {
leg.trySubmitModification();
// Save only resources that have actually changed.
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
// Do the work within an operation because this is a long running
// activity that modifies the workbench.
IRunnableWithProgress operation = new IRunnableWithProgress() {
// This is the method that gets invoked when the operation runs.
public void run(IProgressMonitor monitor) {
// Save the resources to the file system.
boolean first = true;
for (Resource resource : leg.getGoldResourceSet().getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource))) {
try {
long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
savedResources.add(resource);
}
} catch (Exception exception) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
first = false;
}
}
for (Leg l : leg.getOnlineCollaborationSession().getLegs()) {
if(l instanceof OnlineLeg) {
OnlineLeg onlineLeg = (OnlineLeg) l;
onlineLeg.saveExecuted();
}
}
}
};
updateProblemIndication = false;
try {
// This runs the options, and shows progress.
new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation);
// Refresh the necessary state.
((BasicCommandStack) editingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
} catch (Exception exception) {
// Something went wrong that shouldn't.
WTSpec4MEditorPlugin.INSTANCE.log(exception);
}
updateProblemIndication = true;
updateProblemIndication();
}
/**
* This returns whether something has been persisted to the URI of the
* specified resource. The implementation uses the URI converter from the
* editor's resource set to try to open an input stream. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean isPersisted(Resource resource) {
boolean result = false;
try {
InputStream stream = editingDomain.getResourceSet().getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
} catch (IOException e) {
// Ignore
}
return result;
}
/**
* This always returns true because it is not currently supported. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* This also changes the editor's input. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
@Override
public void doSaveAs() {
new ResourceDialog(getSite().getShell(), null, SWT.NONE) {
@Override
protected boolean isSave() {
return true;
}
@Override
protected boolean processResources() {
List<URI> uris = getURIs();
if (uris.size() > 0) {
URI uri = uris.get(0);
doSaveAs(uri, new URIEditorInput(uri));
return true;
} else {
return false;
}
}
}.open();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void doSaveAs(URI uri, IEditorInput editorInput) {
(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
IProgressMonitor progressMonitor = getActionBars().getStatusLineManager() != null
? getActionBars().getStatusLineManager().getProgressMonitor() : new NullProgressMonitor();
doSave(progressMonitor);
}
/**
* This is called during startup. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
@Override
public void init(IEditorSite site, IEditorInput editorInput) {
setSite(site);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
site.setSelectionProvider(this);
site.getPage().addPartListener(partListener);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setFocus() {
if (currentViewerPane != null) {
currentViewerPane.setFocus();
} else {
getControl(getActivePage()).setFocus();
}
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to
* return this editor's overall selection. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
public ISelection getSelection() {
return editorSelection;
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to
* set this editor's overall selection. Calling this result will notify the
* listeners. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSelection(ISelection selection) {
editorSelection = selection;
for (ISelectionChangedListener listener : selectionChangedListeners) {
listener.selectionChanged(new SelectionChangedEvent(this, selection));
}
setStatusLineManager(selection);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setStatusLineManager(ISelection selection) {
IStatusLineManager statusLineManager = currentViewer != null && currentViewer == contentOutlineViewer
? contentOutlineStatusLineManager : getActionBars().getStatusLineManager();
if (statusLineManager != null) {
if (selection instanceof IStructuredSelection) {
Collection<?> collection = ((IStructuredSelection) selection).toList();
switch (collection.size()) {
case 0: {
statusLineManager.setMessage(getString("_UI_NoObjectSelected"));
break;
}
case 1: {
String text = new AdapterFactoryItemDelegator(adapterFactory).getText(collection.iterator().next());
statusLineManager.setMessage(getString("_UI_SingleObjectSelected", text));
break;
}
default: {
statusLineManager
.setMessage(getString("_UI_MultiObjectSelected", Integer.toString(collection.size())));
break;
}
}
} else {
statusLineManager.setMessage("");
}
}
}
/**
* This looks up a string in the plugin's plugin.properties file. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static String getString(String key) {
return WTSpec4MEditorPlugin.INSTANCE.getString(key);
}
/**
* This looks up a string in plugin.properties, making a substitution. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static String getString(String key, Object s1) {
return WTSpec4MEditorPlugin.INSTANCE.getString(key, new Object[] { s1 });
}
/**
* This implements {@link org.eclipse.jface.action.IMenuListener} to help
* fill the context menus with contributions from the Edit menu. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void menuAboutToShow(IMenuManager menuManager) {
((IMenuListener) getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public EditingDomainActionBarContributor getActionBarContributor() {
return (EditingDomainActionBarContributor) getEditorSite().getActionBarContributor();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IActionBars getActionBars() {
return getActionBarContributor().getActionBars();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public AdapterFactory getAdapterFactory() {
return adapterFactory;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void dispose() {
updateProblemIndication = false;
getSite().getPage().removePartListener(partListener);
// adapterFactory.dispose();
if (getActionBarContributor().getActiveEditor() == this) {
getActionBarContributor().setActiveEditor(null);
}
for (PropertySheetPage propertySheetPage : propertySheetPages) {
propertySheetPage.dispose();
}
if (contentOutlinePage != null) {
contentOutlinePage.dispose();
}
super.dispose();
}
/**
* Returns whether the outline view should be presented to the user. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean showOutlineView() {
return true;
}
}
|
package org.jgrapes.net;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.HashSet;
import java.util.IntSummaryStatistics;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Component;
import org.jgrapes.core.Components;
import org.jgrapes.core.EventPipeline;
import org.jgrapes.core.Manager;
import org.jgrapes.core.Self;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.core.events.Error;
import org.jgrapes.core.events.Start;
import org.jgrapes.core.events.Stop;
import org.jgrapes.io.IOSubchannel;
import org.jgrapes.io.IOSubchannel.DefaultSubchannel;
import org.jgrapes.io.NioHandler;
import org.jgrapes.io.events.Close;
import org.jgrapes.io.events.Closed;
import org.jgrapes.io.events.IOError;
import org.jgrapes.io.events.Input;
import org.jgrapes.io.events.NioRegistration;
import org.jgrapes.io.events.NioRegistration.Registration;
import org.jgrapes.io.events.Output;
import org.jgrapes.io.util.AvailabilityListener;
import org.jgrapes.io.util.ManagedBuffer;
import org.jgrapes.io.util.ManagedBufferPool;
import org.jgrapes.io.util.PermitsPool;
import org.jgrapes.net.events.Accepted;
import org.jgrapes.net.events.Ready;
import org.jgrapes.util.events.ConfigurationUpdate;
/**
* Provides a TCP server. The server binds to the given address. If the
* address is {@code null}, address and port are automatically assigned.
* The port may be overwritten by a configuration event
* (see {@link #onConfigurationUpdate(ConfigurationUpdate)}).
*
* The end of record flag is not used by the server.
*/
public class TcpServer extends Component implements NioHandler {
private InetSocketAddress serverAddress = null;
private ServerSocketChannel serverSocketChannel = null;
private int bufferSize = 0;
private Set<TcpChannel> channels = new HashSet<>();
private boolean closing = false;
private ExecutorService executorService = null;
private int backlog = 0;
private PermitsPool connLimiter = null;
private Registration registration = null;
private AvailabilityListener permitsListener = new AvailabilityListener() {
@Override
public void availabilityChanged(PermitsPool pool, boolean available) {
if (registration == null) {
return;
}
registration.updateInterested(
(Boolean)available ? SelectionKey.OP_ACCEPT : 0);
}
};
/**
* Creates a new server, using itself as component channel.
*/
public TcpServer() {
MBeanView.addServer(this);
}
/**
* Creates a new server using the given channel.
*
* @param componentChannel the component's channel
*/
public TcpServer(Channel componentChannel) {
super(componentChannel);
MBeanView.addServer(this);
}
/**
* Sets the address to bind to. If none is set, the address and port
* are assigned automatically.
*
* @param serverAddress the address to bind to
* @return the TCP server for easy chaining
*/
public TcpServer setServerAddress(InetSocketAddress serverAddress) {
this.serverAddress = serverAddress;
return this;
}
/**
* The component can be configured with events that include
* a path (see @link {@link ConfigurationUpdate#paths()})
* that matches this components path (see {@link Manager#path()}).
*
* The following properties are recognized:
*
* `hostname`
* : If given, is used as first parameter for
* {@link InetSocketAddress#InetSocketAddress(String, int)}.
*
* `port`
* : If given, is used as parameter for
* {@link InetSocketAddress#InetSocketAddress(String, int)}
* or {@link InetSocketAddress#InetSocketAddress(int)},
* depending on whether a host name is specified. Defaults to "0".
*
* `backlog`
* : See {@link #setBacklog(int)}.
*
* `bufferSize`
* : See {@link #setBufferSize(int)}.
*
* @param event the event
*/
@Handler
public void onConfigurationUpdate(ConfigurationUpdate event) {
event.values(path()).ifPresent(values -> {
String hostname = values.get("hostname");
if (hostname != null) {
setServerAddress(new InetSocketAddress(hostname,
Integer.parseInt(values.getOrDefault("port", "0"))));
} else if (values.containsKey("port")) {
setServerAddress(new InetSocketAddress(
Integer.parseInt(values.get("port"))));
}
Optional.ofNullable(values.get("backlog")).ifPresent(
value -> setBacklog(Integer.parseInt(value)));
Optional.ofNullable(values.get("bufferSize")).ifPresent(
value -> setBufferSize(Integer.parseInt(value)));
});
}
/**
* Returns the server address. Before starting, the address is the
* address set with {@link #setServerAddress(InetSocketAddress)}. After
* starting the address is obtained from the created socket.
*
* @return the serverAddress
*/
public InetSocketAddress serverAddress() {
try {
return serverSocketChannel == null ? serverAddress
: (InetSocketAddress)serverSocketChannel.getLocalAddress();
} catch (IOException e) {
return serverAddress;
}
}
/**
* Sets the buffer size for the send an receive buffers.
* If no size is set, the system defaults will be used.
*
* @param bufferSize the size to use for the send and receive buffers
* @return the TCP server for easy chaining
*/
public TcpServer setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
/**
* @return the bufferSize
*/
public int bufferSize() {
return bufferSize;
}
/**
* Sets the backlog size.
*
* @param backlog the backlog to set
* @return the TCP server for easy chaining
*/
public TcpServer setBacklog(int backlog) {
this.backlog = backlog;
return this;
}
/**
* @return the backlog
*/
public int backlog() {
return backlog;
}
public TcpServer setConnectionLimiter(PermitsPool connectionLimiter) {
if (connLimiter != null) {
connLimiter.removeListener(permitsListener);
}
this.connLimiter = connectionLimiter;
if (connLimiter != null) {
connLimiter.addListener(permitsListener);
}
return this;
}
/**
* @return the connection Limiter
*/
public PermitsPool getConnectionLimiter() {
return connLimiter;
}
/**
* Sets an executor service to be used by the event pipelines
* that process the data from the network. Setting this
* to an executor service with a limited number of threads
* allows to control the maximum load from the network.
*
* @param executorService the executorService to set
* @return the TCP server for easy chaining
* @see Manager#newEventPipeline(ExecutorService)
*/
public TcpServer setExecutorService(ExecutorService executorService) {
this.executorService = executorService;
return this;
}
/**
* @return the executorService
*/
public ExecutorService executorService() {
return executorService;
}
/**
* Starts the server.
*
* @param event the start event
* @throws IOException if an I/O exception occurred
*/
@Handler
public void onStart(Start event) throws IOException {
closing = false;
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(serverAddress, backlog);
fire(new NioRegistration(this, serverSocketChannel,
SelectionKey.OP_ACCEPT, this), Channel.BROADCAST);
}
@Handler(channels=Self.class)
public void onRegistered(NioRegistration.Completed event)
throws InterruptedException, IOException {
NioHandler handler = event.event().handler();
if (handler == this) {
if (event.event().get() == null) {
fire(new Error(event,
"Registration failed, no NioDispatcher?"));
return;
}
registration = event.event().get();
fire(new Ready(serverSocketChannel.getLocalAddress()));
return;
}
if (handler instanceof TcpChannel) {
((TcpChannel)handler)
.registrationComplete(event.event());
}
}
/* (non-Javadoc)
* @see org.jgrapes.io.NioSelectable#handleOps(int)
*/
@Override
public void handleOps(int ops) {
synchronized (channels) {
if ((ops & SelectionKey.OP_ACCEPT) != 0 && !closing) {
try {
if (connLimiter == null || connLimiter.tryAcquire()) {
SocketChannel socketChannel = serverSocketChannel.accept();
channels.add(new TcpChannel(socketChannel));
}
} catch (IOException e) {
fire(new IOError(null, e));
}
}
}
}
private boolean removeChannel(TcpChannel channel) {
synchronized (channels) {
if(!channels.remove(channel)) {
// Closed already
return false;
}
if (connLimiter != null) {
connLimiter.release();
}
// In case the server is shutting down
channels.notifyAll();
}
return true;
}
/**
* Writes the data passed in the event to the client. The end of record
* flag is ignored.
*
* @param event the event
* @throws IOException if an error occurs
*/
@Handler
public void onOutput(Output<ByteBuffer> event,
TcpChannel channel) {
if (channels.contains(channel)) {
channel.write(event);
}
}
/**
* Shuts down the server or one of the connections to the server
*
* @param event the event
* @throws IOException if an I/O exception occurred
* @throws InterruptedException if the execution was interrupted
*/
@Handler
public void onClose(Close event) throws IOException, InterruptedException {
boolean subOnly = true;
for (Channel channel: event.channels()) {
if (channel instanceof TcpChannel) {
if (channels.contains(channel)) {
((TcpChannel)channel).close();
}
} else {
subOnly = false;
}
}
if (subOnly || !serverSocketChannel.isOpen()) {
return;
}
synchronized (channels) {
closing = true;
// Copy to avoid concurrent modification exception
Set<TcpChannel> conns = new HashSet<>(channels);
for (TcpChannel conn : conns) {
conn.close();
}
while (channels.size() > 0) {
channels.wait();
}
}
serverSocketChannel.close();
closing = false;
fire(new Closed());
}
/**
* Shuts down the server.
*
* @param event the event
*/
@Handler
public void onStop(Stop event) {
if (closing || !serverSocketChannel.isOpen()) {
return;
}
newSyncEventPipeline().fire(new Close(), channel());
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return Components.objectName(this);
}
/**
* The internal representation of a connected client.
*/
private class TcpChannel
extends DefaultSubchannel implements NioHandler {
private SocketChannel nioChannel;
private EventPipeline downPipeline;
private ManagedBufferPool<ManagedBuffer<ByteBuffer>, ByteBuffer>
readBuffers;
private Registration registration = null;
private Queue<ManagedBuffer<ByteBuffer>.ByteBufferView>
pendingWrites = new ArrayDeque<>();
private boolean pendingClose = false;
/**
* @param nioChannel the channel
* @throws IOException if an I/O error occured
*/
public TcpChannel(SocketChannel nioChannel) throws IOException {
super(TcpServer.this);
this.nioChannel = nioChannel;
if (executorService != null) {
downPipeline = newEventPipeline(executorService);
} else {
downPipeline = newEventPipeline();
}
String channelName = Components.objectName(TcpServer.this)
+ "." + Components.objectName(this);
int writeBufferSize = bufferSize == 0
? nioChannel.socket().getSendBufferSize() : bufferSize;
setByteBufferPool(new ManagedBufferPool<>(ManagedBuffer::new,
() -> { return ByteBuffer.allocate(writeBufferSize); }, 2)
.setName(channelName + ".upstream.buffers"));
int readBufferSize = bufferSize == 0
? nioChannel.socket().getReceiveBufferSize() : bufferSize;
readBuffers = new ManagedBufferPool<>(ManagedBuffer::new,
() -> { return ByteBuffer.allocate(readBufferSize); }, 2)
.setName(channelName + ".downstream.buffers");
// Register with dispatcher
nioChannel.configureBlocking(false);
TcpServer.this.fire(
new NioRegistration(this, nioChannel, 0, TcpServer.this),
Channel.BROADCAST);
}
/**
* Invoked when registration has completed.
*
* @param event the completed event
* @throws InterruptedException if the execution was interrupted
* @throws IOException if an I/O error occurred
*/
public void registrationComplete(NioRegistration event)
throws InterruptedException, IOException {
registration = event.get();
downPipeline.fire(new Accepted(nioChannel.getLocalAddress(),
nioChannel.getRemoteAddress(), false,
Collections.emptyList()), this);
registration.updateInterested(SelectionKey.OP_READ);
}
/**
* Write the data on this channel.
*
* @param event the event
*/
public void write(Output<ByteBuffer> event) {
synchronized(pendingWrites) {
if (!nioChannel.isOpen()) {
return;
}
ManagedBuffer<ByteBuffer>.ByteBufferView reader
= event.buffer().newByteBufferView();
if (!pendingWrites.isEmpty()) {
reader.managedBuffer().lockBuffer();
pendingWrites.add(reader);
return;
}
try {
nioChannel.write(reader.get());
} catch (IOException e) {
downPipeline.fire(new IOError(event, e), this);
return;
}
if (!reader.get().hasRemaining()) {
return;
}
reader.managedBuffer().lockBuffer();
pendingWrites.add(reader);
if (pendingWrites.size() == 1) {
registration.updateInterested(
SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
}
}
@Override
public void handleOps(int ops) {
try {
if ((ops & SelectionKey.OP_READ) != 0) {
handleReadOp();
}
if ((ops & SelectionKey.OP_WRITE) != 0) {
handleWriteOp();
}
} catch (InterruptedException e) {
downPipeline.fire(new IOError(null, e));
}
}
/**
* Gets a buffer from the pool and reads available data into it.
* Sends the result as event.
*
* @throws InterruptedException
* @throws IOException
*/
private void handleReadOp() throws InterruptedException {
ManagedBuffer<ByteBuffer> buffer;
buffer = readBuffers.acquire();
try {
int bytes = buffer.fillFromChannel(nioChannel);
if (bytes == 0) {
buffer.unlockBuffer();
return;
}
if (bytes > 0) {
downPipeline.fire(Input.fromSink(buffer, false), this);
return;
}
} catch (IOException e) {
buffer.unlockBuffer();
downPipeline.fire(new IOError(null, e));
return;
}
// EOF (-1) from client
buffer.unlockBuffer();
synchronized (nioChannel) {
if (nioChannel.socket().isOutputShutdown()) {
// Client confirms our close, complete close
try {
nioChannel.close();
} catch (IOException e) {
// Ignored for close
}
return;
}
}
// Client initiates close
removeChannel();
synchronized (pendingWrites) {
synchronized (nioChannel) {
try {
if (!pendingWrites.isEmpty()) {
// Pending writes, delay close
pendingClose = true;
// Mark as client initiated close
nioChannel.shutdownInput();
return;
}
// Nothing left to do, close
nioChannel.close();
} catch (IOException e) {
// Ignored for close
}
}
}
}
/**
* Checks if there is still data to be written. This may be
* a left over in an incompletely written buffer or a complete
* pending buffer.
*
* @throws IOException
* @throws InterruptedException
*/
private void handleWriteOp() throws InterruptedException {
while (true) {
ManagedBuffer<ByteBuffer>.ByteBufferView head = null;
synchronized (pendingWrites) {
if (pendingWrites.isEmpty()) {
// Nothing left to write, stop getting ops
registration.updateInterested(SelectionKey.OP_READ);
// Was the connection closed while we were writing?
if (pendingClose) {
synchronized (nioChannel) {
try {
if (nioChannel.socket().isInputShutdown()) {
// Delayed close from client, complete
nioChannel.close();
} else {
// Delayed close from server, initiate
nioChannel.shutdownOutput();
}
} catch (IOException e) {
// Ignored for close
}
}
pendingClose = false;
}
break; // Nothing left to do
}
head = pendingWrites.peek();
if (!head.get().hasRemaining()) {
// Nothing left in head buffer, try next
head.managedBuffer().unlockBuffer();
pendingWrites.remove();
continue;
}
}
try {
nioChannel.write(head.get()); // write...
} catch (IOException e) {
downPipeline.fire(new IOError(null, e), this);
}
break; // ... and wait for next op
}
}
/**
* Closes this channel.
*
* @throws IOException if an error occurs
* @throws InterruptedException if the execution was interrupted
*/
public void close() throws IOException, InterruptedException {
removeChannel();
synchronized (pendingWrites) {
if (!pendingWrites.isEmpty()) {
// Pending writes, delay close until done
pendingClose = true;
return;
}
// Nothing left to do, proceed
synchronized (nioChannel) {
if (nioChannel.isOpen()) {
// Initiate close, must be confirmed by client
nioChannel.shutdownOutput();
}
}
}
}
private void removeChannel() throws InterruptedException {
if (TcpServer.this.removeChannel(this)) {
Closed evt = new Closed();
downPipeline.fire(evt, this);
evt.get();
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return IOSubchannel.toString(this);
}
}
/**
* An MBean interface for getting information about the TCP servers
* and established connections.
*/
public static interface TcpServerMXBean {
public static class ChannelInfo {
private TcpChannel channel;
public ChannelInfo(TcpChannel channel) {
this.channel = channel;
}
public String getDownstreamPool() {
return channel.readBuffers.name();
}
public String getUpstreamPool() {
return channel.byteBufferPool().name();
}
}
public static class TcpServerInfo {
private TcpServer server;
public TcpServerInfo(TcpServer server) {
this.server = server;
}
public int getPort() {
return ((InetSocketAddress)server.serverAddress()).getPort();
}
public SortedMap<String,ChannelInfo> getChannels() {
SortedMap<String,ChannelInfo> result = new TreeMap<>();
for (TcpChannel channel: server.channels) {
result.put(channel.nioChannel.socket()
.getRemoteSocketAddress().toString(),
new ChannelInfo(channel));
}
return result;
}
}
IntSummaryStatistics getConnectionsPerServerStatistics();
SortedMap<String,TcpServerInfo> getServers();
}
private static class MBeanView implements TcpServerMXBean {
private static Set<TcpServer> allServers
= Collections.synchronizedSet(
Collections.newSetFromMap(
new WeakHashMap<TcpServer, Boolean>()));
public static void addServer(TcpServer server) {
allServers.add(server);
}
@Override
public IntSummaryStatistics getConnectionsPerServerStatistics() {
return allServers.stream().collect(
Collectors.summarizingInt(srv -> srv.channels.size()));
}
@Override
public SortedMap<String,TcpServerInfo> getServers() {
SortedMap<String,TcpServerInfo> result = new TreeMap<>();
for (TcpServer server: allServers) {
int port = server.serverAddress().getPort();
result.put(Components.objectName(server) + " (:" + port + ")",
new TcpServerInfo(server));
}
return result;
}
}
static {
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName mxbeanName = new ObjectName("org.jgrapes.io:type="
+ TcpServer.class.getSimpleName());
mbs.registerMBean(new MBeanView(), mxbeanName);
} catch (MalformedObjectNameException | InstanceAlreadyExistsException
| MBeanRegistrationException | NotCompliantMBeanException e) {
// Does not happen
}
}
}
|
package net.i2p.router.admin;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import net.i2p.data.DataHelper;
import net.i2p.router.RouterContext;
import net.i2p.stat.Frequency;
import net.i2p.stat.FrequencyStat;
import net.i2p.stat.Rate;
import net.i2p.stat.RateStat;
import net.i2p.util.Log;
/**
* Dump the stats to the web admin interface
*/
public class StatsGenerator {
private Log _log;
private RouterContext _context;
public StatsGenerator(RouterContext context) {
_context = context;
_log = context.logManager().getLog(StatsGenerator.class);
}
public void generateStatsPage(OutputStream out) throws IOException {
StringBuffer buf = new StringBuffer(16*1024);
buf.append("<html><head><title>I2P Router Stats</title></head><body>");
buf.append("<h1>Router statistics</h1>");
buf.append("<i><a href=\"/routerConsole.html\">console</a> | <a href=\"/routerStats.html\">stats</a></i><hr />");
buf.append("<form action=\"/routerStats.html\">");
buf.append("<select name=\"go\" onChange='location.href=this.value'>");
out.write(buf.toString().getBytes());
buf.setLength(0);
Map groups = _context.statManager().getStatsByGroup();
for (Iterator iter = groups.keySet().iterator(); iter.hasNext(); ) {
String group = (String)iter.next();
Set stats = (Set)groups.get(group);
buf.append("<option value=\"/routerStats.html#").append(group).append("\">");
buf.append(group).append("</option>\n");
for (Iterator statIter = stats.iterator(); statIter.hasNext(); ) {
String stat = (String)statIter.next();
buf.append("<option value=\"/routerStats.html
buf.append(stat);
buf.append("\">...");
buf.append(stat);
buf.append("</option>\n");
}
out.write(buf.toString().getBytes());
buf.setLength(0);
}
buf.append("</select>");
buf.append("</form>");
buf.append("Statistics gathered during this router's uptime (");
long uptime = _context.router().getUptime();
buf.append(DataHelper.formatDuration(uptime));
buf.append("). The data gathered is quantized over a 1 minute period, so should just be used as an estimate<p />");
out.write(buf.toString().getBytes());
buf.setLength(0);
for (Iterator iter = groups.keySet().iterator(); iter.hasNext(); ) {
String group = (String)iter.next();
Set stats = (Set)groups.get(group);
buf.append("<h2><a name=\"");
buf.append(group);
buf.append("\">");
buf.append(group);
buf.append("</a></h2>");
buf.append("<ul>");
out.write(buf.toString().getBytes());
buf.setLength(0);
for (Iterator statIter = stats.iterator(); statIter.hasNext(); ) {
String stat = (String)statIter.next();
buf.append("<li><b><a name=\"");
buf.append(stat);
buf.append("\">");
buf.append(stat);
buf.append("</a></b><br />");
if (_context.statManager().isFrequency(stat))
renderFrequency(stat, buf);
else
renderRate(stat, buf);
out.write(buf.toString().getBytes());
buf.setLength(0);
}
out.write("</ul><hr />".getBytes());
}
out.write("</body></html>".getBytes());
}
private void renderFrequency(String name, StringBuffer buf) {
FrequencyStat freq = _context.statManager().getFrequency(name);
buf.append("<i>");
buf.append(freq.getDescription());
buf.append("</i><br />");
long periods[] = freq.getPeriods();
Arrays.sort(periods);
for (int i = 0; i < periods.length; i++) {
renderPeriod(buf, periods[i], "frequency");
Frequency curFreq = freq.getFrequency(periods[i]);
buf.append(" <i>avg per period:</i> (");
buf.append(num(curFreq.getAverageEventsPerPeriod()));
buf.append(", max ");
buf.append(num(curFreq.getMaxAverageEventsPerPeriod()));
if ( (curFreq.getMaxAverageEventsPerPeriod() > 0) && (curFreq.getAverageEventsPerPeriod() > 0) ) {
buf.append(", current is ");
buf.append(pct(curFreq.getAverageEventsPerPeriod()/curFreq.getMaxAverageEventsPerPeriod()));
buf.append(" of max");
}
buf.append(")");
//buf.append(" <i>avg interval between updates:</i> (").append(num(curFreq.getAverageInterval())).append("ms, min ");
//buf.append(num(curFreq.getMinAverageInterval())).append("ms)");
buf.append(" <i>strict average per period:</i> ");
buf.append(num(curFreq.getStrictAverageEventsPerPeriod()));
buf.append(" events (averaged ");
buf.append(" using the lifetime of ");
buf.append(num(curFreq.getEventCount()));
buf.append(" events)");
buf.append("<br />");
}
buf.append("<br />");
}
private void renderRate(String name, StringBuffer buf) {
RateStat rate = _context.statManager().getRate(name);
buf.append("<i>");
buf.append(rate.getDescription());
buf.append("</i><br />");
long periods[] = rate.getPeriods();
Arrays.sort(periods);
buf.append("<ul>");
for (int i = 0; i < periods.length; i++) {
buf.append("<li>");
renderPeriod(buf, periods[i], "rate");
Rate curRate = rate.getRate(periods[i]);
buf.append( "<i>avg value:</i> (");
buf.append(num(curRate.getAverageValue()));
buf.append(" peak ");
buf.append(num(curRate.getExtremeAverageValue()));
buf.append(", [");
buf.append(pct(curRate.getPercentageOfExtremeValue()));
buf.append(" of max");
buf.append(", and ");
buf.append(pct(curRate.getPercentageOfLifetimeValue()));
buf.append(" of lifetime average]");
buf.append(")");
buf.append(" <i>highest total period value:</i> (");
buf.append(num(curRate.getExtremeTotalValue()));
buf.append(")");
if (curRate.getLifetimeTotalEventTime() > 0) {
buf.append(" <i>saturation:</i> (");
buf.append(pct(curRate.getLastEventSaturation()));
buf.append(")");
buf.append(" <i>saturated limit:</i> (");
buf.append(num(curRate.getLastSaturationLimit()));
buf.append(")");
buf.append(" <i>peak saturation:</i> (");
buf.append(pct(curRate.getExtremeEventSaturation()));
buf.append(")");
buf.append(" <i>peak saturated limit:</i> (");
buf.append(num(curRate.getExtremeSaturationLimit()));
buf.append(")");
}
buf.append(" <i>events per period:</i> ");
buf.append(num(curRate.getLastEventCount()));
long numPeriods = curRate.getLifetimePeriods();
if (numPeriods > 0) {
double avgFrequency = curRate.getLifetimeEventCount() / (double)numPeriods;
double peakFrequency = curRate.getExtremeEventCount();
buf.append(" (lifetime average: ");
buf.append(num(avgFrequency));
buf.append(", peak average: ");
buf.append(num(curRate.getExtremeEventCount()));
buf.append(")");
}
buf.append("</li>");
if (i + 1 == periods.length) {
// last one, so lets display the strict average
buf.append("<li><b>lifetime average value:</b> ");
buf.append(num(curRate.getLifetimeAverageValue()));
buf.append(" over ");
buf.append(num(curRate.getLifetimeEventCount()));
buf.append(" events<br /></li>");
}
}
buf.append("</ul>");
buf.append("<br />");
}
private static void renderPeriod(StringBuffer buf, long period, String name) {
buf.append("<b>");
buf.append(DataHelper.formatDuration(period));
buf.append(" ");
buf.append(name);
buf.append(":</b> ");
}
private final static DecimalFormat _fmt = new DecimalFormat("###,##0.00");
private final static String num(double num) { synchronized (_fmt) { return _fmt.format(num); } }
private final static DecimalFormat _pct = new DecimalFormat("#0.00%");
private final static String pct(double num) { synchronized (_pct) { return _pct.format(num); } }
}
|
package com.delormeloic.generator.view.slidesforms;
import com.delormeloic.generator.model.slides.SlideWithTitle;
import com.delormeloic.generator.view.converters.FontStringConverter;
import com.delormeloic.generator.view.helpers.FontsHelper;
import com.delormeloic.generator.view.helpers.GridPaneHelper;
import com.delormeloic.generator.view.helpers.TextHelper;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.text.Font;
public class SlideWithTitleForm extends SlideForm
{
/**
* Create a slide with a title form.
*
* @param slideWithTitle
* The slide with a title.
*/
public SlideWithTitleForm(SlideWithTitle slideWithTitle)
{
super(slideWithTitle);
}
/**
* @see com.delormeloic.generator.view.slidesforms.IFormable#toForm()
*/
@Override
public Node toForm()
{
final SlideWithTitle slideWithTitle = (SlideWithTitle) this.slide;
final TextField nameTextField = new TextField();
final CheckBox headerCheckBox = new CheckBox();
final CheckBox footerCheckBox = new CheckBox();
final TextField titleTextField = new TextField();
final ComboBox<Font> titleFontComboBox = new ComboBox<Font>();
titleFontComboBox.getItems().addAll(FontsHelper.getAllAvailableFonts());
titleFontComboBox.setConverter(new FontStringConverter());
nameTextField.textProperty().bindBidirectional(slideWithTitle.getNameProperty());
headerCheckBox.selectedProperty().bindBidirectional(slideWithTitle.getHeaderProperty());
footerCheckBox.selectedProperty().bindBidirectional(slideWithTitle.getFooterProperty());
titleTextField.textProperty().bindBidirectional(slideWithTitle.getTitleProperty());
titleFontComboBox.valueProperty().bindBidirectional(slideWithTitle.getTitleFontProperty());
final Node[] nameField = new Node[] { new Label(TextHelper.getText("slideWithTitleFormNameField")), nameTextField };
final Node[] headerField = new Node[] { new Label(TextHelper.getText("slideWithTitleFormHeaderField")), headerCheckBox };
final Node[] footerField = new Node[] { new Label(TextHelper.getText("slideWithTitleFormFooterField")), footerCheckBox };
final Node[] titleField = new Node[] { new Label(TextHelper.getText("slideWithTitleFormTitleField")), titleTextField };
final Node[] titleFontField = new Node[] { new Label(TextHelper.getText("slideWithTitleFormTitleFontField")), titleFontComboBox };
return GridPaneHelper.buildGridPane(new Node[][] { nameField, GridPaneHelper.getSeparators(2), headerField, footerField, GridPaneHelper.getSeparators(2), titleField, titleFontField });
}
}
|
package com.jaquadro.minecraft.storagedrawers.config;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class CompTierRegistry
{
public class Record {
public ItemStack upper;
public ItemStack lower;
public int convRate;
}
private List<Record> records = new ArrayList<Record>();
public CompTierRegistry () {
register(new ItemStack(Blocks.clay), new ItemStack(Items.clay_ball), 4);
register(new ItemStack(Blocks.snow), new ItemStack(Items.snowball), 4);
register(new ItemStack(Blocks.glowstone), new ItemStack(Items.glowstone_dust), 4);
register(new ItemStack(Blocks.brick_block), new ItemStack(Items.brick), 4);
register(new ItemStack(Blocks.nether_brick), new ItemStack(Items.netherbrick), 4);
register(new ItemStack(Blocks.quartz_block), new ItemStack(Items.quartz), 4);
register(new ItemStack(Blocks.melon_block), new ItemStack(Items.melon), 9);
}
public void register (ItemStack upper, ItemStack lower, int convRate) {
Record r = new Record();
r.upper = upper;
r.lower = lower;
r.convRate = convRate;
records.add(r);
}
public Record findHigherTier (ItemStack stack) {
if (stack == null || stack.getItem() == null)
return null;
for (Record r : records) {
if (stack.isItemEqual(r.lower) && ItemStack.areItemStackTagsEqual(stack, r.lower))
return r;
}
return null;
}
public Record findLowerTier (ItemStack stack) {
if (stack == null || stack.getItem() == null)
return null;
for (Record r : records) {
if (stack.isItemEqual(r.upper) && ItemStack.areItemStackTagsEqual(stack, r.upper))
return r;
}
return null;
}
}
|
package com.subgraph.orchid.directory.consensus;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import com.subgraph.orchid.ConsensusDocument;
import com.subgraph.orchid.DirectoryServer;
import com.subgraph.orchid.KeyCertificate;
import com.subgraph.orchid.RouterStatus;
import com.subgraph.orchid.VoteAuthorityEntry;
import com.subgraph.orchid.crypto.TorPublicKey;
import com.subgraph.orchid.crypto.TorSignature.DigestAlgorithm;
import com.subgraph.orchid.data.HexDigest;
import com.subgraph.orchid.data.Timestamp;
import com.subgraph.orchid.directory.TrustedAuthorities;
public class ConsensusDocumentImpl implements ConsensusDocument {
enum SignatureVerifyStatus { STATUS_UNVERIFIED, STATUS_NEED_CERTS, STATUS_VERIFIED };
private final static Logger logger = Logger.getLogger(ConsensusDocumentImpl.class.getName());
private final static String BW_WEIGHT_SCALE_PARAM = "bwweightscale";
private final static int BW_WEIGHT_SCALE_DEFAULT = 10000;
private final static int BW_WEIGHT_SCALE_MIN = 1;
private final static int BW_WEIGHT_SCALE_MAX = Integer.MAX_VALUE;
private final static String CIRCWINDOW_PARAM = "circwindow";
private final static int CIRCWINDOW_DEFAULT = 1000;
private final static int CIRCWINDOW_MIN = 100;
private final static int CIRCWINDOW_MAX = 1000;
private Set<RequiredCertificate> requiredCertificates = new HashSet<RequiredCertificate>();
private int consensusMethod;
private Timestamp validAfter;
private Timestamp freshUntil;
private Timestamp validUntil;
private int distDelaySeconds;
private int voteDelaySeconds;
private Set<String> clientVersions;
private Set<String> serverVersions;
private Set<String> knownFlags;
private HexDigest signingHash;
private Map<HexDigest, VoteAuthorityEntry> voteAuthorityEntries;
private List<RouterStatus> routerStatusEntries;
private Map<String, Integer> bandwidthWeights;
private Map<String, Integer> parameters;
private int signatureCount;
private boolean isFirstCallToVerifySignatures = true;
private String rawDocumentData;
void setConsensusMethod(int method) { consensusMethod = method; }
void setValidAfter(Timestamp ts) { validAfter = ts; }
void setFreshUntil(Timestamp ts) { freshUntil = ts; }
void setValidUntil(Timestamp ts) { validUntil = ts; }
void setDistDelaySeconds(int seconds) { distDelaySeconds = seconds; }
void setVoteDelaySeconds(int seconds) { voteDelaySeconds = seconds; }
void addClientVersion(String version) { clientVersions.add(version); }
void addServerVersion(String version) { serverVersions.add(version); }
void addParameter(String name, int value) { parameters.put(name, value); }
void addBandwidthWeight(String name, int value) { bandwidthWeights.put(name, value); }
void addSignature(DirectorySignature signature) {
final VoteAuthorityEntry voteAuthority = voteAuthorityEntries.get(signature.getIdentityDigest());
if(voteAuthority == null) {
logger.warning("Consensus contains signature for source not declared in authority section: "+ signature.getIdentityDigest());
return;
}
final List<DirectorySignature> signatures = voteAuthority.getSignatures();
final DigestAlgorithm newSignatureAlgorithm = signature.getSignature().getDigestAlgorithm();
for(DirectorySignature sig: signatures) {
DigestAlgorithm algo = sig.getSignature().getDigestAlgorithm();
if(algo.equals(newSignatureAlgorithm)) {
logger.warning("Consensus contains two or more signatures for same source with same algorithm");
return;
}
}
signatureCount += 1;
signatures.add(signature);
}
void setSigningHash(HexDigest hash) { signingHash = hash; }
void setRawDocumentData(String rawData) { rawDocumentData = rawData; }
ConsensusDocumentImpl() {
clientVersions = new HashSet<String>();
serverVersions = new HashSet<String>();
knownFlags = new HashSet<String>();
voteAuthorityEntries = new HashMap<HexDigest, VoteAuthorityEntry>();
routerStatusEntries = new ArrayList<RouterStatus>();
bandwidthWeights = new HashMap<String, Integer>();
parameters = new HashMap<String, Integer>();
}
void addKnownFlag(String flag) {
knownFlags.add(flag);
}
void addVoteAuthorityEntry(VoteAuthorityEntry entry) {
voteAuthorityEntries.put(entry.getIdentity(), entry);
}
void addRouterStatusEntry(RouterStatusImpl entry) {
routerStatusEntries.add(entry);
}
public Timestamp getValidAfterTime() {
return validAfter;
}
public Timestamp getFreshUntilTime() {
return freshUntil;
}
public Timestamp getValidUntilTime() {
return validUntil;
}
public int getConsensusMethod() {
return consensusMethod;
}
public int getVoteSeconds() {
return voteDelaySeconds;
}
public int getDistSeconds() {
return distDelaySeconds;
}
public Set<String> getClientVersions() {
return clientVersions;
}
public Set<String> getServerVersions() {
return serverVersions;
}
public boolean isLive() {
if(validUntil == null) {
return false;
} else {
return !validUntil.hasPassed();
}
}
public List<RouterStatus> getRouterStatusEntries() {
return Collections.unmodifiableList(routerStatusEntries);
}
public String getRawDocumentData() {
return rawDocumentData;
}
public boolean isValidDocument() {
return (validAfter != null) && (freshUntil != null) && (validUntil != null) &&
(voteDelaySeconds > 0) && (distDelaySeconds > 0) && (signingHash != null) &&
(signatureCount > 0);
}
public HexDigest getSigningHash() {
return signingHash;
}
public synchronized SignatureStatus verifySignatures() {
boolean firstCall = isFirstCallToVerifySignatures;
isFirstCallToVerifySignatures = false;
requiredCertificates.clear();
int verifiedCount = 0;
int certsNeededCount = 0;
final int v3Count = TrustedAuthorities.getInstance().getV3AuthorityServerCount();
final int required = (v3Count / 2) + 1;
for(VoteAuthorityEntry entry: voteAuthorityEntries.values()) {
switch(verifySingleAuthority(entry)) {
case STATUS_FAILED:
break;
case STATUS_NEED_CERTS:
certsNeededCount += 1;
break;
case STATUS_VERIFIED:
verifiedCount += 1;
break;
}
}
if(verifiedCount >= required) {
return SignatureStatus.STATUS_VERIFIED;
} else if(verifiedCount + certsNeededCount >= required) {
if(firstCall) {
logger.info("Certificates need to be retrieved to verify consensus");
}
return SignatureStatus.STATUS_NEED_CERTS;
} else {
return SignatureStatus.STATUS_FAILED;
}
}
private SignatureStatus verifySingleAuthority(VoteAuthorityEntry authority) {
boolean certsNeeded = false;
boolean validSignature = false;
for(DirectorySignature s: authority.getSignatures()) {
DirectoryServer trusted = TrustedAuthorities.getInstance().getAuthorityServerByIdentity(s.getIdentityDigest());
if(trusted == null) {
logger.warning("Consensus signed by unrecognized directory authority: "+ s.getIdentityDigest());
return SignatureStatus.STATUS_FAILED;
} else {
switch(verifySignatureForTrustedAuthority(trusted, s)) {
case STATUS_NEED_CERTS:
certsNeeded = true;
break;
case STATUS_VERIFIED:
validSignature = true;
break;
default:
break;
}
}
}
if(validSignature) {
return SignatureStatus.STATUS_VERIFIED;
} else if(certsNeeded) {
return SignatureStatus.STATUS_NEED_CERTS;
} else {
return SignatureStatus.STATUS_FAILED;
}
}
private SignatureStatus verifySignatureForTrustedAuthority(DirectoryServer trustedAuthority, DirectorySignature signature) {
final KeyCertificate certificate = trustedAuthority.getCertificateByFingerprint(signature.getSigningKeyDigest());
if(certificate == null) {
logger.fine("Missing certificate for signing key: "+ signature.getSigningKeyDigest());
addRequiredCertificateForSignature(signature);
return SignatureStatus.STATUS_NEED_CERTS;
}
if(certificate.isExpired()) {
return SignatureStatus.STATUS_FAILED;
}
final TorPublicKey signingKey = certificate.getAuthoritySigningKey();
if(!signingKey.verifySignature(signature.getSignature(), signingHash)) {
logger.warning("Signature failed on consensus for signing key: "+ signature.getSigningKeyDigest());
return SignatureStatus.STATUS_FAILED;
}
return SignatureStatus.STATUS_VERIFIED;
}
public Set<RequiredCertificate> getRequiredCertificates() {
return requiredCertificates;
}
private void addRequiredCertificateForSignature(DirectorySignature signature) {
requiredCertificates.add(new RequiredCertificateImpl(signature.getIdentityDigest(), signature.getSigningKeyDigest()));
}
public boolean equals(Object o) {
if(!(o instanceof ConsensusDocumentImpl))
return false;
final ConsensusDocumentImpl other = (ConsensusDocumentImpl) o;
return other.getSigningHash().equals(signingHash);
}
public int hashCode() {
return (signingHash == null) ? 0 : signingHash.hashCode();
}
private int getParameterValue(String name, int defaultValue, int minValue, int maxValue) {
if(!parameters.containsKey(name)) {
return defaultValue;
}
final int value = parameters.get(name);
if(value < minValue) {
return minValue;
} else if(value > maxValue) {
return maxValue;
} else {
return value;
}
}
public int getCircWindowParameter() {
return getParameterValue(CIRCWINDOW_PARAM, CIRCWINDOW_DEFAULT, CIRCWINDOW_MIN, CIRCWINDOW_MAX);
}
public int getWeightScaleParameter() {
return getParameterValue(BW_WEIGHT_SCALE_PARAM, BW_WEIGHT_SCALE_DEFAULT, BW_WEIGHT_SCALE_MIN, BW_WEIGHT_SCALE_MAX);
}
public int getBandwidthWeight(String tag) {
if(bandwidthWeights.containsKey(tag)) {
return bandwidthWeights.get(tag);
} else {
return -1;
}
}
}
|
package com.vswamy.hackerranksolutions.problems.warmup;
import java.util.Scanner;
import com.vswamy.hackerranksolutions.interfaces.Problem;
public class HalloweenParty implements Problem
{
@Override
public void run()
{
Scanner scanner = new Scanner(System.in);
int numberOfTestCases = scanner.nextInt();
for(int i = 0; i < numberOfTestCases; i++)
{
long t = scanner.nextLong();
System.out.println(maximumNumPieces(t));
}
return;
}
private long maximumNumPieces(long x)
{
long firsthalf = x / 2;
long secondhalf = x - firsthalf;
return firsthalf * secondhalf;
}
}
|
package org.jivesoftware.spark.ui.conferences;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.bookmark.BookmarkManager;
import org.jivesoftware.smackx.muc.InvitationListener;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.spark.ChatManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.Workspace;
import org.jivesoftware.spark.component.RolloverButton;
import org.jivesoftware.spark.plugin.ContextMenuListener;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomButton;
import org.jivesoftware.spark.ui.ChatRoomClosingListener;
import org.jivesoftware.spark.ui.ChatRoomListener;
import org.jivesoftware.spark.ui.ChatRoomNotFoundException;
import org.jivesoftware.spark.ui.ContactGroup;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.ContactList;
import org.jivesoftware.spark.ui.PresenceListener;
import org.jivesoftware.spark.ui.rooms.ChatRoomImpl;
import org.jivesoftware.spark.ui.rooms.GroupChatRoom;
import org.jivesoftware.spark.ui.status.StatusBar;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.log.Log;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
/**
* Conference plugin is reponsible for the initial loading of MultiUser Chat support. To disable plugin,
* you can remove from the plugins.xml file located in the classpath of Communicator.
*/
public class ConferenceServices {
private static BookmarksUI bookmarksUI;
private boolean mucSupported;
public ConferenceServices() {
ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
mucSupported = manager.includesFeature("http://jabber.org/protocol/muc");
if (mucSupported) {
// Add an invitation listener.
addInvitationListener();
addChatRoomListener();
addPopupListeners();
// Add Join Conference Button to StatusBar
// Get command panel and add View Online/Offline, Add Contact
StatusBar statusBar = SparkManager.getWorkspace().getStatusBar();
JPanel commandPanel = SparkManager.getWorkspace().getCommandPanel();
RolloverButton joinConference = new RolloverButton(SparkRes.getImageIcon(SparkRes.CONFERENCE_IMAGE_16x16));
joinConference.setToolTipText(Res.getString("message.join.conference.room"));
commandPanel.add(joinConference);
joinConference.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ConferenceRoomBrowser rooms = new ConferenceRoomBrowser(bookmarksUI, getDefaultServiceName());
rooms.invoke();
}
});
// Add Presence Listener to send directed presence to Group Chat Rooms.
PresenceListener presenceListener = new PresenceListener() {
public void presenceChanged(final Presence presence) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) {
if (room instanceof GroupChatRoom) {
final Presence p = new Presence(presence.getType(), presence.getStatus(), presence.getPriority(), presence.getMode());
GroupChatRoom groupChatRoom = (GroupChatRoom)room;
String jid = groupChatRoom.getMultiUserChat().getRoom();
p.setTo(jid);
SparkManager.getConnection().sendPacket(p);
}
}
}
});
}
};
SparkManager.getSessionManager().addPresenceListener(presenceListener);
}
}
/**
* Adds an invitation listener to check for any MUC invites.
*/
private static void addInvitationListener() {
// Add Invite Listener
MultiUserChat.addInvitationListener(SparkManager.getConnection(), new InvitationListener() {
public void invitationReceived(final XMPPConnection conn, final String room, final String inviter, final String reason, final String password, final Message message) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Collection<RoomInvitationListener> listeners = new ArrayList<RoomInvitationListener>(SparkManager.getChatManager().getInvitationListeners());
for (RoomInvitationListener listener : listeners) {
boolean handle = listener.handleInvitation(conn, room, inviter, reason, password, message);
if (handle) {
return;
}
}
// Make sure the user is not already in the room.
try {
SparkManager.getChatManager().getChatContainer().getChatRoom(room);
return;
}
catch (ChatRoomNotFoundException e) {
// Ignore :)
}
final GroupChatInvitationUI invitationUI = new GroupChatInvitationUI(room, inviter, password, reason);
String bareJID = StringUtils.parseBareAddress(inviter);
try {
ChatRoom chatRoom = SparkManager.getChatManager().getChatContainer().getChatRoom(bareJID);
// If the ChatRoom exists, add an invitation UI.
chatRoom.getTranscriptWindow().addComponent(invitationUI);
// Notify user of incoming invitation.
chatRoom.increaseUnreadMessageCount();
chatRoom.scrollToBottom();
SparkManager.getChatManager().getChatContainer().fireNotifyOnMessage(chatRoom);
}
catch (ChatRoomNotFoundException e) {
// If it doesn't exists. Create a new Group Chat Room
// Create the Group Chat Room
final MultiUserChat chat = new MultiUserChat(SparkManager.getConnection(), room);
GroupChatRoom groupChatRoom = new GroupChatRoom(chat);
groupChatRoom.getSplitPane().setDividerSize(5);
groupChatRoom.getVerticalSlipPane().setDividerLocation(0.6);
groupChatRoom.getSplitPane().setDividerLocation(0.6);
String roomName = StringUtils.parseName(room);
groupChatRoom.setTabTitle(roomName);
groupChatRoom.getToolBar().setVisible(true);
SparkManager.getChatManager().getChatContainer().addChatRoom(groupChatRoom);
groupChatRoom.getTranscriptWindow().addComponent(invitationUI);
// Notify user of incoming invitation.
groupChatRoom.increaseUnreadMessageCount();
groupChatRoom.scrollToBottom();
SparkManager.getChatManager().getChatContainer().fireNotifyOnMessage(groupChatRoom);
}
// If no listeners handled the invitation, default to generic invite.
//new ConversationInvitation(conn, room, inviter, reason, password, message);
}
});
}
});
}
/**
* Persists bookmarked data, if any.
*/
public void shutdown() {
if (!mucSupported) {
return;
}
}
/**
* Load all bookmarked data.
*/
public void loadConferenceBookmarks() {
final Workspace workspace = SparkManager.getWorkspace();
final SwingWorker bookmarkLoader = new SwingWorker() {
public Object construct() {
try {
BookmarkManager manager = BookmarkManager.getBookmarkManager(SparkManager.getConnection());
return manager.getBookmarkedConferences();
}
catch (XMPPException e) {
Log.error(e);
}
return true;
}
public void finished() {
bookmarksUI = new BookmarksUI();
workspace.getWorkspacePane().addTab(Res.getString("tab.conferences"), SparkRes.getImageIcon(SparkRes.CONFERENCE_IMAGE_16x16), bookmarksUI);
}
};
bookmarkLoader.start();
}
private void addChatRoomListener() {
ChatManager chatManager = SparkManager.getChatManager();
chatManager.addChatRoomListener(new ChatRoomListener() {
public void chatRoomOpened(final ChatRoom room) {
if (room instanceof ChatRoomImpl) {
final ChatRoomDecorator decorator = new ChatRoomDecorator(room);
decorator.decorate();
}
}
public void chatRoomLeft(ChatRoom room) {
}
public void chatRoomClosed(ChatRoom room) {
}
public void chatRoomActivated(ChatRoom room) {
}
public void userHasJoined(ChatRoom room, String userid) {
}
public void userHasLeft(ChatRoom room, String userid) {
}
});
}
public boolean canShutDown() {
return true;
}
public static String getDefaultServiceName() {
String serviceName = null;
Collection services = bookmarksUI.getMucServices();
if (services != null) {
Iterator serviceIterator = services.iterator();
while (serviceIterator.hasNext()) {
serviceName = (String)serviceIterator.next();
break;
}
}
return serviceName;
}
private void addPopupListeners() {
final ContactList contactList = SparkManager.getWorkspace().getContactList();
// Add ContactList items.
final Action inviteAllAction = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
Collection contacts = contactList.getActiveGroup().getContactItems();
startConference(contacts);
}
};
inviteAllAction.putValue(Action.NAME, Res.getString("menuitem.invite.group.to.conference"));
inviteAllAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.CONFERENCE_IMAGE_16x16));
final Action conferenceAction = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
Collection contacts = contactList.getSelectedUsers();
startConference(contacts);
}
};
conferenceAction.putValue(Action.NAME, Res.getString("menuitem.start.a.conference"));
conferenceAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_WORKGROUP_QUEUE_IMAGE));
contactList.addContextMenuListener(new ContextMenuListener() {
public void poppingUp(Object component, JPopupMenu popup) {
Collection col = contactList.getSelectedUsers();
if (component instanceof ContactGroup) {
popup.add(inviteAllAction);
}
else if (component instanceof Collection && col.size() > 0) {
popup.add(conferenceAction);
}
}
public void poppingDown(JPopupMenu popup) {
}
public boolean handleDefaultAction(MouseEvent e) {
return false;
}
});
// Add to Actions Menu
final JMenu actionsMenu = SparkManager.getMainWindow().getMenuByName(Res.getString("menuitem.actions"));
actionsMenu.add(conferenceAction);
}
private void startConference(Collection items) {
final ContactList contactList = SparkManager.getWorkspace().getContactList();
List jids = new ArrayList();
Iterator contacts = items.iterator();
while (contacts.hasNext()) {
ContactItem item = (ContactItem)contacts.next();
ContactGroup contactGroup = contactList.getContactGroup(item.getGroupName());
contactGroup.clearSelection();
if (item.isAvailable()) {
jids.add(item.getJID());
}
}
String userName = StringUtils.parseName(SparkManager.getSessionManager().getJID());
final String roomName = userName + "_" + StringUtils.randomString(3);
String serviceName = getDefaultServiceName();
if (ModelUtil.hasLength(serviceName)) {
ConferenceUtils.inviteUsersToRoom(serviceName, roomName, jids);
}
}
/**
* Returns the UI for the addition and removal of Conference bookmarks.
*
* @return the BookedMarkedConferences UI.
*/
public static BookmarksUI getBookmarkedConferences() {
return bookmarksUI;
}
private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener {
private ChatRoom chatRoom;
private ChatRoomButton inviteButton;
public ChatRoomDecorator(ChatRoom room) {
this.chatRoom = room;
chatRoom.addClosingListener(this);
}
public void decorate() {
// Add Conference Invite Button.
inviteButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.CONFERENCE_IMAGE_24x24));
inviteButton.setToolTipText(Res.getString("title.invite.to.conference"));
chatRoom.getToolBar().addChatRoomButton(inviteButton);
inviteButton.addActionListener(this);
}
public void closing() {
inviteButton.removeActionListener(this);
chatRoom.removeClosingListener(this);
}
public void actionPerformed(ActionEvent e) {
String userName = StringUtils.parseName(SparkManager.getSessionManager().getJID());
final String roomName = userName + "_" + StringUtils.randomString(3);
final List<String> jids = new ArrayList<String>();
jids.add(((ChatRoomImpl)chatRoom).getParticipantJID());
final String serviceName = getDefaultServiceName();
if (serviceName != null) {
SwingWorker worker = new SwingWorker() {
public Object construct() {
try {
Thread.sleep(25);
}
catch (InterruptedException e1) {
Log.error(e1);
}
return "ok";
}
public void finished() {
try {
ConferenceUtils.createPrivateConference(serviceName, Res.getString("message.please.join.in.conference"), roomName, jids);
}
catch (XMPPException e1) {
JOptionPane.showMessageDialog(chatRoom, ConferenceUtils.getReason(e1), Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
}
}
};
worker.start();
}
}
}
}
|
package com.emc.ecs.managementClient;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import com.emc.ecs.managementClient.model.DataServiceReplicationGroup;
import com.emc.ecs.managementClient.model.DataServiceReplicationGroupList;
import com.emc.ecs.serviceBroker.EcsManagementClientException;
import com.emc.ecs.serviceBroker.EcsManagementResourceNotFoundException;
public class ReplicationGroupAction {
public static List<DataServiceReplicationGroup> list(Connection connection)
throws EcsManagementClientException {
UriBuilder uri = connection.getUriBuilder().segment("vdc",
"data-service", "vpools");
Response response = connection.handleRemoteCall("get", uri, null);
DataServiceReplicationGroupList rgList = response
.readEntity(DataServiceReplicationGroupList.class);
return rgList.getReplicationGroups();
}
public static DataServiceReplicationGroup get(Connection connection,
String id) throws EcsManagementClientException,
EcsManagementResourceNotFoundException {
List<DataServiceReplicationGroup> repGroups = list(connection);
Optional<DataServiceReplicationGroup> optionalRg = repGroups.stream()
.filter(rg -> rg.getId().equals(id)).findFirst();
try {
return optionalRg.get();
} catch (NoSuchElementException e) {
throw new EcsManagementResourceNotFoundException(e.getMessage());
}
}
}
|
package com.gaocy.sample.service.impl;
import com.alibaba.fastjson.JSON;
import com.gaocy.sample.model.GuaziModel;
import com.gaocy.sample.spider.SpiderBase;
import com.gaocy.sample.spider.SpiderEnum;
import com.gaocy.sample.util.HttpClientUtil;
import com.gaocy.sample.vo.CarVo;
import com.gaocy.sample.vo.ModelVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class SpiderDealServiceImpl {
private static String URL_LIST_TEMPLATE = "https:
private static DateFormat dfMonth = new SimpleDateFormat("yyyyMM");
private static DateFormat dfDate = new SimpleDateFormat("yyyyMMdd");
private static DateFormat dfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static List<String> userPool = new ArrayList<String>();
private static int userPoolIndex = 0;
static {
userPool.add("guaZiUserInfo=bMxpa%2Asm%2BzylXnh68R4t6");
userPool.add("guaZiUserInfo=cMxpKhg0ZxB%2AGxP4AsnMa");
userPool.add("guaZiUserInfo=cMxpKhg0h%2AhsKkPG%2BjIIwe");
}
public static String getUser() {
userPoolIndex = ++userPoolIndex % userPool.size();
return userPool.get(userPoolIndex);
}
public static void main(String[] args) {
runDealSpider();
}
@Scheduled(cron = "${init.spider.detail.cron}")
public static void runDealSpider() {
Map<String, Integer> idMap = new HashMap<String, Integer>();
String startDateStr = "201701";
Date endDate = new Date();
try {
Date startDate = dfMonth.parse(startDateStr);
SpiderBase.logToFile("logs/" + dfDate.format(new Date()) + "_" + SpiderEnum.guazi_deal, "[ALL START] [" + dfDateTime.format(new Date()) + "] From " + dfDate.format(startDate) + " to " + dfDate.format(endDate));
for (Date indexDate = startDate; indexDate.before(endDate); indexDate = DateUtils.addMonths(indexDate, 1)) {
String indexDateStr = dfMonth.format(indexDate);
Map<String, ModelVo> guaziSeriesEntityMap = GuaziModel.getSeriesMap();
for (Map.Entry<String, ModelVo> entry : guaziSeriesEntityMap.entrySet()) {
int uniqueVoSize = 0;
String seriesId = entry.getKey();
List<CarVo> carVoList = getList(indexDateStr + "00", seriesId);
for (CarVo vo : carVoList) {
String imgUrl = vo.getAddress();
Integer imgUrlCount = idMap.get(imgUrl);
if (null != imgUrlCount && imgUrlCount > 0) {
idMap.put(imgUrl, ++imgUrlCount);
} else {
++uniqueVoSize;
SpiderBase.logToFile(dfDate.format(new Date()) + "/" + vo.getSrc().name().toLowerCase(), JSON.toJSONString(vo));
idMap.put(imgUrl, 1);
}
}
SpiderBase.logToFile("logs/" + dfDate.format(new Date()) + "_" + SpiderEnum.guazi_deal, "[DETAIL] [" + dfDateTime.format(new Date()) + "] query:" + indexDateStr + "_" + seriesId + ", vo size(U/A):" + uniqueVoSize + "/" + carVoList.size());
}
}
} catch (Exception e) {
e.printStackTrace();
}
SpiderBase.logToFile("logs/" + dfDate.format(new Date()) + "_" + SpiderEnum.guazi_deal, "[ALL DONE] [" + dfDateTime.format(new Date()) + "] All car size: " + idMap.size());
}
public static List<CarVo> getList(String dateMontStr, String seriesId) {
List<CarVo> list = new ArrayList<CarVo>();
String url = URL_LIST_TEMPLATE.replaceFirst("<seriesId>", seriesId).replaceFirst("<date>", dateMontStr);
Map<String, String> headerMap = new HashMap<String, String>();
String user = getUser();
headerMap.put("Cookie", user);
SpiderBase.logToFile("logs/" + dfDate.format(new Date()) + "_" + SpiderEnum.guazi_deal + "_url", userPoolIndex + "_" + user + "_" + url);
// String content = HttpClientUtil.get(url, userPoolIndex, headerMap);
// Document document = Jsoup.parse(content);
Document document = SpiderBase.getDoc(url, headerMap);
Elements carDocs = document.select(".deal-list li");
for (Element carDoc : carDocs) {
String img = carDoc.select("img").get(0).attr("src");
String modelName = carDoc.select(".deal-p1").text();
String modelInfo = carDoc.select(".deal-p2").text();
String modelInfoRegex = "(\\d+) \\| (.*?) \\| (.*)";
String year = modelInfo.replaceFirst(modelInfoRegex, "$1");
String mileage = modelInfo.replaceFirst(modelInfoRegex, "$2");
String city = modelInfo.replaceFirst(modelInfoRegex, "$3");
String dealPrice = carDoc.select(".deal-p3 em").text().replaceFirst("", "");
// System.out.println(modelName + "|" + year + "|" + mileage + "|" + city + "|" + dealPrice);
if (StringUtils.isBlank(img)) {
img = carDoc.select("img").get(0).attr("data-src");
if (StringUtils.isBlank(img)) {
continue;
}
}
CarVo vo = new CarVo();
vo.setSrc(SpiderEnum.guazi_deal);
vo.setName(modelName);
vo.setAddress(img);
vo.setRegDate(year + "01");
vo.setMileage(mileage);
vo.setCity(city);
vo.setPrice(dealPrice);
list.add(vo);
// SpiderBase.logToFile(dfDate.format(new Date()) + "/" + vo.getSrc().name().toLowerCase() + "_deal", JSON.toJSONString(vo));
}
// System.out.println(content);
return list;
}
}
|
package com.imaginarycode.minecraft.redisbungee;
import com.google.common.base.Joiner;
import com.google.common.collect.*;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.ProxyPingEvent;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import org.yaml.snakeyaml.Yaml;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class RedisBungee extends Plugin implements Listener {
private static JedisPool pool;
private static String serverId;
private static List<String> servers = Lists.newArrayList();
private static RedisBungee plugin;
private boolean canonicalGlist = true;
protected String getServerId() {
return serverId;
}
protected List<String> getServers() {
return servers;
}
/**
* Get a combined count of all players on this network.
*
* @return a count of all players found
*/
public static int getCount() {
Jedis rsc = pool.getResource();
int c = 0;
try {
c = plugin.getProxy().getOnlineCount();
for (String i : plugin.getServers()) {
if (i.equals(plugin.getServerId())) continue;
if (rsc.exists("server:" + i + ":playerCount"))
c += Integer.valueOf(rsc.get("server:" + i + ":playerCount"));
}
} finally {
pool.returnResource(rsc);
}
return c;
}
/**
* Get a combined list of players on this network.
* <p/>
* Note that this function returns an immutable {@link java.util.Set}.
*
* @return a Set with all players found
*/
public static Set<String> getPlayers() {
List<String> players = Lists.newArrayList();
for (ProxiedPlayer pp : plugin.getProxy().getPlayers()) {
players.add(pp.getName());
}
if (pool != null) {
Jedis rsc = pool.getResource();
try {
for (String i : servers) {
if (i.equals(serverId)) continue;
for (String p : rsc.smembers("server:" + i + ":usersOnline")) {
if (!players.contains(p)) {
players.add(p);
}
}
}
} finally {
pool.returnResource(rsc);
}
}
return ImmutableSet.copyOf(players);
}
/**
* Get the server where the specified player is playing. This function also deals with the case of local players
* as well, and will return local information on them.
*
* @param name a player name
* @return a {@link net.md_5.bungee.api.config.ServerInfo} for the server the player is on.
*/
public static ServerInfo getServerFor(String name) {
ServerInfo server = null;
if (plugin.getProxy().getPlayer(name) != null) return plugin.getProxy().getPlayer(name).getServer().getInfo();
if (pool != null) {
Jedis tmpRsc = pool.getResource();
try {
if (tmpRsc.hexists("player:" + name, "server"))
server = plugin.getProxy().getServerInfo(tmpRsc.hget("player:" + name, "server"));
} finally {
pool.returnResource(tmpRsc);
}
}
return server;
}
private static long getUnixTimestamp() {
return TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
/**
* Get the last time a player was on. If the player is currently online, this will return 0, otherwise it will return
* a value in seconds.
*
* @param name a player name
* @return the last time a player was on, if online returns a 0
*/
public static long getLastOnline(String name) {
long time = 0L;
if (plugin.getProxy().getPlayer(name) != null) return time;
if (pool != null) {
Jedis tmpRsc = pool.getResource();
try {
if (tmpRsc.hexists("player:" + name, "online"))
time = Long.valueOf(tmpRsc.hget("player:" + name, "online"));
} finally {
pool.returnResource(tmpRsc);
}
}
return time;
}
@Override
public void onEnable() {
plugin = this;
try {
loadConfig();
} catch (IOException e) {
e.printStackTrace();
}
if (pool != null) {
Jedis tmpRsc = pool.getResource();
try {
tmpRsc.set("server:" + serverId + ":playerCount", "0"); // reset
for (String i : tmpRsc.smembers("server:" + serverId + ":usersOnline")) {
tmpRsc.srem("server:" + serverId + ":usersOnline", i);
}
} finally {
pool.returnResource(tmpRsc);
}
getProxy().getScheduler().schedule(this, new Runnable() {
@Override
public void run() {
Jedis rsc = pool.getResource();
try {
rsc.set("server:" + plugin.getServerId() + ":playerCount", String.valueOf(getProxy().getOnlineCount()));
} finally {
pool.returnResource(rsc);
}
}
}, 1, 3, TimeUnit.SECONDS);
getProxy().getPluginManager().registerCommand(this, new Command("glist", "bungeecord.command.glist", "redisbungee") {
@Override
public void execute(CommandSender sender, String[] args) {
sender.sendMessage(ChatColor.YELLOW + String.valueOf(getCount()) + " player(s) are currently online.");
if (args.length > 0 && args[0].equals("showall")) {
if (canonicalGlist) {
Multimap<String, String> serverToPlayers = HashMultimap.create(getProxy().getServers().size(), getCount());
for (String p : getPlayers()) {
ServerInfo si = getServerFor(p);
if (si != null)
serverToPlayers.put(si.getName(), p);
}
if (serverToPlayers.size() == 0) return;
List<String> sortedServers = new ArrayList<>(serverToPlayers.keySet());
Collections.sort(sortedServers);
for (String server : sortedServers)
sender.sendMessage(ChatColor.GREEN + "[" + server + "] " + ChatColor.YELLOW + "("
+ serverToPlayers.get(server).size() + "): " + ChatColor.WHITE
+ Joiner.on(", ").join(serverToPlayers.get(server)));
} else {
sender.sendMessage(ChatColor.YELLOW + "Players: " + Joiner.on(", ").join(getPlayers()));
}
} else {
sender.sendMessage(ChatColor.YELLOW + "To see all players online, use /glist showall.");
}
}
});
getProxy().getPluginManager().registerListener(this, this);
}
}
@Override
public void onDisable() {
if (pool != null) {
Jedis tmpRsc = pool.getResource();
try {
tmpRsc.set("server:" + serverId + ":playerCount", "0"); // reset
for (String i : tmpRsc.smembers("server:" + serverId + ":usersOnline")) {
tmpRsc.srem("server:" + serverId + ":usersOnline", i);
}
} finally {
pool.returnResource(tmpRsc);
}
pool.destroy();
}
}
private void loadConfig() throws IOException {
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
File file = new File(getDataFolder(), "config.yml");
if (!file.exists()) {
file.createNewFile();
try (InputStream in = getResourceAsStream("example_config.yml");
OutputStream out = new FileOutputStream(file)) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
Yaml yaml = new Yaml();
Map rawYaml;
try (InputStream in = new FileInputStream(file)) {
rawYaml = (Map) yaml.load(in);
}
String redisServer = "localhost";
try {
redisServer = ((String) rawYaml.get("redis-server"));
} catch (NullPointerException ignored) {
}
try {
serverId = ((String) rawYaml.get("server-id"));
} catch (NullPointerException ignored) {
serverId = "ImADumbIdi0t";
}
try {
canonicalGlist = ((Boolean) rawYaml.get("canonical-glist"));
} catch (NullPointerException ignored) {
}
List<?> tmp = (List<?>) rawYaml.get("linked-servers");
if (tmp != null)
for (Object i : tmp) {
if (i instanceof String) {
servers.add((String) i);
}
}
if (redisServer != null) {
if (!redisServer.equals("")) {
pool = new JedisPool(new JedisPoolConfig(), redisServer);
}
}
}
@EventHandler
public void onPlayerConnect(final PostLoginEvent event) {
if (pool != null) {
Jedis rsc = pool.getResource();
try {
rsc.sadd("server:" + serverId + ":usersOnline", event.getPlayer().getName());
rsc.hset("player:" + event.getPlayer().getName(), "online", "0");
} finally {
pool.returnResource(rsc);
}
getProxy().getScheduler().schedule(this, new Runnable() {
@Override
public void run() {
Jedis rsc = pool.getResource();
try {
rsc.hset("player:" + event.getPlayer().getName(), "server", event.getPlayer().getServer().getInfo().getName());
} finally {
pool.returnResource(rsc);
}
}
}, 1750, TimeUnit.MILLISECONDS);
}
}
@EventHandler
public void onPlayerDisconnect(PlayerDisconnectEvent event) {
if (pool != null) {
Jedis rsc = pool.getResource();
try {
rsc.srem("server:" + serverId + ":usersOnline", event.getPlayer().getName());
rsc.hset("player:" + event.getPlayer().getName(), "online", String.valueOf(getUnixTimestamp()));
rsc.hdel("player:" + event.getPlayer().getName(), "server");
} finally {
pool.returnResource(rsc);
}
}
}
@EventHandler
public void onServerChange(ServerConnectedEvent event) {
if (pool != null) {
Jedis rsc = pool.getResource();
try {
rsc.hset("player:" + event.getPlayer().getName(), "server", event.getServer().getInfo().getName());
} finally {
pool.returnResource(rsc);
}
}
}
@EventHandler
public void onPing(ProxyPingEvent event) {
ServerPing old = event.getResponse();
ServerPing reply = new ServerPing();
reply.setPlayers(new ServerPing.Players(old.getPlayers().getMax(), getCount(), new ServerPing.PlayerInfo[]{}));
reply.setDescription(old.getDescription());
reply.setFavicon(old.getFavicon());
reply.setVersion(old.getVersion());
event.setResponse(reply);
}
}
|
package com.springsource.greenhouse.signup;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/signup")
public class SignupController {
private JdbcTemplate jdbcTemplate;
private AuthenticationManager authenticationManager;
private SignupMessageGateway signupMessageGateway;
@Inject
// TODO eliminate the Qualifier
public SignupController(JdbcTemplate jdbcTemplate, @Qualifier("org.springframework.security.authenticationManager") AuthenticationManager authenticationManager, SignupMessageGateway signupMessageGateway) {
this.jdbcTemplate = jdbcTemplate;
this.authenticationManager = authenticationManager;
this.signupMessageGateway = signupMessageGateway;
}
@RequestMapping(method = RequestMethod.GET)
public SignupForm signupForm() {
return new SignupForm();
}
@RequestMapping(method = RequestMethod.POST)
public String signup(@Valid SignupForm form, BindingResult result, HttpServletRequest request) {
if (result.hasErrors()) {
return null;
}
jdbcTemplate.update("insert into User (firstName, lastName, email, password) values (?, ?, ?, ?)",
form.getFirstName(), form.getLastName(), form.getEmail(), form.getPassword());
Long userId = jdbcTemplate.queryForLong("call identity()");
signupMessageGateway.publish(new SignupMessage(userId, form.getFirstName(), form.getLastName(), form.getEmail()));
signIn(form.getEmail(), form.getPassword(), request);
return "redirect:/";
}
// internal helpers
private void signIn(String username, String password, HttpServletRequest request) {
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (AuthenticationException e) {
SecurityContextHolder.getContext().setAuthentication(null);
}
}
}
|
package edu.mayo.hadoop.commons.minicluster;
import com.github.sakserv.minicluster.config.ConfigVars;
import com.github.sakserv.minicluster.impl.HbaseLocalCluster;
import com.github.sakserv.minicluster.impl.HdfsLocalCluster;
import com.github.sakserv.minicluster.impl.YarnLocalCluster;
import com.github.sakserv.minicluster.impl.ZookeeperLocalCluster;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MiniClusterUtil {
// variables to track what services are currently started in the jvm env.
private static boolean zookeeperStarted = false;
private static boolean yarnStarted = false;
private static boolean hdfsStarted = false;
private static boolean hbaseStarted = false;
private static ZookeeperLocalCluster zookeeperLocalCluster;
private static HdfsLocalCluster hdfsLocalCluster;
private static HbaseLocalCluster hbaseLocalCluster;
private static YarnLocalCluster yarnLocalCluster;
/**
* starts all the services we need.
*
* @throws Exception
*/
public static void startAll(Properties prop) throws Exception {
startZookeeper(prop);
startYarn(prop);
startHBASE(prop);
}
public static synchronized ZookeeperLocalCluster startZookeeper(Properties props) throws Exception {
if (!zookeeperStarted) {
ZookeeperLocalCluster.Builder builder = new ZookeeperLocalCluster.Builder();
builder.setPort(Integer.parseInt(props.getProperty(ConfigVars.ZOOKEEPER_PORT_KEY)));
builder.setTempDir(props.getProperty(ConfigVars.ZOOKEEPER_TEMP_DIR_KEY));
builder.setZookeeperConnectionString(props.getProperty(ConfigVars.ZOOKEEPER_CONNECTION_STRING_KEY));
zookeeperLocalCluster = builder.build();
zookeeperLocalCluster.start();
zookeeperStarted = true;
}
return zookeeperLocalCluster;
}
public static void setUp(Properties props) {
hdfsLocalCluster = new HdfsLocalCluster.Builder().setHdfsNamenodePort(Integer.parseInt(props.getProperty(ConfigVars.HDFS_NAMENODE_PORT_KEY))).setHdfsTempDir(props.getProperty(ConfigVars.HDFS_TEMP_DIR_KEY))
.setHdfsNumDatanodes(Integer.parseInt(props.getProperty(ConfigVars.HDFS_NUM_DATANODES_KEY))).setHdfsEnablePermissions(Boolean.parseBoolean(props.getProperty(ConfigVars.HDFS_ENABLE_PERMISSIONS_KEY)))
.setHdfsFormat(Boolean.parseBoolean(props.getProperty(ConfigVars.HDFS_FORMAT_KEY))).setHdfsEnableRunningUserAsProxyUser(Boolean.parseBoolean(props.getProperty(ConfigVars.HDFS_ENABLE_RUNNING_USER_AS_PROXY_USER)))
.setHdfsConfig(new Configuration()).build();
}
public static YarnLocalCluster startYarn(Properties props) {
YarnLocalCluster yarnLocalCluster = new YarnLocalCluster.Builder()
.setNumNodeManagers(Integer.parseInt(props.getProperty(ConfigVars.YARN_NUM_NODE_MANAGERS_KEY)))
.setNumLocalDirs(Integer.parseInt(props.getProperty(ConfigVars.YARN_NUM_LOCAL_DIRS_KEY)))
.setNumLogDirs(Integer.parseInt(props.getProperty(ConfigVars.YARN_NUM_LOG_DIRS_KEY)))
.setResourceManagerAddress(props.getProperty(ConfigVars.YARN_RESOURCE_MANAGER_ADDRESS_KEY))
.setResourceManagerHostname(props.getProperty(ConfigVars.YARN_RESOURCE_MANAGER_HOSTNAME_KEY))
.setResourceManagerSchedulerAddress(props.getProperty(
ConfigVars.YARN_RESOURCE_MANAGER_SCHEDULER_ADDRESS_KEY))
.setResourceManagerResourceTrackerAddress(props.getProperty(
ConfigVars.YARN_RESOURCE_MANAGER_RESOURCE_TRACKER_ADDRESS_KEY))
.setResourceManagerWebappAddress(props.getProperty(
ConfigVars.YARN_RESOURCE_MANAGER_WEBAPP_ADDRESS_KEY))
.setUseInJvmContainerExecutor(Boolean.parseBoolean(props.getProperty(
ConfigVars.YARN_USE_IN_JVM_CONTAINER_EXECUTOR_KEY)))
.setConfig(new Configuration())
.build();
return yarnLocalCluster;
}
public synchronized static HbaseLocalCluster startHBASE(Properties props) throws Exception {
startZookeeper(props);
if (!hbaseStarted) {
hbaseLocalCluster = new HbaseLocalCluster.Builder().setHbaseMasterPort(Integer.parseInt(props.getProperty(ConfigVars.HBASE_MASTER_PORT_KEY))).setHbaseMasterInfoPort(Integer.parseInt(props.getProperty(ConfigVars.HBASE_MASTER_INFO_PORT_KEY)))
.setNumRegionServers(Integer.parseInt(props.getProperty(ConfigVars.HBASE_NUM_REGION_SERVERS_KEY))).setHbaseRootDir(props.getProperty(ConfigVars.HBASE_ROOT_DIR_KEY))
.setZookeeperPort(Integer.parseInt(props.getProperty(ConfigVars.ZOOKEEPER_PORT_KEY))).setZookeeperConnectionString(props.getProperty(ConfigVars.ZOOKEEPER_CONNECTION_STRING_KEY))
.setZookeeperZnodeParent(props.getProperty(ConfigVars.HBASE_ZNODE_PARENT_KEY)).setHbaseWalReplicationEnabled(Boolean.parseBoolean(props.getProperty(ConfigVars.HBASE_WAL_REPLICATION_ENABLED_KEY)))
.setHbaseConfiguration(new Configuration()).build();
hbaseLocalCluster.start();
hbaseStarted = true;
}
return hbaseLocalCluster;
}
public static Properties loadPropertiesFile(String propFilePath) throws IOException {
try (InputStream input = new FileInputStream(propFilePath)) {
return loadPropertiesStream(input);
}
}
public static Properties loadPropertiesStream(InputStream input) throws IOException {
Properties prop = new Properties();
prop.load(input);
return prop;
}
/**
* stops all services that are running
*/
public static void stopAll() throws Exception {
stopHBASE();
stopZookeeper();
}
public static synchronized void stopZookeeper() throws Exception {
if (zookeeperStarted) {
zookeeperLocalCluster.stop();
zookeeperStarted = false;
}
}
public static void stopHDFS() throws Exception {
if (hdfsStarted) {
hdfsLocalCluster.stop();
hdfsStarted = false;
}
}
public static void stopHBASE() throws Exception {
if (hbaseStarted) {
hbaseLocalCluster.stop();
hbaseStarted = false;
}
}
public static ZookeeperLocalCluster getZookeeperLocalCluster() {
return zookeeperLocalCluster;
}
public static HbaseLocalCluster getHbaseLocalCluster() {
return hbaseLocalCluster;
}
/**
* gets the local directory where hbase is keeping it's files
*/
public static String getHBaseDir(Properties props){
String hbaseRoot = props.getProperty(ConfigVars.HBASE_ROOT_DIR_KEY);
return hbaseRoot;
}
/**
* used for deleting unstable/corrupted hbase files from a bad server shutdown
* @param props
* @throws IOException
*/
public static void deleteLocalHBaseDir(Properties props) throws IOException {
FileUtils.deleteDirectory(new File(getHBaseDir(props)));
}
/**
* gets the local directory where zookeeper is keeping it's files
*/
public static String getZookeeperDir(Properties props){
String hbaseRoot = props.getProperty(ConfigVars.ZOOKEEPER_TEMP_DIR_KEY);
return hbaseRoot;
}
/**
* used for deleting unstable/corrupted hbase files from a bad server shutdown
* @param props
* @throws IOException
*/
public static void deleteLocalZookeeperDir(Properties props) throws IOException {
FileUtils.deleteDirectory(new File(getZookeeperDir(props)));
}
}
|
package gl8080.lifegame.web.resource;
import java.net.URI;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import gl8080.lifegame.application.definition.RegisterGameDefinitionService;
import gl8080.lifegame.application.definition.RemoveGameDefinitionService;
import gl8080.lifegame.application.definition.SearchGameDefinitionService;
import gl8080.lifegame.application.definition.UpdateGameDefinitionService;
import gl8080.lifegame.logic.definition.GameDefinition;
import gl8080.lifegame.util.Maps;
@Path("/game/definition")
@ApplicationScoped
public class GameDefinitionResource {
@Inject
private RegisterGameDefinitionService registerService;
@Inject
private SearchGameDefinitionService searchService;
@Inject
private UpdateGameDefinitionService saveService;
@Inject
private RemoveGameDefinitionService removeService;
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response register(@QueryParam("size") int size) {
GameDefinition gameDefinition = this.registerService.register(size);
long id = gameDefinition.getId();
URI uri = UriBuilder
.fromResource(GameDefinitionResource.class)
.path(GameDefinitionResource.class, "search")
.build(id);
return Response
.created(uri)
.entity(Maps.map("id", id))
.build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public LifeGameDto search(@PathParam("id") long id) {
GameDefinition gameDefinition = this.searchService.search(id);
return LifeGameDto.of(gameDefinition);
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(LifeGameDto dto) {
if (dto == null) {
return Response.status(Status.BAD_REQUEST).build();
}
GameDefinition gameDefinition = this.saveService.update(dto);
return Response.ok()
.entity(Maps.map("version", gameDefinition.getVersion()))
.build();
}
@DELETE
@Path("/{id}")
public Response remove(@PathParam("id") long id) {
this.removeService.remove(id);
return Response.noContent().build();
}
}
|
package i5.las2peer.webConnector;
import i5.las2peer.execution.ServiceInvocationException;
import i5.las2peer.p2p.AgentAlreadyRegisteredException;
import i5.las2peer.p2p.AgentNotKnownException;
import i5.las2peer.p2p.AliasNotFoundException;
import i5.las2peer.p2p.Node;
import i5.las2peer.p2p.ServiceAliasManager.AliasResolveResponse;
import i5.las2peer.p2p.ServiceNameVersion;
import i5.las2peer.p2p.ServiceVersion;
import i5.las2peer.p2p.TimeoutException;
import i5.las2peer.restMapper.RESTResponse;
import i5.las2peer.security.L2pSecurityException;
import i5.las2peer.security.Mediator;
import i5.las2peer.security.PassphraseAgent;
import i5.las2peer.security.UserAgent;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.util.Json;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.ws.rs.core.UriBuilder;
import net.minidev.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.nimbusds.oauth2.sdk.ErrorObject;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.http.HTTPRequest;
import com.nimbusds.oauth2.sdk.http.HTTPRequest.Method;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse;
import com.nimbusds.openid.connect.sdk.UserInfoResponse;
import com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse;
import com.nimbusds.openid.connect.sdk.claims.UserInfo;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsExchange;
/**
* A HttpServer RequestHandler for handling requests to the las2peer Web Connector. Each request will be distributed to
* its corresponding session.
*
*/
public class WebConnectorRequestHandler implements HttpHandler {
private static final String AUTHENTICATION_FIELD = "Authorization";
private static final String ACCESS_TOKEN_KEY = "access_token";
private static final String OIDC_PROVIDER_KEY = "oidc_provider";
private static final int NO_RESPONSE_BODY = -1;
// 0 means chunked transfer encoding, see
// https://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#sendResponseHeaders-int-long-
private static final List<String> INGORE_HEADERS = Arrays.asList(AUTHENTICATION_FIELD.toLowerCase(),
ACCESS_TOKEN_KEY.toLowerCase(), OIDC_PROVIDER_KEY.toLowerCase());
private static final List<String> INGORE_QUERY_PARAMS = Arrays.asList(ACCESS_TOKEN_KEY.toLowerCase(),
OIDC_PROVIDER_KEY.toLowerCase());
private WebConnector connector;
private Node l2pNode;
public WebConnectorRequestHandler(WebConnector connector) {
this.connector = connector;
l2pNode = connector.getL2pNode();
}
@Override
public void handle(HttpExchange exchange) throws IOException {
exchange.getResponseHeaders().set("Server-Name", "las2peer WebConnector");
try {
// TODO workaround (should be removed, options request should be handled as any other request)
if (exchange.getRequestMethod().equalsIgnoreCase("options")) {
sendResponseHeaders(exchange, HttpURLConnection.HTTP_OK, NO_RESPONSE_BODY);
} else {
PassphraseAgent userAgent;
if ((userAgent = authenticate(exchange)) != null) {
invoke(userAgent, exchange);
}
}
} catch (Exception e) {
sendUnexpectedErrorResponse(exchange, e.toString(), e);
}
// otherwise the client waits till the timeout for an answer
exchange.getResponseBody().close();
}
private PassphraseAgent authenticate(HttpExchange exchange) throws UnsupportedEncodingException {
if (exchange.getRequestHeaders().containsKey(AUTHENTICATION_FIELD)
&& exchange.getRequestHeaders().getFirst(AUTHENTICATION_FIELD).toLowerCase().startsWith("basic ")) {
// basic authentication
return authenticateBasic(exchange);
} else if (connector.oidcProviderInfos != null
&& ((exchange.getRequestURI().getRawQuery() != null && exchange.getRequestURI().getRawQuery()
.contains(ACCESS_TOKEN_KEY + "="))
|| exchange.getRequestHeaders().containsKey(ACCESS_TOKEN_KEY) || (exchange.getRequestHeaders()
.containsKey(AUTHENTICATION_FIELD) && exchange.getRequestHeaders()
.getFirst(AUTHENTICATION_FIELD).toLowerCase().startsWith("bearer ")))) {
// openid connect
return authenticateOIDC(exchange);
} else if (connector.defaultLoginUser.length() > 0) {
// anonymous login
return authenticateNamePassword(connector.defaultLoginUser, connector.defaultLoginPassword, exchange);
} else if (exchange.getRequestMethod().equalsIgnoreCase("options")) {
return authenticateNamePassword("anonymous", "anonymous", exchange);
} else {
sendUnauthorizedResponse(exchange, null, exchange.getRemoteAddress() + ": No Authentication provided!");
return null;
}
}
private PassphraseAgent authenticateBasic(HttpExchange exchange) {
// looks like: Authentication Basic <Byte64(name:pass)>
String userPass = exchange.getRequestHeaders().getFirst(AUTHENTICATION_FIELD).substring("BASIC ".length());
userPass = new String(Base64.getDecoder().decode(userPass), StandardCharsets.UTF_8);
int separatorPos = userPass.indexOf(':');
// get username and password
String username = userPass.substring(0, separatorPos);
String password = userPass.substring(separatorPos + 1);
return authenticateNamePassword(username, password, exchange);
}
private PassphraseAgent authenticateOIDC(HttpExchange exchange) throws UnsupportedEncodingException {
// extract token
String token = "";
String oidcProviderURI = connector.defaultOIDCProvider;
if (exchange.getRequestHeaders().containsKey(ACCESS_TOKEN_KEY)) {
// get OIDC parameters from headers
token = exchange.getRequestHeaders().getFirst(ACCESS_TOKEN_KEY);
if (exchange.getRequestHeaders().containsKey(OIDC_PROVIDER_KEY)) {
oidcProviderURI = URLDecoder.decode(exchange.getRequestHeaders().getFirst(OIDC_PROVIDER_KEY), "UTF-8");
}
} else if (exchange.getRequestHeaders().containsKey(AUTHENTICATION_FIELD)
&& exchange.getRequestHeaders().getFirst(AUTHENTICATION_FIELD).toLowerCase().startsWith("bearer ")) {
// get BEARER token from Authentication field
token = exchange.getRequestHeaders().getFirst(AUTHENTICATION_FIELD).substring("BEARER ".length());
if (exchange.getRequestHeaders().containsKey(OIDC_PROVIDER_KEY)) {
oidcProviderURI = URLDecoder.decode(exchange.getRequestHeaders().getFirst(OIDC_PROVIDER_KEY), "UTF-8");
}
} else { // get OIDC parameters from GET values
String[] params = exchange.getRequestURI().getRawQuery().split("&");
for (String param : params) {
String[] keyval = param.split("=");
if (keyval[0].equalsIgnoreCase(ACCESS_TOKEN_KEY)) {
token = keyval[1];
} else if (keyval[0].equalsIgnoreCase(OIDC_PROVIDER_KEY)) {
oidcProviderURI = URLDecoder.decode(keyval[1], "UTF-8");
}
}
}
// validate given OIDC provider and get provider info
JSONObject oidcProviderInfo = null;
if (!connector.oidcProviders.contains(oidcProviderURI)
|| connector.oidcProviderInfos.get(oidcProviderURI) == null) {
sendStringResponse(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR, "The given OIDC provider ("
+ oidcProviderURI
+ ") is not whitelisted! Please make sure the complete OIDC provider URI is added to the config.");
return null;
} else {
oidcProviderInfo = connector.oidcProviderInfos.get(oidcProviderURI);
}
// send request to OpenID Connect user info endpoint to retrieve complete user information
// in exchange for access token.
HTTPRequest hrq;
HTTPResponse hrs;
try {
URI userinfoEndpointUri = new URI(
(String) ((JSONObject) oidcProviderInfo.get("config")).get("userinfo_endpoint"));
hrq = new HTTPRequest(Method.GET, userinfoEndpointUri.toURL());
hrq.setAuthorization("Bearer " + token);
// TODO process all error cases that can happen (in particular invalid tokens)
hrs = hrq.send();
} catch (IOException | URISyntaxException e) {
sendUnexpectedErrorResponse(exchange, "Fetching OIDC user info failed", e);
return null;
}
// process response from OpenID Connect user info endpoint
UserInfoResponse userInfoResponse;
try {
userInfoResponse = UserInfoResponse.parse(hrs);
} catch (ParseException e) {
sendUnexpectedErrorResponse(exchange, "Couldn't parse UserInfo response", e);
return null;
}
// failed request for OpenID Connect user info
if (userInfoResponse instanceof UserInfoErrorResponse) {
UserInfoErrorResponse uier = (UserInfoErrorResponse) userInfoResponse;
ErrorObject err = uier.getErrorObject();
String cause = "Session expired?";
if (err != null) {
cause = err.getDescription();
}
sendStringResponse(exchange, HttpURLConnection.HTTP_UNAUTHORIZED,
"Open ID Connect UserInfo request failed! Cause: " + cause);
return null;
}
// successful request
UserInfo userInfo = ((UserInfoSuccessResponse) userInfoResponse).getUserInfo();
JSONObject ujson = userInfo.toJSONObject();
if (!ujson.containsKey("sub") || !ujson.containsKey("email") || !ujson.containsKey("preferred_username")) {
sendStringResponse(exchange, HttpURLConnection.HTTP_FORBIDDEN,
"Could not get provider information. Please check your scopes.");
return null;
}
String sub = (String) ujson.get("sub");
// TODO choose other scheme for generating agent password
long oidcAgentId = hash(sub);
String password = sub;
synchronized (this.connector.getLockOidc()) {
// TODO lock by agent id for more concurrency
try {
PassphraseAgent pa = (PassphraseAgent) l2pNode.getAgent(oidcAgentId);
pa.unlockPrivateKey(password);
if (pa instanceof UserAgent) {
UserAgent ua = (UserAgent) pa;
ua.setUserData(ujson.toJSONString());
return ua;
} else {
return pa;
}
} catch (L2pSecurityException e) {
sendStringResponse(exchange, HttpURLConnection.HTTP_UNAUTHORIZED, e.getMessage());
return null;
} catch (AgentNotKnownException e) {
UserAgent oidcAgent;
try {
oidcAgent = UserAgent.createUserAgent(oidcAgentId, password);
oidcAgent.unlockPrivateKey(password);
oidcAgent.setEmail((String) ujson.get("email"));
oidcAgent.setLoginName((String) ujson.get("preferred_username"));
oidcAgent.setUserData(ujson.toJSONString());
l2pNode.storeAgent(oidcAgent);
return oidcAgent;
} catch (Exception e1) {
sendUnexpectedErrorResponse(exchange, "OIDC agent creation failed", e1);
return null;
}
}
}
}
private PassphraseAgent authenticateNamePassword(String username, String password, HttpExchange exchange) {
try {
long userId;
PassphraseAgent userAgent;
if (username.matches("-?[0-9].*")) { // username is id
try {
userId = Long.valueOf(username);
} catch (NumberFormatException e) {
throw new L2pSecurityException("The given user does not contain a valid agent id!");
}
} else {// username is string
userId = l2pNode.getAgentIdForLogin(username);
}
userAgent = (PassphraseAgent) l2pNode.getAgent(userId);
userAgent.unlockPrivateKey(password);
return userAgent;
} catch (AgentNotKnownException e) {
sendUnauthorizedResponse(exchange, null, exchange.getRemoteAddress() + ": user " + username + " not found");
} catch (L2pSecurityException e) {
sendUnauthorizedResponse(exchange, null, exchange.getRemoteAddress() + ": passphrase invalid for user "
+ username);
} catch (Exception e) {
sendUnauthorizedResponse(exchange, null, exchange.getRemoteAddress()
+ ": something went horribly wrong. Check your request for correctness.");
}
return null;
}
// helper function to create long hash from string
// TODO should be replaced, although it prooves good knowledge from DSAL ;)
private static long hash(String string) {
long h = 1125899906842597L; // prime
int len = string.length();
for (int i = 0; i < len; i++) {
h = 31 * h + string.charAt(i);
}
return h;
}
private boolean invoke(PassphraseAgent agent, HttpExchange exchange) {
String requestPath = exchange.getRequestURI().getPath();
// welcome page
if (requestPath.equalsIgnoreCase("/")) {
sendStringResponse(exchange, HttpURLConnection.HTTP_OK, "Welcome to las2peer!");
return true;
}
// split path
ArrayList<String> pathSplit = new ArrayList<String>(Arrays.asList(requestPath.split("/")));
pathSplit.removeIf(item -> item == null || "".equals(item));
// resolve service name
String serviceName;
int serviceAliasLength;
try {
AliasResolveResponse response = l2pNode.getServiceAliasManager().resolvePathToServiceName(requestPath);
serviceName = response.getServiceName();
serviceAliasLength = response.getNumMatchedParts();
} catch (AliasNotFoundException e1) {
sendStringResponse(exchange, HttpURLConnection.HTTP_NOT_FOUND, "Could not resolve " + requestPath
+ " to a service name.");
return false;
}
// get service version
ServiceVersion serviceVersion;
boolean versionSpecified = false;
if (pathSplit.size() > serviceAliasLength && pathSplit.get(serviceAliasLength).startsWith("v")) {
try {
serviceVersion = new ServiceVersion(pathSplit.get(serviceAliasLength).substring(1));
versionSpecified = true;
} catch (IllegalArgumentException e) {
serviceVersion = new ServiceVersion("*");
}
} else {
serviceVersion = new ServiceVersion("*");
}
// required service
ServiceNameVersion requiredService = new ServiceNameVersion(serviceName, serviceVersion);
// construct base path
String basePath = "/";
for (int i = 0; i < serviceAliasLength; i++) {
basePath += pathSplit.get(i) + "/";
}
if (versionSpecified) {
basePath += pathSplit.get(serviceAliasLength) + "/";
}
// create mediator
Mediator mediator;
try {
mediator = l2pNode.createMediatorForAgent(agent);
} catch (AgentNotKnownException | L2pSecurityException | AgentAlreadyRegisteredException e) {
// should not occur, since agent is known and unlocked at this point
sendUnexpectedErrorResponse(exchange, "Mediator could not be created", e);
return false;
}
if (exchange.getRequestMethod().equalsIgnoreCase("get")
&& exchange.getRequestURI().getPath().toString().equals(basePath + "swagger.json")) {
return invokeSwagger(exchange, mediator, requiredService, basePath);
} else {
return invokeRestService(exchange, mediator, requiredService, basePath);
}
}
private boolean invokeRestService(HttpExchange exchange, Mediator mediator, ServiceNameVersion requiredService,
String basePath) {
// URIs
URI exchangeUri = exchange.getRequestURI();
UriBuilder exchangeUriBuilder = UriBuilder.fromUri(exchangeUri);
if (!exchangeUri.getPath().endsWith("/")) { // make sure URI ends with "/"
exchangeUriBuilder.path("/");
}
for (String param : INGORE_QUERY_PARAMS) { // remove auth params from uri
exchangeUriBuilder.replaceQueryParam(param);
}
exchangeUri = exchangeUriBuilder.build();
final URI baseUri = getBaseUri(exchange, basePath);
final URI requestUri = getRequestUri(exchange, baseUri, exchangeUri);
// content
byte[] requestContent;
try {
requestContent = getRequestContent(exchange);
} catch (IOException e1) {
sendStringResponse(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR, "An error occurred: " + e1);
return false;
}
if (requestContent == null) {
sendStringResponse(exchange, HttpURLConnection.HTTP_ENTITY_TOO_LARGE,
"Given request body exceeds limit of " + connector.maxRequestBodySize + " bytes");
return false;
}
// headers
HashMap<String, ArrayList<String>> headers = new HashMap<>();
for (Entry<String, List<String>> entry : exchange.getRequestHeaders().entrySet()) {
// exclude some headers for security reasons
if (!INGORE_HEADERS.contains(entry.getKey().toLowerCase())) {
ArrayList<String> list = new ArrayList<>();
list.addAll(entry.getValue());
headers.put(entry.getKey(), list);
}
}
// invoke
Serializable[] params = new Serializable[] { baseUri, requestUri, exchange.getRequestMethod(), requestContent,
headers };
Serializable result = callServiceMethod(exchange, mediator, requiredService, "handle", params);
if (result == null) {
return false;
}
if (result instanceof RESTResponse) {
sendRESTResponse(exchange, (RESTResponse) result);
return true;
} else {
sendStringResponse(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR, "Internal Server Error");
return false;
}
}
private URI getBaseUri(final HttpExchange exchange, final String decodedBasePath) {
final String scheme = (exchange instanceof HttpsExchange) ? "https" : "http";
final URI baseUri;
try {
final List<String> hostHeader = exchange.getRequestHeaders().get("Host");
if (hostHeader != null) {
baseUri = new URI(scheme + "://" + hostHeader.get(0) + decodedBasePath);
} else {
final InetSocketAddress addr = exchange.getLocalAddress();
baseUri = new URI(scheme, null, addr.getHostName(), addr.getPort(), decodedBasePath, null, null);
}
} catch (final URISyntaxException ex) {
throw new IllegalArgumentException(ex);
}
return baseUri;
}
private URI getRequestUri(final HttpExchange exchange, final URI baseUri, final URI exchangeUri) {
try {
return new URI(getServerAddress(baseUri) + exchangeUri);
} catch (URISyntaxException ex) {
throw new IllegalArgumentException(ex);
}
}
private String getServerAddress(final URI baseUri) throws URISyntaxException {
return new URI(baseUri.getScheme(), null, baseUri.getHost(), baseUri.getPort(), null, null, null).toString();
}
private byte[] getRequestContent(HttpExchange exchange) throws IOException {
InputStream is = exchange.getRequestBody();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[4096];
boolean overflow = false;
while ((nRead = is.read(data, 0, data.length)) != -1) {
if (buffer.size() < connector.maxRequestBodySize - data.length) {
// still space left in local buffer
buffer.write(data, 0, nRead);
} else {
overflow = true;
// no break allowed otherwise the client gets an exception (like connection closed)
// so we have to read all given content
}
}
if (overflow) {
return null;
}
return buffer.toByteArray();
}
private boolean invokeSwagger(HttpExchange exchange, Mediator mediator, ServiceNameVersion requiredService,
String basePath) {
// get definitions
Serializable result = callServiceMethod(exchange, mediator, requiredService, "getSwagger",
new Serializable[] {});
if (result == null) {
return false;
}
if (!(result instanceof String)) {
sendStringResponse(exchange, HttpURLConnection.HTTP_NOT_FOUND, "Swagger API declaration not available!");
return false;
}
// deserialize Swagger
Swagger swagger;
try {
swagger = Json.mapper().reader(Swagger.class).readValue((String) result);
} catch (Exception e) {
sendStringResponse(exchange, HttpURLConnection.HTTP_NOT_FOUND, "Swagger API declaration not available!");
return false;
}
// modify Swagger
swagger.setBasePath(basePath);
// OpenID Connect integration
if (connector.oidcProviderInfos != null && connector.defaultOIDCProvider != null
&& !connector.defaultOIDCProvider.isEmpty()) {
// add security definition for default provider
JSONObject infos = connector.oidcProviderInfos.get(connector.defaultOIDCProvider);
OAuth2Definition scheme = new OAuth2Definition();
String authUrl = (String) ((JSONObject) infos.get("config")).get("authorization_endpoint");
scheme.implicit(authUrl);
scheme.addScope("openid", "Access Identity");
scheme.addScope("email", "Access E-Mail-Address");
scheme.addScope("profile", "Access Profile Data");
swagger.addSecurityDefinition("defaultProvider", scheme);
// add security requirements to operations
List<String> scopes = new ArrayList<>();
scopes.add("openid");
scopes.add("email");
scopes.add("profile");
Map<String, Path> paths = swagger.getPaths();
if (paths != null) {
for (Path path : paths.values()) {
for (Operation operation : path.getOperations()) {
operation.addSecurity("defaultProvider", scopes);
}
}
}
}
// serialize Swagger
String json;
try {
json = Json.mapper().writeValueAsString(swagger);
} catch (JsonProcessingException e) {
sendUnexpectedErrorResponse(exchange, "Swagger documentation could not be serialized to JSON", e);
return false;
}
sendStringResponse(exchange, HttpURLConnection.HTTP_OK, json);
return true;
}
private Serializable callServiceMethod(HttpExchange exchange, Mediator mediator, ServiceNameVersion service,
String method, Serializable[] params) {
Serializable result = null;
try {
result = mediator.invoke(service.toString(), method, params, connector.onlyLocalServices());
} catch (AgentNotKnownException | TimeoutException e) {
sendStringResponse(exchange, HttpURLConnection.HTTP_NOT_FOUND, "No service found matching " + service + ".");
} catch (ServiceInvocationException e) {
sendInvocationException(exchange, e);
} catch (Exception e) {
sendUnexpectedErrorResponse(exchange, "Service method invocation failed", e);
}
if (result == null) {
sendUnexpectedErrorResponse(exchange, "Service method invocation failed", null);
}
return result;
}
private void sendInvocationException(HttpExchange exchange, ServiceInvocationException e) {
connector.logError("Exception while processing RMI: " + exchange.getRequestURI().getPath(), e);
// internal exception in service method
Object[] ret = new Object[4];
ret[0] = "Exception during RMI invocation!";
ret[1] = e.getCause().getCause().getClass().getCanonicalName();
ret[2] = e.getCause().getCause().getMessage();
ret[3] = e.getCause().getCause();
String code = ret[0] + "\n" + ret[1] + "\n" + ret[2] + "\n" + ret[3];
sendStringResponse(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR, code);
}
private void sendRESTResponse(HttpExchange exchange, RESTResponse result) {
exchange.getResponseHeaders().putAll(result.getHeaders());
try {
sendResponseHeaders(exchange, result.getHttpCode(), getResponseLength(result.getBody().length));
OutputStream os = exchange.getResponseBody();
if (result.getBody().length > 0) {
os.write(result.getBody());
}
os.close();
} catch (IOException e) {
connector.logError("Sending REST response (Code: " + result.getHttpCode() + ") failed!", e);
}
}
private void sendUnauthorizedResponse(HttpExchange exchange, String answerMessage, String logMessage) {
connector.logMessage(logMessage);
exchange.getResponseHeaders().set("WWW-Authenticate", "Basic realm=\"las2peer WebConnector\"");
if (answerMessage != null) {
sendStringResponse(exchange, HttpURLConnection.HTTP_UNAUTHORIZED, answerMessage);
} else {
try {
sendResponseHeaders(exchange, HttpURLConnection.HTTP_UNAUTHORIZED, NO_RESPONSE_BODY);
// otherwise the client waits till the timeout for an answer
exchange.getResponseBody().close();
} catch (IOException e) {
connector.logMessage(e.getMessage());
}
}
}
private void sendUnexpectedErrorResponse(HttpExchange exchange, String message, Throwable e) {
connector.logError("Internal Server Error: " + message, e);
sendStringResponse(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR, message);
}
private void sendStringResponse(HttpExchange exchange, int responseCode, String response) {
byte[] content = response.getBytes();
exchange.getResponseHeaders().set("content-type", "text/plain");
try {
sendResponseHeaders(exchange, responseCode, content.length);
OutputStream os = exchange.getResponseBody();
os.write(content);
os.close();
} catch (IOException e) {
connector.logMessage(e.getMessage());
}
}
private void sendResponseHeaders(HttpExchange exchange, int responseCode, long contentLength) throws IOException {
// add configured headers
Headers responseHeaders = exchange.getResponseHeaders();
if (connector.enableCrossOriginResourceSharing) {
responseHeaders.add("Access-Control-Allow-Origin", connector.crossOriginResourceDomain);
responseHeaders.add("Access-Control-Max-Age", String.valueOf(connector.crossOriginResourceMaxAge));
// just reply all requested headers
String requestedHeaders = exchange.getRequestHeaders().getFirst("Access-Control-Request-Headers");
if (requestedHeaders != null) {
responseHeaders.add("Access-Control-Allow-Headers", requestedHeaders);
}
responseHeaders.add("Access-Control-Allow-Headers", "Authorization");
responseHeaders.add("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
}
exchange.sendResponseHeaders(responseCode, contentLength);
}
private long getResponseLength(final long contentLength) {
if (contentLength == 0) {
return -1;
}
if (contentLength < 0) {
return 0;
}
return contentLength;
}
}
|
package io.github.aquerr.eaglefactions.commands;
import com.google.common.collect.Lists;
import io.github.aquerr.eaglefactions.EagleFactions;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.service.pagination.PaginationList;
import org.spongepowered.api.service.pagination.PaginationService;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class HelpCommand implements CommandExecutor
{
@Override
public CommandResult execute(CommandSource source, CommandContext context) throws CommandException
{
Map<List<String>, CommandSpec> commands = EagleFactions.getEagleFactions().Subcommands;
List<Text> helpList = Lists.newArrayList();
for (List<String> aliases: commands.keySet())
{
CommandSpec commandSpec = commands.get(aliases);
if(source instanceof Player)
{
Player player = (Player)source;
if(commandSpec.testPermission(player))
{
continue;
}
}
Text commandHelp = Text.builder()
.append(Text.builder()
.append(Text.of(TextColors.AQUA, "/f " + aliases.toString().replace("[","").replace("]","")))
.build())
.append(Text.builder()
.append(Text.of(TextColors.GRAY, " - " + commandSpec.getShortDescription(source).get().toPlain()))
.build())
.build();
helpList.add(commandHelp);
}
//Sort commands alphabetically.
helpList.sort(Text::compareTo);
PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
PaginationList.Builder paginationBuilder = paginationService.builder().title(Text.of(TextColors.GREEN, "EagleFactions Command List")).padding(Text.of("-")).contents(helpList).linesPerPage(10);
paginationBuilder.sendTo(source);
return CommandResult.success ();
}
}
|
package io.katharsis.jackson.serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import io.katharsis.jackson.exception.JsonSerializationException;
import io.katharsis.queryParams.params.IncludedFieldsParams;
import io.katharsis.queryParams.params.TypedParams;
import io.katharsis.request.dto.Attributes;
import io.katharsis.resource.field.ResourceField;
import io.katharsis.resource.information.ResourceInformation;
import io.katharsis.resource.registry.RegistryEntry;
import io.katharsis.resource.registry.ResourceRegistry;
import io.katharsis.response.Container;
import io.katharsis.response.DataLinksContainer;
import io.katharsis.utils.BeanUtils;
import io.katharsis.utils.PropertyUtils;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* This class serializes an single resource which can be included in <i>data</i> field of JSON API response.
*
* @see Container
*/
public class ContainerSerializer extends JsonSerializer<Container> {
private static final String TYPE_FIELD_NAME = "type";
private static final String ID_FIELD_NAME = "id";
private static final String ATTRIBUTES_FIELD_NAME = "attributes";
private static final String RELATIONSHIPS_FIELD_NAME = "relationships";
private static final String LINKS_FIELD_NAME = "links";
private static final String SELF_FIELD_NAME = "self";
private final ResourceRegistry resourceRegistry;
public ContainerSerializer(ResourceRegistry resourceRegistry) {
this.resourceRegistry = resourceRegistry;
}
@Override
public void serialize(Container value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value != null && value.getData() != null) {
gen.writeStartObject();
TypedParams<IncludedFieldsParams> includedFields = value.getResponse()
.getQueryParams()
.getIncludedFields();
writeData(gen, value.getData(), includedFields);
gen.writeEndObject();
} else {
gen.writeObject(null);
}
}
private void writeData(JsonGenerator gen, Object data, TypedParams<IncludedFieldsParams> includedFields) throws IOException {
Class<?> dataClass = data.getClass();
String resourceType = resourceRegistry.getResourceType(dataClass);
gen.writeStringField(TYPE_FIELD_NAME, resourceType);
RegistryEntry entry = resourceRegistry.getEntry(dataClass);
ResourceInformation resourceInformation = entry.getResourceInformation();
try {
writeId(gen, data, resourceInformation.getIdField());
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new JsonSerializationException(
"Error writing id field: " + resourceInformation.getIdField().getUnderlyingName());
}
try {
writeAttributes(gen, data, resourceInformation.getAttributeFields(), includedFields);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
StringBuilder attributeFieldNames = new StringBuilder();
for (ResourceField attributeField : resourceInformation.getAttributeFields()) {
attributeFieldNames.append(attributeField.getUnderlyingName());
attributeFieldNames.append(" ");
}
throw new JsonSerializationException("Error writing basic fields: " +
attributeFieldNames);
}
Set<ResourceField> relationshipFields = getRelationshipFields(resourceType, resourceInformation, includedFields);
writeRelationshipFields(gen, data, relationshipFields);
writeLinksField(gen, data);
}
private Set<ResourceField> getRelationshipFields(String resourceType, ResourceInformation resourceInformation, TypedParams<IncludedFieldsParams> includedFields) {
Set<ResourceField> relationshipFields = new HashSet<>();
for (ResourceField resourceField : resourceInformation.getRelationshipFields()) {
if (isIncluded(resourceType, includedFields, resourceField)) {
relationshipFields.add(resourceField);
}
}
return relationshipFields;
}
private static void writeId(JsonGenerator gen, Object data, ResourceField idField)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
String sourceId = BeanUtils.getProperty(data, idField.getUnderlyingName());
gen.writeObjectField(ID_FIELD_NAME, sourceId);
}
private void writeAttributes(JsonGenerator gen, Object data, Set<ResourceField> attributeFields,
TypedParams<IncludedFieldsParams> includedFields)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
String resourceType = resourceRegistry.getResourceType(data.getClass());
ObjectMapper om = new ObjectMapper();
om.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
@Override
public Object findFilterId(Annotated a) {
Object filterId = super.findFilterId(a);
if (filterId == null) {
filterId = "katharsisFilter";
}
return filterId;
}
});
Set<String> set = new HashSet<>();
for (ResourceField attributeField : attributeFields) {
if (isIncluded(resourceType, includedFields, attributeField)) {
set.add(attributeField.getJsonName());
}
}
FilterProvider fp = new SimpleFilterProvider().addFilter("katharsisFilter", SimpleBeanPropertyFilter.filterOutAllExcept(set));
om.setFilterProvider(fp);
Map<String, Object> dataMap = om.convertValue(data, new TypeReference<Map<String, Object>>() {});
Attributes attributesObject = new Attributes();
for (ResourceField attributeField : attributeFields) {
if (isIncluded(resourceType, includedFields, attributeField)) {
String attributeJsonName = attributeField.getJsonName();
if (dataMap.containsKey(attributeJsonName)) {
Object attributeJsonValue = dataMap.get(attributeJsonName);
if(attributeJsonValue != null)
attributesObject.addAttribute(attributeJsonName, attributeJsonValue);
}
}
}
gen.writeObjectField(ATTRIBUTES_FIELD_NAME, attributesObject);
}
/**
* When <i>fields</i> filter is passed in the query params, <b>attributes</b> and <b>relationships</b> should be
* filtered accordingly to the requested fields.
* @param resourceType JSON API name of a resource
* @param includedFields <i>field</i> query param values
* @param attributeField resource attribute field
* @return <i>true</i> if it should be included in the response, <i>false</i> otherwise
*/
private boolean isIncluded(String resourceType, TypedParams<IncludedFieldsParams> includedFields, ResourceField attributeField) {
IncludedFieldsParams typeIncludedFields = findIncludedFields(includedFields, resourceType);
if (typeIncludedFields == null || typeIncludedFields.getParams().isEmpty()) {
return includedFields == null || includedFields.getParams().isEmpty();
} else {
return typeIncludedFields.getParams().contains(attributeField.getJsonName());
}
}
private static IncludedFieldsParams findIncludedFields(TypedParams<IncludedFieldsParams> includedFields, String
elementName) {
IncludedFieldsParams includedFieldsParams = null;
if (includedFields != null) {
for (Map.Entry<String, IncludedFieldsParams> entry : includedFields.getParams()
.entrySet()) {
if (elementName.equals(entry.getKey())) {
includedFieldsParams = entry.getValue();
}
}
}
return includedFieldsParams;
}
private static void writeRelationshipFields(JsonGenerator gen, Object data, Set<ResourceField> relationshipFields)
throws IOException {
DataLinksContainer dataLinksContainer = new DataLinksContainer(data, relationshipFields);
gen.writeObjectField(RELATIONSHIPS_FIELD_NAME, dataLinksContainer);
}
private void writeLinksField(JsonGenerator gen, Object data) throws IOException {
gen.writeFieldName(LINKS_FIELD_NAME);
gen.writeStartObject();
writeSelfLink(gen, data);
gen.writeEndObject();
}
private void writeSelfLink(JsonGenerator gen, Object data) throws IOException {
Class<?> sourceClass = data.getClass();
String resourceUrl = resourceRegistry.getResourceUrl(sourceClass);
RegistryEntry entry = resourceRegistry.getEntry(sourceClass);
ResourceField idField = entry.getResourceInformation().getIdField();
Object sourceId = PropertyUtils.getProperty(data, idField.getUnderlyingName());
gen.writeStringField(SELF_FIELD_NAME, resourceUrl + "/" + sourceId);
}
public Class<Container> handledType() {
return Container.class;
}
}
|
package nl.topicus.jdbc.transaction;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.List;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.BatchClient;
import com.google.cloud.spanner.BatchReadOnlyTransaction;
import com.google.cloud.spanner.BatchTransactionId;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.Options.QueryOption;
import com.google.cloud.spanner.Options.ReadOption;
import com.google.cloud.spanner.Partition;
import com.google.cloud.spanner.PartitionOptions;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.common.base.Preconditions;
import com.google.rpc.Code;
import nl.topicus.jdbc.CloudSpannerConnection;
import nl.topicus.jdbc.exception.CloudSpannerSQLException;
/**
* An abstraction of transactions on Google Cloud Spanner JDBC connections.
*
* @author loite
*
*/
public class CloudSpannerTransaction implements TransactionContext, BatchReadOnlyTransaction
{
private static final String SAVEPOINTS_NOT_IN_READ_ONLY = "Savepoints are not allowed in read-only mode";
public static class TransactionException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private TransactionException(String message, SQLException cause)
{
super(message, cause);
}
}
private TransactionThread transactionThread;
private ReadOnlyTransaction readOnlyTransaction;
private BatchReadOnlyTransaction batchReadOnlyTransaction;
private DatabaseClient dbClient;
private BatchClient batchClient;
private CloudSpannerConnection connection;
public CloudSpannerTransaction(DatabaseClient dbClient, BatchClient batchClient, CloudSpannerConnection connection)
{
this.dbClient = dbClient;
this.batchClient = batchClient;
this.connection = connection;
}
public boolean isRunning()
{
return batchReadOnlyTransaction != null || readOnlyTransaction != null || transactionThread != null;
}
public boolean hasBufferedMutations()
{
return transactionThread != null && transactionThread.hasBufferedMutations();
}
public int getNumberOfBufferedMutations()
{
return transactionThread == null ? 0 : transactionThread.numberOfBufferedMutations();
}
public void begin() throws SQLException
{
if (connection.isBatchReadOnly())
{
if (batchReadOnlyTransaction == null)
{
batchReadOnlyTransaction = batchClient.batchReadOnlyTransaction(TimestampBound.strong());
}
}
else if (connection.isReadOnly())
{
if (readOnlyTransaction == null)
{
readOnlyTransaction = dbClient.readOnlyTransaction();
}
}
else
{
if (transactionThread == null)
{
transactionThread = new TransactionThread(dbClient);
transactionThread.start();
}
}
}
public Timestamp commit() throws SQLException
{
Timestamp res = null;
try
{
if (connection.isBatchReadOnly())
{
if (batchReadOnlyTransaction != null)
{
batchReadOnlyTransaction.close();
}
}
else if (connection.isReadOnly())
{
if (readOnlyTransaction != null)
{
readOnlyTransaction.close();
}
}
else
{
if (transactionThread != null)
{
res = transactionThread.commit();
}
}
}
finally
{
transactionThread = null;
readOnlyTransaction = null;
batchReadOnlyTransaction = null;
}
return res;
}
public void rollback() throws SQLException
{
try
{
if (connection.isBatchReadOnly())
{
if (batchReadOnlyTransaction != null)
{
batchReadOnlyTransaction.close();
}
}
else if (connection.isReadOnly())
{
if (readOnlyTransaction != null)
{
readOnlyTransaction.close();
}
}
else
{
if (transactionThread != null)
{
transactionThread.rollback();
}
}
}
finally
{
transactionThread = null;
readOnlyTransaction = null;
batchReadOnlyTransaction = null;
}
}
public void setSavepoint(Savepoint savepoint) throws SQLException
{
Preconditions.checkNotNull(savepoint);
checkTransaction();
if (transactionThread == null)
throw new CloudSpannerSQLException(SAVEPOINTS_NOT_IN_READ_ONLY, Code.FAILED_PRECONDITION);
transactionThread.setSavepoint(savepoint);
}
public void rollbackSavepoint(Savepoint savepoint) throws SQLException
{
Preconditions.checkNotNull(savepoint);
checkTransaction();
if (transactionThread == null)
throw new CloudSpannerSQLException(SAVEPOINTS_NOT_IN_READ_ONLY, Code.FAILED_PRECONDITION);
transactionThread.rollbackSavepoint(savepoint);
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
Preconditions.checkNotNull(savepoint);
checkTransaction();
if (transactionThread == null)
throw new CloudSpannerSQLException(SAVEPOINTS_NOT_IN_READ_ONLY, Code.FAILED_PRECONDITION);
transactionThread.releaseSavepoint(savepoint);
}
@FunctionalInterface
private static interface TransactionAction
{
public void apply(String xid) throws SQLException;
}
public void prepareTransaction(String xid) throws SQLException
{
checkTransaction();
preparedTransactionAction(xid, transactionThread::prepareTransaction);
}
public void commitPreparedTransaction(String xid) throws SQLException
{
checkTransaction();
preparedTransactionAction(xid, transactionThread::commitPreparedTransaction);
}
public void rollbackPreparedTransaction(String xid) throws SQLException
{
checkTransaction();
preparedTransactionAction(xid, transactionThread::rollbackPreparedTransaction);
}
private void preparedTransactionAction(String xid, TransactionAction action) throws SQLException
{
try
{
if (connection.isReadOnly())
{
throw new CloudSpannerSQLException(
"Connection is in read-only mode and cannot be used for prepared transactions",
Code.FAILED_PRECONDITION);
}
else
{
action.apply(xid);
}
}
finally
{
transactionThread = null;
readOnlyTransaction = null;
batchReadOnlyTransaction = null;
}
}
private void checkTransaction()
{
if (transactionThread == null && readOnlyTransaction == null && batchReadOnlyTransaction == null)
{
try
{
begin();
}
catch (SQLException e)
{
throw new TransactionException("Failed to start new transaction", e);
}
}
}
@Override
public void buffer(Mutation mutation)
{
checkTransaction();
if (transactionThread == null)
throw new IllegalStateException("Mutations are not allowed in read-only mode");
transactionThread.buffer(mutation);
}
@Override
public void buffer(Iterable<Mutation> mutations)
{
checkTransaction();
if (transactionThread == null)
throw new IllegalStateException("Mutations are not allowed in read-only mode");
transactionThread.buffer(mutations);
}
@Override
public ResultSet executeQuery(Statement statement, QueryOption... options)
{
checkTransaction();
if (batchReadOnlyTransaction != null)
return batchReadOnlyTransaction.executeQuery(statement, options);
else if (readOnlyTransaction != null)
return readOnlyTransaction.executeQuery(statement, options);
else if (transactionThread != null)
return transactionThread.executeQuery(statement);
throw new IllegalStateException("No transaction found (this should not happen)");
}
@Override
public ResultSet read(String table, KeySet keys, Iterable<String> columns, ReadOption... options)
{
return null;
}
@Override
public ResultSet readUsingIndex(String table, String index, KeySet keys, Iterable<String> columns,
ReadOption... options)
{
return null;
}
@Override
public Struct readRow(String table, Key key, Iterable<String> columns)
{
return null;
}
@Override
public Struct readRowUsingIndex(String table, String index, Key key, Iterable<String> columns)
{
return null;
}
@Override
public ResultSet analyzeQuery(Statement statement, QueryAnalyzeMode queryMode)
{
return null;
}
/**
* Close method is needed for the interface, but does not do anything
*/
@Override
public void close()
{
// no-op as there is nothing to close or throw away
}
@Override
public Timestamp getReadTimestamp()
{
if (batchReadOnlyTransaction != null)
return batchReadOnlyTransaction.getReadTimestamp();
if (readOnlyTransaction != null)
return readOnlyTransaction.getReadTimestamp();
return null;
}
@Override
public List<Partition> partitionRead(PartitionOptions partitionOptions, String table, KeySet keys,
Iterable<String> columns, ReadOption... options) throws SpannerException
{
return null;
}
@Override
public List<Partition> partitionReadUsingIndex(PartitionOptions partitionOptions, String table, String index,
KeySet keys, Iterable<String> columns, ReadOption... options) throws SpannerException
{
return null;
}
@Override
public List<Partition> partitionQuery(PartitionOptions partitionOptions, Statement statement,
QueryOption... options) throws SpannerException
{
checkTransaction();
if (batchReadOnlyTransaction != null)
{
return batchReadOnlyTransaction.partitionQuery(partitionOptions, statement, options);
}
return null;
}
@Override
public ResultSet execute(Partition partition) throws SpannerException
{
checkTransaction();
if (batchReadOnlyTransaction != null)
{
return batchReadOnlyTransaction.execute(partition);
}
return null;
}
@Override
public BatchTransactionId getBatchTransactionId()
{
checkTransaction();
if (batchReadOnlyTransaction != null)
{
return batchReadOnlyTransaction.getBatchTransactionId();
}
return null;
}
public BatchReadOnlyTransaction getBatchReadOnlyTransaction()
{
return batchReadOnlyTransaction;
}
}
|
package org.asciidoc.intellij.editor.javafx;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.actions.OpenFileAction;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.impl.ProjectViewPane;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.CaretState;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.JBColor;
import com.intellij.util.PsiNavigateUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.sun.javafx.application.PlatformImpl;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.text.FontSmoothingType;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;
import org.apache.commons.io.IOUtils;
import org.asciidoc.intellij.editor.AsciiDocHtmlPanel;
import org.asciidoc.intellij.editor.AsciiDocPreviewEditor;
import org.asciidoc.intellij.psi.AsciiDocBlockId;
import org.asciidoc.intellij.psi.AsciiDocUtil;
import org.asciidoc.intellij.settings.AsciiDocApplicationSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaFxHtmlPanel extends AsciiDocHtmlPanel {
private Logger log = Logger.getInstance(JavaFxHtmlPanel.class);
private static final NotNullLazyValue<String> MY_SCRIPTING_LINES = new NotNullLazyValue<String>() {
@NotNull
@Override
protected String compute() {
final Class<JavaFxHtmlPanel> clazz = JavaFxHtmlPanel.class;
//noinspection StringBufferReplaceableByString
return new StringBuilder()
.append("<script src=\"").append(clazz.getResource("scrollToElement.js")).append("\"></script>\n")
.append("<script src=\"").append(clazz.getResource("processLinks.js")).append("\"></script>\n")
.append("<script src=\"").append(clazz.getResource("pickSourceLine.js")).append("\"></script>\n")
.append("<script type=\"text/x-mathjax-config\">\n" +
"MathJax.Hub.Config({\n" +
" messageStyle: \"none\",\n" +
" tex2jax: {\n" +
" inlineMath: [[\"\\\\(\", \"\\\\)\"]],\n" +
" displayMath: [[\"\\\\[\", \"\\\\]\"]],\n" +
" ignoreClass: \"nostem|nolatexmath\"\n" +
" },\n" +
" asciimath2jax: {\n" +
" delimiters: [[\"\\\\$\", \"\\\\$\"]],\n" +
" ignoreClass: \"nostem|noasciimath\"\n" +
" },\n" +
" TeX: { equationNumbers: { autoNumber: \"none\" } }\n" +
"});\n" +
"</script>\n")
.append("<script src=\"").append(clazz.getResource("MathJax/MathJax.js")).append("?config=TeX-MML-AM_HTMLorMML\"></script>\n")
.toString();
}
};
@NotNull
private final JPanel myPanelWrapper;
@NotNull
private final List<Runnable> myInitActions = new ArrayList<Runnable>();
@Nullable
private volatile JFXPanel myPanel;
@Nullable
private WebView myWebView;
@Nullable
private String myInlineCss;
@Nullable
private String myInlineCssDarcula;
@Nullable
private String myFontAwesomeCssLink;
@Nullable
private String myDejavuCssLink;
@NotNull
private final ScrollPreservingListener myScrollPreservingListener = new ScrollPreservingListener();
@NotNull
private final BridgeSettingListener myBridgeSettingListener = new BridgeSettingListener();
@NotNull
private String base;
private int lineCount;
private int offset;
private final Path imagesPath;
private final VirtualFile parentDirectory;
public JavaFxHtmlPanel(Document document, Path imagesPath) {
//System.setProperty("prism.lcdtext", "false");
//System.setProperty("prism.text", "t2k");
this.imagesPath = imagesPath;
myPanelWrapper = new JPanel(new BorderLayout());
myPanelWrapper.setBackground(JBColor.background());
lineCount = document.getLineCount();
parentDirectory = FileDocumentManager.getInstance().getFile(document).getParent();
if (parentDirectory != null) {
// parent will be null if we use Language Injection and Fragment Editor
base = parentDirectory.getUrl().replaceAll("^file:
.replaceAll(":", "%3A");
} else {
base = "";
}
try {
myInlineCss = IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("default.css"));
myInlineCssDarcula = myInlineCss + IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("darcula.css"));
myInlineCssDarcula += IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("coderay-darcula.css"));
myInlineCss += IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("coderay.css"));
myFontAwesomeCssLink = "<link rel=\"stylesheet\" href=\"" + JavaFxHtmlPanel.class.getResource("font-awesome/css/font-awesome.min.css") + "\">";
myDejavuCssLink = "<link rel=\"stylesheet\" href=\"" + JavaFxHtmlPanel.class.getResource("dejavu/dejavu.css") + "\">";
} catch (IOException e) {
String message = "Unable to combine CSS resources: " + e.getMessage();
log.error(message, e);
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP
.createNotification("Error rendering asciidoctor", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
runFX(new Runnable() {
@Override
public void run() {
PlatformImpl.startup(new Runnable() {
@Override
public void run() {
myWebView = new WebView();
updateFontSmoothingType(myWebView, false);
myWebView.setContextMenuEnabled(false);
myWebView.setZoom(JBUI.scale(1.f));
myWebView.getEngine().loadContent(prepareHtml("<html><head></head><body>Initializing...</body>"));
final WebEngine engine = myWebView.getEngine();
engine.getLoadWorker().stateProperty().addListener(myBridgeSettingListener);
engine.getLoadWorker().stateProperty().addListener(myScrollPreservingListener);
final Scene scene = new Scene(myWebView);
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
runFX(new Runnable() {
@Override
public void run() {
synchronized (myInitActions) {
myPanel = new JFXPanelWrapper();
Platform.runLater(() -> myPanel.setScene(scene));
for (Runnable action : myInitActions) {
Platform.runLater(action);
}
myInitActions.clear();
}
myPanelWrapper.add(myPanel, BorderLayout.CENTER);
myPanelWrapper.repaint();
}
});
}
});
}
});
}
});
}
});
}
private static void runFX(@NotNull Runnable r) {
IdeEventQueue.unsafeNonblockingExecute(r);
}
private void runInPlatformWhenAvailable(@NotNull final Runnable runnable) {
synchronized (myInitActions) {
if (myPanel == null) {
myInitActions.add(runnable);
} else {
Platform.runLater(runnable);
}
}
}
private boolean isDarcula() {
final AsciiDocApplicationSettings settings = AsciiDocApplicationSettings.getInstance();
switch (settings.getAsciiDocPreviewSettings().getPreviewTheme()) {
case INTELLIJ:
return UIUtil.isUnderDarcula();
case ASCIIDOC:
return false;
case DARCULA:
return true;
default:
return false;
}
}
private static void updateFontSmoothingType(@NotNull WebView view, boolean isGrayscale) {
final FontSmoothingType typeToSet;
if (isGrayscale) {
typeToSet = FontSmoothingType.GRAY;
} else {
typeToSet = FontSmoothingType.LCD;
}
view.fontSmoothingTypeProperty().setValue(typeToSet);
}
@NotNull
@Override
public JComponent getComponent() {
return myPanelWrapper;
}
@Override
public void setHtml(@NotNull String html) {
if (isDarcula()) {
// clear out coderay inline CSS colors as they are barely readable in darcula theme
html = html.replaceAll("<span style=\"color:#[a-zA-Z0-9]*;?", "<span style=\"");
html = html.replaceAll("<span style=\"background-color:#[a-zA-Z0-9]*;?", "<span style=\"");
}
html = "<html><head></head><body>" + html + "</body>";
final String htmlToRender = prepareHtml(html);
runInPlatformWhenAvailable(new Runnable() {
@Override
public void run() {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().loadContent(htmlToRender);
}
});
}
private String findTempImageFile(String _fileName) {
Path file = imagesPath.resolve(_fileName);
if (Files.exists(file)) {
return file.toFile().toString();
}
return null;
}
private String prepareHtml(@NotNull String html) {
/* for each image we'll calculate a MD5 sum of its content. Once the content changes, MD5 and therefore the URL
* will change. The changed URL is necessary for the JavaFX web view to display the new content, as each URL
* will be loaded only once by the JavaFX web view. */
Pattern pattern = Pattern.compile("<img src=\"([^:\"]*)\"");
final Matcher matcher = pattern.matcher(html);
while (matcher.find()) {
final MatchResult matchResult = matcher.toMatchResult();
String file = matchResult.group(1);
String tmpFile = findTempImageFile(file);
String md5;
String replacement;
if (tmpFile != null) {
md5 = calculateMd5(tmpFile, null);
tmpFile = tmpFile.replaceAll("\\\\", "/");
tmpFile = tmpFile.replaceAll(":", "%3A");
if (JavaFxHtmlPanelProvider.isInitialized()) {
replacement = "<img src=\"localfile://" + md5 + "/" + tmpFile + "\"";
} else {
replacement = "<img src=\"file://" + tmpFile.replaceAll("%3A", ":") + "\"";
}
} else {
md5 = calculateMd5(file, base);
if (JavaFxHtmlPanelProvider.isInitialized()) {
replacement = "<img src=\"localfile://" + md5 + "/" + base + "/" + file + "\"";
} else {
replacement = "<img src=\"file://" + base.replaceAll("%3A", ":") + "/" + file + "\"";
}
}
html = html.substring(0, matchResult.start()) +
replacement + html.substring(matchResult.end());
matcher.reset(html);
}
// filter out Twitter's JavaScript, as it is problematic for JDK8 JavaFX
html = html.replaceAll("(?i)<script [a-z ]*src=\"https://platform\\.twitter\\.com/widgets\\.js\" [^>]*></script>", "");
/* Add CSS line and JavaScript for auto-scolling and clickable links */
return html
.replace("<head>", "<head>" + getCssLines(isDarcula() ? myInlineCssDarcula : myInlineCss) + myFontAwesomeCssLink + myDejavuCssLink)
.replace("</body>", getScriptingLines() + "</body>");
}
private String calculateMd5(String file, String base) {
String md5;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
try(FileInputStream fis = new FileInputStream((base != null ? base.replaceAll("%3A", ":") + "/" : "") + file)) {
int nread;
byte[] dataBytes = new byte[1024];
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
}
byte[] mdbytes = md.digest();
StringBuilder sb = new StringBuilder();
for (byte mdbyte : mdbytes) {
sb.append(Integer.toString((mdbyte & 0xff) + 0x100, 16).substring(1));
}
md5 = sb.toString();
} catch (NoSuchAlgorithmException | IOException e) {
md5 = "none";
}
return md5;
}
@Override
public void render() {
runInPlatformWhenAvailable(new Runnable() {
@Override
public void run() {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().reload();
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
myPanelWrapper.repaint();
}
});
}
});
}
@Override
public void scrollToLine(final int line, final int lineCount, int offsetLineNo) {
this.lineCount = lineCount;
this.offset = offsetLineNo;
runInPlatformWhenAvailable(new Runnable() {
@Override
public void run() {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"if ('__IntelliJTools' in window) " +
"__IntelliJTools.scrollToLine(" + line + ", " + lineCount + ", " + offsetLineNo + ");"
);
final Object result = JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"document.documentElement.scrollTop || document.body.scrollTop");
if (result instanceof Number) {
myScrollPreservingListener.myScrollY = ((Number) result).intValue();
}
}
});
}
@Override
public void dispose() {
runInPlatformWhenAvailable(new Runnable() {
@Override
public void run() {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().load("about:blank");
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().getLoadWorker().stateProperty().removeListener(myScrollPreservingListener);
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().getLoadWorker().stateProperty().removeListener(myBridgeSettingListener);
}
});
}
@NotNull
private WebView getWebViewGuaranteed() {
if (myWebView == null) {
throw new IllegalStateException("WebView should be initialized by now. Check the caller thread");
}
return myWebView;
}
@NotNull
private static String getScriptingLines() {
return MY_SCRIPTING_LINES.getValue();
}
@SuppressWarnings("unused")
public class JavaPanelBridge {
public void openLink(@NotNull String link) {
final URI uri;
try {
uri = new URI(link);
} catch (URISyntaxException ex) {
throw new RuntimeException("unable to parse URL " + link);
}
String scheme = uri.getScheme();
if("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) {
BrowserUtil.browse(uri);
} else if ("file".equalsIgnoreCase(scheme) || scheme == null) {
openInEditor(uri);
} else {
log.warn("won't open URI as it might be unsafe: " + uri);
}
}
private boolean openInEditor(@NotNull URI uri) {
return ReadAction.compute(() -> {
String anchor = uri.getFragment();
String path = uri.getPath();
final VirtualFile targetFile;
VirtualFile tmpTargetFile = parentDirectory.findFileByRelativePath(path);
if (tmpTargetFile == null) {
// extension might be skipped if it is an .adoc file
tmpTargetFile = parentDirectory.findFileByRelativePath(path + ".adoc");
}
if (tmpTargetFile == null && path.endsWith(".html")) {
// might link to a .html in the rendered output, but might actually be a .adoc file
tmpTargetFile = parentDirectory.findFileByRelativePath(path.replaceAll("\\.html$", ".adoc"));
}
if (tmpTargetFile == null) {
log.warn("unable to find file for " + uri);
return false;
}
targetFile = tmpTargetFile;
Project project = ProjectUtil.guessProjectForContentFile(targetFile);
if (project == null) {
log.warn("unable to find project for " + uri);
return false;
}
if (targetFile.isDirectory()) {
ProjectView projectView = ProjectView.getInstance(project);
projectView.changeView(ProjectViewPane.ID);
projectView.select(null, targetFile, true);
} else {
boolean anchorFound = false;
if (anchor != null) {
List<AsciiDocBlockId> ids = AsciiDocUtil.findIds(project, targetFile, anchor);
if (!ids.isEmpty()) {
anchorFound = true;
ApplicationManager.getApplication().invokeLater(() -> PsiNavigateUtil.navigate(ids.get(0)));
}
}
if (!anchorFound) {
ApplicationManager.getApplication().invokeLater(() -> OpenFileAction.openFile(targetFile, project));
}
}
return true;
});
}
public void scrollEditorToLine(int sourceLine) {
if(sourceLine <= 0) {
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP.createNotification("Setting cursor position", "line number " + sourceLine + " requested for cursor position, ignoring",
NotificationType.INFORMATION, null);
notification.setImportant(false);
return;
}
ApplicationManager.getApplication().invokeLater(
() -> {
getEditor().getCaretModel().setCaretsAndSelections(
Arrays.asList(new CaretState(new LogicalPosition(sourceLine - 1, 0), null, null))
);
getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER_UP);
}
);
}
public void log(@Nullable String text) {
Logger.getInstance(JavaPanelBridge.class).warn(text);
}
}
private JavaPanelBridge bridge = new JavaPanelBridge();
private class BridgeSettingListener implements ChangeListener<State> {
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue == State.SUCCEEDED) {
JSObject win
= (JSObject) getWebViewGuaranteed().getEngine().executeScript("window");
win.setMember("JavaPanelBridge", bridge);
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"if ('__IntelliJTools' in window) {" +
"__IntelliJTools.processLinks();" +
"__IntelliJTools.pickSourceLine(" + lineCount + ", " + offset + ");" +
"}"
);
}
}
}
private class ScrollPreservingListener implements ChangeListener<State> {
volatile int myScrollY = 0;
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue == State.RUNNING) {
final Object result =
getWebViewGuaranteed().getEngine().executeScript("document.documentElement.scrollTop || document.body.scrollTop");
if (result instanceof Number) {
myScrollY = ((Number) result).intValue();
}
} else if (newValue == State.SUCCEEDED) {
getWebViewGuaranteed().getEngine()
.executeScript("document.documentElement.scrollTop = document.body.scrollTop = " + myScrollY);
}
}
}
}
|
package org.atdl4j.ui.javafx.app.impl;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.util.Callback;
import javafx.util.StringConverter;
import org.apache.log4j.Logger;
import org.atdl4j.config.Atdl4jConfig;
import org.atdl4j.config.Atdl4jConfiguration;
import org.atdl4j.config.Atdl4jOptions;
import org.atdl4j.fixatdl.core.StrategyT;
import org.atdl4j.ui.Atdl4jWidget;
import org.atdl4j.ui.app.Atdl4jCompositePanel;
import org.atdl4j.ui.app.impl.AbstractAtdl4jTesterApp;
import org.atdl4j.ui.javafx.JavaFXWidget;
import org.atdl4j.ui.javafx.config.JavaFXAtdl4jConfiguration;
import org.atdl4j.ui.javafx.impl.JavaFXStrategiesUI;
import org.atdl4j.ui.javafx.impl.JavaFXStrategyUI;
/**
*
* @author daniel.makgonta
*/
public class JavaFXAtdl4jTesterApp extends AbstractAtdl4jTesterApp {
public static final Logger logger = Logger.getLogger(JavaFXAtdl4jTesterApp.class);
private ComboBox<StrategyT> strategyList;
private final ArrayList<Node> strategyWidgets = new ArrayList<Node>();
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Atdl4jConfiguration config = new JavaFXAtdl4jConfiguration();
JavaFXAtdl4jTesterApp tempJavaFXAtdl4jTesterApp = new JavaFXAtdl4jTesterApp();
try {
tempJavaFXAtdl4jTesterApp.mainLine(config, "samples/sample1.xml");
} catch (Exception e) {
if (Atdl4jConfig.getConfig().isCatchAllMainlineExceptions()) {
JavaFXAtdl4jTesterApp.logger.warn("Fatal Exception in mainLine", e);
} else {
throw e;
}
}
}
public ArrayList<? extends Node> getStrategyWidgets() {
return strategyWidgets;
}
public Pane mainLine(Atdl4jConfiguration config, String XMLFilePath) throws Exception {
AnchorPane pane = new AnchorPane();
AnchorPane root = new AnchorPane();
strategyList = new ComboBox<StrategyT>();
strategyList.setMinWidth(120);
HBox containerBox = new HBox();
containerBox.setPadding(new Insets(5, 0, 5, 0));
final VBox strategyBox = new VBox();
root.getChildren().add(containerBox);
// -- Delegate setup to AbstractAtdl4jTesterApp, construct a new
// JavaFX-specific Atdl4jOptions --
Atdl4jOptions atdl4jOptions = new Atdl4jOptions();
atdl4jOptions.setShowEnabledCheckboxOnOptionalClockControl(true);
init(config, atdl4jOptions, pane);
// -- Build the JavaFX panel from Atdl4jTesterPanel (** core GUI component **) --
getAtdl4jTesterPanel().buildAtdl4jTesterPanel(pane, getAtdl4jOptions());
Atdl4jCompositePanel panel = getAtdl4jTesterPanel().getAtdl4jCompositePanel();
panel.parseFixatdlFile(XMLFilePath);
panel.loadScreenWithFilteredStrategies();
final JavaFXStrategiesUI uiList = (JavaFXStrategiesUI) panel.getStrategiesUI();
List<StrategyT> strategies = panel.getStrategiesFilteredStrategyList();
strategyList.getItems().addAll(strategies);
strategyList.setCellFactory(new Callback<ListView<StrategyT>, ListCell<StrategyT>>() {
@Override
public ListCell<StrategyT> call(ListView<StrategyT> param) {
return new StrategyListCell();
}
});
strategyList.setConverter(new StringConverter<StrategyT>() {
@Override
public String toString(StrategyT strategy) {
if (strategy != null) {
return strategy.getUiRep();
}
return null;
}
@Override
public StrategyT fromString(String string) {
return null;
}
});
strategyList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<StrategyT>() {
@Override
public void changed(ObservableValue<? extends StrategyT> observable, StrategyT oldValue, StrategyT newValue) {
strategyBox.getChildren().clear();
strategyWidgets.clear();
JavaFXStrategyUI ui = (JavaFXStrategyUI) uiList.getStrategyUI(newValue, true);
strategyBox.getChildren().add(ui.getParentComponent());
for (Atdl4jWidget<?> widget : ui.getAtdl4jWidgetMap().values()) {
if (widget != null) {
if (((JavaFXWidget) widget).getComponentsExcludingLabel() != null) {
for (Object atomicNode : ((JavaFXWidget) widget).getComponentsExcludingLabel()) {
Node n = (Node) atomicNode;
strategyWidgets.add(n);
}
}
}
}
}
});
root.setPrefWidth(600);
pane.setPrefWidth(400);
root.setPrefHeight(500);
pane.setPrefHeight(400);
containerBox.getChildren().addAll(strategyList, strategyBox);
return root;
}
public void show(javafx.scene.Node n) {
if (n != null) {
if (!(n instanceof Pane) && !(n instanceof Label) && n != strategyList) {
System.out.println(n);
}
if (n instanceof Pane) {
for (int i = 0; i < ((Pane) n).getChildren().size(); i++) {
show(((Pane) n).getChildren().get(i));
}
}
}
}
class StrategyListCell extends ListCell<StrategyT> {
@Override
protected void updateItem(StrategyT item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.getUiRep());
}
}
}
}
|
package org.cruk.mga.workflow;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.ParseException;
import org.cruk.util.CommandLineUtility;
import org.cruk.workflow.assembly.MetaDataLoader;
import org.cruk.workflow.util.ApplicationContextFactory;
import org.cruk.workflow.util.FileFinder;
import org.cruk.workflow.xml2.metadata.LogLevel;
import org.cruk.workflow.xml2.metadata.MetaData;
import org.cruk.workflow.xml2.metadata.ModeSpecific;
import org.cruk.workflow.xml2.metadata.VersionsFileFormat;
import org.cruk.workflow.xml2.pipeline.FilenamePattern;
import org.cruk.workflow.xml2.pipeline.TaskVariableSet;
import org.springframework.context.ApplicationContext;
/**
* Creates the pipeline configuration metadata from a sample sheet.
*
* @author eldrid01
*/
public class CreateMetadataFromSampleSheet extends CommandLineUtility
{
public static final String DEFAULT_MODE = "local";
public static final int DEFAULT_MAX_CPU_RESOURCES = 1;
public static final String DEFAULT_QUEUE = "bioinformatics";
public static final int DEFAULT_MAX_SUBMITTED_JOBS = 50;
public static final String DEFAULT_WORKING_DIR = "@{user.dir}";
public static final String DEFAULT_TEMP_DIR = "${work}/temp";
public static final String DEFAULT_RESOURCES_DIR = "${install}/resources";
public static final String DEFAULT_DATA_DIR = "${work}";
public static final String DEFAULT_OUTPUT_DIR = "${work}";
public static final String DEFAULT_BOWTIE_EXECUTABLE = "bowtie";
public static final String DEFAULT_EXONERATE_EXECUTABLE = "exonerate";
public static final int DEFAULT_SAMPLE_SIZE = 100000;
public static final long DEFAULT_MAX_RECORDS_TO_SAMPLE_FROM = 5000000;
public static final int DEFAULT_CHUNK_SIZE = 5000000;
public static final int DEFAULT_TRIM_LENGTH = 36;
public static final int DEFAULT_PLOT_WIDTH = 800;
public static final int DEFAULT_MIN_SEQUENCE_COUNT = 10;
public static final boolean DEFAULT_SEPARATE_DATASET_REPORTS = false;
private FileFinder fileFinder = new FileFinder();
private String mode;
private int maxCpuResources;
private String queue;
private int maxSubmittedJobs;
private String sampleSheetFilename;
private String workingDirectory;
private String temporaryDirectory;
private String resourcesDirectory;
private String dataDirectory;
private String outputDirectory;
private String bowtieExecutable;
private String exonerateExecutable;
private int sampleSize;
private long maxNumberOfRecordsToSampleFrom;
private int chunkSize;
private int trimLength;
private int plotWidth;
private int minimumSequenceCount;
private boolean separateDatasetReports;
private String runId;
private MetaData meta;
public static void main(String[] args)
{
CreateMetadataFromSampleSheet createMetadataFromSampleSheet = new CreateMetadataFromSampleSheet(args);
createMetadataFromSampleSheet.execute();
}
public CreateMetadataFromSampleSheet(String[] args)
{
super("sample_sheet_file", args);
meta = new MetaData();
}
/**
* Parse command line arguments.
*
* @param args
*/
@Override
protected void parseCommandLineArguments(String[] args)
{
CommandLineParser parser = new DefaultParser();
options.addOption("o", "output-metadata-file", true, "Output pipeline metadata (configuration) file (default: stdout)");
options.addOption("m", "mode", true, "The run mode, either local, slurm or lsf (default: " + DEFAULT_MODE + ")");
options.addOption("n", "max-cpu-resources", true, "Maximum number of CPU processors to use when running in local mode (default: " + DEFAULT_MAX_CPU_RESOURCES + ")");
options.addOption("q", "queue", true, "The queue to submit to when using the Slurm or LSF scheduler (default: " + DEFAULT_QUEUE + ")");
options.addOption("j", "max-submitted-jobs", true, "Maximum number of submitted jobs when using the Slurm or LSF scheduler (default: " + DEFAULT_MAX_SUBMITTED_JOBS + ")");
options.addOption("w", "working-directory", true, "The working directory (default: current directory, referred to as ${work})");
options.addOption("t", "temp-directory", true, "The temporary directory (default: " + DEFAULT_TEMP_DIR + ")");
options.addOption("r", "resources-directory", true, "The MGA resources directory containing the bowtie-indexes subdirectory, the adaptor sequences and the reference genome mapping (default: " + DEFAULT_RESOURCES_DIR + ", where ${install} refers to the MGA installation directory)");
options.addOption("d", "data-directory", true, "The data directory containing the FASTQ sequence files (default: " + DEFAULT_DATA_DIR + ")");
options.addOption(null, "output-directory", true, "The output directory in which the report is created (default: " + DEFAULT_OUTPUT_DIR + ")");
options.addOption("b", "bowtie-executable", true, "The path for the bowtie executable (default: " + DEFAULT_BOWTIE_EXECUTABLE + ")");
options.addOption("e", "exonerate-executable", true, "The path for the exonerate executable (default: " + DEFAULT_EXONERATE_EXECUTABLE + ")");
options.addOption("s", "sample-size", true, "The number of FASTQ records to sample for each dataset (default: " + DEFAULT_SAMPLE_SIZE + ")");
options.addOption(null, "max-records-to-sample-from", true, "The maximum number of FASTQ records to read (sample from) for each dataset (default: " + DEFAULT_MAX_RECORDS_TO_SAMPLE_FROM + ")");
options.addOption("c", "chunk-size", true, "The maximum number of FASTQ records in each chunk/alignment job (default: " + DEFAULT_CHUNK_SIZE + ")");
options.addOption("l", "trim-length", true, "The length to trim sequences to for alignment (default: " + DEFAULT_TRIM_LENGTH + ")");
options.addOption(null, "plot-width", true, "The width of the stacked bar plot in pixels (default: " + DEFAULT_PLOT_WIDTH + ")");
options.addOption(null, "min-sequence-count", true, "The minimum sequence count to use on the y-axis when creating the stacked bar plot (default: " + DEFAULT_MIN_SEQUENCE_COUNT + ")");
options.addOption(null, "separate-dataset-reports", false, "If separate reports for each dataset are required");
mode = DEFAULT_MODE;
maxCpuResources = DEFAULT_MAX_CPU_RESOURCES;
queue = DEFAULT_QUEUE;
maxSubmittedJobs = DEFAULT_MAX_SUBMITTED_JOBS;
workingDirectory = DEFAULT_WORKING_DIR;
temporaryDirectory = DEFAULT_TEMP_DIR;
resourcesDirectory = DEFAULT_RESOURCES_DIR;
dataDirectory = DEFAULT_DATA_DIR;
outputDirectory = DEFAULT_OUTPUT_DIR;
bowtieExecutable = DEFAULT_BOWTIE_EXECUTABLE;
exonerateExecutable = DEFAULT_EXONERATE_EXECUTABLE;
sampleSize = DEFAULT_SAMPLE_SIZE;
maxNumberOfRecordsToSampleFrom = DEFAULT_MAX_RECORDS_TO_SAMPLE_FROM;
chunkSize = DEFAULT_CHUNK_SIZE;
trimLength = DEFAULT_TRIM_LENGTH;
plotWidth = DEFAULT_PLOT_WIDTH;
minimumSequenceCount = DEFAULT_MIN_SEQUENCE_COUNT;
separateDatasetReports = DEFAULT_SEPARATE_DATASET_REPORTS;
try
{
CommandLine commandLine = parser.parse(options, args);
if (commandLine.hasOption("output-metadata-file"))
{
outputFilename = commandLine.getOptionValue("output-metadata-file");
}
if (commandLine.hasOption("mode"))
{
mode = commandLine.getOptionValue("mode").toLowerCase();
if (!mode.equals("local") && !mode.equals("slurm") && !mode.equals("lsf"))
{
error("Error: unrecognized execution mode: " + commandLine.getOptionValue("mode") + " (can be either local, slurm or lsf)");
}
}
if (commandLine.hasOption("max-cpu-resources"))
{
try
{
maxCpuResources = Integer.parseInt(commandLine.getOptionValue("max-cpu-resources"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: max-cpu-resources must be an integer number.");
}
}
if (commandLine.hasOption("queue"))
{
queue = commandLine.getOptionValue("queue");
}
if (commandLine.hasOption("max-submitted-jobs"))
{
try
{
maxSubmittedJobs = Integer.parseInt(commandLine.getOptionValue("max-submitted-jobs"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: max-submitted-jobs must be an integer number.");
}
}
if (commandLine.hasOption("working-directory"))
{
workingDirectory = commandLine.getOptionValue("working-directory");
}
if (commandLine.hasOption("temp-directory"))
{
temporaryDirectory = commandLine.getOptionValue("temp-directory");
}
if (commandLine.hasOption("resources-directory"))
{
resourcesDirectory = commandLine.getOptionValue("resources-directory");
}
if (commandLine.hasOption("data-directory"))
{
dataDirectory = commandLine.getOptionValue("data-directory");
}
if (commandLine.hasOption("output-directory"))
{
outputDirectory = commandLine.getOptionValue("output-directory");
}
if (commandLine.hasOption("bowtie-executable"))
{
bowtieExecutable = commandLine.getOptionValue("bowtie-executable");
}
if (commandLine.hasOption("exonerate-executable"))
{
exonerateExecutable = commandLine.getOptionValue("exonerate-executable");
}
if (commandLine.hasOption("sample-size"))
{
try
{
sampleSize = Integer.parseInt(commandLine.getOptionValue("sample-size"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: sample-size must be an integer number.");
}
}
if (commandLine.hasOption("max-records-to-sample-from"))
{
try
{
maxNumberOfRecordsToSampleFrom = Long.parseLong(commandLine.getOptionValue("max-records-to-sample-from"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: max-records-to-sample-from must be an integer number.");
}
}
if (commandLine.hasOption("chunk-size"))
{
try
{
chunkSize = Integer.parseInt(commandLine.getOptionValue("chunk-size"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: chunk-size must be an integer number.");
}
}
if (commandLine.hasOption("trim-length"))
{
try
{
trimLength = Integer.parseInt(commandLine.getOptionValue("trim-length"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: trim-length must be an integer number.");
}
}
if (commandLine.hasOption("plot-width"))
{
try
{
plotWidth = Integer.parseInt(commandLine.getOptionValue("plot-width"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: plot-width must be an integer number.");
}
}
if (commandLine.hasOption("min-sequence-count"))
{
try
{
minimumSequenceCount = Integer.parseInt(commandLine.getOptionValue("min-sequence-count"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: min-sequence-count must be an integer number.");
}
}
if (commandLine.hasOption("separate-dataset-reports"))
{
separateDatasetReports = commandLine.hasOption("separate-dataset-reports");
}
args = commandLine.getArgs();
if (args.length < 1)
{
error("Error parsing command line: missing arguments", true);
}
sampleSheetFilename = args[0];
}
catch (ParseException e)
{
error("Error parsing command-line options: " + e.getMessage(), true);
}
}
protected void populateMeta()
{
readSampleSheet();
meta.setPipeline("${install}/pipelines/mga.xml");
meta.setMode(mode);
meta.setTempDirectory(temporaryDirectory);
meta.setJobOutputDirectory("${work}/logs");
meta.setSummaryFile("${work}/logs/${runId}.summary.csv", false, false);
meta.setVersionsFile("${work}/logs/${runId}.versions.txt", VersionsFileFormat.TEXT);
meta.setLogFile("${work}/logs/${runId}.pipeline.log", true, LogLevel.NORMAL);
ModeSpecific local = new ModeSpecific("local");
local.setVariable("maxCpuResources", Integer.toString(maxCpuResources));
meta.getModeConfigurations().add(local);
ModeSpecific lsf = new ModeSpecific("lsf");
lsf.setVariable("queue", queue);
lsf.setVariable("maximumSubmittedJobs", Integer.toString(maxSubmittedJobs));
meta.getModeConfigurations().add(lsf);
ModeSpecific slurm = new ModeSpecific("slurm");
slurm.setVariable("queue", queue);
slurm.setVariable("maximumSubmittedJobs", Integer.toString(maxSubmittedJobs));
meta.getModeConfigurations().add(slurm);
meta.setVariable("runId", runId);
meta.setVariable("sampleSheetFile", sampleSheetFilename);
meta.setVariable("work", workingDirectory);
meta.setVariable("dataDir", dataDirectory);
meta.setVariable("outputDir", outputDirectory);
meta.setVariable("resourcesDir", resourcesDirectory);
meta.setVariable("bowtieIndexDir", "${resourcesDir}/bowtie_indexes");
meta.setVariable("adapterFastaFile", "${resourcesDir}/adapters.fa");
meta.setVariable("referenceGenomeMappingFile", "${resourcesDir}/reference_genome_mappings.txt");
meta.setVariable("bowtieExecutable", bowtieExecutable);
meta.setVariable("exonerateExecutable", exonerateExecutable);
meta.setVariable("sampleSize", Integer.toString(sampleSize));
meta.setVariable("maxNumberOfRecordsToSampleFrom", Long.toString(maxNumberOfRecordsToSampleFrom));
meta.setVariable("chunkSize", Integer.toString(chunkSize));
meta.setVariable("trimLength", Integer.toString(trimLength));
meta.setVariable("plotWidth", Integer.toString(plotWidth));
meta.setVariable("minimumSequenceCount", Integer.toString(minimumSequenceCount));
meta.setVariable("separateDatasetReports", Boolean.toString(separateDatasetReports));
}
/**
* Retrieves run details from the LIMS and creates a sample sheet.
*
* @throws Exception
*/
@Override
protected void run() throws Exception
{
ApplicationContext appContext = ApplicationContextFactory.createStartupApplicationContext();
populateMeta();
MetaDataLoader metaLoader = appContext.getBean(MetaDataLoader.class);
metaLoader.writeMetaData(meta, out);
}
/**
* Returns a mapping of dataset IDs to file names.
*/
private void readSampleSheet()
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(sampleSheetFilename));
}
catch (FileNotFoundException e)
{
error("Error: could not find file " + sampleSheetFilename);
}
try
{
boolean inDatasetSection = false;
int lineNumber = 0;
String line = null;
while ((line = reader.readLine()) != null)
{
lineNumber++;
String[] fields = line.split("\\t");
if (inDatasetSection)
{
if (fields.length < 2)
{
error("Error: dataset section in sample sheet contains line with less than two columns at line " + lineNumber + " of sample sheet file " + sampleSheetFilename);
}
String id = fields[0].trim();
if (id.length() == 0)
{
error("Error: missing dataset identifier in first column at line " + lineNumber + " of sample sheet file " + sampleSheetFilename);
}
String filename = fields[1].trim();
if (filename.length() != 0)
{
if (!dataDirectory.equals(DEFAULT_DATA_DIR))
{
filename = filename.replaceAll("\\$\\{dataDir\\}", dataDirectory);
}
String[] filenames = filename.split("\\|");
for (int i = 0; i < filenames.length; i++)
{
File file = new File(filenames[i]);
List<File> files = fileFinder.findFiles(file.getAbsolutePath(), FilenamePattern.WILDCARD, TaskVariableSet.INPUT);
if (files.isEmpty())
{
log.warn("Could not find any files matching pattern " + fields[1].trim() + " at line " + lineNumber + " of sample sheet file " + sampleSheetFilename);
}
}
}
}
else
{
if (fields.length > 1)
{
if (fields[0].trim().equalsIgnoreCase("DatasetId") && fields[1].trim().equalsIgnoreCase("File"))
{
inDatasetSection = true;
}
else if (runId == null && fields[0].equalsIgnoreCase("Run ID") && fields[1].trim().length() > 0)
{
runId = fields[1];
}
}
}
}
if (runId == null)
{
error("Error: Run ID must be specified in header section in sample sheet file " + sampleSheetFilename);
}
if (!inDatasetSection)
{
error("Error: missing dataset section in sample sheet file " + sampleSheetFilename);
}
}
catch (IOException e)
{
error(e);
}
finally
{
try
{
reader.close();
}
catch (IOException e)
{
error("Error closing file " + sampleSheetFilename);
}
}
}
public String getWorkingDirectory()
{
return workingDirectory;
}
public void setWorkingDirectory(String workingDirectory)
{
this.workingDirectory = workingDirectory;
}
public String getResourcesDirectory()
{
return resourcesDirectory;
}
public void setResourcesDirectory(String resourcesDirectory)
{
this.resourcesDirectory = resourcesDirectory;
}
}
|
/**
* Implementation of a Traffic Shaping Handler and Dynamic Statistics.<br>
* <br><br>
*
*
* <P>The main goal of this package is to allow to shape the traffic (bandwidth limitation),
* but also to get statistics on how many bytes are read or written. Both functions can
* be active or inactive (traffic or statistics).</P>
*
* <P>Three classes implement this behavior:<br>
* <ul>
* <li> <tt>PerformanceCounter</tt>: this class is the kernel of the package. It can be accessed to get some extra information
* like the read or write bytes since last check, the read and write bandwidth from last check...</li><br><br>
*
* <li> <tt>PerformanceCounterFactory</tt>: this class has to be implemented in your code in order to implement (eventually empty)
* the accounting method. This class is a Factory for PerformanceCounter which is used in the third class to create the
* necessary PerformanceCounter according to your specifications.</li><br><br>
*
* <li> <tt>TrafficShapingHandler</tt>: this class is the handler to be inserted in your pipeline. The insertion can be wherever
* you want, but <b>it must be placed before any <tt>MemoryAwareThreadPoolExecutor</tt> in your pipeline</b>.</li><br>
* <b><i>It is really recommended
* to have such a</i> <tt>MemoryAwareThreadPoolExecutor</tt> <i>(either non ordered or </i><tt>OrderedMemoryAwareThreadPoolExecutor</tt>
* <i>) in your pipeline</i></b>
* when you want to use this feature with some real traffic shaping, since it will allow to relax the constraint on
* NioWorker to do other jobs if necessary.<br>
* Instead, if you don't, you can have the following situation: if there are more clients
* connected and doing data transfer (either in read or write) than NioWorker, your global performance can be under your specifications or even
* sometimes it will block for a while which can turn to "timeout" operations.
* For instance, let says that you've got 2 NioWorkers, and 10 clients wants to send data to your server. If you set a bandwidth limitation
* of 100KB/s for each channel (client), you could have a final limitation of about 60KB/s for each channel since NioWorkers are
* stopping by this handler.<br><br>
* The method <tt>getMessageSize(MessageEvent)</tt> has to be implemented to specify what is the size of the object to be read or write
* accordingly to the type of object. In simple case, it can be as simple as a call to <tt>getChannelBufferMessageSize(MessageEvent)</tt>.<br>
* </ul></P>
*
* <P>Standard use could be as follow:</P>
*
* <P><ul>
* <li>To activate or deactivate the traffic shaping, change the value corresponding to your desire as
* [Global or per Channel] [Write or Read] Limitation in byte/s.</li><br>
* <tt>PerformanceCounterFactory.NO_LIMIT</tt> (-1)
* stands for no limitation, so the traffic shaping is deactivate (on what you specified).<br>
* You can either change those values with the method <tt>changeConfiguration</tt> in PerformanceCounterFactory or
* directly from the PerformanceCounter method <tt>changeConfiguration</tt>.<br>
* <br>
*
* <li>To activate or deactivate the statistics, you can adjust the delay to a low (not less than 200ms
* for efficiency reasons) or a high value (let say 24H in ms is huge enough to not get the problem)
* or even using <tt>PerformanceCounterFactory.NO_STAT</tt> (-1)</li>.<br>
* And if you don't want to do anything with this statistics, just implement an empty method for
* <tt>PerformanceCounterFactory.accounting(PerformanceCounter)</tt>.<br>
* Again this can be changed either from PerformanceCounterFactory or directly in PerformanceCounter.<br><br>
*
* <li>You can also completely deactivate channel or global PerformanceCounter by setting the boolean to false
* accordingly to your needs in the PerformanceCounterFactory. It will deactivate the global Monitor. For channels monitor,
* it will prevent new monitors to be created (or reversely they will be created for newly connected channels).</li>
* </ul></P><br><br>
*
* <P>So in your application you will create your own PerformanceCounterFactory and setting the values to fit your needs.</P>
* <tt>MyPerformanceCounterFactory myFactory = new MyPerformanceCounter(...);</tt><br><br><br>
* <P>Then you can create your pipeline (using a PipelineFactory since each TrafficShapingHandler must be unique by channel) and adding this handler before
* your MemoryAwareThreadPoolExecutor:</P>
* <tt>pipeline.addLast("MyTrafficShaping",new MyTrafficShapingHandler(myFactory));</tt><br>
* <tt>...</tt><br>
* <tt>pipeline.addLast("MemoryExecutor",new ExecutionHandler(memoryAwareThreadPoolExecutor));</tt><br><br>
*
* <P>TrafficShapingHandler must be unique by channel but however it is still global due to
* the PerformanceCounterFactcory that is shared between all handlers across the channels.</P>
*
*
*
* @apiviz.exclude ^java\.lang\.
*/
package org.jboss.netty.handler.trafficshaping;
|
package org.jnosql.diana.api.column.query;
import org.jnosql.diana.api.column.ColumnCondition;
import org.jnosql.diana.api.column.ColumnDeleteQuery;
/**
* The Column Where whose define the condition in the delete query.
*/
public interface ColumnDeleteWhere {
/**
* Appends a new condition in the select using {@link ColumnCondition#and(ColumnCondition)}
*
* @param condition a condition to be added
* @return the same {@link ColumnDeleteWhere} with the condition appended
* @throws NullPointerException when condition is null
*/
ColumnDeleteWhere and(ColumnCondition condition) throws NullPointerException;
/**
* Appends a new condition in the select using {@link ColumnCondition#or(ColumnCondition)}
*
* @param condition a condition to be added
* @return the same {@link ColumnDeleteWhere} with the condition appended
* @throws NullPointerException when condition is null
*/
ColumnDeleteWhere or(ColumnCondition condition) throws NullPointerException;
/**
* Creates a new instance of {@link ColumnDeleteQuery}
*
* @return a new {@link ColumnDeleteQuery} instance
*/
ColumnDeleteQuery build();
}
|
package org.sample.patron.demo.tasks;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;
import org.sample.patron.demo.entity.ObjectFactory;
import org.sample.patron.demo.entity.User;
import org.sample.patron.demo.entity.UserIdentifier;
import org.sample.patron.demo.entity.UserIdentifier.IdType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Task to correct the Identifiers of a User record.
*
* @author nishen
*/
public class TaskFixUserIdentifiers implements Task
{
private static final Logger log = LoggerFactory.getLogger(TaskFixUserIdentifiers.class);
private Properties config = null;
private String userListFilename = null;
private String identifiersFilename = null;
private String cnFilename = null;
private ObjectFactory of = new ObjectFactory();
// Disable the default empty constructor. We just want to use the
// parameterized one.
@SuppressWarnings("unused")
private TaskFixUserIdentifiers()
{}
/**
* @param args command line args passed in.
* @param config the properties loaded in at run time.
*/
public TaskFixUserIdentifiers(String[] args, Properties config)
{
this.config = config;
// extract relevant command line arguments
if (args != null && args.length > 0)
for (int x = 0; x < args.length; x++)
{
if (args[x].equals("-ids"))
{
if (args.length > (x + 1))
identifiersFilename = args[++x];
}
else if (args[x].equals("-users"))
{
if (args.length > (x + 1))
userListFilename = args[++x];
}
else if (args[x].equals("-cns"))
{
if (args.length > (x + 1))
cnFilename = args[++x];
}
}
log.debug("initialised {}", this.getClass().getCanonicalName());
}
@Override
public void run()
{
log.info("executing task: {}", this.getClass().getSimpleName());
Map<String, String> identifiers = null;
Map<String, String> cns = null;
List<String> userList = null;
if (userListFilename == null)
{
log.error("user list filename required.");
return;
}
if (identifiersFilename == null)
{
log.error("identifiers filename required.");
return;
}
if (cnFilename == null)
{
log.error("cn filename required.");
return;
}
try
{
File userListFile = new File(userListFilename);
userList = getUserList(userListFile);
File idFile = new File(identifiersFilename);
identifiers = getIdentifiers(idFile);
File cnFile = new File(cnFilename);
cns = getCnCaseMapping(cnFile);
}
catch (FileNotFoundException nfe)
{
log.error("cannot find or open file: {}", nfe.getMessage(), nfe);
return;
}
String url = config.getProperty("ws.url.alma");
String key = config.getProperty("ws.url.alma.key");
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
target = target.path("users").queryParam("apikey", key);
for (String oldPrimaryId : userList)
{
log.info("processing user: {}", oldPrimaryId);
String newPrimaryId = identifiers.get(oldPrimaryId.toLowerCase());
if (newPrimaryId == null)
{
log.warn("user partyId not found: {}", oldPrimaryId);
continue;
}
String oneId = cns.get(oldPrimaryId.toLowerCase());
if (oneId == null)
oneId = oldPrimaryId;
WebTarget t = target.path(oldPrimaryId);
User user = t.request(MediaType.APPLICATION_XML_TYPE).get(User.class);
log.info("fetched user: {}", user.getPrimaryId());
// remove PARTY_ID, ONE_ID, INSTITUTION_ID
List<UserIdentifier> idsToRemove = new ArrayList<UserIdentifier>(5);
for (UserIdentifier i : user.getUserIdentifiers().getUserIdentifier())
{
if ("PARTY_ID".equals(i.getIdType().getValue()))
idsToRemove.add(i);
if ("ONE_ID".equals(i.getIdType().getValue()))
idsToRemove.add(i);
if ("INST_ID".equals(i.getIdType().getValue()))
idsToRemove.add(i);
log.info("identifiers [{}]: {}", i.getIdType().getValue(), i.getValue());
}
for (UserIdentifier i : idsToRemove)
user.getUserIdentifiers().getUserIdentifier().remove(i);
// save with oldPrimaryId
JAXBElement<User> jaxbUser = of.createUser(user);
user = t.request(MediaType.APPLICATION_XML).put(Entity.entity(jaxbUser, MediaType.APPLICATION_XML), User.class);
log.info("updated user: {}", user.getPrimaryId());
for (UserIdentifier i : user.getUserIdentifiers().getUserIdentifier())
log.info("identifiers [{}]: {}", i.getIdType().getValue(), i.getValue());
// add new primaryId, oneId
IdType idType = of.createUserIdentifierIdType();
idType.setValue("ONE_ID");
idType.setDesc("ONE_ID");
UserIdentifier userIdentifier = of.createUserIdentifier();
userIdentifier.setIdType(idType);
userIdentifier.setStatus("ACTIVE");
userIdentifier.setValue(oneId);
user.getUserIdentifiers().getUserIdentifier().add(userIdentifier);
user.setPrimaryId(newPrimaryId);
// save with oldPrimaryId
jaxbUser = of.createUser(user);
user = t.request(MediaType.APPLICATION_XML).put(Entity.entity(jaxbUser, MediaType.APPLICATION_XML), User.class);
log.info("updated user: {}", user.getPrimaryId());
}
}
@Override
public Map<String, String> getUsageOptions()
{
Map<String, String> options = new HashMap<String, String>();
options.put("-cns filename", "Common Names from AD");
options.put("-users filename", "list of user identifiers to process");
options.put("-ids filename", "list of OneID mappings to PartyID");
return options;
}
private Map<String, String> getIdentifiers(File file) throws FileNotFoundException
{
Map<String, String> result = new HashMap<String, String>(600000);
Scanner scanner = null;
scanner = new Scanner(file);
scanner.nextLine(); // header line
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
if (line == null || "".equals(line))
continue;
String[] parts = line.split(",");
if (parts == null || parts.length < 2)
continue;
result.put(parts[0].toLowerCase(), parts[1]);
}
scanner.close();
return result;
}
private List<String> getUserList(File file) throws FileNotFoundException
{
List<String> result = new ArrayList<String>(50000);
Scanner scanner = null;
scanner = new Scanner(file);
scanner.nextLine(); // header line
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
if (line == null || "".equals(line))
continue;
String[] parts = line.split(",");
if (parts == null || parts.length < 1)
continue;
result.add(parts[0]);
}
scanner.close();
return result;
}
private Map<String, String> getCnCaseMapping(File file) throws FileNotFoundException
{
Map<String, String> result = new HashMap<String, String>(300000);
Scanner scanner = null;
scanner = new Scanner(file);
scanner.nextLine(); // header line
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
if (line == null || "".equals(line))
continue;
result.put(line.toLowerCase(), line);
}
scanner.close();
return result;
}
}
|
package org.spongepowered.mod.mixin.core.entity;
import net.minecraft.entity.Entity;
import net.minecraftforge.common.util.ITeleporter;
import org.spongepowered.api.event.entity.MoveEntityEvent;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.entity.EntityUtil;
import org.spongepowered.common.interfaces.entity.IMixinEntity;
import org.spongepowered.common.interfaces.world.IMixinTeleporter;
import javax.annotation.Nullable;
@NonnullByDefault
@Mixin(value = Entity.class, priority = 1001)
public abstract class MixinEntity implements IMixinEntity {
@Shadow public net.minecraft.world.World world;
@Shadow public boolean isDead;
@Shadow protected abstract void setSize(float width, float height);
/**
* @author blood - May 30th, 2016
* @author gabizou - May 31st, 2016 - Update for 1.9.4
*
* @reason - rewritten to support {@link MoveEntityEvent.Teleport.Portal}
*
* @param toDimensionId The id of target dimension.
*/
@Nullable
@Overwrite(remap = false)
public net.minecraft.entity.Entity changeDimension(int toDimensionId, ITeleporter teleporter) {
if (!this.world.isRemote && !this.isDead) {
// Sponge Start - Handle teleportation solely in TrackingUtil where everything can be debugged.
return EntityUtil.transferEntityToDimension(this, toDimensionId, (IMixinTeleporter) teleporter);
// Sponge End
}
return null;
}
}
|
package org.supercsv.ext.builder;
import java.lang.annotation.Annotation;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Currency;
import java.util.Locale;
import org.supercsv.cellprocessor.ParseBigDecimal;
import org.supercsv.cellprocessor.ParseDouble;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.ParseLong;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.cellprocessor.ift.DoubleCellProcessor;
import org.supercsv.cellprocessor.ift.LongCellProcessor;
import org.supercsv.cellprocessor.ift.StringCellProcessor;
import org.supercsv.ext.annotation.CsvNumberConverter;
import org.supercsv.ext.cellprocessor.FormatLocaleNumber;
import org.supercsv.ext.cellprocessor.ParseBigInteger;
import org.supercsv.ext.cellprocessor.ParseByte;
import org.supercsv.ext.cellprocessor.ParseFloat;
import org.supercsv.ext.cellprocessor.ParseLocaleNumber;
import org.supercsv.ext.cellprocessor.ParseShort;
import org.supercsv.ext.cellprocessor.constraint.Max;
import org.supercsv.ext.cellprocessor.constraint.Min;
import org.supercsv.ext.cellprocessor.constraint.NumberRange;
import org.supercsv.ext.exception.SuperCsvInvalidAnnotationException;
/**
*
*
* @author T.TSUCHIE
*
*/
public abstract class NumberCellProcessorBuilder<N extends Number & Comparable<N>> extends AbstractCellProcessorBuilder<N> {
protected CsvNumberConverter getAnnotation(final Annotation[] annos) {
if(annos == null || annos.length == 0) {
return null;
}
for(Annotation anno : annos) {
if(anno instanceof CsvNumberConverter) {
return (CsvNumberConverter) anno;
}
}
return null;
}
protected String getPattern(final CsvNumberConverter converterAnno) {
if(converterAnno == null) {
return "";
}
return converterAnno.pattern();
}
protected boolean getLenient(final CsvNumberConverter converterAnno) {
if(converterAnno == null) {
return false;
}
return converterAnno.lenient();
}
protected String getMin(final CsvNumberConverter converterAnno) {
if(converterAnno == null) {
return "";
}
return converterAnno.min();
}
protected String getMax(final CsvNumberConverter converterAnno) {
if(converterAnno == null) {
return "";
}
return converterAnno.max();
}
protected Locale getLocale(final CsvNumberConverter converterAnno) {
if(converterAnno == null) {
return Locale.getDefault();
}
final String language = converterAnno.language();
final String country = converterAnno.country();
if(!language.isEmpty() && !country.isEmpty()) {
return new Locale(language, country);
} else if(!language.isEmpty()) {
return new Locale(language);
}
return Locale.getDefault();
}
protected Currency getCurrency(final CsvNumberConverter converterAnno) {
if(converterAnno == null) {
return null;
} else if(converterAnno.currency().isEmpty()) {
return null;
}
return Currency.getInstance(converterAnno.currency());
}
public static ByteCellProcessorBuilder newByte() {
return new ByteCellProcessorBuilder();
}
public static ShortCellProcessorBuilder newShort() {
return new ShortCellProcessorBuilder();
}
public static IntegerCellProcessorBuilder newInteger() {
return new IntegerCellProcessorBuilder();
}
public static LongCellProcessorBuilder newLong() {
return new LongCellProcessorBuilder();
}
public static FloatCellProcessorBuilder newFloat() {
return new FloatCellProcessorBuilder();
}
public static DoubleCellProcessorBuilder newDouble() {
return new DoubleCellProcessorBuilder();
}
public static BigDecimalCellProcessorBuilder newBigDecimal() {
return new BigDecimalCellProcessorBuilder();
}
public static BigIntegerCellProcessorBuilder newBigInteger() {
return new BigIntegerCellProcessorBuilder();
}
protected CellProcessor prependRangeProcessor(final N min, final N max, final CellProcessor processor) {
CellProcessor cellProcessor = processor;
if(min != null && max != null) {
if(cellProcessor == null) {
cellProcessor = new NumberRange<N>(min, max);
} else {
cellProcessor = new NumberRange<N>(min, max, cellProcessor);
}
} else if(min != null) {
if(cellProcessor == null) {
cellProcessor = new Min<N>(min);
} else {
cellProcessor = new Min<N>(min, cellProcessor);
}
} else if(max != null) {
if(cellProcessor == null) {
cellProcessor = new Max<N>(max);
} else {
cellProcessor = new Max<N>(max, cellProcessor);
}
}
return cellProcessor;
}
protected NumberFormat createNumberFormat(final String pattern, final boolean lenient,
final Currency currency, final DecimalFormatSymbols symbols) {
if(pattern.isEmpty()) {
return null;
}
DecimalFormat value = null;
if(symbols != null) {
value = new DecimalFormat(pattern, symbols);
} else {
value = new DecimalFormat(pattern);
}
value.setParseBigDecimal(true);
if(currency != null) {
value.setCurrency(currency);
}
return value;
}
public static class ByteCellProcessorBuilder extends NumberCellProcessorBuilder<Byte> {
@Override
public CellProcessor buildOutputCellProcessor(final Class<Byte> type, final Annotation[] annos,
final CellProcessor processor, final boolean ignoreValidationProcessor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Byte min = parseNumber(getMin(converterAnno), formatter);
final Byte max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new FormatLocaleNumber(formatter) : new FormatLocaleNumber(formatter, (StringCellProcessor) cellProcessor));
}
if(!ignoreValidationProcessor) {
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
}
return cellProcessor;
}
@Override
public CellProcessor buildInputCellProcessor(final Class<Byte> type, final Annotation[] annos,
final CellProcessor processor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Byte min = parseNumber(getMin(converterAnno), formatter);
final Byte max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new ParseLocaleNumber<Byte>(type, pattern, lenient, currency, symbols) :
new ParseLocaleNumber<Byte>(type, pattern, lenient, currency, symbols, (StringCellProcessor) cellProcessor));
} else {
cellProcessor = (cellProcessor == null ?
new ParseByte() : new ParseByte((LongCellProcessor) cellProcessor));
}
return cellProcessor;
}
protected Byte parseNumber(final String value, final NumberFormat formatter) {
if(value.isEmpty()) {
return null;
}
if(formatter != null) {
try {
return formatter.parse(value).byteValue();
} catch(ParseException e) {
throw new SuperCsvInvalidAnnotationException(
String.format(" value '%s' cannot parse to Byte",
value, formatter), e);
}
}
return Byte.valueOf(value);
}
@Override
public Byte getParseValue(final Class<Byte> type, final Annotation[] annos, final String defaultValue) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
return parseNumber(defaultValue, formatter);
}
}
public static class ShortCellProcessorBuilder extends NumberCellProcessorBuilder<Short> {
@Override
public CellProcessor buildOutputCellProcessor(final Class<Short> type, final Annotation[] annos,
final CellProcessor processor, final boolean ignoreValidationProcessor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Short min = parseNumber(getMin(converterAnno), formatter);
final Short max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new FormatLocaleNumber(formatter) : new FormatLocaleNumber(formatter, (StringCellProcessor) cellProcessor));
}
if(!ignoreValidationProcessor) {
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
}
return cellProcessor;
}
@Override
public CellProcessor buildInputCellProcessor(final Class<Short> type, final Annotation[] annos,
final CellProcessor processor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Short min = parseNumber(getMin(converterAnno), formatter);
final Short max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new ParseLocaleNumber<Short>(type, pattern, lenient, currency, symbols) :
new ParseLocaleNumber<Short>(type, pattern, lenient, currency, symbols, (StringCellProcessor) cellProcessor));
} else {
cellProcessor = (cellProcessor == null ?
new ParseShort() : new ParseShort((LongCellProcessor) cellProcessor));
}
return cellProcessor;
}
protected Short parseNumber(final String value, final NumberFormat formatter) {
if(value.isEmpty()) {
return null;
}
if(formatter != null) {
try {
return formatter.parse(value).shortValue();
} catch(ParseException e) {
throw new SuperCsvInvalidAnnotationException(
String.format(" value '%s' cannot parse to Short",
value, formatter), e);
}
}
return Short.valueOf(value);
}
@Override
public Short getParseValue(final Class<Short> type, final Annotation[] annos, final String defaultValue) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
return parseNumber(defaultValue, formatter);
}
}
public static class IntegerCellProcessorBuilder extends NumberCellProcessorBuilder<Integer> {
@Override
public CellProcessor buildOutputCellProcessor(final Class<Integer> type, final Annotation[] annos,
final CellProcessor processor, final boolean ignoreValidationProcessor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Integer min = parseNumber(getMin(converterAnno), formatter);
final Integer max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new FormatLocaleNumber(formatter) : new FormatLocaleNumber(formatter, (StringCellProcessor) cellProcessor));
}
if(!ignoreValidationProcessor) {
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
}
return cellProcessor;
}
@Override
public CellProcessor buildInputCellProcessor(final Class<Integer> type, final Annotation[] annos,
final CellProcessor processor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Integer min = parseNumber(getMin(converterAnno), formatter);
final Integer max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new ParseLocaleNumber<Integer>(type, pattern, lenient, currency, symbols) :
new ParseLocaleNumber<Integer>(type, pattern, lenient, currency, symbols, (StringCellProcessor) cellProcessor));
} else {
cellProcessor = (cellProcessor == null ?
new ParseInt() : new ParseInt((LongCellProcessor) cellProcessor));
}
return cellProcessor;
}
protected Integer parseNumber(final String value, final NumberFormat formatter) {
if(value.isEmpty()) {
return null;
}
if(formatter != null) {
try {
return formatter.parse(value).intValue();
} catch(ParseException e) {
throw new SuperCsvInvalidAnnotationException(
String.format(" value '%s' cannot parse to Integer",
value, formatter), e);
}
}
return Integer.valueOf(value);
}
@Override
public Integer getParseValue(final Class<Integer> type, final Annotation[] annos, final String defaultValue) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
return parseNumber(defaultValue, formatter);
}
}
public static class LongCellProcessorBuilder extends NumberCellProcessorBuilder<Long> {
@Override
public CellProcessor buildOutputCellProcessor(final Class<Long> type, final Annotation[] annos,
final CellProcessor processor, final boolean ignoreValidationProcessor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Long min = parseNumber(getMin(converterAnno), formatter);
final Long max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new FormatLocaleNumber(formatter) : new FormatLocaleNumber(formatter, (StringCellProcessor) cellProcessor));
}
if(!ignoreValidationProcessor) {
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
}
return cellProcessor;
}
@Override
public CellProcessor buildInputCellProcessor(final Class<Long> type,final Annotation[] annos,
final CellProcessor processor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Long min = parseNumber(getMin(converterAnno), formatter);
final Long max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new ParseLocaleNumber<Long>(type, pattern, lenient, currency, symbols) :
new ParseLocaleNumber<Long>(type, pattern, lenient, currency, symbols, (StringCellProcessor) cellProcessor));
} else {
cellProcessor = (cellProcessor == null ?
new ParseLong() : new ParseLong((LongCellProcessor) cellProcessor));
}
return cellProcessor;
}
protected Long parseNumber(final String value, final NumberFormat formatter) {
if(value.isEmpty()) {
return null;
}
if(formatter != null) {
try {
return formatter.parse(value).longValue();
} catch(ParseException e) {
throw new SuperCsvInvalidAnnotationException(
String.format(" value '%s' cannot parse to Long",
value, formatter), e);
}
}
return Long.valueOf(value);
}
@Override
public Long getParseValue(final Class<Long> type, final Annotation[] annos, final String defaultValue) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
return parseNumber(defaultValue, formatter);
}
}
public static class FloatCellProcessorBuilder extends NumberCellProcessorBuilder<Float> {
@Override
public CellProcessor buildOutputCellProcessor(final Class<Float> type, final Annotation[] annos,
final CellProcessor processor, final boolean ignoreValidationProcessor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Float min = parseNumber(getMin(converterAnno), formatter);
final Float max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new FormatLocaleNumber(formatter) : new FormatLocaleNumber(formatter, (StringCellProcessor) cellProcessor));
}
if(!ignoreValidationProcessor) {
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
}
return cellProcessor;
}
@Override
public CellProcessor buildInputCellProcessor(final Class<Float> type, final Annotation[] annos,
final CellProcessor processor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Float min = parseNumber(getMin(converterAnno), formatter);
final Float max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new ParseLocaleNumber<Float>(type, pattern, lenient, currency, symbols) :
new ParseLocaleNumber<Float>(type, pattern, lenient, currency, symbols, (StringCellProcessor) cellProcessor));
} else {
cellProcessor = (cellProcessor == null ?
new ParseFloat() : new ParseFloat((DoubleCellProcessor) cellProcessor));
}
return cellProcessor;
}
protected Float parseNumber(final String value, final NumberFormat formatter) {
if(value.isEmpty()) {
return null;
}
if(formatter != null) {
try {
return formatter.parse(value).floatValue();
} catch(ParseException e) {
throw new SuperCsvInvalidAnnotationException(
String.format(" value '%s' cannot parse to Float",
value, formatter), e);
}
}
return Float.valueOf(value);
}
@Override
public Float getParseValue(final Class<Float> type, final Annotation[] annos, final String defaultValue) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
return parseNumber(defaultValue, formatter);
}
}
public static class DoubleCellProcessorBuilder extends NumberCellProcessorBuilder<Double> {
@Override
public CellProcessor buildOutputCellProcessor(final Class<Double> type, final Annotation[] annos,
final CellProcessor processor, final boolean ignoreValidationProcessor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Double min = parseNumber(getMin(converterAnno), formatter);
final Double max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new FormatLocaleNumber(formatter) : new FormatLocaleNumber(formatter, (StringCellProcessor) cellProcessor));
}
if(!ignoreValidationProcessor) {
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
}
return cellProcessor;
}
@Override
public CellProcessor buildInputCellProcessor(final Class<Double> type, final Annotation[] annos,
final CellProcessor processor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final Double min = parseNumber(getMin(converterAnno), formatter);
final Double max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new ParseLocaleNumber<Double>(type, pattern, lenient, currency, symbols) :
new ParseLocaleNumber<Double>(type, pattern, lenient, currency, symbols, (StringCellProcessor) cellProcessor));
} else {
cellProcessor = (cellProcessor == null ?
new ParseDouble() : new ParseDouble((DoubleCellProcessor) cellProcessor));
}
return cellProcessor;
}
protected Double parseNumber(final String value, final NumberFormat formatter) {
if(value.isEmpty()) {
return null;
}
if(formatter != null) {
try {
return formatter.parse(value).doubleValue();
} catch(ParseException e) {
throw new SuperCsvInvalidAnnotationException(
String.format(" value '%s' cannot parse to Double",
value, formatter), e);
}
}
return Double.valueOf(value);
}
@Override
public Double getParseValue(final Class<Double> type, final Annotation[] annos, final String defaultValue) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
return parseNumber(defaultValue, formatter);
}
}
public static class BigDecimalCellProcessorBuilder extends NumberCellProcessorBuilder<BigDecimal> {
@Override
public CellProcessor buildOutputCellProcessor(final Class<BigDecimal> type, final Annotation[] annos,
final CellProcessor processor, final boolean ignoreValidationProcessor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final BigDecimal min = parseNumber(getMin(converterAnno), formatter);
final BigDecimal max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new FormatLocaleNumber(formatter) : new FormatLocaleNumber(formatter, (StringCellProcessor) cellProcessor));
}
if(!ignoreValidationProcessor) {
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
}
return cellProcessor;
}
@Override
public CellProcessor buildInputCellProcessor(final Class<BigDecimal> type, final Annotation[] annos,
final CellProcessor processor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final BigDecimal min = parseNumber(getMin(converterAnno), formatter);
final BigDecimal max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new ParseLocaleNumber<BigDecimal>(type, pattern, lenient, currency, symbols) :
new ParseLocaleNumber<BigDecimal>(type, pattern, lenient, currency, symbols, (StringCellProcessor) cellProcessor));
} else {
cellProcessor = (cellProcessor == null ?
new ParseBigDecimal() : new ParseBigDecimal(cellProcessor));
}
return cellProcessor;
}
protected BigDecimal parseNumber(final String value, final NumberFormat formatter) {
if(value.isEmpty()) {
return null;
}
if(formatter != null) {
try {
return (BigDecimal) formatter.parse(value);
} catch(ParseException e) {
throw new SuperCsvInvalidAnnotationException(
String.format(" value '%s' cannot parse to BigDecimal",
value, formatter), e);
}
}
return new BigDecimal(value);
}
@Override
public BigDecimal getParseValue(final Class<BigDecimal> type, final Annotation[] annos, final String defaultValue) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
return parseNumber(defaultValue, formatter);
}
}
public static class BigIntegerCellProcessorBuilder extends NumberCellProcessorBuilder<BigInteger> {
@Override
public CellProcessor buildOutputCellProcessor(final Class<BigInteger> type, final Annotation[] annos,
final CellProcessor processor, final boolean ignoreValidationProcessor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final BigInteger min = parseNumber(getMin(converterAnno), formatter);
final BigInteger max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new FormatLocaleNumber(formatter) : new FormatLocaleNumber(formatter, (StringCellProcessor) cellProcessor));
}
if(!ignoreValidationProcessor) {
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
}
return cellProcessor;
}
@Override
public CellProcessor buildInputCellProcessor(final Class<BigInteger> type, final Annotation[] annos,
final CellProcessor processor) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
final BigInteger min = parseNumber(getMin(converterAnno), formatter);
final BigInteger max = parseNumber(getMax(converterAnno), formatter);
CellProcessor cellProcessor = processor;
cellProcessor = prependRangeProcessor(min, max, cellProcessor);
if(formatter != null) {
cellProcessor = (cellProcessor == null ?
new ParseBigInteger() : new ParseBigInteger(cellProcessor));
} else {
cellProcessor = (cellProcessor == null ?
new ParseLocaleNumber<BigInteger>(type, pattern, lenient, currency, symbols) :
new ParseLocaleNumber<BigInteger>(type, pattern, lenient, currency, symbols, (StringCellProcessor) cellProcessor));
}
return cellProcessor;
}
protected BigInteger parseNumber(final String value, final NumberFormat formatter) {
if(value.isEmpty()) {
return null;
}
if(formatter != null) {
try {
return ((BigDecimal) formatter.parse(value)).toBigIntegerExact();
} catch(ParseException e) {
throw new SuperCsvInvalidAnnotationException(
String.format(" value '%s' cannot parse to BigInteger",
value, formatter), e);
}
}
return new BigInteger(value);
}
@Override
public BigInteger getParseValue(final Class<BigInteger> type, final Annotation[] annos, final String defaultValue) {
final CsvNumberConverter converterAnno = getAnnotation(annos);
final String pattern = getPattern(converterAnno);
final boolean lenient = getLenient(converterAnno);
final Locale locale = getLocale(converterAnno);
final Currency currency = getCurrency(converterAnno);
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
final NumberFormat formatter = createNumberFormat(pattern, lenient, currency, symbols);
return parseNumber(defaultValue, formatter);
}
}
}
|
package org.voltdb.exportclient;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Queue;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.voltcore.utils.CoreUtils;
import org.voltdb.VoltDB;
import org.voltdb.common.Constants;
import org.voltdb.export.AdvertisedDataSource;
import org.voltdb.exportclient.decode.CSVStringDecoder;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.RegionUtils;
import com.amazonaws.services.kinesisfirehose.AmazonKinesisFirehoseClient;
import com.amazonaws.services.kinesisfirehose.model.DescribeDeliveryStreamRequest;
import com.amazonaws.services.kinesisfirehose.model.DescribeDeliveryStreamResult;
import com.amazonaws.services.kinesisfirehose.model.InvalidArgumentException;
import com.amazonaws.services.kinesisfirehose.model.PutRecordBatchRequest;
import com.amazonaws.services.kinesisfirehose.model.PutRecordBatchResponseEntry;
import com.amazonaws.services.kinesisfirehose.model.PutRecordBatchResult;
import com.amazonaws.services.kinesisfirehose.model.Record;
import com.amazonaws.services.kinesisfirehose.model.ResourceNotFoundException;
import com.amazonaws.services.kinesisfirehose.model.ServiceUnavailableException;
import com.google_voltpatches.common.base.Throwables;
import com.google_voltpatches.common.util.concurrent.ListeningExecutorService;
public class KinesisFirehoseExportClient extends ExportClientBase {
private static final ExportClientLogger LOG = new ExportClientLogger();
private Region m_region;
private String m_streamName;
private String m_accessKey;
private String m_secretKey;
private TimeZone m_timeZone;
private String m_recordSeparator;
public static final String ROW_LENGTH_LIMIT = "row.length.limit";
public static final String RECORD_SEPARATOR = "record.separator";
@Override
public void configure(Properties config) throws Exception
{
String regionName = config.getProperty("region","").trim();
if (regionName.isEmpty()) {
throw new IllegalArgumentException("KinesisFirehoseExportClient: must provide a region");
}
m_region = RegionUtils.getRegion(regionName);
m_streamName = config.getProperty("stream.name","").trim();
if (m_streamName.isEmpty()) {
throw new IllegalArgumentException("KinesisFirehoseExportClient: must provide a stream.name");
}
m_accessKey = config.getProperty("access.key","").trim();
if (m_accessKey.isEmpty()) {
throw new IllegalArgumentException("KinesisFirehoseExportClient: must provide an access.key");
}
m_secretKey = config.getProperty("secret.key","").trim();
if (m_secretKey.isEmpty()) {
throw new IllegalArgumentException("KinesisFirehoseExportClient: must provide a secret.key");
}
m_timeZone = TimeZone.getTimeZone(config.getProperty("timezone", VoltDB.REAL_DEFAULT_TIMEZONE.getID()));
m_recordSeparator = config.getProperty(RECORD_SEPARATOR,"\n");
config.setProperty(ROW_LENGTH_LIMIT,
config.getProperty(ROW_LENGTH_LIMIT,Integer.toString(1024000 - m_recordSeparator.length())));
}
@Override
public ExportDecoderBase constructExportDecoder(AdvertisedDataSource source)
{
return new KinesisFirehoseExportDecoder(source);
}
class KinesisFirehoseExportDecoder extends ExportDecoderBase {
private final ListeningExecutorService m_es;
private final CSVStringDecoder m_decoder;
private boolean m_primed = false;
private Queue<List<Record>> m_records;
private List<Record> currentBatch;
private int m_currentBatchSize;
private AmazonKinesisFirehoseClient m_firehoseClient;
public static final int BATCH_NUMBER_LIMIT = 500;
public static final int BATCH_SIZE_LIMIT = 4*1024*1024;
@Override
public ListeningExecutorService getExecutor() {
return m_es;
}
public KinesisFirehoseExportDecoder(AdvertisedDataSource source)
{
super(source);
CSVStringDecoder.Builder builder = CSVStringDecoder.builder();
builder
.dateFormatter(Constants.ODBC_DATE_FORMAT_STRING)
.timeZone(m_timeZone)
.columnNames(source.columnNames)
.columnTypes(source.columnTypes)
;
m_es = CoreUtils.getListeningSingleThreadExecutor(
"Kinesis Firehose Export decoder for partition " + source.partitionId
+ " table " + source.tableName
+ " generation " + source.m_generation, CoreUtils.MEDIUM_STACK_SIZE);
m_decoder = builder.build();
}
private void validateStream() throws RestartBlockException, InterruptedException {
DescribeDeliveryStreamRequest describeHoseRequest = new DescribeDeliveryStreamRequest().
withDeliveryStreamName(m_streamName);
DescribeDeliveryStreamResult describeHoseResult = null;
String status = "UNDEFINED";
describeHoseResult = m_firehoseClient.describeDeliveryStream(describeHoseRequest);
status = describeHoseResult.getDeliveryStreamDescription().getDeliveryStreamStatus();
if("ACTIVE".equalsIgnoreCase(status)){
return;
}
else if("CREATING".equalsIgnoreCase(status)){
Thread.sleep(5000);
validateStream();
}
else {
LOG.error("Cannot use stream %s, responded with %s", m_streamName, status);
throw new RestartBlockException(true);
}
}
final void checkOnFirstRow() throws RestartBlockException {
if (!m_primed) try {
m_firehoseClient = new AmazonKinesisFirehoseClient(
new BasicAWSCredentials(m_accessKey, m_secretKey));
m_firehoseClient.setRegion(m_region);
validateStream();
} catch (AmazonServiceException | InterruptedException e) {
LOG.error("Unable to instantiate a Amazon Kinesis Firehose client", e);
throw new RestartBlockException("Unable to instantiate a Amazon Kinesis Firehose client", e, true);
}
m_primed = true;
}
@Override
public boolean processRow(int rowSize, byte[] rowData) throws RestartBlockException {
if (!m_primed) checkOnFirstRow();
Record record = new Record();
try {
final ExportRowData rd = decodeRow(rowData);
String decoded = m_decoder.decode(null, rd.values) + m_recordSeparator; // add a record separator ;
record.withData(ByteBuffer.wrap(decoded.getBytes(StandardCharsets.UTF_8)));
} catch(IOException e) {
LOG.error("Failed to build record", e);
throw new RestartBlockException("Failed to build record", e, true);
}
// PutRecordBatchRequest can not contain more than 500 records
// And up to a limit of 4 MB for the entire request
if (((m_currentBatchSize + rowSize) > BATCH_SIZE_LIMIT) || (currentBatch.size() >= BATCH_NUMBER_LIMIT)) {
// roll to next batch
m_records.add(currentBatch);
m_currentBatchSize = 0;
currentBatch = new LinkedList<Record>();
}
currentBatch.add(record);
m_currentBatchSize += rowSize;
return true;
}
@Override
public void sourceNoLongerAdvertised(AdvertisedDataSource source)
{
if (m_firehoseClient != null) m_firehoseClient.shutdown();
m_es.shutdown();
try {
m_es.awaitTermination(365, TimeUnit.DAYS);
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
@Override
public void onBlockStart() throws RestartBlockException
{
if (!m_primed) checkOnFirstRow();
m_records = new LinkedList<List<Record>>();
m_currentBatchSize = 0;
currentBatch = new LinkedList<Record>();
}
@Override
public void onBlockCompletion() throws RestartBlockException
{
// add last batch
if (!currentBatch.isEmpty()) {
// roll to next batch
m_records.add(currentBatch);
m_currentBatchSize = 0;
currentBatch = new LinkedList<Record>();
}
try {
List<Record> recordsList;
int sleepTime = 0;
while (!m_records.isEmpty()) {
if (sleepTime > 0)
Thread.sleep(sleepTime);
recordsList = m_records.poll();
PutRecordBatchRequest batchRequest = new PutRecordBatchRequest().
withDeliveryStreamName(m_streamName).
withRecords(recordsList);
PutRecordBatchResult res = m_firehoseClient.putRecordBatch(batchRequest);
if (res.getFailedPutCount() > 0) {
for (PutRecordBatchResponseEntry entry : res.getRequestResponses()) {
if (entry.getErrorMessage() != null && !entry.getErrorMessage().contains("Slow down.")) {
LOG.error("Record failed with response: %s", entry.getErrorMessage());
throw new RestartBlockException(true);
}
}
sleepTime = sleepTime == 0 ? 1000 : sleepTime*2;
} else {
sleepTime = sleepTime == 0 ? 0 : sleepTime-10;
}
}
} catch (ResourceNotFoundException | InvalidArgumentException | ServiceUnavailableException | InterruptedException e) {
LOG.error("Failed to send record batch", e);
throw new RestartBlockException("Failed to send record batch", e, true);
}
}
}
}
|
package ratpack.zipkin.internal;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.http.HttpServerHandler;
import brave.http.HttpTracing;
import brave.propagation.TraceContext;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.http.Headers;
import ratpack.http.HttpMethod;
import ratpack.http.Request;
import ratpack.http.Response;
import ratpack.http.Status;
import ratpack.path.PathBinding;
import ratpack.zipkin.ServerRequest;
import ratpack.zipkin.ServerResponse;
import ratpack.zipkin.ServerTracingHandler;
import java.util.Optional;
/**
* {@link Handler} for Zipkin tracing.
*/
public final class DefaultServerTracingHandler implements ServerTracingHandler {
private final Tracing tracing;
private final HttpServerHandler<ServerRequest, ServerResponse> handler;
private final TraceContext.Extractor<ServerRequest> extractor;
private final Logger logger = LoggerFactory.getLogger(DefaultServerTracingHandler.class);
@Inject
public DefaultServerTracingHandler(final HttpTracing httpTracing) {
this.tracing = httpTracing.tracing();
this.handler = HttpServerHandler.<ServerRequest, ServerResponse>create(httpTracing, new ServerHttpAdapter());
this.extractor = tracing.propagation().extractor((ServerRequest r, String name) -> r.getHeaders().get(name));
}
@Override
public void handle(Context ctx) throws Exception {
ServerRequest request = new ServerRequestImpl(ctx.getRequest());
final Span span = handler.handleReceive(extractor, request);
//place the Span in scope so that downstream code (e.g. Ratpack handlers
//further on in the chain) can see the Span.
final Tracer.SpanInScope scope = tracing.tracer().withSpanInScope(span);
ctx.getResponse().beforeSend(response -> {
ServerResponse serverResponse = new ServerResponseImpl(response, request, ctx.getPathBinding());
handler.handleSend(serverResponse, null, span);
scope.close();
});
ctx.next();
}
private static class ServerRequestImpl implements ServerRequest {
private final Request request;
private ServerRequestImpl(final Request request) {
this.request = request;
}
@Override
public HttpMethod getMethod() {
return request.getMethod();
}
@Override
public String getUri() {
return request.getUri();
}
@Override
public String getPath() {
return request.getPath();
}
@Override
public Headers getHeaders() {
return request.getHeaders();
}
}
private static class ServerResponseImpl implements ServerResponse {
private final Response response;
private final ServerRequest request;
private final PathBinding pathBinding;
public ServerResponseImpl(final Response response, final ServerRequest request, final PathBinding pathBinding) {
this.response = response;
this.request = request;
this.pathBinding = pathBinding;
}
@Override
public Optional<PathBinding> pathBinding() {
return Optional.ofNullable(pathBinding);
}
@Override
public ServerRequest getRequest() {
return this.request;
}
@Override
public Status getStatus() {
return this.response.getStatus();
}
}
}
|
package ru.VirtaMarketAnalyzer.ml.js;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weka.classifiers.functions.LinearRegression;
import weka.core.Instances;
import weka.core.Utils;
import static ru.VirtaMarketAnalyzer.ml.js.ClassifierToJs.getPrivateFieldValue;
public final class LinearRegressionToJson {
private static final Logger logger = LoggerFactory.getLogger(LinearRegressionToJson.class);
public static String toString(final LinearRegression classifier) throws Exception {
final Instances m_TransformedData = (Instances) getPrivateFieldValue(classifier.getClass(), classifier, "m_TransformedData");
final int m_ClassIndex = (int) getPrivateFieldValue(classifier.getClass(), classifier, "m_ClassIndex");
final boolean[] m_SelectedAttributes = (boolean[]) getPrivateFieldValue(classifier.getClass(), classifier, "m_SelectedAttributes");
final double[] m_Coefficients = (double[]) getPrivateFieldValue(classifier.getClass(), classifier, "m_Coefficients");
if (m_TransformedData == null) {
return "Linear Regression: No model built yet.";
}
try {
StringBuffer text = new StringBuffer();
int column = 0;
boolean first = true;
text.append("\nLinear Regression Model\n\n");
text.append(m_TransformedData.classAttribute().name() + " =\n\n");
for (int i = 0; i < m_TransformedData.numAttributes(); i++) {
if ((i != m_ClassIndex) && (m_SelectedAttributes[i])) {
if (!first) {
text.append(" +\n");
} else {
first = false;
}
text.append(Utils.doubleToString(m_Coefficients[column], 12, 4) + " * ");
text.append(m_TransformedData.attribute(i).name());
column++;
}
}
text.append(" +\n" + Utils.doubleToString(m_Coefficients[column], 12, 4));
return text.toString();
} catch (Exception e) {
return "Can't print Linear Regression!";
}
}
public static String toJson(final LinearRegression classifier) throws Exception {
final Instances m_TransformedData = (Instances) getPrivateFieldValue(classifier.getClass(), classifier, "m_TransformedData");
final int m_ClassIndex = (int) getPrivateFieldValue(classifier.getClass(), classifier, "m_ClassIndex");
final boolean[] m_SelectedAttributes = (boolean[]) getPrivateFieldValue(classifier.getClass(), classifier, "m_SelectedAttributes");
final double[] m_Coefficients = (double[]) getPrivateFieldValue(classifier.getClass(), classifier, "m_Coefficients");
if (m_TransformedData == null) {
throw new Exception("Linear Regression: No model built yet.");
}
final StringBuffer text = new StringBuffer();
final StringBuffer json = new StringBuffer();
int column = 0;
boolean first = true;
text.append("\nLinear Regression Model\n\n");
text.append(m_TransformedData.classAttribute().name() + " =\n\n");
json.append("{");
json.append("\"name\": \"" + m_TransformedData.classAttribute().name() + "\"");
json.append(",\"attrs\": [");
for (int i = 0; i < m_TransformedData.numAttributes(); i++) {
if ((i != m_ClassIndex) && (m_SelectedAttributes[i])) {
if (!first) {
text.append(" +\n");
json.append(",");
} else {
first = false;
}
final String coef = Utils.doubleToString(m_Coefficients[column], 12, 4).trim();
text.append(coef + " * ");
text.append(m_TransformedData.attribute(i).name());
final String[] tmp = m_TransformedData.attribute(i).name().split("=");
final String attrName = tmp[0];
json.append("{\"name\": \"" + attrName + "\"");
json.append(",\"coef\": " + coef);
if (tmp.length == 1) {
json.append(",\"values\": []");
} else if (tmp.length == 2) {
final String attrValues = tmp[1];
final String[] attrValue = attrValues.split(",");
json.append(",\"values\": [");
for (int i1 = 0; i1 < attrValue.length; i1++) {
final String value = attrValue[i1];
if (i1 > 0) {
json.append(",");
}
json.append("\"" + value + "\"");
}
json.append("]");
} else {
throw new Exception("tmp.length = " + tmp.length);
}
column++;
json.append("}");
}
}
json.append("]");
json.append(",\"coef\": " + Utils.doubleToString(m_Coefficients[column], 12, 4).trim());
json.append("}");
text.append(" +\n" + Utils.doubleToString(m_Coefficients[column], 12, 4));
//logger.info(json.toString());
return json.toString();
}
}
|
package uk.ac.ebi.ddi.similarityCalculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uk.ac.ebi.ddi.annotation.utils.Constants;
import uk.ac.ebi.ddi.ebe.ws.dao.client.dataset.DatasetWsClient;
import uk.ac.ebi.ddi.ebe.ws.dao.client.domain.DomainWsClient;
import uk.ac.ebi.ddi.ebe.ws.dao.client.europmc.CitationClient;
import uk.ac.ebi.ddi.ebe.ws.dao.model.common.Entry;
import uk.ac.ebi.ddi.ebe.ws.dao.model.common.QueryResult;
import uk.ac.ebi.ddi.ebe.ws.dao.model.domain.Domain;
import uk.ac.ebi.ddi.ebe.ws.dao.model.domain.DomainList;
import uk.ac.ebi.ddi.ebe.ws.dao.model.europmc.CitationResponse;
import uk.ac.ebi.ddi.service.db.model.dataset.*;
import uk.ac.ebi.ddi.service.db.model.similarity.Citations;
import uk.ac.ebi.ddi.service.db.model.similarity.EBISearchPubmedCount;
import uk.ac.ebi.ddi.service.db.model.similarity.ReanalysisData;
import uk.ac.ebi.ddi.service.db.service.dataset.DatasetCountService;
import uk.ac.ebi.ddi.service.db.service.dataset.IDatasetService;
import uk.ac.ebi.ddi.service.db.service.dataset.IDatasetSimilarsService;
import uk.ac.ebi.ddi.service.db.service.similarity.*;
import uk.ac.ebi.ddi.service.db.utils.DatasetSimilarsType;
import uk.ac.ebi.ddi.similarityCalculator.utils.SimilarityConstants;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class SimilarityCounts {
Integer startDataset = 0;
Integer numberOfDataset = 2000;
Integer numberOfCitations = 500;
@Autowired
CitationClient citationClient;
@Autowired
DatasetWsClient datasetWsClient;
@Autowired
ICitationService citationService;
@Autowired
IDatasetService datasetService;
@Autowired
DatasetCountService datasetCountService;
@Autowired
IDatasetStatInfoService datasetStatInfoService;
@Autowired
IReanalysisDataService reanalysisDataService;
@Autowired
IEBIPubmedSearchService ebiPubmedSearchService;
@Autowired
IDatasetSimilarsService similarsService;
@Autowired
DomainWsClient domainWsClient;
private static final Logger LOGGER = LoggerFactory.getLogger(SimilarityCounts.class);
public void getCitationCount(String database, String accession, List<String> secondaryAccession) {
try {
/* List<CitationResponse> citations = new ArrayList<>();
CitationResponse citationResponse = citationClient.getCitations(accession,numberOfCitations);
citations.add(citationResponse);
if(citationResponse.count > numberOfCitations){
while(citationResponse.count % numberOfCitations > 0){
CitationResponse allCitations = citationClient.getCitations(accession,numberOfCitations);
citations.add(allCitations);
}
}
//CitationResponse secondaryCitations = new CitationResponse();
if(!secondaryAccession.isEmpty()) {
secondaryAccession.stream().forEach(acc ->{
CitationResponse secondaryCitations = citationClient.getCitations(acc,);
Dataset dataset = datasetService.read(accession, database);
dataset = addCitationData(dataset, citationResponse, secondaryCitations);
datasetService.update(dataset.getId(),dataset);}
);
return;
}*/
final Dataset dataset = datasetService.read(accession, database);
Set<String> primaryCitationIds = getCitationsSet(accession, dataset);
if (!secondaryAccession.isEmpty()) {
secondaryAccession.forEach(acc -> {
/* CitationResponse secondaryCitations = citationClient.getCitations(acc,);
Dataset dataset = datasetService.read(accession, database);
dataset = addCitationData(dataset, citationResponse, secondaryCitations);
datasetService.update(dataset.getId(),dataset);}*/
Set<String> secondaryCitationIds = getCitationsSet(acc, dataset);
primaryCitationIds.addAll(secondaryCitationIds);
});
//return;
}
addCitationData(dataset, primaryCitationIds);
//datasetService.update(dataset.getId(),dataset);
} catch (Exception ex) {
LOGGER.error("Exception occurred when getting dataset {}, ", accession, ex);
}
}
public Dataset addCitationData(Dataset dataset, Set<String> allCitationIds) {
Dataset updateDataset = datasetService.read(dataset.getAccession(), dataset.getDatabase());
Citations citations = new Citations();
citations.setAccession(dataset.getAccession());
citations.setDatabase(dataset.getDatabase());
citations.setPubmedId(allCitationIds);
citations.setPubmedCount(allCitationIds.size());
citationService.saveCitation(citations);
if (dataset.getScores() != null) {
updateDataset.getScores().setCitationCount(allCitationIds.size());
} else {
Scores scores = new Scores();
scores.setCitationCount(allCitationIds.size());
updateDataset.setScores(scores);
}
HashSet<String> count = new HashSet<>();
count.add(String.valueOf(allCitationIds.size()));
updateDataset.getAdditional().put(Constants.CITATION_FIELD, count);
datasetService.update(updateDataset.getId(), updateDataset);
return dataset;
}
public void addAllCitations() {
try {
for (int i = startDataset; i < datasetService.getDatasetCount() / numberOfDataset; i = i + 1) {
LOGGER.info("value of i is" + i);
datasetService.readAll(i, numberOfDataset).getContent()
.forEach(dt -> getCitationCount(
dt.getDatabase(), dt.getAccession(),
dt.getAdditional().containsKey(Constants.SECONDARY_ACCESSION) ?
new ArrayList<String>(dt.getAdditional().get(Constants.SECONDARY_ACCESSION)) :
new ArrayList<String>()));
}
} catch (Exception ex) {
LOGGER.error("Exception occurred, ", ex);
}
}
public void addSearchCounts(String accession, String pubmedId, String database) {
LOGGER.info("inside add search counts ");
int size = 20;
int searchCount;
try {
HashMap<String, Integer> domainMap = new HashMap<>();
Dataset dataset = datasetService.read(accession, database);
List<String> filteredDomains = new ArrayList<>();
Set<String> secondaryAccession = dataset.getAdditional().get(Constants.SECONDARY_ACCESSION);
String query = pubmedId;
query = (query == null || query.isEmpty()) ? "*:*" : query;
QueryResult queryResult = null;
DomainList domainList = domainWsClient.getDomainByName(SimilarityConstants.OMICS_DOMAIN);
List<String> domains = Arrays.stream(domainList.list).map(Domain::getId).collect(Collectors.toList());
domains.add(SimilarityConstants.ATLAS_GENES);
domains.add(SimilarityConstants.ATLAS_GENES_DIFFERENTIAL);
domains.add("metabolights");
if (!pubmedId.equals("") && !pubmedId.equals("none") && !pubmedId.equals("0")) {
query = "PUBMED:" + query + " OR MEDLINE:" + query + " OR PMID:" + query;
queryResult = datasetWsClient.getDatasets(Constants.ALL_DOMAIN, query,
Constants.DATASET_SUMMARY, Constants.PUB_DATE_FIELD, "descending", 0, size, 10);
}
// int leftCount = queryResult!=null ? queryResult.getDomains().stream().flatMap(
// dtl -> Arrays.stream(dtl.getSubdomains())).
// map(dtl -> Arrays.stream(dtl.getSubdomains())).
// flatMap(sbdt ->sbdt.filter(dt -> !domains.contains(dt.getId()))).mapToInt(dtf ->{
// //filteredDomains.add(dtf.getId() + "~" +dtf.getHitCount());
// return dtf.getHitCount();}).sum():0;
QueryResult queryAccessionResult = datasetWsClient.getDatasets(Constants.ALL_DOMAIN, accession,
Constants.DATASET_SUMMARY, Constants.PUB_DATE_FIELD, "descending", 0, size, 10);
searchCount = queryResult != null && queryResult.getCount() > 0 ? queryResult.getDomains()
.stream()
.flatMap(dtl -> Arrays.stream(dtl.getSubdomains()))
.map(dtl -> Arrays.stream(dtl.getSubdomains()))
.flatMap(sbdt -> sbdt.filter(dt -> !domains.contains(dt.getId())))
.mapToInt(dtf -> {
updateKeyValue(dtf.getId().toLowerCase(), dtf.getHitCount(), domainMap);
//filteredDomains.add(dtf.getId() + "~" +dtf.getHitCount());
return dtf.getHitCount(); })
.sum() : 0;
if (queryAccessionResult != null && queryAccessionResult.getCount() > 0) {
searchCount = searchCount + queryAccessionResult.getDomains()
.parallelStream()
.flatMap(dtl -> Arrays.stream(dtl.getSubdomains()))
.map(dtl -> Arrays.stream(dtl.getSubdomains()))
.flatMap(sbdt -> sbdt.filter(dt -> !domains.contains(dt.getId())))
.mapToInt(dtf -> {
updateKeyValue(dtf.getId().toLowerCase(), dtf.getHitCount(), domainMap);
//filteredDomains.add(dtf.getId() + "~" +dtf.getHitCount());
return dtf.getHitCount(); })
.sum();
}
int allCounts = secondaryAccession != null ? secondaryAccession.parallelStream().mapToInt(dt -> {
QueryResult querySecondaryResult = datasetWsClient.getDatasets(Constants.ALL_DOMAIN, dt,
Constants.DATASET_SUMMARY, Constants.PUB_DATE_FIELD, "descending", 0, size, 10);
return querySecondaryResult.getDomains()
.stream()
.flatMap(dtl -> Arrays.stream(dtl.getSubdomains()))
.map(dtl -> Arrays.stream(dtl.getSubdomains()))
.flatMap(sbdt -> sbdt.filter(dtls -> !domains.contains(dtls.getId())))
.mapToInt(dtf -> {
updateKeyValue(dtf.getId().toLowerCase(), dtf.getHitCount(), domainMap);
//filteredDomains.add(dtf.getId() + "~" +dtf.getHitCount());
return dtf.getHitCount(); })
.sum();
//return querySecondaryResult.getCount();
}).sum() : 0;
searchCount = searchCount + allCounts;
//queryResult.getCount();
Set<String> matchDataset = new HashSet<>();
if (queryResult != null && queryResult.getEntries() != null) {
matchDataset = Arrays.stream(queryResult.getEntries())
.filter(dt -> !dt.getId().equals(accession))
.map(Entry::getId).collect(Collectors.toSet());
}
if (dataset.getCrossReferences() != null) {
Collection<Set<String>> crossReferences = dataset.getCrossReferences().values();
searchCount = searchCount + crossReferences.stream().mapToInt(Set::size).sum();
dataset.getCrossReferences().keySet().forEach(dt -> {
updateKeyValue(dt.toLowerCase(), dataset.getCrossReferences().get(dt).size(), domainMap);
});
}
Set<String> domainSet = domainMap.entrySet().parallelStream()
.map(dt -> dt.getKey() + "~" + dt.getValue()).collect(Collectors.toSet());
EBISearchPubmedCount ebiSearchPubmedCount = new EBISearchPubmedCount();
ebiSearchPubmedCount.setAccession(accession);
ebiSearchPubmedCount.setPubmedCount(searchCount);
Map<String, Set<String>> pubmedDatasets = new HashMap<String, Set<String>>();
pubmedDatasets.put(pubmedId, matchDataset);
ebiSearchPubmedCount.setPubmedDatasetList(pubmedDatasets);
ebiPubmedSearchService.saveEbiSearchPubmed(ebiSearchPubmedCount);
//Dataset dataset = datasetService.read(accession,database);
if (dataset.getScores() != null) {
dataset.getScores().setSearchCount(searchCount);
} else {
Scores scores = new Scores();
scores.setSearchCount(searchCount);
dataset.setScores(scores);
}
HashSet<String> count = new HashSet<>();
count.add(String.valueOf(searchCount));
dataset.getAdditional().put(Constants.SEARCH_FIELD, count);
dataset.getAdditional().put(Constants.SEARCH_DOMAIN, domainSet);
datasetService.update(dataset.getId(), dataset);
} catch (Exception ex) {
LOGGER.error("Exception occurred, query is " + pubmedId + " dataset is " + accession + ", ", ex);
}
}
public Map<String, Integer> updateKeyValue(String key, Integer value, Map<String, Integer> domainMap) {
if (domainMap.containsKey(key)) {
Integer updatedValue = domainMap.get(key);
updatedValue = updatedValue + value;
domainMap.put(key, updatedValue);
} else {
domainMap.put(key, value);
}
return domainMap;
}
public void saveReanalysisCount() {
List<ReanalysisData> reanalysisData = datasetStatInfoService.reanalysisCount();
reanalysisData.parallelStream().forEach(dt -> reanalysisDataService.saveReanalysis(dt));
}
public void saveSearchcounts() {
try {
for (int i = startDataset; i < datasetService.getDatasetCount() / numberOfDataset; i = i + 1) {
datasetService.readAll(i, numberOfDataset).getContent()
.parallelStream()
.map(data -> {
if (data.getCrossReferences() != null
&& data.getCrossReferences().get(Constants.PUBMED_FIELD) != null) {
data.getCrossReferences().get(Constants.PUBMED_FIELD)
.forEach(dta -> addSearchCounts(data.getAccession(), dta, data.getDatabase()));
} else {
addSearchCounts(data.getAccession(), "", data.getDatabase());
}
return "";
}).count();
// datasetService.readAll(i, numberOfDataset).getContent().parallelStream()
// .filter(data -> data.getCrossReferences() != null
// && data.getCrossReferences().get(Constants.PUBMED_FIELD) != null)
// .forEach(dt -> dt.getCrossReferences().get(Constants.PUBMED_FIELD)
// .forEach(dta -> addSearchCounts(dt.getAccession(), dta, dt.getDatabase())));
//Thread.sleep(3000);
}
} catch (Exception ex) {
LOGGER.error("error inside savesearch count exception message is " + ex.getMessage());
}
}
public void saveLeftSearchcounts() {
try {
long count = 0;
int[] iarr = {0};
int pages = datasetService.getWithoutSearchDomains(0, numberOfDataset).getTotalPages();
for (int i = startDataset; i < pages; i = i + 1) {
System.out.println("page number is " + i);
datasetService.getWithoutSearchDomains(i, numberOfDataset).getContent().parallelStream()
.map(data -> {
if (data.getCrossReferences() != null
&& data.getCrossReferences().get(Constants.PUBMED_FIELD) != null) {
data.getCrossReferences().get(Constants.PUBMED_FIELD).
forEach(dta -> addSearchCounts(data.getAccession(), dta, data.getDatabase()));
} else {
addSearchCounts(data.getAccession(), "", data.getDatabase());
}
return "";
}).count();
//Thread.sleep(3000);
}
System.out.println(count);
} catch (Exception ex) {
LOGGER.error("error inside savesearch count exception message is " + ex.getMessage());
}
}
public void getPageRecords() {
for (int i = startDataset; i < datasetService.getDatasetCount() / numberOfDataset; i = i + 1) {
//System.out.println("value of i is" + i);
datasetService.readAll(i, numberOfDataset).getContent().stream().
forEach(dt -> System.out.print(dt.getAccession()));
}
}
public void renalyseBioModels() {
List<Dataset> datasets = datasetService.findByDatabaseBioModels(Constants.BIOMODELS_DATABASE);
datasets.parallelStream().forEach(data -> addSimilarDataset(
data.getAccession(),
data.getDatabase(),
data.getCrossReferences().get("biomodels__db")));
}
public void addSimilarDataset(String accession, String database, Set<String> similarAccession) {
DatasetSimilars datasetSimilars = new DatasetSimilars();
datasetSimilars.setAccession(accession);
datasetSimilars.setDatabase(database);
Set<SimilarDataset> similarDatasets = new HashSet<SimilarDataset>();
for (String similarAcc : similarAccession) {
List<Dataset> dataset = datasetService.findByAccession(similarAccession.iterator().next());
if (dataset.size() > 0) {
for (Dataset data : dataset) {
SimilarDataset similar = new SimilarDataset(data, DatasetSimilarsType.REANALYSIS_OF.getType());
similarDatasets.add(similar);
}
}
}
datasetSimilars.setSimilars(similarDatasets);
similarsService.save(datasetSimilars);
}
public void renalysedByBioModels() {
List<Dataset> datasets = datasetService.findByDatabaseBioModels(Constants.BIOMODELS_DATABASE);
datasets.parallelStream().forEach(data -> addSimilarDataset(
data.getAccession(), data.getDatabase(), data.getCrossReferences().get("biomodels__db")));
}
public Set<String> getCitationsSet(String accession, Dataset dataset) {
List<CitationResponse> citations = new ArrayList<>();
Set<String> primaryCit = new HashSet<String>();
int numberOfPages = 0;
CitationResponse primaryCitation = citationClient.getCitations(accession, numberOfCitations, "*");
primaryCit.addAll(Arrays.stream(primaryCitation.citations.get("result"))
.filter(data -> (dataset.getCrossReferences() != null
&& dataset.getCrossReferences().get(Constants.PUBMED_FIELD) != null
&& !dataset.getCrossReferences().get(Constants.PUBMED_FIELD).contains(data.pubmedId)))
.map(dt -> dt.pubmedId).collect(Collectors.toSet()));
if (primaryCitation.count > numberOfCitations) {
while (primaryCitation.count / numberOfCitations - numberOfPages > 0) {
primaryCitation = citationClient.getCitations(accession, numberOfCitations, primaryCitation.cursorMark);
primaryCit.addAll(Arrays.stream(primaryCitation.citations.get("result"))
.filter(data -> (dataset.getCrossReferences() != null
&& dataset.getCrossReferences().get(Constants.PUBMED_FIELD) != null
&& !dataset.getCrossReferences().get(Constants.PUBMED_FIELD).contains(data.pubmedId)))
.map(dt -> dt.pubmedId).collect(Collectors.toSet()));
numberOfPages++;
}
}
return primaryCit;
}
public void addReanalysisKeyword() {
reanalysisDataService.updateReanalysisKeywords();
}
}
|
package org.csstudio.swt.xygraph.figures;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.csstudio.swt.xygraph.linearscale.Range;
import org.csstudio.swt.xygraph.linearscale.AbstractScale.LabelSide;
import org.csstudio.swt.xygraph.linearscale.LinearScale.Orientation;
import org.csstudio.swt.xygraph.undo.OperationsManager;
import org.csstudio.swt.xygraph.undo.ZoomCommand;
import org.csstudio.swt.xygraph.undo.ZoomType;
import org.csstudio.swt.xygraph.util.Log10;
import org.csstudio.swt.xygraph.util.XYGraphMediaFactory;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.SWTGraphics;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
/**
* XY-Graph Figure.
* @author Xihui Chen
* @author Kay Kasemir (performStagger)
*/
public class XYGraph extends Figure{
private static final int GAP = 2;
public final static Color WHITE_COLOR = ColorConstants.white;
public final static Color BLACK_COLOR = ColorConstants.black;
/** Default colors for newly added item, used over when reaching the end.
* <p>
* Very hard to find a long list of distinct colors.
* This list is definitely too short...
*/
final public static RGB[] DEFAULT_TRACES_COLOR =
{
new RGB( 21, 21, 196), // blue
new RGB(242, 26, 26), // red
new RGB( 33, 179, 33), // green
new RGB( 0, 0, 0), // black
new RGB(128, 0, 255), // violett
new RGB(255, 170, 0), // (darkish) yellow
new RGB(255, 0, 240), // pink
new RGB(243, 132, 132), // peachy
new RGB( 0, 255, 11), // neon green
new RGB( 0, 214, 255), // neon blue
new RGB(114, 40, 3), // brown
new RGB(219, 128, 4), // orange
};
private int traceNum = 0;
private boolean transparent = false;
private boolean showLegend = true;
private Map<Axis, Legend> legendMap;
/** Graph title. Should never be <code>null</code> because
* otherwise the ToolbarArmedXYGraph's GraphConfigPage
* can crash.
*/
private String title = "";
private Color titleColor;
private Label titleLabel;
private List<Axis> xAxisList;
private List<Axis> yAxisList;
private PlotArea plotArea;
// TODO Clients can set these to null. Should these be 'final'? Or provider getter?
public Axis primaryXAxis;
public Axis primaryYAxis;
private OperationsManager operationsManager;
private ZoomType zoomType;
/**
* Constructor.
*/
public XYGraph() {
setOpaque(!transparent);
legendMap = new LinkedHashMap<Axis, Legend>();
titleLabel = new Label();
setTitleFont(XYGraphMediaFactory.getInstance().getFont(
new FontData("Arial", 12, SWT.BOLD)));
//titleLabel.setVisible(false);
xAxisList = new ArrayList<Axis>();
yAxisList = new ArrayList<Axis>();
plotArea = new PlotArea(this);
getPlotArea().setOpaque(!transparent);
add(titleLabel);
add(plotArea);
primaryYAxis = new Axis("Y-Axis", true);
primaryYAxis.setOrientation(Orientation.VERTICAL);
primaryYAxis.setTickLableSide(LabelSide.Primary);
primaryYAxis.setAutoScaleThreshold(0.1);
addAxis(primaryYAxis);
primaryXAxis = new Axis("X-Axis", false);
primaryXAxis.setOrientation(Orientation.HORIZONTAL);
primaryXAxis.setTickLableSide(LabelSide.Primary);
addAxis(primaryXAxis);
operationsManager = new OperationsManager();
}
@Override
public boolean isOpaque() {
return false;
}
@Override
protected void layout() {
Rectangle clientArea = getClientArea().getCopy();
boolean hasRightYAxis = false;
boolean hasTopXAxis = false;
boolean hasLeftYAxis = false;
boolean hasBottomXAxis = false;
if(titleLabel != null && titleLabel.isVisible() && !(titleLabel.getText().length() <= 0)){
Dimension titleSize = titleLabel.getPreferredSize();
titleLabel.setBounds(new Rectangle(clientArea.x + clientArea.width/2 - titleSize.width/2,
clientArea.y, titleSize.width, titleSize.height));
clientArea.y += titleSize.height + GAP;
clientArea.height -= titleSize.height + GAP;
}
if(showLegend){
List<Integer> rowHPosList = new ArrayList<Integer>();
List<Dimension> legendSizeList = new ArrayList<Dimension>();
List<Integer> rowLegendNumList = new ArrayList<Integer>();
List<Legend> legendList = new ArrayList<Legend>();
Object[] yAxes = legendMap.keySet().toArray();
int hPos = 0;
int rowLegendNum = 0;
for(int i = 0; i< yAxes.length; i++){
Legend legend = legendMap.get(yAxes[i]);
if(legend != null && legend.isVisible()){
legendList.add(legend);
Dimension legendSize = legend.getPreferredSize(clientArea.width, clientArea.height);
legendSizeList.add(legendSize);
if((hPos+legendSize.width + GAP) > clientArea.width){
if(rowLegendNum ==0)
break;
rowHPosList.add(clientArea.x + (clientArea.width-hPos)/2);
rowLegendNumList.add(rowLegendNum);
rowLegendNum = 1;
hPos = legendSize.width + GAP;
clientArea.height -=legendSize.height +GAP;
if(i==yAxes.length-1){
hPos =legendSize.width + GAP;
rowLegendNum = 1;
rowHPosList.add(clientArea.x + (clientArea.width-hPos)/2);
rowLegendNumList.add(rowLegendNum);
clientArea.height -=legendSize.height +GAP;
}
}else{
hPos+=legendSize.width + GAP;
rowLegendNum++;
if(i==yAxes.length-1){
rowHPosList.add(clientArea.x + (clientArea.width-hPos)/2);
rowLegendNumList.add(rowLegendNum);
clientArea.height -=legendSize.height +GAP;
}
}
}
}
int lm = 0;
int vPos = clientArea.y + clientArea.height + GAP;
for(int i=0; i<rowLegendNumList.size(); i++){
hPos = rowHPosList.get(i);
for(int j=0; j<rowLegendNumList.get(i); j++){
legendList.get(lm).setBounds(new Rectangle(
hPos, vPos, legendSizeList.get(lm).width, legendSizeList.get(lm).height));
hPos += legendSizeList.get(lm).width + GAP;
lm++;
}
vPos += legendSizeList.get(lm-1).height + GAP;
}
}
for(int i=xAxisList.size()-1; i>=0; i
Axis xAxis = xAxisList.get(i);
Dimension xAxisSize = xAxis.getPreferredSize(clientArea.width, clientArea.height);
if(xAxis.getTickLablesSide() == LabelSide.Primary){
if(xAxis.isVisible())
hasBottomXAxis = true;
xAxis.setBounds(new Rectangle(clientArea.x,
clientArea.y + clientArea.height - xAxisSize.height,
xAxisSize.width, xAxisSize.height));
clientArea.height -= xAxisSize.height;
}else{
if(xAxis.isVisible())
hasTopXAxis = true;
xAxis.setBounds(new Rectangle(clientArea.x,
clientArea.y+1,
xAxisSize.width, xAxisSize.height));
clientArea.y += xAxisSize.height ;
clientArea.height -= xAxisSize.height;
}
}
for(int i=yAxisList.size()-1; i>=0; i
Axis yAxis = yAxisList.get(i);
int hintHeight = clientArea.height + (hasTopXAxis ? 1 :0) *yAxis.getMargin()
+ (hasBottomXAxis ? 1 :0) *yAxis.getMargin();
if(hintHeight > getClientArea().height)
hintHeight = clientArea.height;
Dimension yAxisSize = yAxis.getPreferredSize(clientArea.width,
hintHeight);
if(yAxis.getTickLablesSide() == LabelSide.Primary){ // on the left
if(yAxis.isVisible())
hasLeftYAxis = true;
yAxis.setBounds(new Rectangle(clientArea.x,
clientArea.y - (hasTopXAxis? yAxis.getMargin():0),
yAxisSize.width, yAxisSize.height));
clientArea.x += yAxisSize.width;
clientArea.width -= yAxisSize.width;
}else{ // on the right
if(yAxis.isVisible())
hasRightYAxis = true;
yAxis.setBounds(new Rectangle(clientArea.x + clientArea.width - yAxisSize.width -1,
clientArea.y- (hasTopXAxis? yAxis.getMargin():0),
yAxisSize.width, yAxisSize.height));
clientArea.width -= yAxisSize.width;
}
}
//re-adjust xAxis boundss
for(int i=xAxisList.size()-1; i>=0; i
Axis xAxis = xAxisList.get(i);
Rectangle r = xAxis.getBounds().getCopy();
if(hasLeftYAxis)
r.x = clientArea.x - xAxis.getMargin()-1;
r.width = clientArea.width + (hasLeftYAxis ? xAxis.getMargin() : -1) +
(hasRightYAxis? xAxis.getMargin() : 0);
xAxis.setBounds(r);
}
if(plotArea != null && plotArea.isVisible()){
Rectangle plotAreaBound = new Rectangle(
primaryXAxis.getBounds().x + primaryXAxis.getMargin(),
primaryYAxis.getBounds().y + primaryYAxis.getMargin(),
primaryXAxis.getBounds().width - 2*primaryXAxis.getMargin(),
primaryYAxis.getBounds().height - 2*primaryYAxis.getMargin()
);
plotArea.setBounds(plotAreaBound);
}
super.layout();
}
/**
* @param zoomType the zoomType to set
*/
public void setZoomType(ZoomType zoomType) {
this.zoomType = zoomType;
plotArea.setZoomType(zoomType);
for(Axis axis : xAxisList)
axis.setZoomType(zoomType);
for(Axis axis : yAxisList)
axis.setZoomType(zoomType);
}
/**
* @return the zoomType
*/
public ZoomType getZoomType() {
return zoomType;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title.trim();
titleLabel.setText(title);
}
/**
* @param showTitle true if title should be shown; false otherwise.
*/
public void setShowTitle(boolean showTitle){
titleLabel.setVisible(showTitle);
revalidate();
}
/**
* @return true if title should be shown; false otherwise.
*/
public boolean isShowTitle(){
return titleLabel.isVisible();
}
/**
* @param showLegend true if legend should be shown; false otherwise.
*/
public void setShowLegend(boolean showLegend){
this.showLegend = showLegend;
for(Axis yAxis : legendMap.keySet()){
Legend legend = legendMap.get(yAxis);
legend.setVisible(showLegend);
}
revalidate();
}
/**
* @return the showLegend
*/
public boolean isShowLegend() {
return showLegend;
}
/**Add an axis to the graph
* @param axis
*/
public void addAxis(Axis axis){
if(axis.isHorizontal())
xAxisList.add(axis);
else
yAxisList.add(axis);
plotArea.addGrid(new Grid(axis));
add(axis);
axis.setXyGraph(this);
revalidate();
}
/**Remove an axis from the graph
* @param axis
* @return true if this axis exists.
*/
public boolean removeAxis(Axis axis){
remove(axis);
plotArea.removeGrid(axis.getGrid());
revalidate();
if(axis.isHorizontal())
return xAxisList.remove(axis);
else
return yAxisList.remove(axis);
}
/**Add a trace
* @param trace
*/
public void addTrace(Trace trace){
if (trace.getTraceColor() == null)
{ // Cycle through default colors
trace.setTraceColor(XYGraphMediaFactory.getInstance().getColor(
DEFAULT_TRACES_COLOR[traceNum % DEFAULT_TRACES_COLOR.length]));
++traceNum;
}
if(legendMap.containsKey(trace.getYAxis()))
legendMap.get(trace.getYAxis()).addTrace(trace);
else{
legendMap.put(trace.getYAxis(), new Legend());
legendMap.get(trace.getYAxis()).addTrace(trace);
add(legendMap.get(trace.getYAxis()));
}
plotArea.addTrace(trace);
trace.setXYGraph(this);
trace.dataChanged(null);
revalidate();
repaint();
}
/**Remove a trace.
* @param trace
*/
public void removeTrace(Trace trace){
if(legendMap.containsKey(trace.getYAxis())){
legendMap.get(trace.getYAxis()).removeTrace(trace);
if(legendMap.get(trace.getYAxis()).getTraceList().size() <=0){
remove(legendMap.remove(trace.getYAxis()));
}
}
plotArea.removeTrace(trace);
revalidate();
repaint();
}
/**Add an annotation
* @param annotation
*/
public void addAnnotation(Annotation annotation){
plotArea.addAnnotation(annotation);
}
/**Remove an annotation
* @param annotation
*/
public void removeAnnotation(Annotation annotation){
plotArea.removeAnnotation(annotation);
}
/**
* @param titleFont the titleFont to set
*/
public void setTitleFont(Font titleFont) {
titleLabel.setFont(titleFont);
}
/**
* @return the title font.
*/
public Font getTitleFont(){
return titleLabel.getFont();
}
/**
* @param titleColor the titleColor to set
*/
public void setTitleColor(Color titleColor) {
this.titleColor = titleColor;
titleLabel.setForegroundColor(titleColor);
}
/**
* {@inheritDoc}
*/
public void paintFigure(final Graphics graphics) {
if (!transparent) {
graphics.fillRectangle(getClientArea());
}
super.paintFigure(graphics);
}
/**
* @param transparent the transparent to set
*/
public void setTransparent(boolean transparent) {
this.transparent = transparent;
getPlotArea().setOpaque(!transparent);
repaint();
}
/**
* @return the transparent
*/
public boolean isTransparent() {
return transparent;
}
/** TODO This allows clients to change the traces via getPlotArea().getTraceList() and then add/remove/clear/...,
* circumventing the designated addTrace()/removeTrace().
* Can it be non-public?
* @return the plotArea, which contains all the elements drawn inside it.
*/
public PlotArea getPlotArea() {
return plotArea;
}
/** @return Image of the XYFigure. Receiver must dispose. */
public Image getImage(){
Image image = new Image(null, bounds.width + 6, bounds.height + 6);
GC gc = new GC(image);
SWTGraphics graphics = new SWTGraphics(gc);
graphics.translate(-bounds.x + 3, -bounds.y + 3);
graphics.setForegroundColor(getForegroundColor());
graphics.setBackgroundColor(getBackgroundColor());
paint(graphics);
gc.dispose();
return image;
}
/**
* @return the titleColor
*/
public Color getTitleColor() {
if(titleColor == null)
return getForegroundColor();
return titleColor;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @return the operationsManager
*/
public OperationsManager getOperationsManager() {
return operationsManager;
}
/**
* @return the xAxisList
*/
public List<Axis> getXAxisList() {
return xAxisList;
}
/**
* @return the yAxisList
*/
public List<Axis> getYAxisList() {
return yAxisList;
}
/**
* @return the all the axis include xAxes and yAxes.
* yAxisList is appended to xAxisList in the returned list.
*/
public List<Axis> getAxisList(){
List<Axis> list = new ArrayList<Axis>();
list.addAll(xAxisList);
list.addAll(yAxisList);
return list;
}
/**
* @return the legendMap
*/
public Map<Axis, Legend> getLegendMap() {
return legendMap;
}
/**
* Perform forced autoscale to all axes.
*/
public void performAutoScale(){
final ZoomCommand command = new ZoomCommand("Auto Scale", xAxisList, yAxisList);
for(Axis axis : xAxisList){
axis.performAutoScale(true);
}
for(Axis axis : yAxisList){
axis.performAutoScale(true);
}
command.saveState();
operationsManager.addCommand(command);
}
/** Stagger all axes: Autoscale each axis so that traces on various
* axes don't overlap
*/
public void performStagger()
{
final double GAP = 0.1;
final ZoomCommand command = new ZoomCommand("Stagger Axes", null, yAxisList);
// Arrange all axes so they don't overlap by assigning 1/Nth of
// the vertical range to each one
final int N = yAxisList.size();
for (int i=0; i<N; ++i)
{
final Axis yaxis = yAxisList.get(i);
// Does axis handle itself in another way?
if (yaxis.isAutoScale())
continue;
// Determine range of values on this axis
final Range axis_range = yaxis.getTraceDataRange();
// Skip axis which for some reason cannot determine its range
if (axis_range == null)
continue;
double low = axis_range.getLower();
double high = axis_range.getUpper();
if (low == high)
{ // Center trace with constant value (empty range)
final double half = Math.abs(low/2);
low -= half;
high += half;
}
if (yaxis.isLogScaleEnabled())
{ // Transition into log space
low = Log10.log10(low);
high = Log10.log10(high);
}
double span = high - low;
// Make some extra space
low -= GAP*span;
high += GAP*span;
span = high-low;
// With N axes, assign 1/Nth of the vertical plot space to this axis
// by shifting the span down according to the axis index,
// using a total of N*range.
low -= (N-i-1)*span;
high += i*span;
if (yaxis.isLogScaleEnabled())
{ // Revert from log space
low = Log10.pow10(low);
high = Log10.pow10(high);
}
// Sanity check for empty traces
if (low < high &&
!Double.isInfinite(low) && !Double.isInfinite(high))
yaxis.setRange(low, high);
}
command.saveState();
operationsManager.addCommand(command);
}
}
|
// 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, /
// sell copies of the Software, and to permit persons to whom the /
// Software is furnished to do so, subject to the following /
// conditions: /
// included in all copies or substantial portions of the Software. /
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES /
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND /
// 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 org.asn1s.core.type.x680.collection;
import org.asn1s.api.Scope;
import org.asn1s.api.State;
import org.asn1s.api.encoding.EncodingInstructions;
import org.asn1s.api.encoding.tag.TagEncoding;
import org.asn1s.api.encoding.tag.TagMethod;
import org.asn1s.api.exception.ResolutionException;
import org.asn1s.api.exception.ValidationException;
import org.asn1s.api.type.CollectionTypeExtensionGroup;
import org.asn1s.api.type.ComponentType;
import org.asn1s.api.type.Type;
import org.asn1s.api.type.Type.Family;
import org.asn1s.core.type.TaggedTypeImpl;
import org.jetbrains.annotations.NotNull;
import java.util.*;
abstract class AbstractComponentInterpolator
{
private final Scope scope;
private final AbstractCollectionType type;
private final boolean applyAutomaticTags;
private final Map<String, Family> componentFamilyMap = new HashMap<>();
AbstractComponentInterpolator( Scope scope, AbstractCollectionType type )
{
this.scope = scope;
this.type = type;
applyAutomaticTags = type.isAutomaticTags() && mayUseAutomaticTags( type );
}
private static boolean mayUseAutomaticTags( @NotNull AbstractCollectionType collectionType )
{
for( Type type : collectionType.getComponents() )
{
if( type instanceof ComponentType && ( (ComponentType)type ).isExplicitlyTagged() )
return false;
}
for( Type type : collectionType.getComponentsLast() )
{
if( type instanceof ComponentType && ( (ComponentType)type ).isExplicitlyTagged() )
return false;
}
return true;
}
protected abstract void assertTagAmbiguity( Collection<ComponentType> components ) throws ValidationException;
private Scope getScope()
{
return scope;
}
AbstractCollectionType getType()
{
return type;
}
List<ComponentType> interpolate() throws ValidationException, ResolutionException
{
new CollectionValidator( getType() ).validate();
List<ComponentType> components = interpolateComponents();
assertTagAmbiguity( components );
return components;
}
@NotNull
private List<ComponentType> interpolateComponents() throws ValidationException, ResolutionException
{
List<ComponentType> components = new ComponentsBuilder( getType(), componentFamilyMap ).build();
for( ComponentType component : components )
component.validate( getScope() );
return isApplyAutomaticTags() ? new ComponentTagger( componentFamilyMap, components, getScope() ).applyAutomaticTags() : components;
}
private boolean isApplyAutomaticTags()
{
return applyAutomaticTags;
}
private static final class ComponentsBuilder
{
private final AbstractCollectionType type;
private final Map<String, Family> componentFamilyMap;
@SuppressWarnings( "unchecked" )
// 0 - components, 1 - componentsLast, 2 - extensions
private final Collection<ComponentType>[] _comps = new Collection[]{new ArrayList<ComponentType>(), new ArrayList<ComponentType>(), new ArrayList<ComponentType>()};
private final List<ComponentType> result = new ArrayList<>();
private int index;
private ComponentsBuilder( AbstractCollectionType type, Map<String, Family> componentFamilyMap )
{
this.type = type;
this.componentFamilyMap = componentFamilyMap;
}
private List<ComponentType> build() throws ValidationException
{
resolveComponentsImpl( _comps[0], type.getComponents(), -1 );
resolveComponentsImpl( _comps[1], type.getComponentsLast(), -1 );
resolveComponentsImpl( _comps[2], type.getExtensions(), 2 );
registerComponents( _comps[0] );
registerComponents( _comps[2] );
registerComponents( _comps[1] );
return result;
}
private void registerComponents( Iterable<ComponentType> source )
{
for( ComponentType component : source )
//noinspection ValueOfIncrementOrDecrementUsed
addComponentType( result, component, component.getVersion(), index++ );
}
private void resolveComponentsImpl( Collection<ComponentType> list, Iterable<Type> sources, int version ) throws ValidationException
{
if( version == -1 )
for( Type source : sources )
resolveComponentTypeSource( list, source, 1 );
else
for( Type source : sources )
//noinspection ValueOfIncrementOrDecrementUsed
resolveComponentTypeSource( list, source, version++ );
}
private void resolveComponentTypeSource( Collection<ComponentType> list, Type source, int version ) throws ValidationException
{
if( source instanceof ComponentType )
addComponentType( list, (ComponentType)source, version, -1 );
else if( source instanceof ComponentsFromType )
resolveComponentTypeSourceForCompsFromType( list, (ComponentsFromType)source, version );
else if( source instanceof CollectionTypeExtensionGroup )
resolveComponentTypeSourceForExtGroup( list, (CollectionTypeExtensionGroup)source, version );
else
throw new IllegalStateException( "Unable to use type: " + source );
}
private void resolveComponentTypeSourceForExtGroup( Collection<ComponentType> list, CollectionTypeExtensionGroup source, int version ) throws ValidationException
{
int groupVersion = source.getVersion();
if( groupVersion != -1 )
{
if( groupVersion < version )
throw new ValidationException( "Version must be greater than previous group" );
version = groupVersion;
}
for( ComponentType componentType : source.getComponents() )
addComponentType( list, componentType, version, -1 );
}
private void resolveComponentTypeSourceForCompsFromType( Collection<ComponentType> list, ComponentsFromType source, int version )
{
for( ComponentType componentType : source.getComponents() )
addComponentType( list, componentType, version, -1 );
}
private void addComponentType( Collection<ComponentType> list, ComponentType source, int version, int index )
{
if( source.getState() == State.Done )
componentFamilyMap.put( source.getComponentName(), source.getFamily() );
list.add( isShouldKeep( source, version, index ) ? source : createComponentType( source, version, index ) );
}
private static boolean isShouldKeep( ComponentType source, int version, int index )
{
return source.getVersion() == version && index != -1 && source.getIndex() == index;
}
@NotNull
private ComponentType createComponentType( ComponentType source, int version, int index )
{
ComponentType componentType =
new ComponentTypeImpl( index == -1 ? source.getIndex() : index,
version,
source.getComponentName(),
source.getComponentTypeRef(),
source.isOptional(),
source.getDefaultValueRef() );
componentType.setNamespace( type.getNamespace() );
return componentType;
}
}
private static final class CollectionValidator
{
private final AbstractCollectionType type;
private final Collection<String> names;
private CollectionValidator( AbstractCollectionType type )
{
this.type = type;
names = new HashSet<>();
}
public void validate() throws ValidationException
{
assertNames( type.getComponents(), names );
assertNames( type.getExtensions(), names );
assertNames( type.getComponentsLast(), names );
if( isExtensionVersionProhibited() )
assertExtensionGroupHasNoVersion();
else
assertExtensionVersions();
}
private static void assertNames( Iterable<Type> items, Collection<String> names ) throws ValidationException
{
for( Type item : items )
assertName( item, names );
}
private static void assertName( Type item, Collection<String> names ) throws ValidationException
{
if( item instanceof ComponentType )
assertNameForComponentType( (ComponentType)item, names );
else if( item instanceof CollectionTypeExtensionGroup )
assertNameForExtensionGroup( (CollectionTypeExtensionGroup)item, names );
else if( item instanceof ComponentsFromType )
assertNameForComponentsFromType( (ComponentsFromType)item, names );
}
private static void assertNameForComponentsFromType( ComponentsFromType item, Collection<String> names ) throws ValidationException
{
for( ComponentType componentType : item.getComponents() )
assertName( componentType, names );
}
private static void assertNameForExtensionGroup( CollectionTypeExtensionGroup item, Collection<String> names ) throws ValidationException
{
for( ComponentType componentType : item.getComponents() )
assertName( componentType, names );
}
private static void assertNameForComponentType( ComponentType item, Collection<String> names ) throws ValidationException
{
String componentName = item.getComponentName();
if( names.contains( componentName ) )
throw new ValidationException( "ComponentType with name '" + componentName + "' already exist" );
names.add( componentName );
}
private void assertExtensionVersions() throws ValidationException
{
int prevVersion = 1;
for( Type extension : type.getExtensions() )
{
CollectionTypeExtensionGroup group = (CollectionTypeExtensionGroup)extension;
if( prevVersion >= group.getVersion() )
throw new ValidationException( "Extension group version is greater than previous" );
prevVersion = group.getVersion();
}
}
private void assertExtensionGroupHasNoVersion() throws ValidationException
{
for( Type extension : type.getExtensions() )
if( extension instanceof CollectionTypeExtensionGroup && ( (CollectionTypeExtensionGroup)extension ).getVersion() != -1 )
throw new ValidationException( "Extension group version is prohibited: " + type );
}
private boolean isExtensionVersionProhibited()
{
for( Type extension : type.getExtensions() )
if( isVersionProhibitedFor( extension ) )
return true;
return false;
}
private static boolean isVersionProhibitedFor( Type extension )
{
return extension instanceof ComponentType
|| extension instanceof ComponentsFromType
|| extension instanceof CollectionTypeExtensionGroup && ( (CollectionTypeExtensionGroup)extension ).getVersion() == -1;
}
}
private static final class ComponentTagger
{
private final Map<String, Family> componentFamilyMap;
private final List<ComponentType> components;
private final Scope scope;
private final List<ComponentType> result;
private int tagNumber;
private ComponentTagger( Map<String, Family> componentFamilyMap, List<ComponentType> components, Scope scope )
{
this.componentFamilyMap = componentFamilyMap;
this.components = components;
this.scope = scope;
result = new ArrayList<>( components.size() );
}
@NotNull
private List<ComponentType> applyAutomaticTags() throws ResolutionException, ValidationException
{
applyTags( true );
applyTags( false );
result.sort( Comparator.comparingInt( ComponentType:: getIndex ) );
return result;
}
private void applyTags( boolean main ) throws ResolutionException, ValidationException
{
for( ComponentType component : components )
if( component.getVersion() == 1 && main || component.getVersion() > 1 )
result.add( applyTagNumber( component ) );
}
private ComponentType applyTagNumber( ComponentType component ) throws ResolutionException, ValidationException
{
TagMethod method = selectTagMethod( component );
TaggedTypeImpl subType = new TaggedTypeImpl( TagEncoding.context( tagNumber, method ), component.getComponentTypeRef() );
subType.setNamespace( component.getNamespace() );
tagNumber++;
ComponentType taggedComponent = new ComponentTypeImpl( component.getIndex(),
component.getVersion(),
component.getComponentName(),
subType,
component.isOptional(),
component.getDefaultValueRef() );
taggedComponent.setNamespace( component.getNamespace() );
taggedComponent.validate( scope );
return taggedComponent;
}
@NotNull
private TagMethod selectTagMethod( ComponentType component )
{
boolean isChoice = componentFamilyMap.get( component.getComponentName() ) == Family.Choice;
boolean noEncodingAvailable = component.getEncoding( EncodingInstructions.Tag ) == null;
return isChoice && noEncodingAvailable ? TagMethod.Explicit : TagMethod.Implicit;
}
}
}
|
package com.exedio.cope.util;
import java.io.File;
import java.util.Collection;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import com.exedio.cope.Cope;
import com.exedio.cope.Model;
public class ServletUtil
{
private interface Config
{
String getInitParameter(String name);
String getName();
ServletContext getServletContext();
String getKind();
}
private static final Config wrap(final ServletConfig config)
{
return new Config()
{
public String getInitParameter(final String name)
{
return config.getInitParameter(name);
}
public String getName()
{
return config.getServletName();
}
public ServletContext getServletContext()
{
return config.getServletContext();
}
public String getKind()
{
return "servlet";
}
};
}
private static final Config wrap(final FilterConfig config)
{
return new Config()
{
public String getInitParameter(final String name)
{
return config.getInitParameter(name);
}
public String getName()
{
return config.getFilterName();
}
public ServletContext getServletContext()
{
return config.getServletContext();
}
public String getKind()
{
return "filter";
}
};
}
public static final ConnectToken getConnectedModel(final Servlet servlet)
throws ServletException
{
return getConnectedModel(
wrap(servlet.getServletConfig()),
servlet);
}
public static final ConnectToken getConnectedModel(final Filter filter, final FilterConfig config)
throws ServletException
{
return getConnectedModel(
wrap(config),
filter);
}
private static final ConnectToken getConnectedModel(
final Config config,
final Object nameObject)
throws ServletException
{
final String PARAMETER_MODEL = "model";
final String initParam = config.getInitParameter(PARAMETER_MODEL);
final String name = config.getName();
final ServletContext context = config.getServletContext();
final String description =
config.getKind() + ' ' +
'"' + name + '"' + ' ' +
'(' + nameObject.getClass().getName() + '@' + System.identityHashCode(nameObject) + ')';
final String modelName;
final String modelNameSource;
if(initParam==null)
{
final String contextParam = context.getInitParameter(PARAMETER_MODEL);
if(contextParam==null)
throw new ServletException(description + ": neither init-param nor context-param '"+PARAMETER_MODEL+"' set");
modelName = contextParam;
modelNameSource = "context-param";
}
else
{
modelName = initParam;
modelNameSource = "init-param";
}
final Model result;
try
{
result = Cope.getModel(modelName);
}
catch(IllegalArgumentException e)
{
throw new ServletException(description + ", " + modelNameSource + ' ' + PARAMETER_MODEL + ':' + ' ' + e.getMessage(), e);
}
return connect(result, config, description);
}
/**
* Connects the model using the properties from
* the file <tt>cope.properties</tt>
* in the directory <tt>WEB-INF</tt>
* of the web application.
* @see Model#connect(com.exedio.cope.ConnectProperties)
* @see ConnectToken#issue(Model,com.exedio.cope.ConnectProperties,String)
*/
public static final ConnectToken connect(final Model model, final ServletConfig config, final String name)
{
return connect(model, wrap(config), name);
}
public static final ConnectToken connect(final Model model, final FilterConfig config, final String name)
{
return connect(model, wrap(config), name);
}
private static final ConnectToken connect(final Model model, final Config config, final String name)
{
final String propertiesInitParam = config.getInitParameter("cope.properties");
final String propertiesFile = propertiesInitParam!=null ? propertiesInitParam : "WEB-INF/cope.properties";
final ServletContext context = config.getServletContext();
return ConnectToken.issue(model,
new com.exedio.cope.ConnectProperties(
new File(context.getRealPath(propertiesFile)), getPropertyContext(context)), name);
}
public static final Properties.Source getPropertyContext(final ServletContext context)
{
final String prefix =
context.getInitParameter("com.exedio.cope.contextPrefix");
return new Properties.Source(){
public String get(final String key)
{
return context.getInitParameter(prefix!=null ? (prefix+key) : key);
}
public Collection<String> keySet()
{
return null;
}
public String getDescription()
{
return toString();
}
@Override
public String toString()
{
return
"javax.servlet.ServletContext.getInitParameter " +
"of '" + context.getServletContextName() + '\'' +
(prefix!=null ? (" with prefix '"+prefix+'\'') : "");
}
};
}
/**
* @deprecated Use {@link #getConnectedModel(Servlet)} instead
*/
@Deprecated
public static final ConnectToken getModel(final Servlet servlet)
throws ServletException
{
return getConnectedModel(servlet);
}
/**
* @deprecated Use {@link #getConnectedModel(Filter,FilterConfig)} instead
*/
@Deprecated
public static final ConnectToken getModel(final Filter filter, final FilterConfig config)
throws ServletException
{
return getConnectedModel(filter, config);
}
/**
* @deprecated Renamed to {@link #connect(Model, ServletConfig, String)}.
*/
@Deprecated
public static final ConnectToken initialize(final Model model, final ServletConfig config, final String name)
{
return connect(model, config, name);
}
}
|
package pacman.modele;
import pacman.carte.Labyrinthe;
public class Modele {
protected Labyrinthe laby;
public Modele(Labyrinthe laby){
this.laby=laby;
}
public boolean murADroite(){
return (laby.getPacman().getLargeur()==laby.getLargeur()-1);
}
public boolean murAGauche(){
return (laby.getPacman().getLargeur()==0);
}
public boolean murEnHaut(){
return (laby.getPacman().getHauteur()==laby.getHauteur()-1);
}
public boolean murEnBas(){
return (laby.getPacman().getHauteur()==0);
}
public int getCoordonneeHauteur(){
return(laby.getPacman().getHauteur());
}
public int getCoordonneeLargeur(){
return(laby.getPacman().getLargeur());
}
/**
* Methodes de deplacement du Pacman
*/
public void deplacerPacmanGauche(){
laby.deplacerPacmanGauche();
}
public void deplacerPacmanDroite(){
laby.deplacerPacmanDroite();
}
public void deplacerPacmanBas(){
laby.deplacerPacmanBas();
}
public void deplacerPacmanHaut(){
laby.deplacerPacmanHaut();
}
}
|
package org.crunchytorch.coddy.application.exception.handler.impl;
import org.crunchytorch.coddy.application.data.Response;
import org.crunchytorch.coddy.application.exception.handler.IExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
public class ExceptHandler implements IExceptionHandler<Exception> {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptHandler.class);
@Override
@ExceptionHandler(Exception.class)
public ResponseEntity<Response> handler(Exception e) {
LOGGER.error(e.getMessage(), e);
return this.handler(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
|
package org.ovirt.engine.core.vdsbroker;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.businessentities.NonOperationalReason;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSDomainsData;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsDynamic;
import org.ovirt.engine.core.common.businessentities.VdsSpmStatus;
import org.ovirt.engine.core.common.businessentities.VdsStatistics;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.SetVdsStatusVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VdsIdAndVdsVDSCommandParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.utils.lock.EngineLock;
import org.ovirt.engine.core.utils.lock.LockManagerFactory;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation;
import org.ovirt.engine.core.utils.timer.SchedulerUtil;
import org.ovirt.engine.core.utils.timer.SchedulerUtilQuartzImpl;
import org.ovirt.engine.core.vdsbroker.irsbroker.IRSErrorException;
import org.ovirt.engine.core.vdsbroker.irsbroker.IrsBrokerCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.CollectVdsNetworkDataVDSCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.GetCapabilitiesVDSCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.IVdsServer;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSNetworkException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSRecoveringException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsServerConnector;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsServerWrapper;
import org.ovirt.engine.core.vdsbroker.xmlrpc.XmlRpcUtils;
public class VdsManager {
private VDS _vds;
private long lastUpdate;
private long updateStartTime;
private static Log log = LogFactory.getLog(VdsManager.class);
public boolean getRefreshStatistics() {
return (_refreshIteration == _numberRefreshesBeforeSave);
}
private static final int VDS_REFRESH_RATE = Config.<Integer> GetValue(ConfigValues.VdsRefreshRate) * 1000;
private String onTimerJobId;
private final int _numberRefreshesBeforeSave = Config.<Integer> GetValue(ConfigValues.NumberVmRefreshesBeforeSave);
private int _refreshIteration = 1;
private final Object _lockObj = new Object();
private static Map<Guid, String> recoveringJobIdMap = new ConcurrentHashMap<Guid, String>();
private boolean isSetNonOperationalExecuted;
private MonitoringStrategy monitoringStrategy;
private EngineLock monitoringLock;
public Object getLockObj() {
return _lockObj;
}
public static void cancelRecoveryJob(Guid vdsId) {
String jobId = recoveringJobIdMap.remove(vdsId);
if (jobId != null) {
log.infoFormat("Cancelling the recovery from crash timer for VDS {0} because vds started initializing", vdsId);
try {
SchedulerUtilQuartzImpl.getInstance().deleteJob(jobId);
} catch (Exception e) {
log.warnFormat("Failed deleting job {0} at cancelRecoveryJob", jobId);
}
}
}
private final AtomicInteger mFailedToRunVmAttempts;
private final AtomicInteger mUnrespondedAttempts;
private static final int VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES = Config
.<Integer> GetValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes);
private String duringFailureJobId;
private boolean privateInitialized;
public boolean getInitialized() {
return privateInitialized;
}
public void setInitialized(boolean value) {
privateInitialized = value;
}
private IVdsServer _vdsProxy;
public IVdsServer getVdsProxy() {
return _vdsProxy;
}
public Guid getVdsId() {
return _vdsId;
}
private boolean mBeforeFirstRefresh = true;
public boolean getbeforeFirstRefresh() {
return mBeforeFirstRefresh;
}
public void setbeforeFirstRefresh(boolean value) {
mBeforeFirstRefresh = value;
}
private final Guid _vdsId;
private VdsManager(VDS vds) {
log.info("Entered VdsManager constructor");
_vds = vds;
_vdsId = vds.getId();
monitoringStrategy = MonitoringStrategyFactory.getMonitoringStrategyForVds(vds);
mUnrespondedAttempts = new AtomicInteger();
mFailedToRunVmAttempts = new AtomicInteger();
monitoringLock = new EngineLock(Collections.singletonMap(_vdsId.toString(),
new Pair<String, String>(LockingGroup.VDS_INIT.name(), "")), null);
if (_vds.getStatus() == VDSStatus.PreparingForMaintenance) {
_vds.setPreviousStatus(_vds.getStatus());
} else {
_vds.setPreviousStatus(VDSStatus.Up);
}
// if ssl is on and no certificate file
if (Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)
&& !new File(Config.resolveCertificatePath()).exists()) {
if (_vds.getStatus() != VDSStatus.Maintenance && _vds.getStatus() != VDSStatus.InstallFailed) {
setStatus(VDSStatus.NonResponsive, _vds);
UpdateDynamicData(_vds.getDynamicData());
}
log.error("Could not find VDC Certificate file.");
AuditLogableBase logable = new AuditLogableBase(_vdsId);
AuditLogDirector.log(logable, AuditLogType.CERTIFICATE_FILE_NOT_FOUND);
}
InitVdsBroker();
_vds = null;
}
public static VdsManager buildVdsManager(VDS vds) {
VdsManager vdsManager = new VdsManager(vds);
return vdsManager;
}
public void schedulJobs() {
SchedulerUtil sched = SchedulerUtilQuartzImpl.getInstance();
duringFailureJobId = sched.scheduleAFixedDelayJob(this, "OnVdsDuringFailureTimer", new Class[0],
new Object[0], VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES, VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES,
TimeUnit.MINUTES);
sched.pauseJob(duringFailureJobId);
// start with refresh statistics
_refreshIteration = _numberRefreshesBeforeSave - 1;
onTimerJobId = sched.scheduleAFixedDelayJob(this, "OnTimer", new Class[0], new Object[0], VDS_REFRESH_RATE,
VDS_REFRESH_RATE, TimeUnit.MILLISECONDS);
}
private void InitVdsBroker() {
log.infoFormat("Initialize vdsBroker ({0},{1})", _vds.getHostName(), _vds.getPort());
// Get the values of the timeouts:
int clientTimeOut = Config.<Integer> GetValue(ConfigValues.vdsTimeout) * 1000;
int connectionTimeOut = Config.<Integer>GetValue(ConfigValues.vdsConnectionTimeout) * 1000;
int clientRetries = Config.<Integer>GetValue(ConfigValues.vdsRetries);
Pair<VdsServerConnector, HttpClient> returnValue =
XmlRpcUtils.getConnection(_vds.getHostName(),
_vds.getPort(),
clientTimeOut,
connectionTimeOut,
clientRetries,
VdsServerConnector.class,
Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers));
_vdsProxy = new VdsServerWrapper(returnValue.getFirst(), returnValue.getSecond());
}
public void UpdateVmDynamic(VmDynamic vmDynamic) {
DbFacade.getInstance().getVmDynamicDao().update(vmDynamic);
}
private VdsUpdateRunTimeInfo _vdsUpdater;
private final VdsMonitor vdsMonitor = new VdsMonitor();
@OnTimerMethodAnnotation("OnTimer")
public void OnTimer() {
if (LockManagerFactory.getLockManager().acquireLock(monitoringLock).getFirst()) {
try {
setIsSetNonOperationalExecuted(false);
Guid vdsId = null;
Guid storagePoolId = null;
String vdsName = null;
ArrayList<VDSDomainsData> domainsList = null;
synchronized (getLockObj()) {
_vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
if (_vds == null) {
log.errorFormat("VdsManager::refreshVdsRunTimeInfo - OnTimer is NULL for {0}",
getVdsId());
return;
}
try {
if (_refreshIteration == _numberRefreshesBeforeSave) {
_refreshIteration = 1;
} else {
_refreshIteration++;
}
if (isMonitoringNeeded()) {
setStartTime();
_vdsUpdater = new VdsUpdateRunTimeInfo(VdsManager.this, _vds, monitoringStrategy);
_vdsUpdater.Refresh();
mUnrespondedAttempts.set(0);
setLastUpdate();
}
if (!getInitialized() && _vds.getStatus() != VDSStatus.NonResponsive
&& _vds.getStatus() != VDSStatus.PendingApproval) {
log.infoFormat("Initializing Host: {0}", _vds.getName());
ResourceManager.getInstance().HandleVdsFinishedInit(_vds.getId());
setInitialized(true);
}
} catch (VDSNetworkException e) {
logNetworkException(e);
} catch (VDSRecoveringException ex) {
HandleVdsRecoveringException(ex);
} catch (IRSErrorException ex) {
logFailureMessage(ex);
} catch (RuntimeException ex) {
logFailureMessage(ex);
}
try {
if (_vdsUpdater != null) {
_vdsUpdater.AfterRefreshTreatment();
// Get vds data for updating domains list, ignoring vds which is down, since it's not
// connected
// the storage anymore (so there is no sense in updating the domains list in that case).
if (_vds != null && _vds.getStatus() != VDSStatus.Maintenance) {
vdsId = _vds.getId();
vdsName = _vds.getName();
storagePoolId = _vds.getStoragePoolId();
domainsList = _vds.getDomains();
}
}
_vds = null;
_vdsUpdater = null;
} catch (IRSErrorException ex) {
logAfterRefreshFailureMessage(ex);
if (log.isDebugEnabled()) {
logException(ex);
}
} catch (RuntimeException ex) {
logAfterRefreshFailureMessage(ex);
logException(ex);
}
}
// Now update the status of domains, this code should not be in
// synchronized part of code
if (domainsList != null) {
IrsBrokerCommand.UpdateVdsDomainsData(vdsId, vdsName, storagePoolId, domainsList);
}
} catch (Exception e) {
log.error("Timer update runtimeinfo failed. Exception:", e);
} finally {
LockManagerFactory.getLockManager().releaseLock(monitoringLock);
}
}
}
private void logFailureMessage(RuntimeException ex) {
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, error = '{2}', continuing.",
_vds.getId(),
_vds.getName(),
ex);
}
private static void logException(final RuntimeException ex) {
log.error("ResourceManager::refreshVdsRunTimeInfo", ex);
}
private void logAfterRefreshFailureMessage(RuntimeException ex) {
log.warnFormat(
"Failed to AfterRefreshTreatment VDS error = '{0}', continuing.",
ExceptionUtils.getMessage(ex));
}
public boolean isMonitoringNeeded() {
return (monitoringStrategy.isMonitoringNeeded(_vds) &&
_vds.getStatus() != VDSStatus.Installing &&
_vds.getStatus() != VDSStatus.InstallFailed &&
_vds.getStatus() != VDSStatus.Reboot &&
_vds.getStatus() != VDSStatus.Maintenance &&
_vds.getStatus() != VDSStatus.PendingApproval && _vds.getStatus() != VDSStatus.Down);
}
private void HandleVdsRecoveringException(VDSRecoveringException ex) {
if (_vds.getStatus() != VDSStatus.Initializing && _vds.getStatus() != VDSStatus.NonOperational) {
setStatus(VDSStatus.Initializing, _vds);
DbFacade.getInstance().getVdsDynamicDao().updateStatus(_vds.getId(), VDSStatus.Initializing);
AuditLogableBase logable = new AuditLogableBase(_vds.getId());
logable.addCustomValue("ErrorMessage", ex.getMessage());
AuditLogDirector.log(logable, AuditLogType.VDS_INITIALIZING);
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, error = {2}, continuing.",
_vds.getId(),
_vds.getName(),
ex.getMessage());
final int VDS_RECOVERY_TIMEOUT_IN_MINUTES = Config.<Integer> GetValue(ConfigValues.VdsRecoveryTimeoutInMintues);
String jobId = SchedulerUtilQuartzImpl.getInstance().scheduleAOneTimeJob(this, "onTimerHandleVdsRecovering", new Class[0],
new Object[0], VDS_RECOVERY_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
recoveringJobIdMap.put(_vds.getId(), jobId);
}
}
@OnTimerMethodAnnotation("onTimerHandleVdsRecovering")
public void onTimerHandleVdsRecovering() {
recoveringJobIdMap.remove(getVdsId());
VDS vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
if (vds.getStatus() == VDSStatus.Initializing) {
try {
ResourceManager
.getInstance()
.getEventListener()
.vdsNonOperational(vds.getId(),
NonOperationalReason.TIMEOUT_RECOVERING_FROM_CRASH,
true,
true,
Guid.Empty);
setIsSetNonOperationalExecuted(true);
} catch (RuntimeException exp) {
log.errorFormat(
"HandleVdsRecoveringException::Error in recovery timer treatment, vds = {0} : {1}, error = {2}.",
vds.getId(),
vds.getName(),
exp.getMessage());
}
}
}
/**
* Save dynamic data to cache and DB.
*
* @param dynamicData
*/
public void UpdateDynamicData(VdsDynamic dynamicData) {
DbFacade.getInstance().getVdsDynamicDao().update(dynamicData);
}
/**
* Save statistics data to cache and DB.
*
* @param statisticsData
*/
public void UpdateStatisticsData(VdsStatistics statisticsData) {
DbFacade.getInstance().getVdsStatisticsDao().update(statisticsData);
}
public VDS activate() {
VDS vds = null;
try {
// refresh vds from db in case changed while was down
log.debugFormat(
"Trying to activate host {0} , meanwhile setting status to Unassigned.",
getVdsId());
vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
/**
* refresh capabilities
*/
VDSStatus newStatus = refreshCapabilities(new AtomicBoolean(), vds, true);
if (log.isDebugEnabled()) {
log.debugFormat(
"Succeeded to refreshCapabilities for host {0} , new status will be {1} ",
getVdsId(),
newStatus);
}
} catch (java.lang.Exception e) {
log.infoFormat("Failed to activate VDS = {0} with error: {1}.",
getVdsId(), e.getMessage());
} finally {
if (vds != null) {
UpdateDynamicData(vds.getDynamicData());
// Update VDS after testing special hardware capabilities
monitoringStrategy.processHardwareCapabilities(vds);
// Always check VdsVersion
ResourceManager.getInstance().getEventListener().handleVdsVersion(vds.getId());
}
}
return vds;
}
public void setStatus(VDSStatus status, VDS vds) {
synchronized (getLockObj()) {
if (vds == null) {
vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
}
if (vds.getPreviousStatus() != vds.getStatus()) {
vds.setPreviousStatus(vds.getStatus());
if (_vds != null) {
_vds.setPreviousStatus(vds.getStatus());
}
}
// update to new status
vds.setStatus(status);
if (_vds != null) {
_vds.setStatus(status);
}
switch (status) {
case NonOperational:
if (_vds != null) {
_vds.setNonOperationalReason(vds.getNonOperationalReason());
}
if(vds.getVmCount() > 0) {
break;
}
case NonResponsive:
case Down:
case Maintenance:
vds.setCpuSys(Double.valueOf(0));
vds.setCpuUser(Double.valueOf(0));
vds.setCpuIdle(Double.valueOf(0));
vds.setCpuLoad(Double.valueOf(0));
vds.setUsageCpuPercent(0);
vds.setUsageMemPercent(0);
vds.setUsageNetworkPercent(0);
if (_vds != null) {
_vds.setCpuSys(Double.valueOf(0));
_vds.setCpuUser(Double.valueOf(0));
_vds.setCpuIdle(Double.valueOf(0));
_vds.setCpuLoad(Double.valueOf(0));
_vds.setUsageCpuPercent(0);
_vds.setUsageMemPercent(0);
_vds.setUsageNetworkPercent(0);
}
default:
break;
}
}
}
/**
* This function called when vds have failed vm attempts one in predefined time. Its increments failure attemts to
* one
*
* @param obj
* @param arg
*/
@OnTimerMethodAnnotation("OnVdsDuringFailureTimer")
public void OnVdsDuringFailureTimer() {
synchronized (getLockObj()) {
VDS vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
/**
* Disable timer if vds returns from suspitious mode
*/
if (mFailedToRunVmAttempts.decrementAndGet() == 0) {
SchedulerUtilQuartzImpl.getInstance().pauseJob(duringFailureJobId);
}
/**
* Move vds to Up status from error
*/
if (mFailedToRunVmAttempts.get() < Config.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)
&& vds.getStatus() == VDSStatus.Error) {
setStatus(VDSStatus.Up, vds);
DbFacade.getInstance().getVdsDynamicDao().updateStatus(getVdsId(), VDSStatus.Up);
}
log.infoFormat("OnVdsDuringFailureTimer of vds {0} entered. Attempts after {1}", vds.getName(),
mFailedToRunVmAttempts);
}
}
public void failedToRunVm(VDS vds) {
if (mFailedToRunVmAttempts.get() < Config.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)
&& mFailedToRunVmAttempts.incrementAndGet() >= Config
.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)) {
ResourceManager.getInstance().runVdsCommand(VDSCommandType.SetVdsStatus,
new SetVdsStatusVDSCommandParameters(vds.getId(), VDSStatus.Error));
SchedulerUtilQuartzImpl.getInstance().resumeJob(duringFailureJobId);
AuditLogableBase logable = new AuditLogableBase(vds.getId());
logable.addCustomValue("Time", Config.<Integer> GetValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes)
.toString());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILED_TO_RUN_VMS);
log.infoFormat("Vds {0} moved to Error mode after {1} attempts. Time: {2}", vds.getName(),
mFailedToRunVmAttempts, new java.util.Date());
}
}
public void SuccededToRunVm(Guid vmId) {
mUnrespondedAttempts.set(0);
ResourceManager.getInstance().SuccededToRunVm(vmId, _vds.getId());
}
public VDSStatus refreshCapabilities(AtomicBoolean processHardwareCapsNeeded, VDS vds, boolean skipMgmtNet) {
log.debug("GetCapabilitiesVDSCommand started method");
VDS oldVDS = vds.clone();
GetCapabilitiesVDSCommand<VdsIdAndVdsVDSCommandParametersBase> vdsBrokerCommand =
new GetCapabilitiesVDSCommand<VdsIdAndVdsVDSCommandParametersBase>(new VdsIdAndVdsVDSCommandParametersBase(vds));
vdsBrokerCommand.execute();
if (vdsBrokerCommand.getVDSReturnValue().getSucceeded()) {
// Verify version capabilities
HashSet<Version> hostVersions = null;
Version clusterCompatibility = vds.getVdsGroupCompatibilityVersion();
if (FeatureSupported.hardwareInfo(clusterCompatibility) &&
// If the feature is enabled in cluster level, we continue by verifying that this VDS also
// supports the specific cluster level. Otherwise getHardwareInfo API won't exist for the
// host and an exception will be raised by vdsm.
(hostVersions = vds.getSupportedClusterVersionsSet()) != null &&
hostVersions.contains(clusterCompatibility)) {
VDSReturnValue ret = ResourceManager.getInstance().runVdsCommand(VDSCommandType.GetHardwareInfo,
new VdsIdAndVdsVDSCommandParametersBase(vds));
if (!ret.getSucceeded()) {
AuditLogableBase logable = new AuditLogableBase(vds.getId());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILED_TO_GET_HOST_HARDWARE_INFO);
}
}
VDSStatus returnStatus = vds.getStatus();
NonOperationalReason nonOperationalReason =
CollectVdsNetworkDataVDSCommand.persistAndEnforceNetworkCompliance(vds, skipMgmtNet);
if (nonOperationalReason != NonOperationalReason.NONE) {
setIsSetNonOperationalExecuted(true);
if (returnStatus != VDSStatus.NonOperational) {
if (log.isDebugEnabled()) {
log.debugFormat(
"refreshCapabilities:GetCapabilitiesVDSCommand vds {0} networks do not match its cluster networks, vds will be moved to NonOperational",
vds.getStaticData().getId());
}
vds.setStatus(VDSStatus.NonOperational);
vds.setNonOperationalReason(nonOperationalReason);
returnStatus = vds.getStatus();
}
}
// We process the software capabilities.
VDSStatus oldStatus = vds.getStatus();
monitoringStrategy.processSoftwareCapabilities(vds);
returnStatus = vds.getStatus();
if (returnStatus != oldStatus && returnStatus == VDSStatus.NonOperational) {
setIsSetNonOperationalExecuted(true);
}
processHardwareCapsNeeded.set(monitoringStrategy.processHardwareCapabilitiesNeeded(oldVDS, vds));
return returnStatus;
} else if (vdsBrokerCommand.getVDSReturnValue().getExceptionObject() != null) {
// if exception is VDSNetworkException then call to
// handleNetworkException
if (vdsBrokerCommand.getVDSReturnValue().getExceptionObject() instanceof VDSNetworkException
&& handleNetworkException((VDSNetworkException) vdsBrokerCommand.getVDSReturnValue()
.getExceptionObject(), vds)) {
UpdateDynamicData(vds.getDynamicData());
UpdateStatisticsData(vds.getStatisticsData());
}
throw vdsBrokerCommand.getVDSReturnValue().getExceptionObject();
} else {
log.errorFormat("refreshCapabilities:GetCapabilitiesVDSCommand failed with no exception!");
throw new RuntimeException(vdsBrokerCommand.getVDSReturnValue().getExceptionString());
}
}
private long calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) {
int spmIndicator = 0;
if (spmStatus != VdsSpmStatus.None) {
spmIndicator = 1;
}
return TimeUnit.SECONDS.toMillis((int)(
// delay time can be fracture number, casting it to int should be enough
Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) +
(Config.<Double> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) +
(Config.<Double> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount)));
}
/**
* Handle network exception, return true if save vdsDynamic to DB is needed.
*
* @param ex
* @return
*/
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) {
if (vds.getStatus() != VDSStatus.Down) {
long timeoutToFence = calcTimeoutToFence(vds.getVmCount(), vds.getSpmStatus());
if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount)
|| (lastUpdate + timeoutToFence) > System.currentTimeMillis()) {
boolean result = false;
if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance
&& vds.getStatus() != VDSStatus.NonResponsive) {
setStatus(VDSStatus.Connecting, vds);
result = true;
}
mUnrespondedAttempts.incrementAndGet();
return result;
}
if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) {
setStatus(VDSStatus.NonResponsive, vds);
return true;
}
setStatus(VDSStatus.NonResponsive, vds);
log.errorFormat(
"Server failed to respond, vds_id = {0}, vds_name = {1}, vm_count = {2}, " +
"spm_status = {3}, non-responsive_timeout = {5} error = {4}",
vds.getId(), vds.getName(), vds.getVmCount(), vds.getSpmStatus(), timeoutToFence,
ex.getMessage());
AuditLogableBase logable = new AuditLogableBase(vds.getId());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE);
ResourceManager.getInstance().getEventListener().vdsNotResponding(vds);
}
return true;
}
public void dispose() {
log.info("vdsManager::disposing");
SchedulerUtilQuartzImpl.getInstance().deleteJob(onTimerJobId);
XmlRpcUtils.shutDownConnection(((VdsServerWrapper) _vdsProxy).getHttpClient());
}
/**
* Log the network exception depending on the VDS status.
*
* @param e
* The exception to log.
*/
private void logNetworkException(VDSNetworkException e) {
switch (_vds.getStatus()) {
case Down:
break;
case NonResponsive:
log.debugFormat(
"Failed to refresh VDS , vds = {0} : {1}, VDS Network Error, continuing.\n{2}",
_vds.getId(),
_vds.getName(),
e.getMessage());
break;
default:
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, VDS Network Error, continuing.\n{2}",
_vds.getId(),
_vds.getName(),
e.getMessage());
}
}
public void setIsSetNonOperationalExecuted(boolean isExecuted) {
this.isSetNonOperationalExecuted = isExecuted;
}
public boolean isSetNonOperationalExecuted() {
return isSetNonOperationalExecuted;
}
private void setStartTime() {
updateStartTime = System.currentTimeMillis();
}
private void setLastUpdate() {
lastUpdate = System.currentTimeMillis();
}
/**
* @return elapsed time in milliseconds it took to update the Host run-time info. 0 means the updater never ran.
*/
public long getLastUpdateElapsed() {
return lastUpdate - updateStartTime;
}
/**
* @return VdsMonitor a class with means for lock and conditions for signaling
*/
public VdsMonitor getVdsMonitor() {
return vdsMonitor;
}
}
|
package org.intermine.bio.dataconversion;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.sql.Database;
import org.intermine.xml.full.Item;
/**
* Read Ensembl SNP data directly from MySQL variarion database.
* @author Richard Smith
*/
public class EnsemblSnpDbConverter extends BioDBConverter
{
private static final String DATASET_TITLE = "Ensembl SNP data";
private static final String DATA_SOURCE_NAME = "Ensembl";
// TODO move this to a parser argument
int taxonId = 9606;
private Map<String, String> sources = new HashMap<String, String>();
private Map<String, String> states = new HashMap<String, String>();
private Map<String, String> transcripts = new HashMap<String, String>();
private Map<String, String> noTranscriptConsequences = new HashMap<String, String>();
private static final Logger LOG = Logger.getLogger(EnsemblSnpDbConverter.class);
/**
* Construct a new EnsemblSnpDbConverter.
* @param database the database to read from
* @param model the Model used by the object store we will write to with the ItemWriter
* @param writer an ItemWriter used to handle Items created
*/
public EnsemblSnpDbConverter(Database database, Model model, ItemWriter writer) {
super(database, model, writer, DATA_SOURCE_NAME, DATASET_TITLE);
}
/**
* {@inheritDoc}
*/
public void process() throws Exception {
// a database has been initialised from properties starting with db.ensembl-snp-db
Connection connection = getDatabase().getConnection();
Set<String> chrNames = new HashSet<String>();
//int MIN_CHROMOSOME = 1;
int MIN_CHROMOSOME = 20;
for (int i = MIN_CHROMOSOME; i <= 22; i++) {
chrNames.add("" + i);
}
chrNames.add("X");
chrNames.add("Y");
for (String chrName : chrNames) {
process(connection, chrName);
}
connection.close();
}
/**
* {@inheritDoc}
*/
public void process(Connection connection, String chrName) throws Exception {
LOG.info("Starting to process chromosome " + chrName);
ResultSet res = queryVariation(connection, chrName);
int counter = 0;
int snpCounter = 0;
Item currentSnp = null;
Set<String> seenLocsForSnp = new HashSet<String>();
String currentRsNumber = null;
Set<String> consequenceIdentifiers = new HashSet<String>();
while (res.next()) {
counter++;
String rsNumber = res.getString("variation_name");
if (rsNumber.equals(currentRsNumber)) {
int start = res.getInt("seq_region_start");
int end = res.getInt("seq_region_end");
int strand = res.getInt("seq_region_strand");
int chrStart = Math.min(start, end);
int chrEnd = Math.max(start, end);
String chrLocStr = chrName + ":" + chrStart;
if (!seenLocsForSnp.contains(chrLocStr)) {
seenLocsForSnp.add(chrLocStr);
// if this location is on a chromosome we want, store it
Item loc = createItem("Location");
loc.setAttribute("start", "" + chrStart);
loc.setAttribute("end", "" + chrEnd);
loc.setAttribute("strand", "" + strand);
loc.setReference("feature", currentSnp);
loc.setReference("locatedOn", getChromosome(chrName, taxonId));
store(loc);
}
}
if (!rsNumber.equals(currentRsNumber)) {
// STORE PREVIOUS SNP
if (currentSnp != null) {
storeSnp(currentSnp, consequenceIdentifiers);
snpCounter++;
}
// START NEW SNP
currentRsNumber = rsNumber;
seenLocsForSnp = new HashSet<String>();
consequenceIdentifiers = new HashSet<String>();
String alleles = res.getString("allele_string");
currentSnp = createItem("SNP");
currentSnp.setAttribute("primaryIdentifier", rsNumber);
currentSnp.setAttribute("alleles", alleles);
currentSnp.setReference("organism", getOrganismItem(taxonId));
int mapWeight = res.getInt("map_weight");
boolean uniqueLocation = (mapWeight == 1) ? true : false;
currentSnp.setAttribute("uniqueLocation", "" + uniqueLocation);
String type = determineType(alleles);
if (type != null) {
currentSnp.setAttribute("type", type);
}
// CHROMOSOME AND LOCATION
// if SNP is mapped to multiple locations don't set chromosome and
// chromosomeLocation references
int start = res.getInt("seq_region_start");
int end = res.getInt("seq_region_end");
int chrStrand = res.getInt("seq_region_strand");
int chrStart = Math.min(start, end);
int chrEnd = Math.max(start, end);
Item loc = createItem("Location");
loc.setAttribute("start", "" + chrStart);
loc.setAttribute("end", "" + chrEnd);
loc.setAttribute("strand", "" + chrStrand);
loc.setReference("locatedOn", getChromosome(chrName, taxonId));
loc.setReference("feature", currentSnp);
store(loc);
// if mapWeight is 1 there is only one chromosome location, so set shortcuts
if (uniqueLocation) {
currentSnp.setReference("chromosome", getChromosome(chrName, taxonId));
currentSnp.setReference("chromosomeLocation", loc);
}
seenLocsForSnp.add(chrName + ":" + chrStart);
// SOURCE
String source = res.getString("s.name");
currentSnp.setReference("source", getSourceIdentifier(source));
// VALIDATION STATES
String validationStatus = res.getString("validation_status");
List<String> validationStates = getValidationStateCollection(validationStatus);
if (!validationStates.isEmpty()) {
currentSnp.setCollection("validations", validationStates);
}
}
// CONSEQUENCE TYPES
String cdnaStart = res.getString("cdna_start");
if (StringUtils.isBlank(cdnaStart)) {
String typeStr = res.getString("vf.consequence_type");
for (String type : typeStr.split(",")) {
consequenceIdentifiers.add(getConsequenceIdentifier(type));
}
} else {
String type = res.getString("tv.consequence_type");
String peptideAlleles = res.getString("peptide_allele_string");
String transcriptStableId = res.getString("transcript_stable_id");
Item consequenceItem = createItem("Consequence");
consequenceItem.setAttribute("type", type);
if (!StringUtils.isBlank(peptideAlleles)) {
consequenceItem.setAttribute("peptideAlleles", peptideAlleles);
}
if (!StringUtils.isBlank(transcriptStableId)) {
consequenceItem.setReference("transcript",
getTranscriptIdentifier(transcriptStableId));
}
consequenceIdentifiers.add(consequenceItem.getIdentifier());
store(consequenceItem);
}
if (counter % 1000 == 0) {
LOG.info("Read " + counter + " rows total, stored " + snpCounter + " SNPs. for chr"
+ chrName);
}
}
if (currentSnp != null) {
storeSnp(currentSnp, consequenceIdentifiers);
}
LOG.info("Finished " + counter + " rows total, stored " + snpCounter + " SNPs for chr"
+ chrName);
}
private void storeSnp(Item snp, Set<String> consequenceIdentifiers)
throws ObjectStoreException {
if (!consequenceIdentifiers.isEmpty()) {
snp.setCollection("consequences", new ArrayList<String>(consequenceIdentifiers));
}
store(snp);
}
private String determineType(String alleleStr) {
String type = null;
if (!StringUtils.isBlank(alleleStr)) {
// snp if e.g. A/C or A|C
if (alleleStr.matches("/^[ACGTN]([\\|\\\\\\/][ACGTN])+$/i")) {
type = "snp";
} else if ("cnv".equalsIgnoreCase(alleleStr)) {
type = alleleStr.toLowerCase();
} else if ("cnv_probe".equalsIgnoreCase(alleleStr)) {
type = alleleStr.toLowerCase();
} else if ("hgmd_mutation".equalsIgnoreCase(alleleStr)) {
type = alleleStr.toLowerCase();
} else {
String[] alleles = alleleStr.split("[\\|\\/\\\\]");
// if (alleles.length == 1) {
// type = "het";
}
}
return type;
}
private String getSourceIdentifier(String name) throws ObjectStoreException {
String sourceIdentifier = sources.get(name);
if (sourceIdentifier == null) {
Item source = createItem("Source");
source.setAttribute("name", name);
store(source);
sourceIdentifier = source.getIdentifier();
sources.put(name, sourceIdentifier);
}
return sourceIdentifier;
}
private String getTranscriptIdentifier(String transcriptStableId) throws ObjectStoreException {
String transcriptIdentifier = transcripts.get(transcriptStableId);
if (transcriptIdentifier == null) {
Item transcript = createItem("Transcript");
transcript.setAttribute("primaryIdentifier", transcriptStableId);
store(transcript);
transcriptIdentifier = transcript.getIdentifier();
transcripts.put(transcriptStableId, transcriptIdentifier);
}
return transcriptIdentifier;
}
private List<String> getValidationStateCollection(String input) throws ObjectStoreException {
List<String> stateIdentifiers = new ArrayList<String>();
if (!StringUtils.isBlank(input)) {
for (String state : input.split(",")) {
stateIdentifiers.add(getStateIdentifier(state));
}
}
return stateIdentifiers;
}
private String getStateIdentifier(String name) throws ObjectStoreException {
String stateIdentifier = states.get(name);
if (stateIdentifier == null) {
Item state = createItem("ValidationState");
state.setAttribute("name", name);
store(state);
stateIdentifier = state.getIdentifier();
states.put(name, stateIdentifier);
}
return stateIdentifier;
}
private String getConsequenceIdentifier(String type) throws ObjectStoreException {
String consequenceIdentifier = noTranscriptConsequences.get(type);
if (consequenceIdentifier == null) {
Item consequence = createItem("Consequence");
consequence.setAttribute("type", type);
store(consequence);
consequenceIdentifier = consequence.getIdentifier();
noTranscriptConsequences.put(type, consequenceIdentifier);
}
return consequenceIdentifier;
}
private ResultSet queryVariation(Connection connection, String chrName)
throws SQLException {
String query = "SELECT vf.variation_name, vf.allele_string, "
+ " sr.name,"
+ " vf.map_weight, vf.seq_region_start, vf.seq_region_end, vf.seq_region_strand, "
+ " s.name,"
+ " vf.validation_status,"
+ " vf.consequence_type,"
+ " tv.cdna_start,tv.consequence_type,tv.peptide_allele_string,tv.transcript_stable_id"
+ " FROM seq_region sr, source s, variation_feature vf "
+ " LEFT JOIN (transcript_variation tv)"
+ " ON (vf.variation_feature_id = tv.variation_feature_id"
+ " AND tv.cdna_start is not null)"
+ " WHERE vf.seq_region_id = sr.seq_region_id"
+ " AND vf.source_id = s.source_id"
+ " AND sr.name = " + chrName
+ " ORDER BY vf.variation_id";
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSetTitle(int taxonId) {
return DATASET_TITLE;
}
}
|
package org.commcare.adapters;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;
import org.commcare.CommCareApplication;
import org.commcare.dalvik.R;
import org.commcare.logging.AndroidLogger;
import org.commcare.logging.XPathErrorLogger;
import org.commcare.models.AndroidSessionWrapper;
import org.commcare.preferences.DeveloperPreferences;
import org.commcare.suite.model.EntityDatum;
import org.commcare.suite.model.Entry;
import org.commcare.suite.model.Menu;
import org.commcare.suite.model.MenuDisplayable;
import org.commcare.suite.model.SessionDatum;
import org.commcare.suite.model.Suite;
import org.commcare.util.CommCarePlatform;
import org.commcare.utils.MediaUtil;
import org.commcare.views.media.AudioButton;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.javarosa.xpath.parser.XPathSyntaxException;
import java.io.File;
import java.util.Hashtable;
import java.util.Vector;
/**
* Adapter class to handle both Menu and Entry items
*
* @author wspride
*/
public class MenuAdapter implements ListAdapter {
private final AndroidSessionWrapper asw;
final Context context;
MenuDisplayable[] displayableData;
public MenuAdapter(Context context, CommCarePlatform platform, String menuID) {
this.context = context;
String menuTitle = null;
Vector<MenuDisplayable> items = new Vector<>();
Hashtable<String, Entry> map = platform.getMenuMap();
asw = CommCareApplication._().getCurrentSessionWrapper();
EvaluationContext ec;
for (Suite s : platform.getInstalledSuites()) {
for (Menu m : s.getMenus()) {
String xpathExpression = "";
try {
XPathExpression relevance = m.getMenuRelevance();
if (m.getMenuRelevance() != null) {
xpathExpression = m.getMenuRelevanceRaw();
ec = asw.getEvaluationContext(m.getId());
if (!XPathFuncExpr.toBoolean(relevance.eval(ec))) {
continue;
}
}
if (m.getId().equals(menuID)) {
if (menuTitle == null) {
//TODO: Do I need args, here?
try {
menuTitle = m.getName().evaluate();
} catch (Exception e) {
e.printStackTrace();
}
}
xpathExpression = addRelevantCommandEntries(m, items, map, xpathExpression);
continue;
}
addUnaddedMenu(menuID, m, items);
} catch (XPathSyntaxException xpse) {
XPathErrorLogger.INSTANCE.logErrorToCurrentApp(xpathExpression, xpse.getMessage());
CommCareApplication._().triggerHandledAppExit(context, Localization.get("app.menu.display.cond.bad.xpath", new String[]{xpathExpression, xpse.getMessage()}));
displayableData = new MenuDisplayable[0];
return;
} catch (XPathException xpe) {
XPathErrorLogger.INSTANCE.logErrorToCurrentApp(xpe);
CommCareApplication._().triggerHandledAppExit(context, Localization.get("app.menu.display.cond.xpath.err", new String[]{xpathExpression, xpe.getMessage()}));
displayableData = new MenuDisplayable[0];
return;
}
}
}
displayableData = new MenuDisplayable[items.size()];
items.copyInto(displayableData);
}
private String addRelevantCommandEntries(Menu m, Vector<MenuDisplayable> items,
Hashtable<String, Entry> map,
String xpathExpression)
throws XPathSyntaxException {
for (String command : m.getCommandIds()) {
xpathExpression = "";
XPathExpression mRelevantCondition = m.getCommandRelevance(m.indexOfCommand(command));
if (mRelevantCondition != null) {
xpathExpression = m.getCommandRelevanceRaw(m.indexOfCommand(command));
EvaluationContext ec = asw.getEvaluationContext();
Object ret = mRelevantCondition.eval(ec);
try {
if (!XPathFuncExpr.toBoolean(ret)) {
continue;
}
} catch (XPathTypeMismatchException e) {
final String msg = "relevancy condition for menu item returned non-boolean value : " + ret;
XPathErrorLogger.INSTANCE.logErrorToCurrentApp(e.getSource(), msg);
Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, msg);
throw new RuntimeException(msg);
}
if (!XPathFuncExpr.toBoolean(ret)) {
continue;
}
}
Entry e = map.get(command);
if (e.isView()) {
//If this is a "view", not an "entry"
//we only want to display it if all of its
//datums are not already present
if (asw.getSession().getNeededDatum(e) == null) {
continue;
}
}
items.add(e);
}
return xpathExpression;
}
private static void addUnaddedMenu(String menuID, Menu m, Vector<MenuDisplayable> items) {
if (menuID.equals(m.getRoot())) {
//make sure we didn't already add this ID
boolean idExists = false;
for (Object o : items) {
if (o instanceof Menu) {
if (((Menu) o).getId().equals(m.getId())) {
idExists = true;
break;
}
}
}
if (!idExists) {
items.add(m);
}
}
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int arg0) {
return true;
}
@Override
public int getCount() {
return (displayableData.length);
}
@Override
public Object getItem(int i) {
return displayableData[i];
}
@Override
public long getItemId(int i) {
Object tempItem = displayableData[i];
if (tempItem instanceof Menu) {
return ((Menu) tempItem).getId().hashCode();
} else {
return ((Entry) tempItem).getCommandId().hashCode();
}
}
@Override
public int getItemViewType(int i) {
return 0;
}
enum NavIconState {
NONE, NEXT, JUMP
}
@Override
public View getView(int i, View v, ViewGroup vg) {
MenuDisplayable menuDisplayable = displayableData[i];
// inflate view
View menuListItem = v;
if (menuListItem == null) {
// inflate it and do not attach to parent, or we will get the 'addView not supported' exception
menuListItem = LayoutInflater.from(context).inflate(R.layout.menu_list_item_modern, vg, false);
}
TextView rowText = (TextView) menuListItem.findViewById(R.id.row_txt);
setupTextView(rowText, menuDisplayable);
AudioButton mAudioButton = (AudioButton) menuListItem.findViewById(R.id.row_soundicon);
setupAudioButton(mAudioButton, menuDisplayable);
// set up the image, if available
ImageView mIconView = (ImageView) menuListItem.findViewById(R.id.row_img);
setupImageView(mIconView, menuDisplayable);
return menuListItem;
}
private void setupAudioButton(AudioButton mAudioButton, MenuDisplayable menuDisplayable){
// set up audio
final String audioURI = menuDisplayable.getAudioURI();
String audioFilename = "";
if (audioURI != null && !audioURI.equals("")) {
try {
audioFilename = ReferenceManager._().DeriveReference(audioURI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e("AVTLayout", "Invalid reference exception");
e.printStackTrace();
}
}
File audioFile = new File(audioFilename);
// First set up the audio button
if (!"".equals(audioFilename) && audioFile.exists()) {
// Set not focusable so that list onclick will work
mAudioButton.setFocusable(false);
mAudioButton.setFocusableInTouchMode(false);
mAudioButton.resetButton(audioURI, true);
} else {
if (mAudioButton != null) {
mAudioButton.resetButton(audioURI, false);
((LinearLayout) mAudioButton.getParent()).removeView(mAudioButton);
}
}
}
public void setupTextView(TextView textView, MenuDisplayable menuDisplayable){
// set up text
String mQuestionText = textViewHelper(menuDisplayable);
//Final change, remove any numeric context requests. J2ME uses these to
//help with numeric navigation.
if (mQuestionText != null) {
mQuestionText = Localizer.processArguments(mQuestionText, new String[]{""}).trim();
}
textView.setText(mQuestionText);
}
public void setupImageView(ImageView mIconView, MenuDisplayable menuDisplayable){
String imageURI = menuDisplayable.getImageURI();
Bitmap image = MediaUtil.inflateDisplayImage(context, imageURI);
if (mIconView != null) {
if(image != null) {
mIconView.setImageBitmap(image);
mIconView.setAdjustViewBounds(true);
}
else{
setupDefaultIcon(mIconView, menuDisplayable, getIconState(menuDisplayable));
}
}
}
private NavIconState getIconState(MenuDisplayable menuDisplayable){
NavIconState iconChoice = NavIconState.NEXT;
//figure out some icons
if (menuDisplayable instanceof Entry) {
SessionDatum datum = asw.getSession().getNeededDatum((Entry) menuDisplayable);
if (datum == null || !(datum instanceof EntityDatum)) {
iconChoice = NavIconState.JUMP;
}
}
if (!DeveloperPreferences.isNewNavEnabled()) {
iconChoice = NavIconState.NONE;
}
return iconChoice;
}
protected void setupDefaultIcon(ImageView mIconView, MenuDisplayable menuDisplayable,
NavIconState iconChoice){
if (mIconView != null) {
switch (iconChoice) {
case NEXT:
mIconView.setImageResource(R.drawable.avatar_module);
break;
case JUMP:
mIconView.setImageResource(R.drawable.avatar_form);
break;
case NONE:
mIconView.setVisibility(View.GONE);
break;
}
}
}
/*
* Helper to build the TextView for the HorizontalMediaView constructor
*/
private static String textViewHelper(MenuDisplayable e) {
return e.getDisplayText();
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public void registerDataSetObserver(DataSetObserver arg0) {
}
@Override
public void unregisterDataSetObserver(DataSetObserver arg0) {
}
}
|
package uk.co.uwcs.choob.modules;
import java.util.*;
/** Some functions to help with time and date manipulation. */
public final class DateModule {
/**
* Units of time used in these functions.
*/
private static enum TimeUnit {
WEEK("w", 7 * 24 * 60 * 60 * 1000),
DAY("d", 24 * 60 * 60 * 1000),
HOUR("h", 60 * 60 * 1000),
MINUTE("m", 60 * 1000),
SECOND("s", 1000),
MILLISECOND("ms", 1);
private final String longToken;
private final String shortToken;
private final int duration;
TimeUnit(String shortToken, int duration) {
this.longToken = this.toString().toLowerCase();
this.shortToken = shortToken;
this.duration = duration;
}
public String quantity(boolean useShortTokens, long quantity) {
if (useShortTokens) {
return quantity + shortToken;
} else {
return quantity + " " + longToken + (quantity > 1 ? "s" : "");
}
}
public String lessThanOne(boolean useShortTokens) {
if (useShortTokens) {
return "<1" + shortToken;
} else {
return "less than " + ((this == HOUR) ? "an" : "a") + " "
+ longToken;
}
}
public int duration() {
return duration;
}
}
/**
* Helper, converts a long (ms) time to a Map.
*/
final static Map<TimeUnit, Long> getTimeUnitMap(long interval) {
Map<TimeUnit, Long> map = new EnumMap<TimeUnit, Long>(TimeUnit.class);
for (TimeUnit unit : EnumSet.allOf(TimeUnit.class)) {
final long quantity = (interval / unit.duration());
map.put(unit, quantity);
interval -= quantity * unit.duration();
}
return map;
}
/** Gives a minimal representation of the given time interval, ie 1w6d. */
public final String timeMicroStamp(final long i) {
return timeMicroStamp(i, 2);
}
/**
* Gives a minimal representation of the given time interval, with the
* specified (maximum) number of elements.
*/
public final String timeMicroStamp(final long i, final int granularity) {
return timeStamp(i, true, granularity, TimeUnit.MILLISECOND);
}
/**
* Gives a long representation of the given time interval, ie. "1 week and 6
* days"
*/
public final String timeLongStamp(final long i) {
return timeLongStamp(i, 2);
}
/**
* Gives a long representation of the given time interval, with the
* specified (maximum) number of elements.
*/
public final String timeLongStamp(final long i, final int granularity) {
return timeStamp(i, false, granularity, TimeUnit.MILLISECOND);
}
/**
* General function for generating approximate string representations of
* time periods.
*
* @param interval
* The time interval in question.
* @param shortTokens
* Use the condensed form (1w6d) or generate full English (1 week
* and 6 days).
* @param replyDetail
* Maximum number of parts to return.
* @param minGranularity
* Minimum level of output, i.e. passing 'days' here will cause
* 1w2d3h4m5s to only output 1w2d. Default is 'millisecond'.
*/
public final String timeStamp(final long interval,
final boolean shortTokens, final int replyDetail,
final TimeUnit minGranularity) {
final Map<TimeUnit, Long> unitQuantity = getTimeUnitMap(interval);
Set<TimeUnit> usedUnits = EnumSet.noneOf(TimeUnit.class);
int remainingDetail = replyDetail;
/*
* Go through the map, discard empty or invalid parts until we have
* enough (replyDetail).
*/
for (TimeUnit unit : TimeUnit.values()) {
if (remainingDetail <= 0) {
break;
}
if (unitQuantity.get(unit) != 0) {
usedUnits.add(unit);
remainingDetail
}
if (unit == minGranularity) {
break;
}
}
/*
* Take the desired parts of the map, and build a string.
*/
final String time;
if (usedUnits.size() == 0) {
// Special case: the period is less than the minGranularity.
time = minGranularity.lessThanOne(shortTokens);
} else {
// Build a list of the result tokens.
List<String> result = new ArrayList<String>();
for (TimeUnit unit : usedUnits) {
result.add(unit.quantity(shortTokens, unitQuantity.get(unit)));
}
final StringBuilder b = new StringBuilder();
// Concatenate the result as a string.
if (shortTokens) {
for (String token : result) {
b.append(token);
}
} else {
b.append(result.remove(0));
if (result.size() > 0) {
String lastToken = result.remove(result.size() - 1);
for (String token : result) {
b.append(", ");
b.append(token);
}
b.append(" and ");
b.append(lastToken);
}
}
time = b.toString();
}
return time;
}
}
|
package net.bytebuddy.dynamic.scaffold;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Test;
import static net.bytebuddy.matcher.ElementMatchers.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
public class MethodGraphCompilerDefaultTest {
@Test
public void testTrivial() throws Exception {
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(TypeDescription.OBJECT);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().size()));
assertThat(methodGraph.getSuperGraph().listNodes().size(), is(0));
assertThat(methodGraph.getInterfaceGraph(mock(TypeDescription.class)).listNodes().size(), is(0));
for (MethodDescription methodDescription : TypeDescription.OBJECT.getDeclaredMethods()) {
MethodGraph.Node node = methodGraph.locate(methodDescription.asToken());
assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
assertThat(node.isMadeVisible(), is(false));
assertThat(node.getBridges().size(), is(0));
assertThat(node.getRepresentative(), is(methodDescription));
assertThat(methodGraph.listNodes().contains(node), is(true));
}
}
@Test
public void testSimpleClass() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(SimpleClass.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 1));
assertThat(methodGraph.getSuperGraph().listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size()));
assertThat(methodGraph.getInterfaceGraph(mock(TypeDescription.class)).listNodes().size(), is(0));
for (MethodDescription methodDescription : TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual())) {
MethodGraph.Node node = methodGraph.locate(methodDescription.asToken());
assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
assertThat(node.isMadeVisible(), is(false));
assertThat(node.getBridges().size(), is(0));
assertThat(node.getRepresentative(), is(methodDescription));
assertThat(methodGraph.listNodes().contains(node), is(true));
}
MethodDescription constructor = typeDescription.getDeclaredMethods().filter(isConstructor()).getOnly();
MethodGraph.Node constructorNode = methodGraph.locate(constructor.asToken());
assertThat(constructorNode.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
assertThat(constructorNode.isMadeVisible(), is(false));
assertThat(constructorNode.getBridges().size(), is(0));
assertThat(constructorNode.getRepresentative(), is(constructor));
assertThat(methodGraph.listNodes().contains(constructorNode), is(true));
}
@Test
public void testSimpleInterface() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(SimpleInterface.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(0));
}
@Test
public void testClassInheritance() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(ClassBase.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
MethodDescription method = typeDescription.getDeclaredMethods().filter(isMethod()).getOnly();
MethodGraph.Node methodNode = methodGraph.locate(method.asToken());
assertThat(methodNode.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
assertThat(methodNode.isMadeVisible(), is(false));
assertThat(methodNode.getBridges().size(), is(0));
assertThat(methodNode.getRepresentative(), is(method));
assertThat(methodGraph.listNodes().contains(methodNode), is(true));
MethodGraph.Node baseNode = methodGraph.getSuperGraph().locate(method.asToken());
assertThat(methodNode, not(is(baseNode)));
assertThat(baseNode.getRepresentative(), is(typeDescription.getSuperType().getDeclaredMethods().filter(representedBy(method.asToken())).getOnly()));
}
@Test
public void testInterfaceImplementation() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(InterfaceBase.InnerClass.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
MethodDescription method = typeDescription.getInterfaces().getOnly().getDeclaredMethods().getOnly();
MethodGraph.Node methodNode = methodGraph.locate(method.asToken());
assertThat(methodNode.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
assertThat(methodNode.isMadeVisible(), is(false));
assertThat(methodNode.getBridges().size(), is(0));
assertThat(methodNode.getRepresentative(), is(method));
assertThat(methodGraph.listNodes().contains(methodNode), is(true));
}
@Test
public void testInterfaceExtension() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(InterfaceBase.InnerInterface.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(1));
MethodDescription method = typeDescription.getInterfaces().getOnly().getDeclaredMethods().getOnly();
MethodGraph.Node methodNode = methodGraph.locate(method.asToken());
assertThat(methodNode.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
assertThat(methodNode.isMadeVisible(), is(false));
assertThat(methodNode.getBridges().size(), is(0));
assertThat(methodNode.getRepresentative(), is(method));
assertThat(methodGraph.listNodes().contains(methodNode), is(true));
}
@Test
public void testMultipleInheritance() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(MultipleInheritance.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
MethodDescription method = typeDescription.getSuperType().getDeclaredMethods().filter(isMethod()).getOnly();
MethodGraph.Node methodNode = methodGraph.locate(method.asToken());
assertThat(methodNode.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
assertThat(methodNode.isMadeVisible(), is(false));
assertThat(methodNode.getBridges().size(), is(0));
assertThat(methodNode.getRepresentative(), is(method));
assertThat(methodGraph.listNodes().contains(methodNode), is(true));
MethodGraph.Node baseNode = methodGraph.getInterfaceGraph(new TypeDescription.ForLoadedType(InterfaceBase.class)).locate(method.asToken());
assertThat(methodNode, not(is(baseNode)));
assertThat(baseNode.getRepresentative(), is(typeDescription.getInterfaces().getOnly().getDeclaredMethods().getOnly()));
}
@Test
public void testGenericClassSingleEvolution() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(GenericClassBase.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
}
@Test
public void testGenericClassMultipleEvolution() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(GenericClassBase.Intermediate.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
}
@Test
public void testReturnTypeClassSingleEvolution() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(ReturnTypeClassBase.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
}
@Test
public void testReturnTypeClassMultipleEvolution() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(ReturnTypeClassBase.Intermediate.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
}
@Test
public void testGenericInterfaceSingleEvolution() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(ReturnTypeInterfaceBase.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(1));
}
@Test
public void testGenericInterfaceMultipleEvolution() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(ReturnTypeInterfaceBase.Intermediate.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(1));
}
@Test
public void testReturnTypeInterfaceSingleEvolution() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(ReturnTypeInterfaceBase.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(1));
}
@Test
public void testReturnTypeInterfaceMultipleEvolution() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(ReturnTypeInterfaceBase.Intermediate.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(1));
}
@Test
public void testVisibilityBridge() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(VisibilityBridgeTarget.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
}
@Test
public void testGenericVisibilityBridge() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(GenericVisibilityBridgeTarget.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
}
@Test
public void testMethodConvergence() throws Exception {
TypeDescription typeDescription = new TypeDescription.ForLoadedType(MethodConvergence.Inner.class);
MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().make(typeDescription);
assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 2));
}
@Test
public void testObjectProperties() throws Exception {
ObjectPropertyAssertion.of(MethodGraph.Compiler.Default.class).apply();
}
public static class SimpleClass {
/* empty */
}
public interface SimpleInterface {
/* empty */
}
public static class ClassBase {
public void foo() {
/* empty */
}
static class Inner extends ClassBase {
@Override
public void foo() {
/* empty */
}
}
}
public interface InterfaceBase {
void foo();
abstract class InnerClass implements InterfaceBase {
/* empty */
}
interface InnerInterface extends InterfaceBase {
/* empty */
}
}
public static class MultipleInheritance extends ClassBase implements InterfaceBase {
/* empty */
}
public static class GenericClassBase<T> {
public void foo(T t) {
/* empty */
}
public static class Inner extends GenericClassBase<Void> {
@Override
public void foo(Void t) {
/* empty */
}
}
public static class Intermediate<T extends Number> extends GenericClassBase<T> {
@Override
public void foo(T t) {
/* empty */
}
public static class Inner extends Intermediate<Integer> {
@Override
public void foo(Integer t) {
/* empty */
}
}
}
}
public static class ReturnTypeClassBase {
Object foo() {
return null;
}
public static class Inner extends ReturnTypeClassBase {
@Override
Void foo() {
return null;
}
}
public static class Intermediate extends ReturnTypeClassBase {
@Override
Number foo() {
return null;
}
public static class Inner extends Intermediate {
@Override
Integer foo() {
return null;
}
}
}
}
public interface GenericInterfaceBase<T> {
void foo(T t);
interface Inner extends GenericInterfaceBase<Void> {
@Override
void foo(Void t);
}
interface Intermediate<T extends Number> extends GenericInterfaceBase<T> {
@Override
void foo(T t);
interface Inner extends Intermediate<Integer> {
@Override
void foo(Integer t);
}
}
}
public interface ReturnTypeInterfaceBase {
Object foo();
interface Inner extends ReturnTypeInterfaceBase {
@Override
Void foo();
}
interface Intermediate extends ReturnTypeInterfaceBase {
@Override
Number foo();
interface Inner extends Intermediate {
@Override
Integer foo();
}
}
}
static class VisibilityBridgeBase {
public void foo() {
/* empty */
}
}
public static class VisibilityBridgeTarget extends VisibilityBridgeBase {
/* empty */
}
static class GenericVisibilityBridgeBase<T> {
public void foo(T t) {
/* empty */
}
}
static class GenericVisibilityBridge extends GenericVisibilityBridgeBase<Void> {
@Override
public void foo(Void aVoid) {
/* empty */
}
}
public static class GenericVisibilityBridgeTarget extends GenericVisibilityBridge {
/* empty */
}
public static class MethodConvergence<T> {
public T foo(T arg) {
return null;
}
public Void foo(Void arg) {
return null;
}
public static class Inner extends MethodConvergence<Void> {
@Override
public Void foo(Void arg) {
return null;
}
}
}
}
|
package com.github.sormuras.bach.workflow;
import com.github.sormuras.bach.Bach;
import com.github.sormuras.bach.api.CodeSpace;
import com.github.sormuras.bach.internal.Paths;
import com.github.sormuras.bach.tool.JLinkCall;
import java.nio.file.Path;
import java.util.List;
public class GenerateImageWorkflow extends BachWorkflow {
public GenerateImageWorkflow(Bach bach) {
super(bach);
}
public void generate() {
generateCustomRuntimeImage();
}
public void generateCustomRuntimeImage() {
var project = bach().project();
if (!project.tools().enabled("jlink")) return;
if (project.spaces().main().modules().isEmpty()) {
bach().log("Main module list is empty, nothing to do here.");
return;
}
bach().say("Generate custom runtime image");
var image = project.folders().workspace("image");
Paths.deleteDirectories(image);
bach().run(jlink(image));
}
protected JLinkCall jlink(Path image) {
var project = bach().project();
var folders = project.folders();
var paths = List.of(folders.modules(CodeSpace.MAIN), folders.externalModules());
var main = project.spaces().main();
var tweaks = project.tools().tweaks();
return new JLinkCall()
.ifTrue(bach().options().verbose(), args -> args.with("--verbose"))
.with("--add-modules", main.modules().toNames(","))
.with("--module-path", paths)
.withAll(tweaks.arguments(CodeSpace.MAIN, "jlink"))
.with("--output", image);
}
}
|
package org.zstack.zql.ast;
import org.apache.commons.lang.StringUtils;
import org.zstack.core.db.EntityMetadata;
import org.zstack.header.core.StaticInit;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.query.*;
import org.zstack.header.rest.APINoSee;
import org.zstack.header.search.Inventory;
import org.zstack.header.search.Parent;
import org.zstack.header.search.TypeField;
import org.zstack.utils.*;
import org.zstack.utils.logging.CLogger;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
import static org.codehaus.groovy.runtime.InvokerHelper.asList;
public class ZQLMetadata {
private static final CLogger logger = Utils.getLogger(ZQLMetadata.class);
public static final String USER_TAG_NAME = "__userTag__";
public static final String SYS_TAG_NAME = "__systemTag__";
public static class ExpandQueryMetadata {
public Class selfVOClass;
public Class targetVOClass;
public Class targetInventoryClass;
public String selfKeyName;
public String targetKeyName;
public String name;
public boolean hidden;
}
public static class ExpandQueryAliasMetadata {
public String aliasName;
public String expandQueryText;
}
public static class InventoryMetadata {
public Class selfInventoryClass;
public transient Inventory inventoryAnnotation;
public Map<String, ExpandQueryMetadata> expandQueries = new HashMap<>();
public Map<String, ExpandQueryAliasMetadata> expandQueryAliases = new HashMap<>();
public Set<String> selfInventoryFieldNames;
public boolean hasInventoryField(String fname) {
if (fname.equals(SYS_TAG_NAME) || fname.equals(USER_TAG_NAME)) {
return true;
} else {
return selfInventoryFieldNames.contains(fname);
}
}
public void errorIfNoField(String fname) {
if (!hasInventoryField(fname)) {
throw new CloudRuntimeException(String.format("inventory[${selfInventoryClass}] has no field[%s]", fname));
}
}
public boolean isUs(String inventoryName) {
return selfInventoryClass.getSimpleName().equalsIgnoreCase(inventoryName);
}
public String fullInventoryName() {
return selfInventoryClass.getName();
}
public String simpleInventoryName() {
return selfInventoryClass.getSimpleName();
}
}
/**
* key: the full class name of inventory, e.g. org.zstack.host.HostInventory
* value: InventoryMetadata
*/
public static Map<String, InventoryMetadata> inventoryMetadata = new HashMap<>();
/**
* key: parent inventory class
* value:
* key: type
* value: child inventory class
*/
public static Map<Class, Map<String, Class>> typeFieldToParentInventory = new HashMap<>();
/**
* key: inventory class
* value: field annotated by @TypeField
*/
public static Map<Class, Field> inventoryTypeFields = new HashMap<>();
public interface ChainQueryStruct {
default void verify() {
}
}
public static InventoryMetadata findInventoryMetadata(String queryName) {
String qname = String.format("%sinventory", queryName);
Optional<InventoryMetadata> opt = inventoryMetadata.values().stream().filter(i->i.isUs(qname)).findFirst();
DebugUtils.Assert(opt.isPresent(), String.format("cannot find inventory with name[%s]", queryName));
return opt.get();
}
public static InventoryMetadata getInventoryMetadataByName(String name) {
InventoryMetadata m = inventoryMetadata.get(name);
DebugUtils.Assert(m != null, String.format("cannot find metadata for inventory class[%s]", name));
return m;
}
public static class FieldChainQuery implements ChainQueryStruct {
public InventoryMetadata self;
public ExpandQueryMetadata right;
public String fieldName;
@Override
public void verify() {
if (right != null) {
InventoryMetadata him = getInventoryMetadataByName(right.targetInventoryClass.getName());
if (!him.hasInventoryField(fieldName)) {
throw new CloudRuntimeException(String.format("inventory class[%s] not having field[%s]", him.selfInventoryClass, fieldName));
}
} else {
if (!self.hasInventoryField(fieldName)) {
throw new CloudRuntimeException(String.format("inventory class[%s] not having field[%s]", self.selfInventoryClass, fieldName));
}
}
}
@Override
public String toString() {
return "FieldChainQuery{" +
"self=" + self.selfInventoryClass +
", right=" + right.name +
", fieldName='" + fieldName + '\'' +
'}';
}
}
public static class ExpandChainQuery implements ChainQueryStruct {
public String selfKey;
public InventoryMetadata self;
public ExpandQueryMetadata right;
@Override
public String toString() {
return "ExpandChainQuery{" +
"selfKey='" + selfKey + '\'' +
", self=" + self.selfInventoryClass +
", right=" + right.name +
'}';
}
}
public static List<ChainQueryStruct> createChainQuery(String inventoryName, List<String> nestConditionNames) {
return new ChainQueryStructGetter(inventoryName, nestConditionNames).get();
}
private static class ChainQueryStructGetter {
String inventoryName;
List<String> nestConditionNames;
public ChainQueryStructGetter(String inventoryName, List<String> nestConditionNames) {
this.inventoryName = inventoryName;
this.nestConditionNames = nestConditionNames;
}
List<ChainQueryStruct> get() {
DebugUtils.Assert(!nestConditionNames.isEmpty(), String.format("empty nestConditionNames for inventoryName[%s]", inventoryName));
InventoryMetadata metadata = inventoryMetadata.get(inventoryName);
if (metadata == null) {
throw new CloudRuntimeException(String.format("cannot find metadata for query target[%s]", inventoryName));
}
List<ChainQueryStruct> ret = new ArrayList<>();
if (nestConditionNames.size() == 1) {
FieldChainQuery f = new FieldChainQuery();
f.self = metadata;
f.fieldName = nestConditionNames.get(0);
ret.add(f);
} else {
String lastField = nestConditionNames.get(nestConditionNames.size()-1);
List<String> processedConditionsNames = new ArrayList<>();
preProcessingNestConditionNames(
metadata,
nestConditionNames.subList(0, nestConditionNames.size()-1).iterator(),
processedConditionsNames
);
Iterator<String> iterator = processedConditionsNames.iterator();
InventoryMetadata self = metadata;
ExpandQueryMetadata left = null;
while (iterator.hasNext()) {
String expandedQueryName = iterator.next();
ExpandQueryMetadata e = self.expandQueries.get(expandedQueryName);
if (e == null) {
throw new CloudRuntimeException(String.format("no expand query[%s] found on %s", expandedQueryName, self.selfInventoryClass));
}
ExpandChainQuery em = new ExpandChainQuery();
em.selfKey = left == null ? null : left.targetKeyName;
em.self = self;
em.right = e;
self = getInventoryMetadataByName(em.right.targetInventoryClass.getName());
left = em.right;
ret.add(em);
}
ExpandChainQuery last = (ExpandChainQuery) ret.get(ret.size()-1);
FieldChainQuery f = new FieldChainQuery();
f.right = last.right;
f.self = last.self;
f.fieldName = lastField;
ret.add(f);
}
ret.forEach(ChainQueryStruct::verify);
return ret;
}
private void preProcessingNestConditionNames(InventoryMetadata current, Iterator<String> names, List<String> result) {
if (!names.hasNext()) {
return;
}
String name = names.next();
ExpandQueryAliasMetadata alias = current.expandQueryAliases.get(name);
if (alias != null) {
List<String> newNames = new ArrayList<>();
Collections.addAll(newNames, alias.expandQueryText.split("\\."));
names.forEachRemaining(newNames::add);
preProcessingNestConditionNames(current, newNames.iterator(), result);
} else {
ExpandQueryMetadata expand = current.expandQueries.get(name);
if (expand == null) {
throw new CloudRuntimeException(String.format("invalid nested query condition[%s] on %s," +
"the expanded target[%s] have no expanded query[%s]",
StringUtils.join(names, "."),
current.selfInventoryClass,
current.selfInventoryClass,
name
));
}
current = inventoryMetadata.get(expand.targetInventoryClass.getName());
if (current == null) {
throw new CloudRuntimeException(String.format("unable to find inventory metadata for %s", expand.targetInventoryClass));
}
result.add(name);
preProcessingNestConditionNames(current, names, result);
}
}
}
public static Class getChildInventoryClassByType(Class parentInventory, String type) {
Map<String, Class> m = typeFieldToParentInventory.get(parentInventory);
if (m == null) {
throw new CloudRuntimeException(String.format("inventory class[%s] has no children inventory classes", parentInventory));
}
Class child = m.get(type);
if (child == null) {
return parentInventory;
} else {
return child;
}
}
private static void fillInventoryMetadata(Class clz,
List<ExpandedQuery> queries, List<ExpandedQueryAlias> aliases,
List<ExpandedQuery> queryForOther, List<ExpandedQueryAlias> aliasForOther) {
Inventory inventory = (Inventory) clz.getAnnotation(Inventory.class);
if (inventory == null) {
throw new CloudRuntimeException(String.format("class[%s] not annotated by @Inventory", clz));
}
for (Parent parent : inventory.parent()) {
Class parentInventory = parent.inventoryClass();
Map<String, Class> children = typeFieldToParentInventory.computeIfAbsent(parentInventory, x->new HashMap<>());
children.put(parent.type(), clz);
}
InventoryMetadata metadata = inventoryMetadata.computeIfAbsent(clz.getName(), x-> {
InventoryMetadata m = new InventoryMetadata();
m.inventoryAnnotation = inventory;
m.selfInventoryClass = clz;
m.selfInventoryFieldNames = FieldUtils.getAllFields(clz).stream()
.filter(i->!i.isAnnotationPresent(APINoSee.class))
.map(Field::getName)
.collect(Collectors.toSet());
return m;
});
if (queries != null) {
queries.forEach(it-> {
if (it.target() != Object.class && it.target() != clz) {
if (queryForOther == null) {
throw new CloudRuntimeException(String.format("found %s has an expanded query with target[%s], but queryForOther == null", clz, it.target()));
}
queryForOther.add(it);
return;
}
Class targetInventoryClass = it.inventoryClass();
if (!targetInventoryClass.isAnnotationPresent(Inventory.class)) {
throw new CloudRuntimeException(String.format("inventory class[%s] is query expanded by %s but not have @Inventory annotation", targetInventoryClass, clz));
}
ExpandQueryMetadata emetadata = new ExpandQueryMetadata();
emetadata.selfVOClass = inventory.mappingVOClass();
emetadata.targetVOClass = ((Inventory)targetInventoryClass.getAnnotation(Inventory.class)).mappingVOClass();
emetadata.targetInventoryClass = it.inventoryClass();
emetadata.selfKeyName = it.foreignKey();
emetadata.targetKeyName = it.expandedInventoryKey();
emetadata.name = it.expandedField();
emetadata.hidden = it.hidden();
metadata.expandQueries.put(emetadata.name, emetadata);
});
}
if (aliases != null) {
aliases.forEach(it -> {
if (it.target() != Object.class && it.target() != clz) {
if (queryForOther == null) {
throw new CloudRuntimeException(String.format("found %s has an expanded alias with target[%s], but aliasForOther == null", clz, it.target()));
}
aliasForOther.add(it);
return;
}
ExpandQueryAliasMetadata e = new ExpandQueryAliasMetadata();
e.aliasName = it.alias();
e.expandQueryText = it.expandedField();
metadata.expandQueryAliases.put(it.alias(), e);
});
}
FieldUtils.getAllFields(clz).stream().filter(f->f.isAnnotationPresent(Queryable.class)).forEach(f-> {
if (TypeUtils.isPrimitiveOrWrapper(f.getType())) {
return;
}
if (!Collection.class.isAssignableFrom(f.getType())) {
return;
}
Class gtype = FieldUtils.getGenericType(f);
if (gtype == null) {
return;
}
if (TypeUtils.isPrimitiveOrWrapper(gtype)) {
return;
}
Inventory targetInventoryAnnotation = (Inventory) gtype.getAnnotation(Inventory.class);
if (targetInventoryAnnotation == null) {
throw new CloudRuntimeException(String.format("field[%s] of inventory[%s] is annotated of @Queryable, however it's generic type[%s] is " +
" not annotated by @Inventory", f.getName(), clz, gtype));
}
Queryable queryable = f.getAnnotation(Queryable.class);
// create a expanded query for Queryable field
ExpandQueryMetadata emetadata = new ExpandQueryMetadata();
emetadata.selfVOClass = inventory.mappingVOClass();
emetadata.targetVOClass = targetInventoryAnnotation.mappingVOClass();
emetadata.targetInventoryClass = gtype;
emetadata.selfKeyName = EntityMetadata.getPrimaryKeyField(emetadata.selfVOClass).getName();
emetadata.targetKeyName = queryable.joinColumn().name();
emetadata.name = f.getName();
metadata.expandQueries.put(emetadata.name, emetadata);
});
inventoryMetadata.put(clz.getName(), metadata);
}
@StaticInit(order = -1)
static void staticInit() {
List<ExpandedQuery> queryForOther = new ArrayList<>();
List<ExpandedQueryAlias> aliasForOther = new ArrayList<>();
BeanUtils.reflections.getTypesAnnotatedWith(Inventory.class).stream().filter(i->i.isAnnotationPresent(Inventory.class))
.forEach(clz -> {
List<ExpandedQuery> expandedQueries = new ArrayList<>();
List<ExpandedQueryAlias> expandedQueryAliases = new ArrayList<>();
if (clz.isAnnotationPresent(ExpandedQueries.class)) {
Collections.addAll(expandedQueries, clz.getAnnotation(ExpandedQueries.class).value());
}
if (clz.isAnnotationPresent(ExpandedQueryAliases.class)) {
Collections.addAll(expandedQueryAliases, clz.getAnnotation(ExpandedQueryAliases.class).value());
}
fillInventoryMetadata(clz,
!expandedQueries.isEmpty() ? expandedQueries : null,
!expandedQueryAliases.isEmpty() ? expandedQueryAliases : null,
queryForOther, aliasForOther);
});
queryForOther.forEach(it -> {
Class clz = it.target();
fillInventoryMetadata(clz, asList(it), null, null, null);
});
aliasForOther.forEach(it -> {
Class clz = it.target();
fillInventoryMetadata(clz, null, asList(it), null, null);
});
inventoryMetadata.values().forEach(m -> inventoryMetadata.values().forEach(pm -> {
if (pm == m) {
return;
}
if (pm.selfInventoryClass.isAssignableFrom(m.selfInventoryClass)) {
m.expandQueries.putAll(pm.expandQueries);
m.expandQueryAliases.putAll(pm.expandQueryAliases);
}
}));
BeanUtils.reflections.getFieldsAnnotatedWith(TypeField.class).forEach(tf -> {
Field f = inventoryTypeFields.get(tf.getDeclaringClass());
if (f != null) {
throw new CloudRuntimeException(String.format("inventory class[%s] has two fields[%s,%s] annotated by @TypeField",
f.getDeclaringClass(), tf.getName(), f.getName()));
}
inventoryTypeFields.put(tf.getDeclaringClass(), tf);
});
}
public static Field getTypeFieldOfInventoryClass(Class invClass) {
return inventoryTypeFields.get(invClass);
}
}
|
package com.redhat.ceylon.compiler.java;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import ceylon.language.ArraySequence;
import ceylon.language.AssertionException;
import ceylon.language.Callable;
import ceylon.language.Integer;
import ceylon.language.Iterable;
import ceylon.language.Iterator;
import ceylon.language.Ranged;
import ceylon.language.Sequential;
import ceylon.language.empty_;
import ceylon.language.finished_;
import com.redhat.ceylon.cmr.api.ArtifactResult;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Class;
import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes;
import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
public class Util {
static {
// Make sure the rethrow class is loaded if ever we need to rethrow
// errors such as StackOverflowError, otherwise if we have to rethrow it
// we will not be able to load that class since we've ran out of stack
ceylon.language.impl.rethrow_.class.toString();
}
public static String declClassName(String name) {
return name.replace("::", ".");
}
public static void loadModule(String name, String version, ArtifactResult result, ClassLoader classLoader){
Metamodel.loadModule(name, version, result, classLoader);
}
public static boolean isReified(java.lang.Object o, TypeDescriptor type){
return Metamodel.isReified(o, type);
}
/**
* Returns true if the given object satisfies ceylon.language.Identifiable
*/
public static boolean isIdentifiable(java.lang.Object o){
return satisfiesInterface(o, "ceylon.language.Identifiable");
}
/**
* Returns true if the given object extends ceylon.language.Basic
*/
public static boolean isBasic(java.lang.Object o){
return extendsClass(o, "ceylon.language.Basic");
}
/**
* Returns true if the given object extends the given class
*/
public static boolean extendsClass(java.lang.Object o, String className) {
if(o == null)
return false;
if(className == null)
throw new AssertionException("Type name cannot be null");
return classExtendsClass(o.getClass(), className);
}
private static boolean classExtendsClass(java.lang.Class<?> klass, String className) {
if(klass == null)
return false;
if (klass.getName().equals(className))
return true;
if ((className.equals("ceylon.language.Basic"))
&& klass!=java.lang.Object.class
//&& klass!=java.lang.String.class
&& !klass.isAnnotationPresent(Class.class)
&& (!klass.isInterface() || !klass.isAnnotationPresent(Ceylon.class))) {
//TODO: this is broken for a Java class that
// extends a Ceylon class
return true;
}
return classExtendsClass(getCeylonSuperClass(klass), className);
}
private static java.lang.Class<?> getCeylonSuperClass(java.lang.Class<?> klass) {
Class classAnnotation = klass.getAnnotation(Class.class);
// only consider Class.extendsType() if non-empty
if (classAnnotation != null && !classAnnotation.extendsType().isEmpty()) {
String superclassName = declClassName(classAnnotation.extendsType());
int i = superclassName.indexOf('<');
if (i>0) {
superclassName = superclassName.substring(0, i);
}
if (superclassName.isEmpty()) {
throw new RuntimeException("Malformed @Class.extendsType() annotation value: "+classAnnotation.extendsType());
}
try {
return java.lang.Class.forName(superclassName, true, klass.getClassLoader());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
// we consider that subclasses of Object that do not have any @Ceylon.extendsType() are in fact subclasses of Basic
if(klass.getSuperclass() != java.lang.Object.class)
return klass.getSuperclass();
// Anything has no super class
if(klass == ceylon.language.Anything.class)
return null;
// The default super class is Basic
return ceylon.language.Basic.class;
}
/**
* Returns true if the given object satisfies the given interface
*/
public static boolean satisfiesInterface(java.lang.Object o, String className){
if(o == null)
return false;
if(className == null)
throw new AssertionException("Type name cannot be null");
// we use a hash set to speed things up for interfaces, to avoid looking at them twice
Set<java.lang.Class<?>> alreadyVisited = new HashSet<java.lang.Class<?>>();
return classSatisfiesInterface(o.getClass(), className, alreadyVisited);
}
private static boolean classSatisfiesInterface(java.lang.Class<?> klass, String className,
Set<java.lang.Class<?>> alreadyVisited) {
if(klass == null
|| klass == ceylon.language.Anything.class)
return false;
if ((className.equals("ceylon.language.Identifiable"))
&& klass!=java.lang.Object.class
//&& klass!=java.lang.String.class
&& !klass.isAnnotationPresent(Ceylon.class)) {
//TODO: this is broken for a Java class that
// extends a Ceylon class
return true;
}
// try the interfaces
if(lookForInterface(klass, className, alreadyVisited))
return true;
// try its superclass
return classSatisfiesInterface(getCeylonSuperClass(klass), className, alreadyVisited);
}
private static boolean lookForInterface(java.lang.Class<?> klass, String className,
Set<java.lang.Class<?>> alreadyVisited){
if (klass.getName().equals(className))
return true;
// did we already visit this type?
if(!alreadyVisited.add(klass))
return false;
// first see if it satisfies it directly
SatisfiedTypes satisfiesAnnotation = klass.getAnnotation(SatisfiedTypes.class);
if (satisfiesAnnotation!=null){
for (String satisfiedType : satisfiesAnnotation.value()){
satisfiedType = declClassName(satisfiedType);
int i = satisfiedType.indexOf('<');
if (i>0) {
satisfiedType = satisfiedType.substring(0, i);
}
try {
if (lookForInterface(
java.lang.Class.forName(satisfiedType, true, klass.getClassLoader()),
className, alreadyVisited)) {
return true;
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}else{
// otherwise look at this class's interfaces
for (java.lang.Class<?> intrface : klass.getInterfaces()){
if (lookForInterface(intrface, className, alreadyVisited))
return true;
}
}
// no luck
return false;
}
// Java variadic conversions
@SuppressWarnings("unchecked")
public static <T> List<T> collectIterable(Iterable<? extends T, ? extends java.lang.Object> sequence) {
List<T> list = new LinkedList<T>();
if (sequence != null) {
Iterator<? extends T> iterator = sequence.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
list.add((T)o);
}
}
return list;
}
public static boolean[] toBooleanArray(ceylon.language.Iterable<? extends ceylon.language.Boolean, ? extends java.lang.Object> sequence,
boolean... initialElements){
if(sequence instanceof ceylon.language.List)
return toBooleanArray((ceylon.language.List<? extends ceylon.language.Boolean>)sequence, initialElements);
List<ceylon.language.Boolean> list = collectIterable(sequence);
boolean[] ret = new boolean[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.Boolean e : list){
ret[i++] = e.booleanValue();
}
return ret;
}
public static boolean[] toBooleanArray(ceylon.language.List<? extends ceylon.language.Boolean> sequence,
boolean... initialElements){
boolean[] ret = new boolean[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().booleanValue();
sequence = (ceylon.language.List<? extends ceylon.language.Boolean>)sequence.getRest();
}
return ret;
}
public static byte[] toByteArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ? extends java.lang.Object> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toByteArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence, initialElements);
List<ceylon.language.Integer> list = collectIterable(sequence);
byte[] ret = new byte[initialElements.length + list.size()];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (byte) initialElements[i];
}
for(ceylon.language.Integer e : list){
ret[i++] = (byte)e.longValue();
}
return ret;
}
public static byte[] toByteArray(ceylon.language.List<? extends ceylon.language.Integer> sequence,
long... initialElements){
byte[] ret = new byte[initialElements.length + (int) sequence.getSize()];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (byte) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (byte) sequence.getFirst().longValue();
sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest();
}
return ret;
}
public static short[] toShortArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ? extends java.lang.Object> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toShortArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence, initialElements);
List<ceylon.language.Integer> list = collectIterable(sequence);
short[] ret = new short[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (short) initialElements[i];
}
for(ceylon.language.Integer e : list){
ret[i++] = (short)e.longValue();
}
return ret;
}
public static short[] toShortArray(ceylon.language.List<? extends ceylon.language.Integer> sequence,
long... initialElements){
short[] ret = new short[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (short) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (short) sequence.getFirst().longValue();
sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest();
}
return ret;
}
public static int[] toIntArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ? extends java.lang.Object> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toIntArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence, initialElements);
List<ceylon.language.Integer> list = collectIterable(sequence);
int[] ret = new int[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (int) initialElements[i];
}
for(ceylon.language.Integer e : list){
ret[i++] = (int)e.longValue();
}
return ret;
}
public static int[] toIntArray(ceylon.language.List<? extends ceylon.language.Integer> sequence,
long... initialElements){
int[] ret = new int[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (int) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (int) sequence.getFirst().longValue();
sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest();
}
return ret;
}
public static long[] toLongArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ? extends java.lang.Object> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toLongArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence, initialElements);
List<ceylon.language.Integer> list = collectIterable(sequence);
long[] ret = new long[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.Integer e : list){
ret[i++] = e.longValue();
}
return ret;
}
public static long[] toLongArray(ceylon.language.List<? extends ceylon.language.Integer> sequence,
long... initialElements){
long[] ret = new long[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().longValue();
sequence = (ceylon.language.List<? extends ceylon.language.Integer>)sequence.getRest();
}
return ret;
}
public static float[] toFloatArray(ceylon.language.Iterable<? extends ceylon.language.Float, ? extends java.lang.Object> sequence,
double... initialElements){
if(sequence instanceof ceylon.language.List)
return toFloatArray((ceylon.language.List<? extends ceylon.language.Float>)sequence, initialElements);
List<ceylon.language.Float> list = collectIterable(sequence);
float[] ret = new float[initialElements.length + list.size()];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (float) initialElements[i];
}
for(ceylon.language.Float e : list){
ret[i++] = (float)e.doubleValue();
}
return ret;
}
public static float[] toFloatArray(ceylon.language.List<? extends ceylon.language.Float> sequence,
double... initialElements){
float[] ret = new float[initialElements.length + (int) sequence.getSize()];
int i = 0;
for(;i<initialElements.length;i++){
ret[i] = (float) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (float) sequence.getFirst().doubleValue();
sequence = (ceylon.language.List<? extends ceylon.language.Float>)sequence.getRest();
}
return ret;
}
public static double[] toDoubleArray(ceylon.language.Iterable<? extends ceylon.language.Float, ? extends java.lang.Object> sequence,
double... initialElements){
if(sequence instanceof ceylon.language.List)
return toDoubleArray((ceylon.language.List<? extends ceylon.language.Float>)sequence, initialElements);
List<ceylon.language.Float> list = collectIterable(sequence);
double[] ret = new double[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.Float e : list){
ret[i++] = e.doubleValue();
}
return ret;
}
public static double[] toDoubleArray(ceylon.language.List<? extends ceylon.language.Float> sequence,
double... initialElements){
double[] ret = new double[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().doubleValue();
sequence = (ceylon.language.List<? extends ceylon.language.Float>)sequence.getRest();
}
return ret;
}
public static char[] toCharArray(ceylon.language.Iterable<? extends ceylon.language.Character, ? extends java.lang.Object> sequence,
int... initialElements){
if(sequence instanceof ceylon.language.List)
return toCharArray((ceylon.language.List<? extends ceylon.language.Character>)sequence, initialElements);
List<ceylon.language.Character> list = collectIterable(sequence);
char[] ret = new char[list.size() + initialElements.length];
int i=0;
// FIXME: this is invalid and should yield a larger array by splitting chars > 16 bits in two
for(;i<initialElements.length;i++){
ret[i] = (char) initialElements[i];
}
for(ceylon.language.Character e : list){
ret[i++] = (char)e.intValue();
}
return ret;
}
public static char[] toCharArray(ceylon.language.List<? extends ceylon.language.Character> sequence,
int... initialElements){
char[] ret = new char[(int) sequence.getSize() + initialElements.length];
int i=0;
// FIXME: this is invalid and should yield a larger array by splitting chars > 16 bits in two
for(;i<initialElements.length;i++){
ret[i] = (char) initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = (char) sequence.getFirst().intValue();
sequence = (ceylon.language.List<? extends ceylon.language.Character>)sequence.getRest();
}
return ret;
}
public static int[] toCodepointArray(ceylon.language.Iterable<? extends ceylon.language.Character, ? extends java.lang.Object> sequence,
int... initialElements){
if(sequence instanceof ceylon.language.List)
return toCodepointArray((ceylon.language.List<? extends ceylon.language.Character>)sequence, initialElements);
List<ceylon.language.Character> list = collectIterable(sequence);
int[] ret = new int[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.Character e : list){
ret[i++] = e.intValue();
}
return ret;
}
public static int[] toCodepointArray(ceylon.language.List<? extends ceylon.language.Character> sequence,
int... initialElements){
int[] ret = new int[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().intValue();
sequence = (ceylon.language.List<? extends ceylon.language.Character>)sequence.getRest();
}
return ret;
}
public static java.lang.String[] toJavaStringArray(ceylon.language.Iterable<? extends ceylon.language.String, ? extends java.lang.Object> sequence,
java.lang.String... initialElements){
if(sequence instanceof ceylon.language.List)
return toJavaStringArray((ceylon.language.List<? extends ceylon.language.String>)sequence, initialElements);
List<ceylon.language.String> list = collectIterable(sequence);
java.lang.String[] ret = new java.lang.String[list.size() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
for(ceylon.language.String e : list){
ret[i++] = e.toString();
}
return ret;
}
public static java.lang.String[] toJavaStringArray(ceylon.language.List<? extends ceylon.language.String> sequence,
java.lang.String... initialElements){
java.lang.String[] ret = new java.lang.String[(int) sequence.getSize() + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = initialElements[i];
}
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst().toString();
sequence = (ceylon.language.List<? extends ceylon.language.String>)sequence.getRest();
}
return ret;
}
public static <T> T[] toArray(ceylon.language.List<? extends T> sequence,
T[] ret, T... initialElements){
System.arraycopy(initialElements, 0, ret, 0, initialElements.length);
int i=initialElements.length;
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst();
sequence = (ceylon.language.List<? extends T>)sequence.getRest();
}
return ret;
}
public static <T> T[] toArray(ceylon.language.List<? extends T> sequence,
java.lang.Class<T> klass, T... initialElements){
@SuppressWarnings("unchecked")
T[] ret = (T[]) java.lang.reflect.Array.newInstance(klass, (int)sequence.getSize() + initialElements.length);
System.arraycopy(initialElements, 0, ret, 0, initialElements.length);
int i=initialElements.length;
while(!sequence.getEmpty()){
ret[i++] = sequence.getFirst();
sequence = (ceylon.language.List<? extends T>)sequence.getRest();
}
return ret;
}
public static <T> T[] toArray(ceylon.language.Iterable<? extends T, ? extends java.lang.Object> iterable,
java.lang.Class<T> klass, T... initialElements){
List<T> list = collectIterable(iterable);
@SuppressWarnings("unchecked")
T[] ret = (T[]) java.lang.reflect.Array.newInstance(klass, list.size() + initialElements.length);
// fast path
if(initialElements.length == 0){
// fast copy of list
list.toArray(ret);
}else{
// fast copy of initialElements
System.arraycopy(initialElements, 0, ret, 0, initialElements.length);
// slow iteration for list :(
int i = initialElements.length;
for(T o : list)
ret[i++] = o;
}
return ret;
}
public static <T> T checkNull(T t) {
if(t == null)
throw new AssertionException("null value returned from native call not assignable to Object");
return t;
}
/**
* Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence}
* wrapping the given elements, depending on whether the given array is
* empty
* @param elements The elements
* @return A Sequential
*/
public static <T> Sequential<T> sequentialInstance(TypeDescriptor $reifiedT, T[] elements) {
if (elements.length == 0) {
return (Sequential)empty_.get_();
}
// Annoyingly this implies an extra copy
return ArraySequence.<T>instance($reifiedT, elements);
}
public static Sequential<? extends ceylon.language.String> sequentialInstanceBoxed(java.lang.String[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(java.lang.String element : elements){
newArray[i++] = ceylon.language.String.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.String.$TypeDescriptor$, newArray);
}
public static Sequential<? extends ceylon.language.Integer> sequentialInstanceBoxed(long[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(long element : elements){
newArray[i++] = ceylon.language.Integer.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Integer.$TypeDescriptor$, newArray);
}
public static Sequential<? extends ceylon.language.Character> sequentialInstanceBoxed(int[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(int element : elements){
newArray[i++] = ceylon.language.Character.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Character.$TypeDescriptor$, newArray);
}
public static Sequential<? extends ceylon.language.Boolean> sequentialInstanceBoxed(boolean[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(boolean element : elements){
newArray[i++] = ceylon.language.Boolean.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Boolean.$TypeDescriptor$, newArray);
}
public static Sequential<? extends ceylon.language.Float> sequentialInstanceBoxed(double[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(double element : elements){
newArray[i++] = ceylon.language.Float.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Float.$TypeDescriptor$, newArray);
}
/**
* Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence}
* wrapping the given elements, depending on whether the given array and varargs are
* empty
* @param rest The elements at the end of the sequence
* @param elements the elements at the start of the sequence
* @return A Sequential
*/
public static <T> Sequential<? extends T> sequentialInstance(TypeDescriptor $reifiedT, Sequential<? extends T> rest, T... elements) {
return sequentialInstance($reifiedT, 0, elements.length, elements, true, rest);
}
/**
* Returns a Sequential made by concatenating the {@code length} elements
* of {@code elements} starting from {@code state} with the elements of
* {@code rest}: <code> {*elements[start:length], *rest}</code>.
*
* <strong>This method does not copy {@code elements} unless it has to</strong>
*/
public static <T> Sequential<? extends T> sequentialInstance(
TypeDescriptor $reifiedT,
int start, int length, T[] elements, boolean copy,
Sequential<? extends T> rest) {
if (length == 0){
if(rest.getEmpty()) {
return (Sequential)empty_.get_();
}
return rest;
}
// elements is not empty
if(rest.getEmpty()) {
return new ArraySequence($reifiedT, elements, start, length, copy);
}
// we have both, let's find the total size
int total = (int) (rest.getSize() + length);
java.lang.Object[] newArray = new java.lang.Object[total];
System.arraycopy(elements, start, newArray, 0, length);
Iterator<? extends T> iterator = rest.iterator();
int i = length;
for(Object elem; (elem = iterator.next()) != finished_.get_(); i++){
newArray[i] = elem;
}
return ArraySequence.<T>instance($reifiedT, newArray);
}
/**
* Method for instantiating a Range (or Empty) from a Tree.SpreadOp,
* {@code start:length}.
* @param start The start
* @param length The size of the Range to create
* @return A range
*/
public static <T extends ceylon.language.Ordinal<? extends T>> Sequential<T> spreadOp(TypeDescriptor $reifiedT, T start, long length) {
if (length <= 0) {
return (Sequential)empty_.get_();
}
if (start instanceof ceylon.language.Integer) {
ceylon.language.Integer startInt = (ceylon.language.Integer)start;
return new ceylon.language.Range($reifiedT, startInt,
ceylon.language.Integer.instance(startInt.longValue() + (length - 1)));
} else if (start instanceof ceylon.language.Character) {
ceylon.language.Character startChar = (ceylon.language.Character)start;
return new ceylon.language.Range($reifiedT, startChar,
ceylon.language.Character.instance((int)(startChar.intValue() + length - 1)));
} else {
T end = start;
long ii = 0L;
while (++ii < length) {
end = end.getSuccessor();
}
return new ceylon.language.Range($reifiedT, start, end);
}
}
/**
* Returns a runtime exception. To be used by implementors of mixin methods used to access super-interfaces $impl fields
* for final classes that don't and will never need them
*/
public static RuntimeException makeUnimplementedMixinAccessException() {
return new RuntimeException("Internal error: should never be called");
}
/**
* Specialised version of Tuple.spanFrom for when the typechecker determines that it can do better than the generic one
* that returns a Sequential. Here we return a Tuple, although our type signature hides this.
*/
public static Sequential tuple_spanFrom(Ranged tuple, ceylon.language.Integer index){
Sequential seq = (Sequential)tuple;
long i = index.longValue();
while(i
seq = seq.getRest();
}
return seq;
}
public static boolean[] fillArray(boolean[] array, boolean val){
Arrays.fill(array, val);
return array;
}
public static byte[] fillArray(byte[] array, byte val){
Arrays.fill(array, val);
return array;
}
public static short[] fillArray(short[] array, short val){
Arrays.fill(array, val);
return array;
}
public static int[] fillArray(int[] array, int val){
Arrays.fill(array, val);
return array;
}
public static long[] fillArray(long[] array, long val){
Arrays.fill(array, val);
return array;
}
public static float[] fillArray(float[] array, float val){
Arrays.fill(array, val);
return array;
}
public static double[] fillArray(double[] array, double val){
Arrays.fill(array, val);
return array;
}
public static char[] fillArray(char[] array, char val){
Arrays.fill(array, val);
return array;
}
public static <T> T[] fillArray(T[] array, T val){
Arrays.fill(array, val);
return array;
}
/**
* Returns a runtime exception. To be used by implementors of Java array methods used to make sure they are never called
*/
public static RuntimeException makeJavaArrayWrapperException() {
return new RuntimeException("Internal error: should never be called");
}
/**
* Throws an exception without having to declare it. This uses a Ceylon helper that does
* this because Ceylon does not have checked exceptions. This is merely to avoid a javac
* check wrt. checked exceptions.
* Stef tried using Unsafe.throwException() but Unsafe.getUnsafe() throws if we have a
* ClassLoader, and the only other way is using reflection to get to it, which starts
* to smell real bad when we can just use a Ceylon helper.
*/
public static void rethrow(final Throwable t){
ceylon.language.impl.rethrow_.rethrow(t);
}
/**
* Null-safe equals.
*/
public static boolean eq(Object a, Object b) {
if(a == null)
return b == null;
if(b == null)
return false;
return a.equals(b);
}
/**
* Applies the given function to the given arguments. The argument types are assumed to be correct and
* will not be checked. This method will properly deal with variadic functions. The arguments are expected
* to be spread in the given sequential, even in the case of variadic functions, which means that there will
* be no spreading of any Sequential instance in the given arguments. On the contrary, a portion of the given
* arguments may be packaged into a Sequential if the given function is variadic.
*
* @param function the function to apply
* @param arguments the argument values to pass to the function
* @return the function's return value
*/
public static <Return> Return apply(Callable<? extends Return> function, Sequential<? extends Object> arguments){
int variadicParameterIndex = function.$getVariadicParameterIndex$();
switch ((int) arguments.getSize()) {
case 0:
// even if the function is variadic it will overload $call so we're good
return function.$call$();
case 1:
// if the first param is variadic, just pass the sequence along
if(variadicParameterIndex == 0)
return function.$callvariadic$(arguments);
return function.$call$(arguments.get(Integer.instance(0)));
case 2:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential)arguments.spanFrom(Integer.instance(1)));
// no variadic param, or after we run out of elements to pass
default:
return function.$call$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)));
}
case 3:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential)arguments.spanFrom(Integer.instance(1)));
// extract the first and second, pass the rest
case 2: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
(Sequential)arguments.spanFrom(Integer.instance(2)));
// no variadic param, or after we run out of elements to pass
default:
return function.$call$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
arguments.get(Integer.instance(2)));
}
default:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential)arguments.spanFrom(Integer.instance(1)));
// extract the first and second, pass the rest
case 2: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
(Sequential)arguments.spanFrom(Integer.instance(2)));
case 3: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
arguments.get(Integer.instance(2)),
(Sequential)arguments.spanFrom(Integer.instance(3)));
// no variadic param
case -1:
java.lang.Object[] args = Util.toArray(arguments, new java.lang.Object[(int) arguments.getSize()]);
return function.$call$(args);
// we have a variadic param in there bothering us
default:
// we stuff everything before the variadic into an array
int beforeVariadic = (int)Math.min(arguments.getSize(), variadicParameterIndex);
boolean needsVariadic = beforeVariadic < arguments.getSize();
args = new java.lang.Object[beforeVariadic + (needsVariadic ? 1 : 0)];
Iterator iterator = arguments.iterator();
java.lang.Object it;
int i=0;
while(i < beforeVariadic && (it = iterator.next()) != finished_.get_()){
args[i++] = it;
}
// add the remainder as a variadic arg if required
if(needsVariadic){
args[i] = arguments.spanFrom(Integer.instance(beforeVariadic));
return function.$callvariadic$(args);
}
return function.$call$(args);
}
}
}
public static <T> java.lang.Class<T> getJavaClassForDescriptor(TypeDescriptor descriptor) {
if(descriptor == TypeDescriptor.NothingType
|| descriptor == ceylon.language.Object.$TypeDescriptor$
|| descriptor == ceylon.language.Anything.$TypeDescriptor$
|| descriptor == ceylon.language.Basic.$TypeDescriptor$
|| descriptor == ceylon.language.Null.$TypeDescriptor$
|| descriptor == ceylon.language.Identifiable.$TypeDescriptor$)
return (java.lang.Class<T>) Object.class;
if(descriptor instanceof TypeDescriptor.Class)
return (java.lang.Class<T>) ((TypeDescriptor.Class) descriptor).getKlass();
if(descriptor instanceof TypeDescriptor.Member)
return getJavaClassForDescriptor(((TypeDescriptor.Member) descriptor).getMember());
if(descriptor instanceof TypeDescriptor.Intersection)
return (java.lang.Class<T>) Object.class;
if(descriptor instanceof TypeDescriptor.Union){
TypeDescriptor.Union union = (TypeDescriptor.Union) descriptor;
TypeDescriptor[] members = union.getMembers();
// special case for optional types
if(members.length == 2){
if(members[0] == ceylon.language.Null.$TypeDescriptor$)
return getJavaClassForDescriptor(members[1]);
if(members[1] == ceylon.language.Null.$TypeDescriptor$)
return getJavaClassForDescriptor(members[0]);
}
return (java.lang.Class<T>) Object.class;
}
return (java.lang.Class<T>) Object.class;
}
public static int arrayLength(Object o) {
if (o instanceof Object[])
return ((Object[])o).length;
else if (o instanceof boolean[])
return ((boolean[])o).length;
else if (o instanceof float[])
return ((float[])o).length;
else if (o instanceof double[])
return ((double[])o).length;
else if (o instanceof char[])
return ((char[])o).length;
else if (o instanceof byte[])
return ((byte[])o).length;
else if (o instanceof short[])
return ((short[])o).length;
else if (o instanceof int[])
return ((int[])o).length;
else if (o instanceof long[])
return ((long[])o).length;
throw new ClassCastException(notArrayType(o));
}
public static long getIntegerArray(Object o, int index) {
if (o instanceof byte[])
return ((byte[])o)[index];
else if (o instanceof short[])
return ((short[])o)[index];
else if (o instanceof int[])
return ((int[])o)[index];
else if (o instanceof long[])
return ((long[])o)[index];
throw new ClassCastException(notArrayType(o));
}
public static double getDoubleArray(Object o, int index) {
if (o instanceof float[])
return ((float[])o)[index];
else if (o instanceof double[])
return ((double[])o)[index];
throw new ClassCastException(notArrayType(o));
}
public static int getCharacterArray(Object o, int index) {
if (o instanceof char[])
return ((char[])o)[index];
throw new ClassCastException(notArrayType(o));
}
public static boolean getBooleanArray(Object o, int index) {
if (o instanceof boolean[])
return ((boolean[])o)[index];
throw new ClassCastException(notArrayType(o));
}
public static Object getObjectArray(Object o, int index) {
if (o instanceof Object[])
return ((Object[])o)[index];
else if (o instanceof boolean[])
return ceylon.language.Boolean.instance(((boolean[])o)[index]);
else if (o instanceof float[])
return ceylon.language.Float.instance(((float[])o)[index]);
else if (o instanceof double[])
return ceylon.language.Float.instance(((double[])o)[index]);
else if (o instanceof char[])
return ceylon.language.Character.instance(((char[])o)[index]);
else if (o instanceof byte[])
return ceylon.language.Integer.instance(((byte[])o)[index]);
else if (o instanceof short[])
return ceylon.language.Integer.instance(((short[])o)[index]);
else if (o instanceof int[])
return ceylon.language.Integer.instance(((int[])o)[index]);
else if (o instanceof long[])
return ceylon.language.Integer.instance(((long[])o)[index]);
throw new ClassCastException(notArrayType(o));
}
private static String notArrayType(Object o) {
return (o == null ? "null" : o.getClass().getName()) + " is not an array type";
}
}
|
package cucumber.eclipse.editor.steps.jdt;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import cucumber.eclipse.editor.preferences.CucumberUserSettingsPage;
import cucumber.eclipse.steps.integration.IStepDefinitions;
import cucumber.eclipse.steps.integration.IStepListener;
import cucumber.eclipse.steps.integration.Step;
import cucumber.eclipse.steps.integration.StepsChangedEvent;
import cucumber.eclipse.steps.jdt.StepDefinitions;
/**
* @author girija.panda@nokia.com
*
* Purpose: Inhering 'cucumber.eclipse.steps.jdt.StepDefinitions' class
* is to avoid plugin-dependency conflicts due to
* 'CucumberUserSettingsPage' class. Supports reusing of
* Step-Definitions from external JAR(.class) exists in class-path.
* Reads the package name of external JAR from 'User Settings' of
* Cucumber-Preference page and Populate the step proposals from
* external JAR
*
* Also Modified For Issue #211 : Duplicate Step definitions
*
*/
public class JDTStepDefinitions extends StepDefinitions implements IStepDefinitions {
private CucumberUserSettingsPage userSettingsPage = new CucumberUserSettingsPage();
// 1. To get Steps as Set from both Java-Source and JAR file
@Override
public Set<Step> getSteps(IFile featurefile, IProgressMonitor progressMonitor) throws JavaModelException, CoreException {
// Commented By Girija to use LinkedHashSet Instead of HashSet
// Set<Step> steps = new HashSet<Step>();
// Used LinkedHashSet : Import all steps from step-definition File
Set<Step> steps = new LinkedHashSet<Step>();
try {
//Scan project and direct referenced projects...
Set<IProject> projects = new LinkedHashSet<IProject>();
IProject project = featurefile.getProject();
if(project.isAccessible()) { // skip closed project
projects.add(project);
projects.addAll(Arrays.asList(project.getReferencedProjects()));
SubMonitor subMonitor = SubMonitor.convert(progressMonitor, projects.size());
for (IProject projectToScan : projects) {
scanProject(projectToScan, featurefile, steps, subMonitor.newChild(1));
}
}
} finally {
if (progressMonitor != null) {
progressMonitor.done();
}
}
return steps;
}
private void scanProject(IProject project, IFile featurefile, Set<Step> steps, IProgressMonitor progressMonitor) throws JavaModelException, CoreException {
try {
// Get Package name/s from 'User-Settings' preference
final String externalPackageName = this.userSettingsPage.getPackageName();
//System.out.println("Package Names = " + externalPackageName);
String[] extPackages = externalPackageName.trim().split(COMMA);
//#239:Only match step implementation in same package as feature file
final boolean onlyPackages = this.userSettingsPage.getOnlyPackages();
final String onlySpeficicPackagesValue = this.userSettingsPage.getOnlySpecificPackage().trim();
final boolean onlySpeficicPackages= onlySpeficicPackagesValue.length() == 0 ? false : true;
String featurefilePackage = featurefile.getParent().getFullPath().toString();
if (project.isNatureEnabled(JAVA_PROJECT)) {
IJavaProject javaProject = JavaCore.create(project);
IPackageFragment[] packages = javaProject.getPackageFragments();
SubMonitor subMonitor = SubMonitor.convert(progressMonitor, packages.length);
for (IPackageFragment javaPackage : packages) {
// Get Packages from source folder of current project
// #239:Only match step implementation in same package as feature file
if (javaPackage.getKind() == JAVA_SOURCE ) {
subMonitor.subTask("Scanning "+javaPackage.getPath().toString());
if ((!onlyPackages || featurefilePackage.startsWith(javaPackage.getPath().toString())) &&
(!onlySpeficicPackages || javaPackage.getElementName().startsWith(onlySpeficicPackagesValue))) {
// System.out.println("Package Name-1
// :"+javaPackage.getElementName());
// Collect All Steps From Source
collectCukeStepsFromSource(javaProject, javaPackage, steps, progressMonitor);
}
}
// Get Packages from JAR exists in class-path
if ((javaPackage.getKind() == JAVA_JAR_BINARY) && !externalPackageName.equals("")) {
subMonitor.subTask("Scanning package "+javaPackage.getElementName());
// Iterate all external packages
for (String extPackageName : extPackages) {
// Check package from external JAR/class file
if (javaPackage.getElementName().equals(extPackageName.trim())
|| javaPackage.getElementName().startsWith(extPackageName.trim())) {
// Collect All Steps From JAR
collectCukeStepsFromJar(javaPackage, steps);
}
}
}
subMonitor.worked(1);
}
}
} finally {
if (progressMonitor != null) {
progressMonitor.done();
}
}
}
/**
* Collect all cuke-steps from java-source Files
*
* @param javaProject
* @param javaPackage
* @param steps
* @param progressMonitor
* @throws JavaModelException
* @throws CoreException
*/
public void collectCukeStepsFromSource(IJavaProject javaProject, IPackageFragment javaPackage, Set<Step> steps, IProgressMonitor progressMonitor)
throws JavaModelException, CoreException {
for (ICompilationUnit iCompUnit : javaPackage.getCompilationUnits()) {
// Collect and add Steps
steps.addAll(getCukeSteps(javaProject, iCompUnit, progressMonitor));
}
}
/**
* Collect all cuke-steps from .class file of Jar
*
* @param javaPackage
* @param steps
* @throws JavaModelException
* @throws CoreException
*/
public void collectCukeStepsFromJar(IPackageFragment javaPackage, Set<Step> steps)
throws JavaModelException, CoreException {
@SuppressWarnings("deprecation")
IClassFile[] classFiles = javaPackage.getClassFiles();
for (IClassFile classFile : classFiles) {
// +classFile.getElementName());
steps.addAll(getCukeSteps(javaPackage, classFile));
}
}
@Override
public void addStepListener(IStepListener listener) {
//this.listeners.add(listener);
//#240:For Changes in step implementation is reflected in feature file
StepDefinitions.listeners.add(listener);
}
@Override
public void removeStepListener(IStepListener listener) {
//this.listeners.remove(listener);
//#240:For Changes in step implementation is reflected in feature file
StepDefinitions.listeners.remove(listener);
}
public void notifyListeners(StepsChangedEvent event) {
for (IStepListener listener : listeners) {
listener.onStepsChanged(event);
}
}
}
|
package com.exedio.cope;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.exedio.dsmf.Table;
public final class UniqueConstraint extends Feature
{
private final FunctionField<?>[] attributes;
private final List<FunctionField<?>> attributeList;
private String databaseID;
private UniqueConstraint(final FunctionField<?>[] attributes)
{
this.attributes = attributes;
this.attributeList = Collections.unmodifiableList(Arrays.asList(attributes));
for(final FunctionField attribute : attributes)
attribute.registerUniqueConstraint(this);
}
/**
* Is not public, because one should use {@link Item#UNIQUE} etc.
*/
UniqueConstraint(final FunctionField attribute)
{
this(new FunctionField[]{attribute});
}
public UniqueConstraint(final FunctionField attribute1, final FunctionField attribute2)
{
this(new FunctionField[]{attribute1, attribute2});
}
public UniqueConstraint(final FunctionField attribute1, final FunctionField attribute2, final FunctionField attribute3)
{
this(new FunctionField[]{attribute1, attribute2, attribute3});
}
public UniqueConstraint(final FunctionField attribute1, final FunctionField attribute2, final FunctionField attribute3, final FunctionField attribute4)
{
this(new FunctionField[]{attribute1, attribute2, attribute3, attribute4});
}
/**
* @deprecated Renamed to {@link #getFields()}.
*/
@Deprecated
public final List<FunctionField<?>> getUniqueAttributes()
{
return getFields();
}
public final List<FunctionField<?>> getFields()
{
return attributeList;
}
static final String IMPLICIT_UNIQUE_SUFFIX = "ImplicitUnique";
final void connect(final Database database)
{
if(this.databaseID!=null)
throw new RuntimeException();
final String featureName = getName();
final String databaseName =
featureName.endsWith(IMPLICIT_UNIQUE_SUFFIX)
? featureName.substring(0, featureName.length()-IMPLICIT_UNIQUE_SUFFIX.length())
: featureName;
this.databaseID = database.makeName(getType().id + '_' + databaseName + "_Unq").intern();
database.addUniqueConstraint(databaseID, this);
}
final void disconnect()
{
if(this.databaseID==null)
throw new RuntimeException();
this.databaseID = null;
}
private final String getDatabaseID()
{
if(databaseID==null)
throw new RuntimeException();
return databaseID;
}
final void makeSchema(final Table dsmfTable)
{
final StringBuffer bf = new StringBuffer();
bf.append('(');
for(int i = 0; i<attributes.length; i++)
{
if(i>0)
bf.append(',');
final FunctionField<?> uniqueAttribute = attributes[i];
bf.append(uniqueAttribute.getColumn().protectedID);
}
bf.append(')');
new com.exedio.dsmf.UniqueConstraint(dsmfTable, getDatabaseID(), bf.toString());
}
@Override
final String toStringNonInitialized()
{
final StringBuffer buf = new StringBuffer();
buf.append("unique(");
buf.append(attributes[0].toString());
for(int i = 1; i<attributes.length; i++)
{
buf.append(',');
buf.append(attributes[i].toString());
}
buf.append(')');
return buf.toString();
}
/**
* Finds an item by its unique attributes.
* @return null if there is no matching item.
*/
public final Item searchUnique(final Object[] values)
{
// TODO: search nativly for unique constraints
final List<FunctionField<?>> fields = getFields();
if(fields.size()!=values.length)
throw new RuntimeException("-"+fields.size()+'-'+values.length);
final Iterator<FunctionField<?>> fieldIter = fields.iterator();
final Condition[] conditions = new Condition[fields.size()];
for(int j = 0; fieldIter.hasNext(); j++)
conditions[j] = Cope.equalAndCast(fieldIter.next(), values[j]);
return getType().searchSingleton(new CompositeCondition(CompositeCondition.Operator.AND, conditions));
}
}
|
package quantumworks.droidPluginGen.pluginGen.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class ProjectMainView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project_main_view);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.project_main_view, menu);
return true;
}
}
|
package cyclops.streams.syncflux;
import com.oath.cyclops.ReactiveConvertableSequence;
import cyclops.companion.Streams;
import cyclops.companion.reactor.Fluxs;
import cyclops.control.Maybe;
import cyclops.control.Option;
import cyclops.data.Vector;
import cyclops.data.tuple.Tuple2;
import cyclops.data.tuple.Tuple3;
import cyclops.data.tuple.Tuple4;
import cyclops.function.Monoid;
import cyclops.futurestream.LazyReact;
import cyclops.reactive.FluxReactiveSeq;
import cyclops.reactive.ReactiveSeq;
import cyclops.reactive.Spouts;
import cyclops.reactive.collections.mutable.ListX;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Flux;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
//see BaseSequentialSeqTest for in order tests
public class SyncReactiveStreamXTest {
public static Executor ex = Executors.newFixedThreadPool(10);
public static final LazyReact r = new LazyReact(10,10);
ReactiveSeq<Integer> empty;
ReactiveSeq<Integer> nonEmpty;
@Before
public void setup(){
empty = of();
nonEmpty = of(1);
}
protected <U> ReactiveSeq<U> of(U... array){
return FluxReactiveSeq.reactiveSeq(Flux.just(array));
}
@Test
public void flatMapPublisher() throws InterruptedException{
//of(1,2,3)
// .mergeMap(i->Maybe.of(i)).printOut();
assertThat(of(1,2,3)
.mergeMap(i-> Maybe.of(i))
.to(ReactiveConvertableSequence::converter).listX(),equalTo(Arrays.asList(1,2,3)));
}
private void sleep2(int time){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Object value() {
return "jello";
}
private int value2() {
return 200;
}
@Test
public void batchBySize(){
System.out.println(of(1,2,3,4,5,6).grouped(3).collect(Collectors.toList()));
assertThat(of(1,2,3,4,5,6).grouped(3).collect(Collectors.toList()).size(),is(2));
}
@Test
public void limitWhileTest(){
List<Integer> list = new ArrayList<>();
while(list.size()==0){
list = of(1,2,3,4,5,6).limitWhile(it -> it<4)
.peek(it -> System.out.println(it)).collect(Collectors.toList());
}
assertThat(Arrays.asList(1,2,3,4,5,6),hasItem(list.get(0)));
}
@Test
public void testScanLeftStringConcat() {
assertThat(of("a", "b", "c").scanLeft("", String::concat).toList().size(),
is(4));
}
@Test
public void testScanLeftSum() {
assertThat(of("a", "ab", "abc").map(str->str.length()).scanLeft(0, (u, t) -> u + t).toList().size(),
is(asList(0, 1, 3, 6).size()));
}
@Test
public void testScanRightStringConcatMonoid() {
assertThat(of("a", "b", "c").scanRight(Monoid.of("", String::concat)).toList().size(),
is(asList("", "c", "bc", "abc").size()));
}
@Test
public void testScanRightStringConcat() {
assertThat(of("a", "b", "c").scanRight("", String::concat).toList().size(),
is(asList("", "c", "bc", "abc").size()));
}
@Test
public void testScanRightSum() {
assertThat(of("a", "ab", "abc").map(str->str.length()).scanRight(0, (t, u) -> u + t).toList().size(),
is(asList(0, 3, 5, 6).size()));
}
@Test
public void cycleIterateIterable(){
Iterator<Integer> it = ReactiveSeq.fromIterable(Arrays.asList(1)).stream().cycle(2).iterator();
List<Integer> list2 = new ArrayList<>();
while(it.hasNext())
list2.add(it.next());
assertThat(list2,equalTo(ListX.of(1,1)));
}
@Test
public void cycleIterate(){
Iterator<Integer> it = of(1).stream().cycle(2).iterator();
List<Integer> list2 = new ArrayList<>();
while(it.hasNext())
list2.add(it.next());
assertThat(list2,equalTo(ListX.of(1,1)));
}
@Test
public void cycleIterate2(){
Iterator<Integer> it = of(1,2).stream().cycle(2).iterator();
List<Integer> list2 = new ArrayList<>();
while(it.hasNext())
list2.add(it.next());
assertThat(list2,equalTo(ListX.of(1,2,1,2)));
}
@Test
public void testReverse() {
assertThat( of(1, 2, 3).reverse().toList(), equalTo(asList(3, 2, 1)));
}
@Test
public void testReverseList() {
assertThat( Spouts.fromIterable(Arrays.asList(10,400,2,-1))
.reverse().toList(), equalTo(asList(-1, 2, 400,10)));
}
@Test
public void testReverseListLimit() {
assertThat( Spouts.fromIterable(Arrays.asList(10,400,2,-1)).limit(2)
.reverse().toList(), equalTo(asList(400, 10)));
}
@Test
public void testReverseRange() {
assertThat( ReactiveSeq.range(0,10)
.reverse().toList(), equalTo(asList(10,9,8,7,6,5,4,3,2,1)));
}
@Test
public void testCycleLong() {
assertEquals(asList(1, 2, 1, 2, 1, 2), Streams.oneShotStream(Stream.of(1, 2)).cycle(3).to(ReactiveConvertableSequence::converter).listX());
assertEquals(asList(1, 2, 3, 1, 2, 3), Streams.oneShotStream(Stream.of(1, 2,3)).cycle(2).to(ReactiveConvertableSequence::converter).listX());
}
@Test
public void onEmptySwitchEmpty(){
for(int i=0;i<1000;i++) {
assertThat(of()
.onEmptySwitch(() -> of(1, 2, 3))
.toList(),
equalTo(Arrays.asList(1, 2, 3)));
}
}
private int sleep(Integer i) {
if(i==0)
return i;
try {
Thread.currentThread().sleep(i);
} catch (InterruptedException e) {
}
return i;
}
@Test
public void skipTime(){
List<Integer> result = of(0,2,3,4,5,6)
.peek(i->sleep(i*100))
.skip(1000,TimeUnit.MILLISECONDS)
.toList();
assertThat(result.size(), Matchers.isOneOf(3,4));
assertThat(result,hasItems(4,5,6));
}
@Test
public void limitTime(){
List<Integer> result = of(1,2,3,4,5,6)
.peek(i->sleep(i*100))
.limit(1000, TimeUnit.MILLISECONDS)
.toList();
assertThat(result,equalTo(Arrays.asList(1,2,3)));
}
@Test
public void skipUntil(){
assertEquals(asList(3, 4, 5), of(1, 2, 3, 4, 5).skipUntil(i -> i % 3 == 0).toList());
}
@Test
public void simpleZip(){
of(1,2,3)
.zip(of(100,200))
.forEach(System.out::println);
}
@Test
public void zip2of(){
List<Tuple2<Integer,Integer>> list =of(1,2,3,4,5,6)
.zip(of(100,200,300,400).stream())
.to(ReactiveConvertableSequence::converter).listX();
System.out.println(list);
List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList());
assertThat(right,hasItem(100));
assertThat(right,hasItem(200));
assertThat(right,hasItem(300));
assertThat(right,hasItem(400));
List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList());
System.out.println(left);
assertThat(Arrays.asList(1,2,3,4,5,6),hasItem(left.get(0)));
}
@Test
public void dropRight(){
System.out.println(of(1,2,3).skipLast(1).toList());
assertThat(of(1,2,3).dropRight(1).toList(),hasItems(1,2));
}
@Test
public void dropRight2(){
assertThat(of(1,2,3).dropRight(2).toList(),hasItems(1));
}
@Test
public void skipLast1(){
assertThat(of(1,2,3).skipLast(1).toList(),hasItems(1,2));
}
@Test
public void testSkipLast(){
assertThat(of(1,2,3,4,5)
.skipLast(2)
.to(ReactiveConvertableSequence::converter).listX(),equalTo(Arrays.asList(1,2,3)));
}
@Test
public void testSkipLastForEach(){
List<Integer> list = new ArrayList();
of(1,2,3,4,5).skipLast(2)
.forEach(n->{list.add(n);});
assertThat(list,equalTo(Arrays.asList(1,2,3)));
}
@Test
public void testCycle() {
assertEquals(asList(1, 1, 1, 1, 1,1),of(1).cycle().limit(6).toList());
}
@Test
public void testIterable() {
List<Integer> list = of(1, 2, 3).to().collection(LinkedList::new);
for (Integer i :of(1, 2, 3)) {
assertThat(list,hasItem(i));
}
}
@Test
public void testDuplicate(){
Tuple2<ReactiveSeq<Integer>, ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).duplicate();
assertTrue(copies._1().anyMatch(i->i==2));
assertTrue(copies._2().anyMatch(i->i==2));
}
@Test
public void testTriplicate(){
Tuple3<ReactiveSeq<Integer>, ReactiveSeq<Integer>, ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).triplicate();
assertTrue(copies._1().anyMatch(i->i==2));
assertTrue(copies._2().anyMatch(i->i==2));
assertTrue(copies._3().anyMatch(i->i==2));
}
@Test
public void testQuadriplicate(){
Tuple4<ReactiveSeq<Integer>, ReactiveSeq<Integer>, ReactiveSeq<Integer>,ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).quadruplicate();
assertTrue(copies._1().anyMatch(i->i==2));
assertTrue(copies._2().anyMatch(i->i==2));
assertTrue(copies._3().anyMatch(i->i==2));
assertTrue(copies._4().anyMatch(i->i==2));
}
@Test
public void testDuplicateFilter(){
Tuple2<ReactiveSeq<Integer>, ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).duplicate();
assertTrue(copies._1().filter(i->i%2==0).toList().size()==3);
assertTrue(copies._2().filter(i->i%2==0).toList().size()==3);
}
@Test
public void testTriplicateFilter(){
Tuple3<ReactiveSeq<Integer>, ReactiveSeq<Integer>, ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).triplicate();
assertTrue(copies._1().filter(i->i%2==0).toList().size()==3);
assertTrue(copies._2().filter(i->i%2==0).toList().size()==3);
assertTrue(copies._3().filter(i->i%2==0).toList().size()==3);
}
@Test
public void testQuadriplicateFilter(){
Tuple4<ReactiveSeq<Integer>, ReactiveSeq<Integer>, ReactiveSeq<Integer>,ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).quadruplicate();
assertTrue(copies._1().filter(i->i%2==0).toList().size()==3);
assertTrue(copies._2().filter(i->i%2==0).toList().size()==3);
assertTrue(copies._3().filter(i->i%2==0).toList().size()==3);
assertTrue(copies._4().filter(i->i%2==0).toList().size()==3);
}
@Test
public void testDuplicateLimit(){
Tuple2<ReactiveSeq<Integer>, ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).duplicate();
assertTrue(copies._1().limit(3).toList().size()==3);
assertTrue(copies._2().limit(3).toList().size()==3);
}
@Test
public void testTriplicateLimit(){
Tuple3<ReactiveSeq<Integer>, ReactiveSeq<Integer>, ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).triplicate();
assertTrue(copies._1().limit(3).toList().size()==3);
assertTrue(copies._2().limit(3).toList().size()==3);
assertTrue(copies._3().limit(3).toList().size()==3);
}
@Test
public void testQuadriplicateLimit(){
Tuple4<ReactiveSeq<Integer>, ReactiveSeq<Integer>, ReactiveSeq<Integer>,ReactiveSeq<Integer>> copies =of(1,2,3,4,5,6).quadruplicate();
assertTrue(copies._1().limit(3).toList().size()==3);
assertTrue(copies._2().limit(3).toList().size()==3);
assertTrue(copies._3().limit(3).toList().size()==3);
assertTrue(copies._4().limit(3).toList().size()==3);
}
public void prepend(){
List<String> result = of(1,2,3).prependAll(100,200,300)
.map(it ->it+"!!").collect(Collectors.toList());
assertThat(result,equalTo(Arrays.asList("100!!","200!!","300!!","1!!","2!!","3!!")));
}
@Test
public void append(){
List<String> result = of(1,2,3).appendAll(100,200,300)
.map(it ->it+"!!").collect(Collectors.toList());
assertThat(result,equalTo(Arrays.asList("1!!","2!!","3!!","100!!","200!!","300!!")));
}
@Test
public void concatStreams(){
List<String> result = of(1,2,3).appendStream(of(100,200,300))
.map(it ->it+"!!").collect(Collectors.toList());
assertThat(result,equalTo(Arrays.asList("1!!","2!!","3!!","100!!","200!!","300!!")));
}
@Test
public void shuffle(){
assertEquals(3, of(1, 2, 3).shuffle().to(ReactiveConvertableSequence::converter).listX().size());
}
@Test
public void shuffleRandom(){
Random r = new Random();
assertEquals(3, of(1, 2, 3).shuffle(r).to(ReactiveConvertableSequence::converter).listX().size());
}
@Test
public void prependStreams(){
List<String> result = of(1,2,3).prependStream(of(100,200,300))
.map(it ->it+"!!").collect(Collectors.toList());
assertThat(result,equalTo(Arrays.asList("100!!","200!!","300!!","1!!","2!!","3!!")));
}
@Test
public void testGroupByEager() {
cyclops.data.HashMap<Integer, cyclops.data.Vector<Integer>> map1 =of(1, 2, 3, 4).groupBy(i -> i % 2);
assertEquals(Option.some(cyclops.data.Vector.of(2, 4)), map1.get(0));
assertEquals(Option.some(Vector.of(1, 3)), map1.get(1));
assertEquals(2, map1.size());
}
@Test
public void testJoin() {
assertEquals("123".length(),of(1, 2, 3).join().length());
assertEquals("1, 2, 3".length(), of(1, 2, 3).join(", ").length());
assertEquals("^1|2|3$".length(), of(1, 2, 3).join("|", "^", "$").length());
}
@Test
public void testSkipWhile() {
Supplier<ReactiveSeq<Integer>> s = () -> of(1, 2, 3, 4, 5);
assertTrue(s.get().skipWhile(i -> false).toList().containsAll(asList(1, 2, 3, 4, 5)));
assertEquals(asList(), s.get().skipWhile(i -> true).toList());
}
@Test
public void testSkipUntil() {
Supplier<ReactiveSeq<Integer>> s = () -> of(1, 2, 3, 4, 5);
assertEquals(asList(), s.get().skipUntil(i -> false).toList());
assertTrue(s.get().skipUntil(i -> true).toList().containsAll(asList(1, 2, 3, 4, 5)));
}
@Test(expected= NullPointerException.class)
public void testSkipUntilWithNulls() {
Supplier<ReactiveSeq<Integer>> s = () -> of(1, 2, null, 3, 4, 5);
assertTrue(s.get().skipUntil(i -> true).toList().containsAll(asList(1, 2, null, 3, 4, 5)));
}
@Test
public void testLimitWhile() {
Supplier<ReactiveSeq<Integer>> s = () -> of(1, 2, 3, 4, 5);
assertEquals(asList(), s.get().limitWhile(i -> false).toList());
assertTrue( s.get().limitWhile(i -> i < 3).toList().size()!=5);
assertTrue(s.get().limitWhile(i -> true).toList().containsAll(asList(1, 2, 3, 4, 5)));
}
@Test
public void testLimitUntil() {
assertTrue(of(1, 2, 3, 4, 5).limitUntil(i -> false).toList().containsAll(asList(1, 2, 3, 4, 5)));
assertFalse(of(1, 2, 3, 4, 5).limitUntil(i -> i % 3 == 0).toList().size()==5);
assertEquals(asList(), of(1, 2, 3, 4, 5).limitUntil(i -> true).toList());
}
@Test(expected = NullPointerException.class)
public void testLimitUntilWithNulls() {
System.out.println(of(1, 2, null, 3, 4, 5).limitUntil(i -> false).toList());
assertTrue(of(1, 2, null, 3, 4, 5).limitUntil(i -> false).toList().containsAll(asList(1, 2, null, 3, 4, 5)));
}
@Test
public void testMinByMaxBy() {
Supplier<ReactiveSeq<Integer>> s = () -> of(1, 2, 3, 4, 5, 6);
assertEquals(1, (int) s.get().maxBy(t -> Math.abs(t - 5)).orElse(-1));
assertEquals(5, (int) s.get().minBy(t -> Math.abs(t - 5)).orElse(-1));
assertEquals(6, (int) s.get().maxBy(t -> "" + t).orElse(-1));
assertEquals(1, (int) s.get().minBy(t -> "" + t).orElse(-1));
}
@Test
public void testFoldLeft() {
for(int i=0;i<100;i++){
Supplier<ReactiveSeq<String>> s = () -> of("a", "b", "c");
assertTrue(s.get().reduce("", String::concat).contains("a"));
assertTrue(s.get().reduce("", String::concat).contains("b"));
assertTrue(s.get().reduce("", String::concat).contains("c"));
assertEquals(3, (int) s.get().map(str->str.length()).foldLeft(0, (u, t) -> u + t));
assertEquals(3, (int) s.get().map(str->str.length()).foldRight(0, (t, u) -> u + t));
}
}
@Test
public void testFoldRight(){
Supplier<ReactiveSeq<String>> s = () -> of("a", "b", "c");
assertTrue(s.get().foldRight("", String::concat).contains("a"));
assertTrue(s.get().foldRight("", String::concat).contains("b"));
assertTrue(s.get().foldRight("", String::concat).contains("c"));
assertEquals(3, (int) s.get().map(str->str.length())
.foldRight(0, (t, u) -> u + t));
}
//tests converted from lazy-reactiveSeq suite
@Test
public void flattenEmpty() throws Exception {
assertTrue(this.<ReactiveSeq<Integer>>of().to(ReactiveSeq::flatten).toList().isEmpty());
}
@Test
public void flatten() throws Exception {
assertThat(of(Arrays.asList(1,2)).to(ReactiveSeq::flattenIterable).toList().size(),equalTo(asList(1, 2).size()));
}
@Test
public void flattenEmptyStream() throws Exception {
assertThat(this.<Integer>of(1,2,3,4,5,5,6,8,9,10).limit(10).collect(Collectors.toList()).size(),
equalTo(asList(2, 3, 4, 5, 6, 7, 0, 0, 0, 0).size()));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.