answer
stringlengths 17
10.2M
|
|---|
package com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.classes.BaseClass;
public abstract class AbstractSuperClass implements SuperClass
{
/**
* FullName of the default parent page for a document containing xwiki class.
*/
private static final String DEFAULT_XWIKICLASS_PARENT = "XWiki.XWikiClasses";
/**
* The resource file extension containing pages contents.
*/
private static final String DOCUMENTCONTENT_EXT = ".svn";
/**
* Resource path prefix for the class sheets documents content.
*/
private static final String DOCUMENTCONTENT_SHEET_PREFIX = "sheets/";
/**
* Resource path prefix for the class templates documents content.
*/
private static final String DOCUMENTCONTENT_TEMPLATE_PREFIX = "templates/";
/**
* Symbol used in HQL request to insert and protect value when executing the request.
*/
private static final String HQL_PARAMETER_STRING = "?";
/**
* Space prefix of class document.
*
* @see #getClassSpace()
*/
private final String classSpacePrefix;
/**
* Prefix of class document.
*
* @see #getClassPrefix()
*/
private final String classPrefix;
/**
* Space of class document.
*
* @see #getClassSpace()
*/
private final String classSpace;
/**
* Name of class document.
*
* @see #getClassName()
*/
private final String className;
/**
* Full name of class document.
*
* @see #getClassFullName()
*/
private final String classFullName;
/**
* Space of class sheet document.
*
* @see #getClassSpace()
*/
private final String classSheetSpace;
/**
* Name of class sheet document.
*
* @see #getClassSheetName()
*/
private final String classSheetName;
/**
* Full name of class sheet document.
*
* @see #getClassSheetFullName()
*/
private final String classSheetFullName;
/**
* Space of class template document.
*
* @see #getClassSpace()
*/
private final String classTemplateSpace;
/**
* Name of class template document.
*
* @see #getClassTemplateName()
*/
private final String classTemplateName;
/**
* Full name of class template document.
*
* @see #getClassTemplateFullName()
*/
private final String classTemplateFullName;
/**
* Default content of class template document.
*/
private final String classSheetDefaultContent;
/**
* Default content of class sheet document.
*/
private final String classTemplateDefaultContent;
/**
* Base class managed.
*/
private BaseClass baseClass;
/**
* Store for any database name if documents used for manage this class has been checked.
*/
private final Set databasesInitedMap = new HashSet();
/**
* Constructor for AbstractSuperClass.
*
* @param prefix the prefix of class document.
* @see #AbstractSuperClass(String, String)
* @see #AbstractSuperClass(String, String, boolean)
*/
protected AbstractSuperClass(String prefix)
{
this(XWIKI_CLASS_SPACE_PREFIX, prefix);
}
/**
* Constructor for AbstractSuperClass.
*
* @param spaceprefix the space prefix of class document.
* @param prefix the prefix of class document.
* @see #AbstractSuperClass(String)
* @see #AbstractSuperClass(String, String, boolean)
*/
protected AbstractSuperClass(String spaceprefix, String prefix)
{
this(spaceprefix, prefix, true);
}
/**
* Constructor for AbstractSuperClass.
*
* @param spaceprefix the space of class document.
* @param prefix the prefix of class document.
* @param dispatch Indicate if it had to use standard XWiki applications space names.
* @see #AbstractSuperClass(String)
* @see #AbstractSuperClass(String, String)
*/
protected AbstractSuperClass(String spaceprefix, String prefix, boolean dispatch)
{
classSpacePrefix = spaceprefix;
classPrefix = prefix;
classSpace = dispatch ? classSpacePrefix + XWIKI_CLASS_SPACE_SUFFIX : classSpacePrefix;
className = classPrefix + XWIKI_CLASS_SUFFIX;
classFullName = classSpace + SuperDocument.SPACE_DOC_SEPARATOR + className;
classSheetSpace =
dispatch ? classSpacePrefix + XWIKI_CLASSSHEET_SPACE_SUFFIX : classSpacePrefix;
classSheetName = classPrefix + XWIKI_CLASSSHEET_SUFFIX;
classSheetFullName = classSheetSpace + SuperDocument.SPACE_DOC_SEPARATOR + classSheetName;
classTemplateSpace =
dispatch ? classSpacePrefix + XWIKI_CLASSTEMPLATE_SPACE_SUFFIX : classSpacePrefix;
classTemplateName = classPrefix + XWIKI_CLASSTEMPLATE_SUFFIX;
classTemplateFullName =
classTemplateSpace + SuperDocument.SPACE_DOC_SEPARATOR + classTemplateName;
classSheetDefaultContent =
"## you can modify this page to customize the presentation of your object\n\n"
+ "1 Document $doc.name\n\n#set($class = $doc.getObject(\"" + classFullName
+ "\").xWikiClass)\n" + "\n" + "<dl>\n"
+ " #foreach($prop in $class.properties)\n"
+ " <dt> ${prop.prettyName} </dt>\n"
+ " <dd>$doc.display($prop.getName())</dd>\n #end\n" + "</dl>\n";
classTemplateDefaultContent = "#includeForm(\"" + classSheetFullName + "\")\n";
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.SuperClass#getClassSpacePrefix()
*/
public String getClassSpacePrefix()
{
return classSpacePrefix;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassSpace()
*/
public String getClassSpace()
{
return classSpace;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassPrefix()
*/
public String getClassPrefix()
{
return classPrefix;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassName()
*/
public String getClassName()
{
return className;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassFullName()
*/
public String getClassFullName()
{
return classFullName;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassTemplateName()
*/
public String getClassTemplateSpace()
{
return classTemplateSpace;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassTemplateName()
*/
public String getClassTemplateName()
{
return classTemplateName;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassTemplateFullName()
*/
public String getClassTemplateFullName()
{
return classTemplateFullName;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassSheetName()
*/
public String getClassSheetSpace()
{
return classSheetSpace;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassSheetName()
*/
public String getClassSheetName()
{
return classSheetName;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassSheetFullName()
*/
public String getClassSheetFullName()
{
return classSheetFullName;
}
/**
* Check if all necessary documents for manage this class in this context exists and update.
* Create if not exists. Thread safe.
*
* @param context the XWiki context.
* @throws XWikiException error when saving documents.
* @see #checkClassDocument(XWikiContext)
*/
protected void check(XWikiContext context) throws XWikiException
{
synchronized (databasesInitedMap) {
if (!this.databasesInitedMap.contains(context.getDatabase())) {
checkClassDocument(context);
checkClassSheetDocument(context);
checkClassTemplateDocument(context);
this.databasesInitedMap.add(context.getDatabase());
}
}
}
/**
* Check if class document exists in this context and update. Create if not exists.
*
* @param context the XWiki context.
* @throws XWikiException error when saving document.
*/
private void checkClassDocument(XWikiContext context) throws XWikiException
{
XWikiDocument doc;
XWiki xwiki = context.getWiki();
boolean needsUpdate = false;
try {
doc = xwiki.getDocument(getClassFullName(), context);
} catch (Exception e) {
doc = new XWikiDocument();
doc.setSpace(getClassSpace());
doc.setName(getClassName());
doc.setParent(DEFAULT_XWIKICLASS_PARENT);
needsUpdate = true;
}
this.baseClass = doc.getxWikiClass();
needsUpdate |= updateBaseClass(this.baseClass);
if (doc.isNew() || needsUpdate) {
xwiki.saveDocument(doc, context);
}
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassSheetDefaultContent()
*/
public String getClassSheetDefaultContent()
{
return classSheetDefaultContent;
}
/**
* Load an entire resource text file into {@link String}.
*
* @param path the path to the resource file.
* @return the entire content of the resource text file.
*/
private String getResourceDocumentContent(String path)
{
InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
if (in != null) {
try {
StringBuffer content = new StringBuffer(in.available());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
for (String str = reader.readLine(); str != null; str = reader.readLine()) {
content.append(str);
content.append('\n');
}
return content.toString();
} catch (IOException e) {
// No resource file as been found or there is a problem when read it.
}
}
return null;
}
/**
* Check if class sheet document exists in this context and update. Create if not exists.
*
* @param context the XWiki context.
* @throws XWikiException error when saving document.
*/
private void checkClassSheetDocument(XWikiContext context) throws XWikiException
{
XWikiDocument doc;
XWiki xwiki = context.getWiki();
boolean needsUpdate = false;
try {
doc = xwiki.getDocument(getClassSheetFullName(), context);
} catch (Exception e) {
doc = new XWikiDocument();
doc.setSpace(getClassSheetSpace());
doc.setName(getClassSheetName());
doc.setParent(getClassFullName());
needsUpdate = true;
}
if (doc.isNew()) {
String content =
getResourceDocumentContent(DOCUMENTCONTENT_SHEET_PREFIX + getClassSheetFullName()
+ DOCUMENTCONTENT_EXT);
doc.setContent(content != null ? content : getClassSheetDefaultContent());
}
if (doc.isNew() || needsUpdate) {
xwiki.saveDocument(doc, context);
}
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassTemplateDefaultContent()
*/
public String getClassTemplateDefaultContent()
{
return classTemplateDefaultContent;
}
/**
* Check if class template document exists in this context and update. Create if not exists.
*
* @param context the XWiki context.
* @throws XWikiException error when saving document.
*/
private void checkClassTemplateDocument(XWikiContext context) throws XWikiException
{
XWikiDocument doc;
XWiki xwiki = context.getWiki();
boolean needsUpdate = false;
try {
doc = xwiki.getDocument(getClassTemplateFullName(), context);
} catch (Exception e) {
doc = new XWikiDocument();
doc.setSpace(getClassTemplateSpace());
doc.setName(getClassTemplateName());
needsUpdate = true;
}
if (doc.getObject(getClassFullName()) == null) {
doc.createNewObject(getClassFullName(), context);
needsUpdate = true;
}
if (doc.isNew()) {
String content =
getResourceDocumentContent(DOCUMENTCONTENT_TEMPLATE_PREFIX
+ getClassTemplateFullName() + DOCUMENTCONTENT_EXT);
doc.setContent(content != null ? content : getClassTemplateDefaultContent());
doc.setParent(getClassFullName());
}
needsUpdate |= updateClassTemplateDocument(doc);
if (doc.isNew() || needsUpdate) {
xwiki.saveDocument(doc, context);
}
}
/**
* Initialize template document with default content.
*
* @param doc the class template document that will be saved.
* @return true if <code>doc</code> modified.
*/
protected boolean updateClassTemplateDocument(XWikiDocument doc)
{
return false;
}
/**
* Configure BaseClass.
*
* @param baseClass the baseClass to configure.
* @return true if <code>baseClass</code> modified.
*/
protected boolean updateBaseClass(BaseClass baseClass)
{
boolean needUpdate = false;
if (!baseClass.getName().equals(getClassFullName())) {
baseClass.setName(getClassFullName());
needUpdate = true;
}
return needUpdate;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getBaseClass()
*/
public BaseClass getBaseClass()
{
if (this.baseClass == null) {
this.baseClass = new BaseClass();
updateBaseClass(this.baseClass);
}
return this.baseClass;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassDocument(com.xpn.xwiki.XWikiContext)
*/
public Document getClassDocument(XWikiContext context) throws XWikiException
{
check(context);
return context.getWiki().getDocument(getClassFullName(), context).newDocument(context);
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassSheetDocument(com.xpn.xwiki.XWikiContext)
*/
public Document getClassSheetDocument(XWikiContext context) throws XWikiException
{
check(context);
return context.getWiki().getDocument(getClassSheetFullName(), context).newDocument(
context);
}
/**
* {@inheritDoc}
*
* @see SuperClass#getClassTemplateDocument(com.xpn.xwiki.XWikiContext)
*/
public Document getClassTemplateDocument(XWikiContext context) throws XWikiException
{
check(context);
return context.getWiki().getDocument(getClassTemplateFullName(), context).newDocument(
context);
}
/**
* {@inheritDoc}
*
* @see SuperClass#isInstance(com.xpn.xwiki.doc.XWikiDocument)
*/
public boolean isInstance(XWikiDocument doc)
{
return doc.getObject(getClassFullName()) != null;
}
/**
* {@inheritDoc}
*
* @see SuperClass#isInstance(com.xpn.xwiki.doc.XWikiDocument)
*/
public boolean isInstance(Document doc)
{
return doc.getObject(getClassFullName()) != null;
}
/**
* {@inheritDoc}
*
* @see SuperClass#getItemDocumentDefaultName(java.lang.String, XWikiContext)
*/
public String getItemDocumentDefaultName(String itemName, XWikiContext context)
{
String name = context.getWiki().clearName(itemName, true, true, context);
return getClassPrefix() + name.substring(0, 1).toUpperCase()
+ name.substring(1).toLowerCase();
}
/**
* {@inheritDoc}
*
* @see SuperClass#getItemDocumentDefaultFullName(java.lang.String, XWikiContext)
*/
public String getItemDocumentDefaultFullName(String itemName, XWikiContext context)
{
return getClassSpacePrefix() + SuperDocument.SPACE_DOC_SEPARATOR
+ getItemDocumentDefaultName(itemName, context);
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.SuperClass#getItemDefaultName(java.lang.String)
*/
public String getItemDefaultName(String docFullName)
{
return docFullName.substring(
(getClassSpacePrefix() + SuperDocument.SPACE_DOC_SEPARATOR + getClassPrefix())
.length()).toLowerCase();
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.SuperClass#getSuperDocument(java.lang.String,
* int, boolean, com.xpn.xwiki.XWikiContext)
*/
public SuperDocument getSuperDocument(String itemName, int objectId, boolean validate,
XWikiContext context) throws XWikiException
{
XWikiDocument doc =
context.getWiki().getDocument(getItemDocumentDefaultFullName(itemName, context),
context);
if (doc.isNew() || !isInstance(doc)) {
throw new SuperDocumentDoesNotExistException(itemName + " object does not exist");
}
return newSuperDocument(doc, objectId, context);
}
/**
* Construct HQL where clause to use with {@link com.xpn.xwiki.store.XWikiStoreInterface}
* "searchDocuments" methods.
*
* @param fieldDescriptors the list of fields name/value constraints. Format : [[fieldName1,
* typeField1, valueField1][fieldName2, typeField2, valueField2]].
* @param parameterValues the where clause values that replace the question marks (?).
* @return a HQL where clause.
*/
public String createWhereClause(String[][] fieldDescriptors, List parameterValues)
{
StringBuffer from = new StringBuffer(", BaseObject as obj");
StringBuffer where =
new StringBuffer(" where doc.fullName=obj.name and obj.className="
+ HQL_PARAMETER_STRING);
parameterValues.add(getClassFullName());
where.append(" and obj.name<>" + HQL_PARAMETER_STRING);
parameterValues.add(getClassTemplateFullName());
String andSymbol = " and ";
if (fieldDescriptors != null) {
for (int i = 0; i < fieldDescriptors.length; ++i) {
String fieldName = fieldDescriptors[i][0];
String type = fieldDescriptors[i][1];
String value = fieldDescriptors[i][2];
if (type != null) {
String fieldPrefix = "field" + i;
from.append(", " + type + " as " + fieldPrefix);
where.append(andSymbol + "obj.id=" + fieldPrefix + ".id.id");
where.append(andSymbol + fieldPrefix + ".name=" + HQL_PARAMETER_STRING);
parameterValues.add(fieldName);
where.append(andSymbol + "lower(" + fieldPrefix + ".value)="
+ HQL_PARAMETER_STRING);
parameterValues.add(value.toLowerCase());
} else {
where.append(" and lower(doc." + fieldName + ")=" + HQL_PARAMETER_STRING);
parameterValues.add(value.toLowerCase());
}
}
}
return from.append(where).toString();
}
/**
* Find all XWikiDocument containing object of this XWiki class.
*
* @param context the XWiki context.
* @return the list of found {@link SuperDocument}.
* @throws XWikiException error when searching for document in database.
* @see #getClassFullName()
*/
public List searchSuperDocuments(XWikiContext context) throws XWikiException
{
return searchSuperDocumentsByFields(null, context);
}
/**
* Search in instances of this document class.
*
* @param fieldName the name of field.
* @param fieldValue the value of field.
* @param fieldType the type of field.
* @param context the XWiki context.
* @return the list of found {@link SuperDocument}.
* @throws XWikiException error when searching for documents from in database.
*/
public List searchSuperDocumentsByField(String fieldName, String fieldValue,
String fieldType, XWikiContext context) throws XWikiException
{
String[][] fieldDescriptors = new String[][] {{fieldName, fieldType, fieldValue}};
return searchSuperDocumentsByFields(fieldDescriptors, context);
}
/**
* Search in instances of this document class.
*
* @param fieldDescriptors the list of fields name/value constraints. Format : [[fieldName1,
* typeField1, valueField1][fieldName2, typeField2, valueField2]].
* @param context the XWiki context.
* @return the list of found {@link SuperDocument}.
* @throws XWikiException error when searching for documents from in database.
*/
public List searchSuperDocumentsByFields(String[][] fieldDescriptors, XWikiContext context)
throws XWikiException
{
check(context);
List parameterValues = new ArrayList();
String where = createWhereClause(fieldDescriptors, parameterValues);
return newSuperDocumentList(context.getWiki().getStore().searchDocuments(where,
parameterValues, context), context);
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.SuperClass#newSuperDocument(com.xpn.xwiki.doc.XWikiDocument,
* int, com.xpn.xwiki.XWikiContext)
*/
public SuperDocument newSuperDocument(XWikiDocument doc, int objId, XWikiContext context)
throws XWikiException
{
return new DefaultSuperDocument(this, doc, objId, context);
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.SuperClass#newSuperDocument(java.lang.String,
* int, com.xpn.xwiki.XWikiContext)
*/
public SuperDocument newSuperDocument(String docFullName, int objId, XWikiContext context)
throws XWikiException
{
return newSuperDocument(context.getWiki().getDocument(docFullName, context), objId,
context);
}
/**
* {@inheritDoc}
*
* @see SuperClass#newSuperDocument(com.xpn.xwiki.XWikiContext)
*/
public SuperDocument newSuperDocument(XWikiContext context) throws XWikiException
{
return newSuperDocument(new XWikiDocument(), 0, context);
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.SuperClass#newSuperDocumentList(com.xpn.xwiki.doc.XWikiDocument,
* com.xpn.xwiki.XWikiContext)
*/
public List newSuperDocumentList(XWikiDocument document, XWikiContext context)
throws XWikiException
{
List documents = new ArrayList(1);
documents.add(document);
return newSuperDocumentList(documents, context);
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.SuperClass#newSuperDocumentList(java.util.List,
* com.xpn.xwiki.XWikiContext)
*/
public List newSuperDocumentList(List documents, XWikiContext context) throws XWikiException
{
List list = new ArrayList(documents.size());
for (Iterator it = documents.iterator(); it.hasNext();) {
XWikiDocument doc = (XWikiDocument) it.next();
List objects = doc.getObjects(getClassFullName());
int i = 0;
for (Iterator itObject = objects.iterator(); itObject.hasNext(); ++i) {
if (itObject.next() != null) {
list.add(newSuperDocument(doc, i, context));
}
}
}
return list;
}
}
|
package org.openhab.binding.zwave.test.internal.converter;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.types.State;
import org.junit.Before;
import org.junit.Test;
import org.openhab.binding.zwave.handler.ZWaveControllerHandler;
import org.openhab.binding.zwave.handler.ZWaveThingChannel;
import org.openhab.binding.zwave.handler.ZWaveThingChannel.DataType;
import org.openhab.binding.zwave.internal.converter.ZWaveMultiLevelSwitchConverter;
import org.openhab.binding.zwave.internal.protocol.SerialMessage;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveMultiLevelSwitchCommandClass;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent;
public class ZWaveMultiLevelSwitchConverterTest {
private ZWaveControllerHandler controller;
private ZWaveThingChannel channel;
private ZWaveCommandClassValueEvent event;
private ZWaveNode node;
private PercentType percentType;
private ZWaveMultiLevelSwitchCommandClass commandClass;
@Before
public void setup() {
controller = mock(ZWaveControllerHandler.class);
channel = mock(ZWaveThingChannel.class);
event = mock(ZWaveCommandClassValueEvent.class);
node = mock(ZWaveNode.class);
percentType = mock(PercentType.class);
commandClass = mock(ZWaveMultiLevelSwitchCommandClass.class);
}
@Test
public void handleEvent_PercentType0invertPercentFalse_returnPercentType0() throws Exception {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "false");
when(channel.getArguments()).thenReturn(configMap);
when(event.getValue()).thenReturn(0);
when(channel.getDataType()).thenReturn(DataType.PercentType);
State state = sut.handleEvent(channel, event);
assertEquals(new PercentType(0), state);
}
@Test
public void handleEvent_PercentType99invertPercentFalse_returnPercentType100() {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "false");
when(channel.getArguments()).thenReturn(configMap);
when(event.getValue()).thenReturn(99);
when(channel.getDataType()).thenReturn(DataType.PercentType);
State state = sut.handleEvent(channel, event);
assertEquals(new PercentType(100), state);
}
@Test
public void handleEvent_PercentType0invertPercentTrue_returnPercentType100() throws Exception {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "true");
when(channel.getArguments()).thenReturn(configMap);
when(event.getValue()).thenReturn(0);
when(channel.getDataType()).thenReturn(DataType.PercentType);
State state = sut.handleEvent(channel, event);
assertEquals(new PercentType(100), state);
}
@Test
public void handleEvent_PercentType1invertPercentTrue_returnPercentType100() {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "true");
when(channel.getArguments()).thenReturn(configMap);
when(event.getValue()).thenReturn(1);
when(channel.getDataType()).thenReturn(DataType.PercentType);
State state = sut.handleEvent(channel, event);
assertEquals(new PercentType(100), state);
}
@Test
public void handleEvent_OnOffType0invertFalse_returnOnOffTypeOff() {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_control", "false");
when(channel.getArguments()).thenReturn(configMap);
when(event.getValue()).thenReturn(0);
when(channel.getDataType()).thenReturn(DataType.OnOffType);
State state = sut.handleEvent(channel, event);
assertEquals(OnOffType.OFF, state);
}
@Test
public void handleEvent_OnOffType1invertFalse_returnOnOffTypeOn() {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_control", "false");
when(channel.getArguments()).thenReturn(configMap);
when(event.getValue()).thenReturn(1);
when(channel.getDataType()).thenReturn(DataType.OnOffType);
State state = sut.handleEvent(channel, event);
assertEquals(OnOffType.ON, state);
}
@Test
public void handleEvent_OnOffType0invertTrue_returnOnOffTypeOn() {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_control", "true");
when(channel.getArguments()).thenReturn(configMap);
when(event.getValue()).thenReturn(0);
when(channel.getDataType()).thenReturn(DataType.OnOffType);
State state = sut.handleEvent(channel, event);
assertEquals(OnOffType.ON, state);
}
@Test
public void handleEvent_OnOffType1invertTrue_returnOnOffTypeOff() {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_control", "true");
when(channel.getArguments()).thenReturn(configMap);
when(event.getValue()).thenReturn(1);
when(channel.getDataType()).thenReturn(DataType.OnOffType);
State state = sut.handleEvent(channel, event);
assertEquals(OnOffType.OFF, state);
}
@Test
public void receiveCommand_PercentType0invertPercentFalse_setValue0() throws Exception {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
setupReceiveCommand();
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "false");
when(channel.getArguments()).thenReturn(configMap);
when(percentType.intValue()).thenReturn(0);
sut.receiveCommand(channel, node, percentType);
verify(commandClass).setValueMessage(0);
}
@Test
public void receiveCommand_PercentType0invertPercentTrue_setValue99() throws Exception {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
setupReceiveCommand();
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "true");
when(channel.getArguments()).thenReturn(configMap);
when(percentType.intValue()).thenReturn(0);
sut.receiveCommand(channel, node, percentType);
verify(commandClass).setValueMessage(99);
}
@Test
public void receiveCommand_PercentType80invertPercentFalse_setValue80() throws Exception {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
setupReceiveCommand();
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "false");
when(channel.getArguments()).thenReturn(configMap);
when(percentType.intValue()).thenReturn(80);
sut.receiveCommand(channel, node, percentType);
verify(commandClass).setValueMessage(80);
}
@Test
public void receiveCommand_PercentType80invertPercentTrue_setValue20() throws Exception {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
setupReceiveCommand();
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "true");
when(channel.getArguments()).thenReturn(configMap);
when(percentType.intValue()).thenReturn(80);
sut.receiveCommand(channel, node, percentType);
verify(commandClass).setValueMessage(20);
}
@Test
public void receiveCommand_PercentType100invertPercentFalse_setValue99() throws Exception {
ZWaveMultiLevelSwitchConverter sut = new ZWaveMultiLevelSwitchConverter(controller);
setupReceiveCommand();
Map<String, String> configMap = new HashMap<>();
configMap.put("config_invert_percent", "false");
when(channel.getArguments()).thenReturn(configMap);
when(percentType.intValue()).thenReturn(100);
sut.receiveCommand(channel, node, percentType);
verify(commandClass).setValueMessage(99);
}
private void setupReceiveCommand() {
when(channel.getDataType()).thenReturn(DataType.PercentType);
when(channel.getEndpoint()).thenReturn(1);
when(node.resolveCommandClass(CommandClass.SWITCH_MULTILEVEL, channel.getEndpoint())).thenReturn(commandClass);
when(node.encapsulate(any(SerialMessage.class), any(ZWaveMultiLevelSwitchCommandClass.class), anyInt()))
.thenReturn(new SerialMessage());
}
}
|
package org.hswebframework.web.dao.mybatis.mapper;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.ezorm.rdb.meta.RDBColumnMetaData;
import org.hswebframework.ezorm.rdb.render.SqlAppender;
import org.hswebframework.ezorm.rdb.render.dialect.Dialect;
import org.hswebframework.ezorm.rdb.render.dialect.RenderPhase;
import org.hswebframework.ezorm.rdb.render.dialect.function.SqlFunction;
import org.hswebframework.ezorm.rdb.render.dialect.term.BoostTermTypeMapper;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author zhouhao
* @since 3.0.0-RC
*/
@Slf4j
public abstract class TreeStructureSqlTermCustomizer extends AbstractSqlTermCustomizer {
boolean not = false;
boolean parent = false;
public TreeStructureSqlTermCustomizer(String termType, boolean not, boolean parent) {
super(termType);
this.not = not;
}
protected abstract String getTableName();
protected abstract List<String> getTreePathByTerm(List<Object> termValue);
@Override
public SqlAppender accept(String wherePrefix, Term term, RDBColumnMetaData column, String tableAlias) {
ChangedTermValue termValue = createChangedTermValue(term);
Dialect dialect = column.getTableMetaData().getDatabaseMetaData().getDialect();
List<String> paths;
if (termValue.getOld() == termValue.getValue()) {
List<Object> value = BoostTermTypeMapper.convertList(column, termValue.getOld());
paths = getTreePathByTerm(value)
.stream()
.map(path -> path.concat("%"))
.collect(Collectors.toList());
termValue.setValue(paths);
} else {
paths = ((List) termValue.getValue());
}
SqlAppender termCondition = new SqlAppender();
termCondition.add(not ? "not " : "", "exists(select 1 from ", getTableName(), " tmp where tmp.u_id = ", createColumnName(column, tableAlias));
int len = paths.size();
if (len > 0) {
termCondition.add(" and (");
}
for (int i = 0; i < len; i++) {
if (i > 0) {
termCondition.addSpc("or");
}
if (parent) {
SqlFunction function = dialect.getFunction(SqlFunction.concat);
String concat;
if (function == null) {
concat = getTableName() + ".path";
log.warn("concat,Dialect.installFunction!");
} else {
concat = function.apply(SqlFunction.Param.of(RenderPhase.where, Arrays.asList("tmp.path", "'%'")));
}
termCondition.add("#{", wherePrefix, ".value.value[", i, "]}", " like ", concat);
} else {
termCondition.add("tmp.path like #{", wherePrefix, ".value.value[", i, "]}");
}
}
if (len > 0) {
termCondition.add(")");
}
termCondition.add(")");
return termCondition;
}
}
|
package org.opencb.opencga.storage.hadoop.utils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.KeyOnlyFilter;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.compress.DeflateCodec;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileAsBinaryOutputFormat;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.opencga.core.common.IOUtils;
import org.opencb.opencga.storage.core.exceptions.StorageEngineException;
import org.opencb.opencga.storage.hadoop.variant.AbstractVariantsTableDriver;
import org.opencb.opencga.storage.hadoop.variant.HadoopVariantStorageOptions;
import org.opencb.opencga.storage.hadoop.variant.mr.VariantMapReduceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.opencb.opencga.storage.hadoop.variant.HadoopVariantStorageOptions.WRITE_MAPPERS_LIMIT_FACTOR;
public class DeleteHBaseColumnDriver extends AbstractHBaseDriver {
public static final String COLUMNS_TO_DELETE = "columns_to_delete";
public static final String DELETE_ALL_COLUMNS = "delete_all_columns";
public static final String REGIONS_TO_DELETE = "regions_to_delete";
public static final String TWO_PHASES_PARAM = "two_phases_delete";
public static final String USE_REDUCE_STEP = "use_reduce_step";
private static final Logger LOGGER = LoggerFactory.getLogger(DeleteHBaseColumnDriver.class);
// This separator is not valid at Bytes.toStringBinary
private static final String REGION_SEPARATOR = "\\\\";
public static final String DELETE_HBASE_COLUMN_TASK_CLASS = "delete.hbase.column.task.class";
private Map<String, List<String>> columns;
private List<Pair<byte[], byte[]>> regions;
private Path outdir;
public void setupJob(Job job, String table) throws IOException {
Set<String> allColumns = columns.entrySet()
.stream()
.flatMap(e -> Stream.concat(Stream.of(e.getKey()), e.getValue().stream()))
.collect(Collectors.toSet());
job.getConfiguration().set(COLUMNS_TO_DELETE, serializeColumnsToDelete(columns));
// There is a maximum number of counters
job.getConfiguration().setStrings(COLUMNS_TO_COUNT, new ArrayList<>(allColumns)
.subList(0, Math.min(allColumns.size(), 50)).toArray(new String[0]));
Scan templateScan = new Scan();
int caching = job.getConfiguration().getInt(HadoopVariantStorageOptions.MR_HBASE_SCAN_CACHING.key(), 100);
LOGGER.info("Scan set Caching to " + caching);
templateScan.setCaching(caching); // 1 is the default in Scan
templateScan.setCacheBlocks(false); // don't set to true for MR jobs
templateScan.setFilter(new KeyOnlyFilter());
for (String column : allColumns) {
String[] split = column.split(":");
templateScan.addColumn(Bytes.toBytes(split[0]), Bytes.toBytes(split[1]));
}
List<Scan> scans;
if (!regions.isEmpty()) {
scans = new ArrayList<>(regions.size() / 2);
for (Pair<byte[], byte[]> region : regions) {
Scan scan = new Scan(templateScan);
scans.add(scan);
if (region.getFirst() != null && region.getFirst().length != 0) {
scan.setStartRow(region.getFirst());
}
if (region.getSecond() != null && region.getSecond().length != 0) {
scan.setStopRow(region.getSecond());
}
}
} else {
scans = Collections.singletonList(templateScan);
}
// set other scan attrs
boolean twoPhases = Boolean.parseBoolean(getParam(TWO_PHASES_PARAM));
if (!twoPhases) {
VariantMapReduceUtil.initTableMapperJob(job, table, scans, DeleteHBaseColumnMapper.class);
VariantMapReduceUtil.setOutputHBaseTable(job, table);
VariantMapReduceUtil.setNoneReduce(job);
} else {
VariantMapReduceUtil.initTableMapperJob(job, table, scans, DeleteHBaseColumnToProtoMapper.class);
outdir = getTempOutdir("opencga_delete", table, true);
outdir.getFileSystem(getConf()).deleteOnExit(outdir);
LOGGER.info(" * Temporary outdir file: " + outdir.toUri());
job.setOutputFormatClass(SequenceFileAsBinaryOutputFormat.class);
job.setOutputValueClass(BytesWritable.class);
job.setOutputKeyClass(BytesWritable.class);
SequenceFileAsBinaryOutputFormat.setOutputPath(job, outdir);
SequenceFileAsBinaryOutputFormat.setCompressOutput(job, true);
SequenceFileAsBinaryOutputFormat.setOutputCompressionType(job, SequenceFile.CompressionType.BLOCK);
SequenceFileAsBinaryOutputFormat.setOutputCompressorClass(job, DeflateCodec.class);
if (Boolean.getBoolean(getParam(USE_REDUCE_STEP))) {
float writeMappersLimitFactor = Float.parseFloat(getParam(WRITE_MAPPERS_LIMIT_FACTOR.key(),
WRITE_MAPPERS_LIMIT_FACTOR.defaultValue().toString()));
int serversSize = getServersSize(table);
int numReducers = Math.round(writeMappersLimitFactor * serversSize);
LOGGER.info("Set job reducers to " + numReducers + ". ServersSize: " + serversSize
+ ", writeMappersLimitFactor: " + writeMappersLimitFactor);
// Limit number of generated parts, and even the size of the parts
VariantMapReduceUtil.setNumReduceTasks(job, numReducers);
} else {
VariantMapReduceUtil.setNoneReduce(job);
}
}
}
@Override
protected void postExecution(boolean succeed) throws IOException, StorageEngineException {
super.postExecution(succeed);
try {
if (succeed) {
if (outdir != null) {
FileSystem fs = outdir.getFileSystem(getConf());
ContentSummary contentSummary = fs.getContentSummary(outdir);
LOGGER.info("Generated file " + outdir.toUri());
LOGGER.info(" - Size (HDFS) : " + IOUtils.humanReadableByteCount(contentSummary.getLength(), false));
LOGGER.info(" - SpaceConsumed (raw) : " + IOUtils.humanReadableByteCount(contentSummary.getSpaceConsumed(), false));
LOGGER.info(" - FileCount : " + contentSummary.getFileCount());
RemoteIterator<LocatedFileStatus> it = fs.listFiles(outdir, true);
while (it.hasNext()) {
LocatedFileStatus fileStatus = it.next();
ContentSummary thiscontent = fs.getContentSummary(fileStatus.getPath());
LOGGER.info(" - " + fileStatus.getPath().getName() + " : "
+ IOUtils.humanReadableByteCount(thiscontent.getLength(), false));
}
String writeMappersLimitFactor = getParam(WRITE_MAPPERS_LIMIT_FACTOR.key(),
WRITE_MAPPERS_LIMIT_FACTOR.defaultValue().toString());
int code = new HBaseWriterDriver(getConf()).run(HBaseWriterDriver.buildArgs(table,
new ObjectMap()
.append(HBaseWriterDriver.INPUT_FILE_PARAM, outdir.toUri().toString())
.append(WRITE_MAPPERS_LIMIT_FACTOR.key(), writeMappersLimitFactor)));
if (code != 0) {
throw new StorageEngineException("Error writing mutations");
}
}
}
} catch (StorageEngineException e) {
// Don't double wrap this exception
throw e;
} catch (Exception e) {
throw new StorageEngineException("Error writing mutations", e);
} finally {
if (outdir != null) {
deleteTemporaryFile(outdir);
}
}
}
@Override
protected void parseAndValidateParameters() throws IOException {
super.parseAndValidateParameters();
DeleteHBaseColumnTask task = getDeleteHBaseColumnTask(getConf());
columns = task.getColumnsToDelete(getConf());
if (columns.isEmpty()) {
if (getConf().getBoolean(DELETE_ALL_COLUMNS, false)) {
LOGGER.info("Delete ALL columns");
} else {
throw new IllegalArgumentException("No columns specified!");
}
}
for (Map.Entry<String, List<String>> entry : columns.entrySet()) {
checkColumn(entry.getKey());
for (String s : entry.getValue()) {
checkColumn(s);
}
}
regions = task.getRegionsToDelete(getConf());
}
private void checkColumn(String column) {
if (!column.contains(":")) {
throw new IllegalArgumentException("Malformed column '" + column + "'. Requires <family>:<column>");
}
}
private static String serializeColumnsToDelete(Map<String, List<String>> columnsToDelete) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, List<String>> entry : columnsToDelete.entrySet()) {
if (sb.length() > 0) {
sb.append(";");
}
sb.append(entry.getKey());
if (CollectionUtils.isNotEmpty(entry.getValue())) {
sb.append("
sb.append(String.join(",", entry.getValue()));
}
}
return sb.toString();
}
@Override
protected String getJobName() {
return "opencga: delete columns from table '" + table + '\'';
}
@Override
protected String getUsage() {
return "Usage: " + getClass().getSimpleName()
+ " [generic options] <table> <family_1>:<column_1>(,<family_n>:<column_n>)* (<key> <value>)*";
}
public static String[] buildArgs(String table, List<String> columns, ObjectMap options) {
return buildArgs(table, columns.stream().collect(Collectors.toMap(s -> s, s -> Collections.emptyList())), options);
}
public static String[] buildArgs(String table, Map<String, List<String>> columns, ObjectMap options) {
return buildArgs(table, columns, false, null, options);
}
public static String[] buildArgs(String table, Map<String, List<String>> columns, boolean deleteAllColumns,
List<Pair<byte[], byte[]>> regions, ObjectMap options) {
ObjectMap args = new ObjectMap();
if (deleteAllColumns) {
args.append(DELETE_ALL_COLUMNS, true);
} else {
args.append(COLUMNS_TO_DELETE, serializeColumnsToDelete(columns));
}
if (regions != null) {
StringBuilder sb = new StringBuilder();
Iterator<Pair<byte[], byte[]>> iterator = regions.iterator();
while (iterator.hasNext()) {
Pair<byte[], byte[]> region = iterator.next();
String start = Bytes.toStringBinary(region.getFirst());
String end = Bytes.toStringBinary(region.getSecond());
sb.append(start);
sb.append(REGION_SEPARATOR);
sb.append(end);
if (iterator.hasNext()) {
sb.append(REGION_SEPARATOR);
}
}
args.append(REGIONS_TO_DELETE, sb.toString());
}
args.putAll(options);
return buildArgs(table, args);
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
main(args, (Class<? extends AbstractVariantsTableDriver>) MethodHandles.lookup().lookupClass());
}
public static class DeleteHBaseColumnToProtoMapper extends TableMapper<BytesWritable, BytesWritable> {
private DeleteHBaseColumnTask task;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
task = getDeleteHBaseColumnTask(context.getConfiguration());
task.setup(context);
}
@Override
protected void map(ImmutableBytesWritable key, Result result, Context context) throws IOException, InterruptedException {
for (Mutation value : task.map(result)) {
ClientProtos.MutationProto proto;
if (value instanceof Delete) {
proto = ProtobufUtil.toMutation(ClientProtos.MutationProto.MutationType.DELETE, value);
} else if (value instanceof Put) {
proto = ProtobufUtil.toMutation(ClientProtos.MutationProto.MutationType.PUT, value);
} else {
throw new IllegalArgumentException("Unknown mutation type " + value.getClass());
}
context.write(new BytesWritable(value.getRow()), new BytesWritable(proto.toByteArray()));
}
// Indicate that the process is still alive
context.progress();
}
}
public static class DeleteHBaseColumnMapper extends TableMapper<ImmutableBytesWritable, Mutation> {
private DeleteHBaseColumnTask task;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
task = getDeleteHBaseColumnTask(context.getConfiguration());
task.setup(context);
}
@Override
protected void map(ImmutableBytesWritable key, Result result, Context context) throws IOException, InterruptedException {
for (Mutation mutation : task.map(result)) {
context.write(key, mutation);
}
// Indicate that the process is still alive
context.progress();
}
}
public static class DeleteHBaseColumnTask {
private TaskAttemptContext context;
protected Set<String> columnsToCount;
protected Map<String, List<String>> columnsToDelete;
protected boolean deleteAllColumns;
protected void initCounter(String counter) {
count(counter, 0);
}
protected final void count(String counter) {
count(counter, 1);
}
protected final void count(String counter, int incr) {
context.getCounter(COUNTER_GROUP_NAME, counter).increment(incr);
}
protected final void setup(TaskAttemptContext context) throws IOException {
this.context = context;
setup(context.getConfiguration());
initCounter("INPUT_ROWS");
initCounter("DELETE");
initCounter("NO_DELETE");
}
protected void setup(Configuration configuration) throws IOException {
deleteAllColumns = configuration.getBoolean(DELETE_ALL_COLUMNS, false);
columnsToCount = new HashSet<>(configuration.get(COLUMNS_TO_COUNT) == null
? Collections.emptyList()
: Arrays.asList(configuration.getStrings(COLUMNS_TO_COUNT)));
columnsToDelete = getColumnsToDelete(configuration);
}
protected List<Mutation> map(Result result) {
Delete delete = new Delete(result.getRow());
count("INPUT_ROWS");
if (deleteAllColumns) {
count("DELETE");
return Collections.singletonList(delete);
} else {
for (Cell cell : result.rawCells()) {
byte[] family = CellUtil.cloneFamily(cell);
byte[] qualifier = CellUtil.cloneQualifier(cell);
String c = Bytes.toString(family) + ':' + Bytes.toString(qualifier);
List<String> otherColumns = columnsToDelete.get(c);
if (columnsToDelete.containsKey(c)) {
delete.addColumn(family, qualifier);
for (String otherColumn : otherColumns) {
if (columnsToCount.contains(otherColumn)) {
count(otherColumn);
}
String[] split = otherColumn.split(":", 2);
delete.addColumn(Bytes.toBytes(split[0]), Bytes.toBytes(split[1]));
}
if (columnsToCount.contains(c)) {
count(c);
}
}
}
if (delete.isEmpty()) {
count("NO_DELETE");
return Collections.emptyList();
} else {
count("DELETE");
return Collections.singletonList(delete);
}
}
}
public List<Pair<byte[], byte[]>> getRegionsToDelete(Configuration configuration) {
List<Pair<byte[], byte[]>> regions = new ArrayList<>();
String regionsStr = configuration.get(REGIONS_TO_DELETE);
if (regionsStr != null && !regionsStr.isEmpty()) {
String[] split = StringUtils.splitByWholeSeparatorPreserveAllTokens(regionsStr, REGION_SEPARATOR);
if (split.length % 2 != 0) {
throw new IllegalArgumentException("Expected pair number of elements in region. Got " + split.length);
}
for (int i = 0; i < split.length; i += 2) {
regions.add(new Pair<>(Bytes.toBytesBinary(split[i]), Bytes.toBytesBinary(split[i + 1])));
}
}
return regions;
}
public Map<String, List<String>> getColumnsToDelete(Configuration conf) {
Map<String, List<String>> columns;
if (conf.get(COLUMNS_TO_DELETE) == null) {
columns = Collections.emptyMap();
} else {
String[] columnStrings = conf.get(COLUMNS_TO_DELETE).split(";");
columns = new HashMap<>(columnStrings.length);
for (String elem : columnStrings) {
String[] split = elem.split("
if (split.length > 1) {
columns.put(split[0], Arrays.asList(split[1].split(",")));
} else {
columns.put(elem, Collections.emptyList());
}
}
}
return columns;
}
}
public static Class<? extends DeleteHBaseColumnTask> getDeleteHbaseColumnTaskClass(Configuration configuration) {
return configuration
.getClass(DELETE_HBASE_COLUMN_TASK_CLASS, DeleteHBaseColumnTask.class, DeleteHBaseColumnTask.class);
}
public static DeleteHBaseColumnTask getDeleteHBaseColumnTask(Configuration configuration) {
Class<? extends DeleteHBaseColumnTask> taskClass = getDeleteHbaseColumnTaskClass(configuration);
try {
return taskClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException("Unable to create new instance of " + DeleteHBaseColumnTask.class, e);
}
}
}
|
package org.opendaylight.controller.samples.differentiatedforwarding.openstack;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import org.opendaylight.controller.samples.differentiatedforwarding.openstack.performance.BwExpReport;
import org.opendaylight.controller.samples.differentiatedforwarding.openstack.performance.BwReport;
import org.openstack4j.model.compute.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReportManager {
private static Logger log = LoggerFactory.getLogger(ReportManager.class);
public static String getReportName(String prefix){
String name;
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
Date date = new Date();
name = prefix + "-" + dateFormat.format(date);
return name;
}
public static String createExpDir(String dirPath){
String dirName = getReportName(dirPath+"/exp");
if(new File(dirName).mkdirs()){
return dirName;
} else {
return null;
}
}
public static void writeReport(List<BwExpReport> reports, String outputFile, boolean append){
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile, append)));
for (BwExpReport bwExpReport : reports) {
if (bwExpReport == null) continue;
writer.println(bwExpReport.toString());
}
} catch (IOException e) {
log.error("writeReport", e);
} finally {
if (writer != null){
writer.close();
}
}
log.info("writeReport: generated log: {}", outputFile);
}
public static void writeReportObjects(List<BwExpReport> reports, String outputFile) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(outputFile));
oos.writeObject(reports);
} catch (Exception e) {
log.error("writeReportObjects", e);
} finally {
try {
if (oos != null) oos.close();
} catch (IOException e) {
log.error("writeReportObjects", e);
}
}
}
public static List<BwExpReport> readReportObjects(String inputFile){
List<BwExpReport> reports = null;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(inputFile));
reports = (List<BwExpReport>) ois.readObject();
} catch (Exception e) {
log.error("readReportObjects", e);
} finally {
try {
ois.close();
} catch (IOException e) {
log.error("readReportObjects", e);
}
}
return reports;
}
public static void writeReport(String[] reports, String outputFile, boolean append){
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile, append)));
for (String bwReport : reports) {
writer.println(bwReport.toString());
}
} catch (IOException e) {
log.error("writeReport", e);
} finally {
if (writer != null){
writer.close();
}
}
log.info("writeReport: generated log: {}", outputFile);
}
public static void writeReport(Object report, String outputFile, boolean append){
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile, append)));
writer.println(report.toString());
} catch (IOException e) {
log.error("writeReport", e);
} finally {
if (writer != null){
writer.close();
}
}
log.info("writeReport: generated log: {}", outputFile);
}
public static void main(String[] args) {
// writeReport(new String[]{"a", "b", "c"}, "/tmp/bw-20141117-181019", false);
// int classValue, int networkIndex, int instanceNum,
// int retries, int maxRetries, int acceptableFailurePercentage,
// Date startTime, Date endTime,
// boolean deleteNetwork, boolean deleteInstances,
// boolean networkMayExist, boolean runClassExpConcurrently,
// boolean runInstanceExpConcurrently, Network network,
// List<? extends Server> instances, Set<Server> reachableInstances,
// Set<Server> notReachableinstances, ArrayList<BwReport> nuttcpReports
// BwExpReport bwExpReport = new BwExpReport(1, 1, 1,
// 1, 1, 1,
// new Date(), new Date(),
// true, true,
// true, true,
// true, null,
// new ArrayList<Server>(), new HashSet<Server>(),
// new HashSet<Server>(), new ArrayList<BwReport>());
// List<BwExpReport> reports = new ArrayList<>();
// reports.add(bwExpReport);
// writeReportObjects(reports, "/tmp/obj");
List<BwExpReport> reports2 = readReportObjects("/tmp/classes[1][con=true]-nets2-instances16[con=true]-20141126-180419.obj");
System.out.println(reports2);
}
}
|
package fr.openwide.core.test.jpa.more.business;
import java.util.Date;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import fr.openwide.core.jpa.exception.SecurityServiceException;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkErrorType;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkStatus;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkWrapper;
import fr.openwide.core.jpa.more.business.link.service.IExternalLinkCheckerService;
import fr.openwide.core.jpa.util.EntityManagerUtils;
import fr.openwide.core.test.jpa.more.config.spring.ExternalLinkCheckerTestConfig;
@ContextConfiguration(classes = ExternalLinkCheckerTestConfig.class)
public class TestExternalLinkCheckerService extends AbstractJpaMoreTestCase {
@Autowired
private IExternalLinkCheckerService externalLinkCheckerService;
@Autowired
private EntityManagerUtils entityManagerUtils;
@Test
public void testExternalLinkCheckerService() throws Exception {
Long id1 = null;
Long id2 = null;
Long id3 = null;
Long id4 = null;
Long id5 = null;
Long id6 = null;
Long id7 = null;
Long id8 = null;
Long id9 = null;
Long id10 = null;
Long id11 = null;
Long id12 = null;
Long id13 = null;
Long id14 = null;
{
id1 = createLink("http:
id2 = createLink("http://zzz.totototototo.zzz/totoz/");
id3 = createLink("http:
id4 = createLink("http://zzz.totototototo.zzz/totoz/");
id5 = createLink("http:
id6 = createLink("http: http://example.com/");
id7 = createLink("http://62.210.184.140/V2/Partenaires/00043/Images/Chalet 95/dheilly003.JPG");
id8 = createLink("http://hotel.reservit.com/reservit/avail-info.php?hotelid=104461&userid=4340d8abb651c8ca20e6cd57a844f5708354&__utma=1.804870725.1361370840.1361370840.1361370840.1&__utmc=1&__utmz=1.1361370840.1.1.utmcsr=%28direct%29|utmccn=%28direct%29|utmcmd=%28none%29");
id9 = createLink("http:
id10 = createLink("http://drome-hotel.for-system.com/index.aspx?Globales/ListeIdFournisseur=20716");
id11 = createLink("http://cyclosyennois.free.fr/");
id12 = createLink("http://lacroisee26.com/");
id13 = createLink("http://ledauphine.com/");
id14 = createLink("https:
}
Date beforeFirstBatchDate = new Date();
Thread.sleep(1000); // Make sure the checkDate will not be exactly the same
{
externalLinkCheckerService.checkBatch();
}
entityManagerUtils.getEntityManager().clear();
{
checkStatusOK(id1, beforeFirstBatchDate);
ExternalLinkWrapper externalLink2 = externalLinkWrapperService.getById(id2);
Assert.assertEquals(ExternalLinkStatus.OFFLINE, externalLink2.getStatus());
Assert.assertEquals(1, externalLink2.getConsecutiveFailures());
Assert.assertNull(externalLink2.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.IO, externalLink2.getLastErrorType());
Assert.assertTrue(externalLink2.getLastCheckDate().after(beforeFirstBatchDate));
ExternalLinkWrapper externalLink3 = externalLinkWrapperService.getById(id3);
Assert.assertEquals(ExternalLinkStatus.OFFLINE, externalLink3.getStatus());
Assert.assertEquals(1, externalLink3.getConsecutiveFailures());
Assert.assertEquals(Integer.valueOf(HttpStatus.SC_NOT_FOUND), externalLink3.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.HTTP, externalLink3.getLastErrorType());
Assert.assertTrue(externalLink3.getLastCheckDate().after(beforeFirstBatchDate));
// Same URL as externalLink2, so this link should carry the same data
ExternalLinkWrapper externalLink4 = externalLinkWrapperService.getById(id4);
Assert.assertEquals(externalLink2.getStatus(), externalLink4.getStatus());
Assert.assertEquals(externalLink2.getConsecutiveFailures(), externalLink4.getConsecutiveFailures());
Assert.assertEquals(externalLink2.getLastStatusCode(), externalLink4.getLastStatusCode());
Assert.assertEquals(externalLink2.getLastErrorType(), externalLink4.getLastErrorType());
Assert.assertEquals(externalLink2.getLastCheckDate(), externalLink2.getLastCheckDate());
checkStatusOK(id5, beforeFirstBatchDate);
// Invalid URL
ExternalLinkWrapper externalLink6 = externalLinkWrapperService.getById(id6);
Assert.assertEquals(ExternalLinkStatus.DEAD_LINK, externalLink6.getStatus());
Assert.assertEquals(0, externalLink6.getConsecutiveFailures());
Assert.assertNull(externalLink6.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.URI_SYNTAX, externalLink6.getLastErrorType());
Assert.assertTrue(externalLink6.getLastCheckDate().after(beforeFirstBatchDate));
checkStatusOK(id7, beforeFirstBatchDate);
checkStatusOK(id8, beforeFirstBatchDate);
checkStatusOK(id9, beforeFirstBatchDate);
checkStatusOK(id10, beforeFirstBatchDate);
checkStatusOK(id11, beforeFirstBatchDate);
checkStatusOK(id12, beforeFirstBatchDate);
checkStatusOK(id13, beforeFirstBatchDate);
checkStatusOK(id14, beforeFirstBatchDate);
}
Date beforeSecondBatchDate = new Date();
Thread.sleep(1000); // Make sure the checkDate will not be exactly the same
{
externalLinkCheckerService.checkBatch();
}
entityManagerUtils.getEntityManager().clear();
{
checkStatusOK(id1, beforeSecondBatchDate);
ExternalLinkWrapper externalLink2 = externalLinkWrapperService.getById(id2);
Assert.assertEquals(ExternalLinkStatus.OFFLINE, externalLink2.getStatus());
Assert.assertEquals(2, externalLink2.getConsecutiveFailures());
Assert.assertNull(externalLink2.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.IO, externalLink2.getLastErrorType());
Assert.assertTrue(externalLink2.getLastCheckDate().after(beforeSecondBatchDate));
ExternalLinkWrapper externalLink3 = externalLinkWrapperService.getById(id3);
Assert.assertEquals(ExternalLinkStatus.OFFLINE, externalLink3.getStatus());
Assert.assertEquals(2, externalLink3.getConsecutiveFailures());
Assert.assertEquals(Integer.valueOf(HttpStatus.SC_NOT_FOUND), externalLink3.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.HTTP, externalLink3.getLastErrorType());
Assert.assertTrue(externalLink3.getLastCheckDate().after(beforeSecondBatchDate));
// Same URL as externalLink2, so this link should carry the same data
ExternalLinkWrapper externalLink4 = externalLinkWrapperService.getById(id4);
Assert.assertEquals(externalLink2.getStatus(), externalLink4.getStatus());
Assert.assertEquals(externalLink2.getConsecutiveFailures(), externalLink4.getConsecutiveFailures());
Assert.assertEquals(externalLink2.getLastStatusCode(), externalLink4.getLastStatusCode());
Assert.assertEquals(externalLink2.getLastErrorType(), externalLink4.getLastErrorType());
Assert.assertEquals(externalLink2.getLastCheckDate(), externalLink2.getLastCheckDate());
checkStatusOK(id5, beforeSecondBatchDate);
// Invalid URL
ExternalLinkWrapper externalLink6 = externalLinkWrapperService.getById(id6);
Assert.assertEquals(ExternalLinkStatus.DEAD_LINK, externalLink6.getStatus());
Assert.assertEquals(0, externalLink6.getConsecutiveFailures());
Assert.assertNull(externalLink6.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.URI_SYNTAX, externalLink6.getLastErrorType());
Assert.assertTrue(externalLink6.getLastCheckDate().after(beforeFirstBatchDate));
checkStatusOK(id7, beforeSecondBatchDate);
}
}
private Long createLink(String url) throws ServiceException, SecurityServiceException {
ExternalLinkWrapper externalLink = new ExternalLinkWrapper(url);
externalLinkWrapperService.create(externalLink);
return externalLink.getId();
}
private void checkStatusOK(Long id, Date beforeFirstBatchDate) {
checkStatus(id, beforeFirstBatchDate,
ExternalLinkStatus.ONLINE, 0, Integer.valueOf(HttpStatus.SC_OK), null);
}
private void checkStatus(Long id, Date beforeFirstBatchDate,
ExternalLinkStatus externalLinkStatus,
int consecutiveFailures,
Integer httpStatus,
ExternalLinkErrorType errorType) {
ExternalLinkWrapper externalLink = externalLinkWrapperService.getById(id);
Assert.assertEquals(externalLinkStatus, externalLink.getStatus());
Assert.assertEquals(consecutiveFailures, externalLink.getConsecutiveFailures());
Assert.assertEquals(httpStatus, externalLink.getLastStatusCode());
Assert.assertEquals(errorType, externalLink.getLastErrorType());
Assert.assertTrue(externalLink.getLastCheckDate().after(beforeFirstBatchDate));
}
}
|
package io.quarkus.rest.client.reactive.deployment;
import static io.quarkus.arc.processor.MethodDescriptors.MAP_PUT;
import static io.quarkus.rest.client.reactive.deployment.DotNames.CLIENT_EXCEPTION_MAPPER;
import static io.quarkus.rest.client.reactive.deployment.DotNames.CLIENT_HEADER_PARAM;
import static io.quarkus.rest.client.reactive.deployment.DotNames.CLIENT_HEADER_PARAMS;
import static io.quarkus.rest.client.reactive.deployment.DotNames.REGISTER_CLIENT_HEADERS;
import static io.quarkus.rest.client.reactive.deployment.DotNames.REGISTER_PROVIDER;
import static io.quarkus.rest.client.reactive.deployment.DotNames.REGISTER_PROVIDERS;
import static java.util.Arrays.asList;
import static org.jboss.resteasy.reactive.common.processor.EndpointIndexer.CDI_WRAPPER_SUFFIX;
import static org.jboss.resteasy.reactive.common.processor.scanning.ResteasyReactiveScanner.BUILTIN_HTTP_ANNOTATIONS_TO_METHOD;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Typed;
import javax.inject.Singleton;
import javax.ws.rs.Priorities;
import javax.ws.rs.RuntimeType;
import javax.ws.rs.core.MediaType;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.rest.client.RestClientDefinitionException;
import org.eclipse.microprofile.rest.client.ext.QueryParamStyle;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.CompositeIndex;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
import org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.CustomScopeAnnotationsBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor;
import io.quarkus.arc.deployment.UnremovableBeanBuildItem;
import io.quarkus.arc.processor.BuiltinScope;
import io.quarkus.arc.processor.ScopeInfo;
import io.quarkus.deployment.Capabilities;
import io.quarkus.deployment.Capability;
import io.quarkus.deployment.Feature;
import io.quarkus.deployment.GeneratedClassGizmoAdaptor;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.ConfigurationTypeBuildItem;
import io.quarkus.deployment.builditem.ExtensionSslNativeSupportBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.util.AsmUtil;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.jaxrs.client.reactive.deployment.JaxrsClientReactiveEnricherBuildItem;
import io.quarkus.jaxrs.client.reactive.deployment.RestClientDefaultConsumesBuildItem;
import io.quarkus.jaxrs.client.reactive.deployment.RestClientDefaultProducesBuildItem;
import io.quarkus.jaxrs.client.reactive.deployment.RestClientDisableSmartDefaultProduces;
import io.quarkus.rest.client.reactive.runtime.AnnotationRegisteredProviders;
import io.quarkus.rest.client.reactive.runtime.HeaderCapturingServerFilter;
import io.quarkus.rest.client.reactive.runtime.HeaderContainer;
import io.quarkus.rest.client.reactive.runtime.RestClientReactiveCDIWrapperBase;
import io.quarkus.rest.client.reactive.runtime.RestClientReactiveConfig;
import io.quarkus.rest.client.reactive.runtime.RestClientRecorder;
import io.quarkus.restclient.config.RestClientsConfig;
import io.quarkus.restclient.config.deployment.RestClientConfigUtils;
import io.quarkus.resteasy.reactive.spi.ContainerRequestFilterBuildItem;
import io.quarkus.runtime.LaunchMode;
class RestClientReactiveProcessor {
private static final Logger log = Logger.getLogger(RestClientReactiveProcessor.class);
private static final DotName REGISTER_REST_CLIENT = DotName.createSimple(RegisterRestClient.class.getName());
private static final DotName SESSION_SCOPED = DotName.createSimple(SessionScoped.class.getName());
private static final DotName KOTLIN_METADATA_ANNOTATION = DotName.createSimple("kotlin.Metadata");
private static final String DISABLE_SMART_PRODUCES_QUARKUS = "quarkus.rest-client.disable-smart-produces";
private static final String KOTLIN_INTERFACE_DEFAULT_IMPL_SUFFIX = "$DefaultImpls";
private static final Set<DotName> SKIP_COPYING_ANNOTATIONS_TO_GENERATED_CLASS = Set.of(
REGISTER_REST_CLIENT,
REGISTER_PROVIDER,
REGISTER_PROVIDERS,
CLIENT_HEADER_PARAM,
CLIENT_HEADER_PARAMS,
REGISTER_CLIENT_HEADERS);
@BuildStep
void announceFeature(BuildProducer<FeatureBuildItem> features) {
features.produce(new FeatureBuildItem(Feature.REST_CLIENT_REACTIVE));
}
@BuildStep
void registerQueryParamStyleForConfig(BuildProducer<ConfigurationTypeBuildItem> configurationTypes) {
configurationTypes.produce(new ConfigurationTypeBuildItem(QueryParamStyle.class));
}
@BuildStep
ExtensionSslNativeSupportBuildItem activateSslNativeSupport() {
return new ExtensionSslNativeSupportBuildItem(Feature.REST_CLIENT_REACTIVE);
}
@BuildStep
void setUpDefaultMediaType(BuildProducer<RestClientDefaultConsumesBuildItem> consumes,
BuildProducer<RestClientDefaultProducesBuildItem> produces,
BuildProducer<RestClientDisableSmartDefaultProduces> disableSmartProduces,
RestClientReactiveConfig config) {
consumes.produce(new RestClientDefaultConsumesBuildItem(MediaType.APPLICATION_JSON, 10));
produces.produce(new RestClientDefaultProducesBuildItem(MediaType.APPLICATION_JSON, 10));
Config mpConfig = ConfigProvider.getConfig();
Optional<Boolean> disableSmartProducesConfig = mpConfig.getOptionalValue(DISABLE_SMART_PRODUCES_QUARKUS, Boolean.class);
if (config.disableSmartProduces || disableSmartProducesConfig.orElse(false)) {
disableSmartProduces.produce(new RestClientDisableSmartDefaultProduces());
}
}
@BuildStep
void registerRestClientListenerForTracing(
Capabilities capabilities,
BuildProducer<NativeImageResourceBuildItem> resource,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
if (capabilities.isPresent(Capability.SMALLRYE_OPENTRACING)) {
resource.produce(new NativeImageResourceBuildItem(
"META-INF/services/org.eclipse.microprofile.rest.client.spi.RestClientListener"));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, false, false,
"io.smallrye.opentracing.SmallRyeRestClientListener"));
}
}
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void setupAdditionalBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeans,
RestClientRecorder restClientRecorder) {
restClientRecorder.setRestClientBuilderResolver();
additionalBeans.produce(new AdditionalBeanBuildItem(RestClient.class));
additionalBeans.produce(AdditionalBeanBuildItem.unremovableOf(HeaderContainer.class));
}
@BuildStep
UnremovableBeanBuildItem makeConfigUnremovable() {
return UnremovableBeanBuildItem.beanTypes(RestClientsConfig.class);
}
@BuildStep
void setupRequestCollectingFilter(BuildProducer<ContainerRequestFilterBuildItem> filters) {
filters.produce(new ContainerRequestFilterBuildItem(HeaderCapturingServerFilter.class.getName()));
}
@BuildStep
void addMpClientEnricher(BuildProducer<JaxrsClientReactiveEnricherBuildItem> enrichers) {
enrichers.produce(new JaxrsClientReactiveEnricherBuildItem(new MicroProfileRestClientEnricher()));
}
private void searchForJaxRsMethods(List<MethodInfo> listOfKnownMethods, ClassInfo startingInterface, CompositeIndex index) {
for (MethodInfo method : startingInterface.methods()) {
if (isRestMethod(method)) {
listOfKnownMethods.add(method);
}
}
List<DotName> otherImplementedInterfaces = startingInterface.interfaceNames();
for (DotName otherInterface : otherImplementedInterfaces) {
ClassInfo superInterface = index.getClassByName(otherInterface);
if (superInterface != null)
searchForJaxRsMethods(listOfKnownMethods, superInterface, index);
}
}
@BuildStep
void registerHeaderFactoryBeans(CombinedIndexBuildItem index,
BuildProducer<AdditionalBeanBuildItem> additionalBeans) {
Collection<AnnotationInstance> annotations = index.getIndex().getAnnotations(REGISTER_CLIENT_HEADERS);
for (AnnotationInstance registerClientHeaders : annotations) {
AnnotationValue value = registerClientHeaders.value();
if (value != null) {
Type clientHeaderFactoryType = value.asClass();
String factoryTypeName = clientHeaderFactoryType.name().toString();
if (!MicroProfileRestClientEnricher.DEFAULT_HEADERS_FACTORY.equals(factoryTypeName)) {
additionalBeans.produce(AdditionalBeanBuildItem.unremovableOf(factoryTypeName));
}
}
}
}
/**
* Creates an implementation of `AnnotationRegisteredProviders` class with a constructor that:
* <ul>
* <li>puts all the providers registered by the @RegisterProvider annotation in a
* map using the {@link AnnotationRegisteredProviders#addProviders(String, Map)} method</li>
* <li>registers all the provider implementations annotated with @Provider using
* {@link AnnotationRegisteredProviders#addGlobalProvider(Class, int)}</li>
* </ul>
*
*
* @param indexBuildItem index
* @param generatedBeans build producer for generated beans
*/
@BuildStep
void registerProvidersFromAnnotations(CombinedIndexBuildItem indexBuildItem,
BuildProducer<GeneratedBeanBuildItem> generatedBeans,
BuildProducer<GeneratedClassBuildItem> generatedClasses,
BuildProducer<UnremovableBeanBuildItem> unremovableBeans,
RestClientReactiveConfig clientConfig) {
String annotationRegisteredProvidersImpl = AnnotationRegisteredProviders.class.getName() + "Implementation";
IndexView index = indexBuildItem.getIndex();
Map<String, List<AnnotationInstance>> annotationsByClassName = new HashMap<>();
for (AnnotationInstance annotation : index.getAnnotations(REGISTER_PROVIDER)) {
String targetClass = annotation.target().asClass().name().toString();
annotationsByClassName.computeIfAbsent(targetClass, key -> new ArrayList<>())
.add(annotation);
}
for (AnnotationInstance annotation : index.getAnnotations(REGISTER_PROVIDERS)) {
String targetClass = annotation.target().asClass().name().toString();
annotationsByClassName.computeIfAbsent(targetClass, key -> new ArrayList<>())
.addAll(asList(annotation.value().asNestedArray()));
}
try (ClassCreator classCreator = ClassCreator.builder()
.className(annotationRegisteredProvidersImpl)
.classOutput(new GeneratedBeanGizmoAdaptor(generatedBeans))
.superClass(AnnotationRegisteredProviders.class)
.build()) {
classCreator.addAnnotation(Singleton.class.getName());
MethodCreator constructor = classCreator
.getMethodCreator(MethodDescriptor.ofConstructor(annotationRegisteredProvidersImpl));
constructor.invokeSpecialMethod(MethodDescriptor.ofConstructor(AnnotationRegisteredProviders.class),
constructor.getThis());
if (clientConfig.providerAutodiscovery) {
for (AnnotationInstance instance : index.getAnnotations(ResteasyReactiveDotNames.PROVIDER)) {
ClassInfo providerClass = instance.target().asClass();
// ignore providers annotated with `@ConstrainedTo(SERVER)`
AnnotationInstance constrainedToInstance = providerClass
.classAnnotation(ResteasyReactiveDotNames.CONSTRAINED_TO);
if (constrainedToInstance != null) {
if (RuntimeType.valueOf(constrainedToInstance.value().asEnum()) == RuntimeType.SERVER) {
continue;
}
}
if (providerClass.interfaceNames().contains(ResteasyReactiveDotNames.FEATURE)) {
continue; // features should not be automatically registered for the client, see javadoc for Feature
}
int priority = getAnnotatedPriority(index, providerClass.name().toString(), Priorities.USER);
constructor.invokeVirtualMethod(
MethodDescriptor.ofMethod(AnnotationRegisteredProviders.class, "addGlobalProvider",
void.class, Class.class,
int.class),
constructor.getThis(), constructor.loadClassFromTCCL(providerClass.name().toString()),
constructor.load(priority));
}
}
Map<String, ClientExceptionMapperHandler.Result> ifaceToGeneratedMapper = new HashMap<>();
ClientExceptionMapperHandler clientExceptionMapperHandler = new ClientExceptionMapperHandler(
new GeneratedClassGizmoAdaptor(generatedClasses, true));
for (AnnotationInstance instance : index.getAnnotations(CLIENT_EXCEPTION_MAPPER)) {
ClientExceptionMapperHandler.Result result = clientExceptionMapperHandler
.generateResponseExceptionMapper(instance);
if (ifaceToGeneratedMapper.containsKey(result.interfaceName)) {
throw new IllegalStateException("Only a single instance of '" + CLIENT_EXCEPTION_MAPPER
+ "' is allowed per REST Client interface. Offending class is '" + result.interfaceName + "'");
}
ifaceToGeneratedMapper.put(result.interfaceName, result);
}
for (Map.Entry<String, List<AnnotationInstance>> annotationsForClass : annotationsByClassName.entrySet()) {
ResultHandle map = constructor.newInstance(MethodDescriptor.ofConstructor(HashMap.class));
for (AnnotationInstance value : annotationsForClass.getValue()) {
String className = value.value().asString();
AnnotationValue priorityAnnotationValue = value.value("priority");
int priority;
if (priorityAnnotationValue == null) {
priority = getAnnotatedPriority(index, className, Priorities.USER);
} else {
priority = priorityAnnotationValue.asInt();
}
constructor.invokeInterfaceMethod(MAP_PUT, map, constructor.loadClassFromTCCL(className),
constructor.load(priority));
}
String ifaceName = annotationsForClass.getKey();
if (ifaceToGeneratedMapper.containsKey(ifaceName)) {
// remove the interface from the generated mapper since it's going to be handled now
// the remaining entries will be handled later
ClientExceptionMapperHandler.Result result = ifaceToGeneratedMapper.remove(ifaceName);
constructor.invokeInterfaceMethod(MAP_PUT, map, constructor.loadClass(result.generatedClassName),
constructor.load(result.priority));
}
constructor.invokeVirtualMethod(
MethodDescriptor.ofMethod(AnnotationRegisteredProviders.class, "addProviders", void.class, String.class,
Map.class),
constructor.getThis(), constructor.load(ifaceName), map);
}
// add the remaining generated mappers
for (Map.Entry<String, ClientExceptionMapperHandler.Result> entry : ifaceToGeneratedMapper.entrySet()) {
ResultHandle map = constructor.newInstance(MethodDescriptor.ofConstructor(HashMap.class));
constructor.invokeInterfaceMethod(MAP_PUT, map, constructor.loadClass(entry.getValue().generatedClassName),
constructor.load(entry.getValue().priority));
constructor.invokeVirtualMethod(
MethodDescriptor.ofMethod(AnnotationRegisteredProviders.class, "addProviders", void.class, String.class,
Map.class),
constructor.getThis(), constructor.load(entry.getKey()), map);
}
constructor.returnValue(null);
}
unremovableBeans.produce(UnremovableBeanBuildItem.beanClassNames(annotationRegisteredProvidersImpl));
}
private int getAnnotatedPriority(IndexView index, String className, int defaultPriority) {
ClassInfo providerClass = index.getClassByName(DotName.createSimple(className));
int priority = defaultPriority;
if (providerClass == null) {
log.warnv("Unindexed provider class {0}. The priority of the provider will be set to {1}. ", className,
defaultPriority);
} else {
AnnotationInstance priorityAnnoOnProvider = providerClass.classAnnotation(ResteasyReactiveDotNames.PRIORITY);
if (priorityAnnoOnProvider != null) {
priority = priorityAnnoOnProvider.value().asInt();
}
}
return priority;
}
@BuildStep
AdditionalBeanBuildItem registerProviderBeans(CombinedIndexBuildItem combinedIndex) {
IndexView index = combinedIndex.getIndex();
List<AnnotationInstance> allInstances = new ArrayList<>(index.getAnnotations(REGISTER_PROVIDER));
for (AnnotationInstance annotation : index.getAnnotations(REGISTER_PROVIDERS)) {
allInstances.addAll(asList(annotation.value().asNestedArray()));
}
allInstances.addAll(index.getAnnotations(REGISTER_CLIENT_HEADERS));
AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder().setUnremovable();
for (AnnotationInstance annotationInstance : allInstances) {
// Make sure all providers not annotated with @Provider but used in @RegisterProvider are registered as beans
AnnotationValue value = annotationInstance.value();
if (value != null) {
builder.addBeanClass(value.asClass().toString());
}
}
return builder.build();
}
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void addRestClientBeans(Capabilities capabilities,
CombinedIndexBuildItem combinedIndexBuildItem,
CustomScopeAnnotationsBuildItem scopes,
BuildProducer<GeneratedBeanBuildItem> generatedBeans,
RestClientReactiveConfig clientConfig,
RestClientRecorder recorder) {
CompositeIndex index = CompositeIndex.create(combinedIndexBuildItem.getIndex());
Set<AnnotationInstance> registerRestClientAnnos = new HashSet<>(index.getAnnotations(REGISTER_REST_CLIENT));
Map<String, String> configKeys = new HashMap<>();
for (AnnotationInstance registerRestClient : registerRestClientAnnos) {
ClassInfo jaxrsInterface = registerRestClient.target().asClass();
// for each interface annotated with @RegisterRestClient, generate a $$CDIWrapper CDI bean that can be injected
if (Modifier.isAbstract(jaxrsInterface.flags())) {
validateKotlinDefaultMethods(jaxrsInterface, index);
List<MethodInfo> methodsToImplement = new ArrayList<>();
// search this interface and its super interfaces for jaxrs methods
searchForJaxRsMethods(methodsToImplement, jaxrsInterface, index);
// search this interface for default methods
// we could search for default methods in super interfaces too,
// but emitting the correct invokespecial instruction would become convoluted
// (as invokespecial may only reference a method from a _direct_ super interface)
for (MethodInfo method : jaxrsInterface.methods()) {
boolean isDefault = !Modifier.isAbstract(method.flags()) && !Modifier.isStatic(method.flags());
if (isDefault) {
methodsToImplement.add(method);
}
}
if (methodsToImplement.isEmpty()) {
continue;
}
String wrapperClassName = jaxrsInterface.name().toString() + CDI_WRAPPER_SUFFIX;
try (ClassCreator classCreator = ClassCreator.builder()
.className(wrapperClassName)
.classOutput(new GeneratedBeanGizmoAdaptor(generatedBeans))
.interfaces(jaxrsInterface.name().toString())
.superClass(RestClientReactiveCDIWrapperBase.class)
.build()) {
// CLASS LEVEL
final Optional<String> configKey = getConfigKey(registerRestClient);
configKey.ifPresent(
key -> configKeys.put(jaxrsInterface.name().toString(), key));
final ScopeInfo scope = computeDefaultScope(capabilities, ConfigProvider.getConfig(), jaxrsInterface,
configKey, clientConfig);
// add a scope annotation, e.g. @Singleton
classCreator.addAnnotation(scope.getDotName().toString());
classCreator.addAnnotation(RestClient.class);
// e.g. @Typed({InterfaceClass.class})
// needed for CDI to inject the proper wrapper in case of
// subinterfaces
org.objectweb.asm.Type asmType = org.objectweb.asm.Type
.getObjectType(jaxrsInterface.name().toString().replace('.', '/'));
classCreator.addAnnotation(Typed.class.getName(), RetentionPolicy.RUNTIME)
.addValue("value", new org.objectweb.asm.Type[] { asmType });
for (AnnotationInstance annotation : jaxrsInterface.classAnnotations()) {
if (SKIP_COPYING_ANNOTATIONS_TO_GENERATED_CLASS.contains(annotation.name())) {
continue;
}
// scope annotation is added to the generated class already, see above
if (scopes.isScopeIn(Set.of(annotation))) {
continue;
}
classCreator.addAnnotation(annotation);
}
// CONSTRUCTOR:
MethodCreator constructor = classCreator
.getMethodCreator(MethodDescriptor.ofConstructor(classCreator.getClassName()));
AnnotationValue baseUri = registerRestClient.value("baseUri");
ResultHandle baseUriHandle = constructor.load(baseUri != null ? baseUri.asString() : "");
constructor.invokeSpecialMethod(
MethodDescriptor.ofConstructor(RestClientReactiveCDIWrapperBase.class, Class.class, String.class,
String.class),
constructor.getThis(),
constructor.loadClassFromTCCL(jaxrsInterface.toString()),
baseUriHandle,
configKey.isPresent() ? constructor.load(configKey.get()) : constructor.loadNull());
constructor.returnValue(null);
// METHODS:
for (MethodInfo method : methodsToImplement) {
// for each method that corresponds to making a rest call, create a method like:
// public JsonArray get() {
// return ((InterfaceClass)this.getDelegate()).get();
// for each default method, create a method like:
// public JsonArray get() {
// return InterfaceClass.super.get();
MethodCreator methodCreator = classCreator.getMethodCreator(MethodDescriptor.of(method));
methodCreator.setSignature(AsmUtil.getSignatureIfRequired(method));
// copy method annotations, there can be interceptors bound to them:
for (AnnotationInstance annotation : method.annotations()) {
if (annotation.target().kind() == AnnotationTarget.Kind.METHOD
&& !BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.containsKey(annotation.name())
&& !ResteasyReactiveDotNames.PATH.equals(annotation.name())) {
methodCreator.addAnnotation(annotation);
}
}
ResultHandle result;
int parameterCount = method.parameters().size();
ResultHandle[] params = new ResultHandle[parameterCount];
for (int i = 0; i < parameterCount; i++) {
params[i] = methodCreator.getMethodParam(i);
}
if (Modifier.isAbstract(method.flags())) { // RestClient method
ResultHandle delegate = methodCreator.invokeVirtualMethod(
MethodDescriptor.ofMethod(RestClientReactiveCDIWrapperBase.class, "getDelegate",
Object.class),
methodCreator.getThis());
result = methodCreator.invokeInterfaceMethod(method, delegate, params);
} else { // default method
result = methodCreator.invokeSpecialInterfaceMethod(method, methodCreator.getThis(), params);
}
methodCreator.returnValue(result);
}
}
}
}
if (LaunchMode.current() == LaunchMode.DEVELOPMENT) {
recorder.setConfigKeys(configKeys);
}
}
// By default, Kotlin does not use Java interface default methods, but generates a helper class that contains the implementation.
// In order to avoid the extra complexity of having to deal with this mode, we simply fail the build when this situation is encountered
// and provide an actionable error message on how to remedy the situation.
private void validateKotlinDefaultMethods(ClassInfo jaxrsInterface, IndexView index) {
if (jaxrsInterface.classAnnotation(KOTLIN_METADATA_ANNOTATION) != null) {
var potentialDefaultImplClass = DotName
.createSimple(jaxrsInterface.name().toString() + KOTLIN_INTERFACE_DEFAULT_IMPL_SUFFIX);
if (index.getClassByName(potentialDefaultImplClass) != null) {
throw new RestClientDefinitionException(String.format(
"Using Kotlin default methods on interfaces that are not backed by Java 8 default interface methods is not supported. See %s for more details. Offending interface is '%s'.",
"https://kotlinlang.org/docs/java-to-kotlin-interop.html#default-methods-in-interfaces",
jaxrsInterface.name().toString()));
}
}
}
private boolean isRestMethod(MethodInfo method) {
if (!Modifier.isAbstract(method.flags())) {
return false;
}
for (AnnotationInstance annotation : method.annotations()) {
if (annotation.target().kind() == AnnotationTarget.Kind.METHOD
&& BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.containsKey(annotation.name())) {
return true;
} else if (annotation.name().equals(ResteasyReactiveDotNames.PATH)) {
return true;
}
}
return false;
}
private Optional<String> getConfigKey(AnnotationInstance registerRestClientAnnotation) {
AnnotationValue configKeyValue = registerRestClientAnnotation.value("configKey");
return configKeyValue != null
? Optional.of(configKeyValue.asString())
: Optional.empty();
}
private ScopeInfo computeDefaultScope(Capabilities capabilities, Config config,
ClassInfo restClientInterface,
Optional<String> configKey,
RestClientReactiveConfig mpClientConfig) {
ScopeInfo scopeToUse = null;
Optional<String> scopeConfig = RestClientConfigUtils.findConfiguredScope(config, restClientInterface, configKey);
BuiltinScope globalDefaultScope = BuiltinScope.from(DotName.createSimple(mpClientConfig.scope));
if (globalDefaultScope == null) {
log.warnv("Unable to map the global rest client scope: '{}' to a scope. Using @ApplicationScoped",
mpClientConfig.scope);
globalDefaultScope = BuiltinScope.APPLICATION;
}
if (scopeConfig.isPresent()) {
final DotName scope = DotName.createSimple(scopeConfig.get());
final BuiltinScope builtinScope = builtinScopeFromName(scope);
if (builtinScope != null) { // override default @Dependent scope with user defined one.
scopeToUse = builtinScope.getInfo();
} else if (capabilities.isPresent(Capability.SERVLET)) {
if (scope.equals(SESSION_SCOPED) || scope.toString().equalsIgnoreCase(SESSION_SCOPED.withoutPackagePrefix())) {
scopeToUse = new ScopeInfo(SESSION_SCOPED, true);
}
}
if (scopeToUse == null) {
log.warnf("Unsupported default scope {} provided for rest client {}. Defaulting to {}",
scope, restClientInterface.name(), globalDefaultScope.getName());
scopeToUse = globalDefaultScope.getInfo();
}
} else {
final Set<DotName> annotations = restClientInterface.annotations().keySet();
for (final DotName annotationName : annotations) {
final BuiltinScope builtinScope = BuiltinScope.from(annotationName);
if (builtinScope != null) {
scopeToUse = builtinScope.getInfo();
break;
}
if (annotationName.equals(SESSION_SCOPED)) {
scopeToUse = new ScopeInfo(SESSION_SCOPED, true);
break;
}
}
}
// Initialize a default @Dependent scope as per the spec
return scopeToUse != null ? scopeToUse : globalDefaultScope.getInfo();
}
private BuiltinScope builtinScopeFromName(DotName scopeName) {
BuiltinScope scope = BuiltinScope.from(scopeName);
if (scope == null) {
for (BuiltinScope builtinScope : BuiltinScope.values()) {
if (builtinScope.getName().withoutPackagePrefix().equalsIgnoreCase(scopeName.toString())) {
scope = builtinScope;
}
}
}
return scope;
}
}
|
package org.eclipse.smarthome.binding.mqtt.generic.internal.values;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.core.library.CoreItemFactory;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.library.types.StringType;
import org.eclipse.smarthome.core.library.types.UpDownType;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.State;
import org.eclipse.smarthome.core.types.StateDescription;
import org.eclipse.smarthome.core.types.UnDefType;
/**
* Implements a percentage value. Minimum and maximum are definable.
*
* @author David Graeff - Initial contribution
*/
@NonNullByDefault
public class NumberValue implements Value {
private State state = UnDefType.UNDEF;
private final double min;
private final double max;
private final double step;
private final Boolean isDecimal;
private final boolean isPercent;
private List<Class<? extends Command>> commandTypes = Stream
.of(DecimalType.class, IncreaseDecreaseType.class, UpDownType.class).collect(Collectors.toList());
private DecimalType numberValue;
public NumberValue(@Nullable Boolean isDecimal, @Nullable BigDecimal min, @Nullable BigDecimal max,
@Nullable BigDecimal step, boolean isPercent) {
this.isDecimal = isDecimal == null ? false : isDecimal;
this.min = min == null ? 0.0 : min.doubleValue();
this.max = max == null ? 100.0 : max.doubleValue();
if (isPercent && this.min >= this.max) {
throw new IllegalArgumentException("Min need to be smaller than max!");
}
this.step = step == null ? 1.0 : step.doubleValue();
this.isPercent = isPercent;
numberValue = new DecimalType();
}
@Override
public State getValue() {
return state;
}
@Override
public String update(Command command) throws IllegalArgumentException {
if (isPercent) {
if (command instanceof DecimalType) {
double v = ((DecimalType) command).doubleValue();
v = (v - min) * 100.0 / (max - min);
numberValue = new PercentType(new BigDecimal(v));
} else if (command instanceof IncreaseDecreaseType) {
if (((IncreaseDecreaseType) command) == IncreaseDecreaseType.INCREASE) {
final double v = numberValue.doubleValue() + step;
numberValue = new PercentType(new BigDecimal(v <= max ? v : max));
} else {
double v = numberValue.doubleValue() - step;
numberValue = new PercentType(new BigDecimal(v >= min ? v : min));
}
} else if (command instanceof UpDownType) {
if (((UpDownType) command) == UpDownType.UP) {
final double v = numberValue.doubleValue() + step;
numberValue = new PercentType(new BigDecimal(v <= max ? v : max));
} else {
final double v = numberValue.doubleValue() - step;
numberValue = new PercentType(new BigDecimal(v >= min ? v : min));
}
} else {
throw new IllegalArgumentException(
"Type " + command.getClass().getName() + " not supported for PercentValue");
}
if (isDecimal) {
state = numberValue;
return numberValue.toString();
} else {
state = numberValue;
return String.valueOf(numberValue.intValue());
}
} else {
if (command instanceof DecimalType) {
numberValue = (DecimalType) command;
} else if (command instanceof IncreaseDecreaseType) {
double v;
if (((IncreaseDecreaseType) command) == IncreaseDecreaseType.INCREASE) {
v = numberValue.doubleValue() + step;
} else {
v = numberValue.doubleValue() - step;
}
numberValue = new DecimalType(v);
} else if (command instanceof UpDownType) {
double v;
if (((UpDownType) command) == UpDownType.UP) {
v = numberValue.doubleValue() + step;
} else {
v = numberValue.doubleValue() - step;
}
numberValue = new DecimalType(v);
} else {
throw new IllegalArgumentException(
"Type " + command.getClass().getName() + " not supported for NumberValue");
}
if (isDecimal) {
state = numberValue;
return numberValue.toString();
} else {
state = numberValue;
return String.valueOf(numberValue.intValue());
}
}
}
@Override
public String getItemType() {
return isPercent ? CoreItemFactory.DIMMER : CoreItemFactory.NUMBER;
}
@Override
public StateDescription createStateDescription(String unit, boolean readOnly) {
return new StateDescription(new BigDecimal(min), new BigDecimal(max), new BigDecimal(step),
"%s " + unit.replace("%", "%%"), readOnly, Collections.emptyList());
}
@Override
public List<Class<? extends Command>> getSupportedCommandTypes() {
return commandTypes;
}
@Override
public void resetState() {
state = UnDefType.UNDEF;
}
}
|
package org.innovateuk.ifs.application.overview.controller;
import org.innovateuk.ifs.security.BaseControllerSecurityTest;
import org.innovateuk.ifs.user.resource.Role;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class ApplicationOverviewControllerSecurityTest extends BaseControllerSecurityTest<ApplicationOverviewController> {
@Override
protected Class<? extends ApplicationOverviewController> getClassUnderTest() {
return ApplicationOverviewController.class;
}
@Test
public void applicationOverview() {
List<Role> roles = new ArrayList<>();
roles.add(Role.APPLICANT);
roles.add(Role.KNOWLEDGE_TRANSFER_ADVISER);
roles.add(Role.COFUNDER);
assertRolesCanPerform(() -> classUnderTest.applicationOverview(null, 0L, null), roles);
}
@Test
public void termsAndConditions() {
List<Role> roles = new ArrayList<>();
roles.add(Role.APPLICANT);
roles.add(Role.KNOWLEDGE_TRANSFER_ADVISER);
roles.add(Role.COFUNDER);
assertRolesCanPerform(() -> classUnderTest.termsAndConditions(), roles);
}
}
|
package io.subutai.core.hubmanager.impl.environment.state.build;
import java.util.Set;
import com.google.common.collect.Sets;
import io.subutai.common.environment.Node;
import io.subutai.common.environment.Nodes;
import io.subutai.common.network.UsedNetworkResources;
import io.subutai.common.peer.PeerException;
import io.subutai.core.hubmanager.api.exception.HubManagerException;
import io.subutai.core.hubmanager.impl.environment.state.Context;
import io.subutai.core.hubmanager.impl.environment.state.StateHandler;
import io.subutai.core.identity.api.model.User;
import io.subutai.core.identity.api.model.UserToken;
import io.subutai.hub.share.dto.UserTokenDto;
import io.subutai.hub.share.dto.environment.ContainerStateDto;
import io.subutai.hub.share.dto.environment.EnvironmentNodeDto;
import io.subutai.hub.share.dto.environment.EnvironmentNodesDto;
import io.subutai.hub.share.dto.environment.EnvironmentPeerDto;
public class ExchangeInfoStateHandler extends StateHandler
{
private static final String PATH = "/rest/v1/environments/%s/containers";
public ExchangeInfoStateHandler( Context ctx )
{
super( ctx, "Preparing initial data" );
}
@Override
protected Object doHandle( EnvironmentPeerDto peerDto ) throws HubManagerException
{
try
{
logStart();
checkResources( peerDto );
EnvironmentPeerDto resultDto = getReservedNetworkResource( peerDto );
UserToken token =
ctx.hubManager.getUserToken( peerDto.getEnvironmentInfo().getOwnerId(), peerDto.getPeerId() );
final User user = ctx.identityManager.getUser( token.getUserId() );
UserTokenDto userTokenDto = new UserTokenDto();
userTokenDto.setSsUserId( user.getId() );
userTokenDto.setEnvId( resultDto.getEnvironmentInfo().getHubId() );
userTokenDto.setAuthId( user.getAuthId() );
userTokenDto.setToken( token.getFullToken() );
userTokenDto.setTokenId( token.getTokenId() );
userTokenDto.setValidDate( token.getValidDate() );
userTokenDto.setType( UserTokenDto.Type.ENV_USER );
userTokenDto.setState( UserTokenDto.State.READY );
resultDto.setUserToken( userTokenDto );
logEnd();
return resultDto;
}
catch ( Exception e )
{
throw new HubManagerException( e );
}
}
private void checkResources( EnvironmentPeerDto peerDto ) throws HubManagerException, PeerException
{
EnvironmentNodesDto nodesDto = ctx.restClient.getStrict( path( PATH, peerDto ), EnvironmentNodesDto.class );
Set<Node> newNodes = Sets.newHashSet();
Set<String> removedContainers = Sets.newHashSet();
for ( EnvironmentNodeDto nodeDto : nodesDto.getNodes() )
{
if ( nodeDto.getState() == ContainerStateDto.BUILDING )
{
newNodes.add( new Node( nodeDto.getHostName(), nodeDto.getContainerName(), nodeDto.getContainerQuota(),
ctx.localPeer.getId(), nodeDto.getHostId(), nodeDto.getTemplateId() ) );
}
else if ( nodeDto.getState() == ContainerStateDto.ABORTING )
{
removedContainers.add( nodeDto.getContainerId() );
}
}
if ( !newNodes.isEmpty() && !ctx.localPeer.canAccommodate( new Nodes( newNodes, removedContainers, null ) ) )
{
throw new HubManagerException(
String.format( "Peer %s can not accommodate the requested containers", ctx.localPeer.getId() ) );
}
}
private EnvironmentPeerDto getReservedNetworkResource( EnvironmentPeerDto peerDto ) throws HubManagerException
{
try
{
UsedNetworkResources usedNetworkResources = ctx.localPeer.getUsedNetworkResources();
peerDto.setVnis( usedNetworkResources.getVnis() );
peerDto.setContainerSubnets( usedNetworkResources.getContainerSubnets() );
peerDto.setP2pSubnets( usedNetworkResources.getP2pSubnets() );
return peerDto;
}
catch ( Exception e )
{
throw new HubManagerException( e );
}
}
@Override
protected String getToken( EnvironmentPeerDto peerDto )
{
try
{
UserToken userToken = ctx.envUserHelper.getUserTokenFromHub( peerDto.getSsUserId() );
return userToken.getFullToken();
}
catch ( Exception e )
{
log.error( e.getMessage() );
}
return null;
}
}
|
package org.opendaylight.controller.samples.differentiatedforwarding.openstack.performance;
import java.util.ArrayList;
import java.util.List;
import org.opendaylight.controller.samples.differentiatedforwarding.openstack.ReportManager;
import org.opendaylight.controller.samples.differentiatedforwarding.openstack.ssh.OvsManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Exp {
private static Logger log = LoggerFactory.getLogger(Exp.class);
public static final boolean DELETE_INSTANCES = true;
public static final boolean DELETE_NETWORKS = true;
public static final boolean FIX_OVS = false;
// This is more like a wrong name. It should be ClassNetwork concurrency. It runs the networks concurrently with the given classes.
public static final boolean RUN_CLASSES_CONCURRENTLY = true;
public static final boolean RUN_INSTANCES_CONCURRENTLY = false;
int[] instanceRange;
int[] networkRange;
// Total number of instances
int maxInstances = 128;
int maxNetworks = 32;
int minInstances = 1;
int minNetworks = 1;
// max DSCP 64, 6bit
int[] classRange = {1, 2, 3, 4};
// Sequential vs Concurrent runs of the experiments.
boolean runClassExpConcurrently = false;
boolean runInstanceExpConcurrently = false;
String expDir = "";
public Exp(int[] classRange, int minNetworks, int maxNetworks, int minInstances, int maxInstances, boolean runClassExpConcurrently, boolean runInstanceExpConcurrently) {
this.minInstances = minInstances;
this.maxInstances = maxInstances;
this.minNetworks = minNetworks;
this.maxNetworks = maxNetworks;
this.classRange = classRange;
//(n & (n - 1)) != 0 return error checking for 2^x conformity
this.runClassExpConcurrently = runClassExpConcurrently;
this.runInstanceExpConcurrently = runInstanceExpConcurrently;
this.expDir = ReportManager.createExpDir("/home/aryan/data");
}
public void exec() {
List<String> errors = new ArrayList<>();
for (int netNum = minNetworks; netNum <= maxNetworks; netNum = netNum * 2) {
// Each network requires at least two instances to run an exp.
for (int insNum = Math.max(netNum * 2, minInstances); insNum <= maxInstances; insNum = insNum * 2) {
SubExp subExp = null;
try {
subExp = new SubExp(classRange, netNum, insNum, runClassExpConcurrently, runInstanceExpConcurrently, expDir);
subExp.exec();
log.info("SubExp {} is executed completely. Dir {}", subExp.getSubExpName(), expDir);
Thread.sleep(1000*insNum);
boolean readyForNext = true;
if (FIX_OVS) readyForNext = OvsManager.fixNucs();
if (!readyForNext){
log.error("OVS is not ready for the next experiment.");
return;
}
log.info("Sleeping for {}ms before next SubExp.", (1000*10*insNum));
Thread.sleep(1000*10*insNum);
} catch (Exception e) {
log.error("exec(): Skipping to the next SubExp", e);
errors.add("Error at " + subExp.getSubExpName() + ": " + e.getMessage());
}
log.info("Going for next SubExp
}
}
for (String string : errors) {
log.error(string);
}
}
public static Exp getSimpleExp(int[] classRange) {
int computeSize = 3;
int networkSize = classRange.length;
int instanceSize = computeSize * networkSize;
Exp exp = new Exp( classRange, networkSize, networkSize, instanceSize, instanceSize, RUN_CLASSES_CONCURRENTLY, RUN_INSTANCES_CONCURRENTLY);
return exp;
}
public static void main(String[] args) {
// NOTE: Keep the size of network and class range identical to make the plots meaningful.
// int[] classRange = {1};
// new Exp( classRange, 1, 1, 2, 2, RUN_CLASSES_CONCURRENTLY, RUN_INSTANCES_CONCURRENTLY).exec();
int[] classRange = {1,2,3,4};
getSimpleExp(classRange).exec();
// new Exp( classRange, 1, 8, 1, 32, RUN_CLASSES_CONCURRENTLY, RUN_INSTANCES_CONCURRENTLY).exec();
// new Exp( classRange, 1, 8, 64, 128, RUN_CLASSES_CONCURRENTLY, RUN_INSTANCES_CONCURRENTLY).exec();
// new Exp( classRange, 1, 1, 1, 2, RUN_CLASSES_CONCURRENTLY, RUN_INSTANCES_CONCURRENTLY).exec();
// new Exp( classRange, 3, 3, 24, 24, RUN_CLASSES_CONCURRENTLY, RUN_INSTANCES_CONCURRENTLY).exec();
// new Exp( classRange, 3, 3, 96, 256, RUN_CLASSES_CONCURRENTLY, RUN_INSTANCES_CONCURRENTLY).exec();
}
}
|
package com.b2international.snowowl.snomed.api.impl.validation.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.ihtsdo.drools.domain.Concept;
import org.ihtsdo.drools.domain.Constants;
import org.ihtsdo.drools.domain.Description;
import org.ihtsdo.drools.domain.Relationship;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.http.ExtendedLocale;
import com.b2international.snowowl.eventbus.IEventBus;
import com.b2international.snowowl.snomed.SnomedConstants.LanguageCodeReferenceSetIdentifierMapping;
import com.b2international.snowowl.snomed.api.impl.DescriptionService;
import com.b2international.snowowl.snomed.api.impl.validation.domain.ValidationSnomedDescription;
import com.b2international.snowowl.snomed.core.domain.ISnomedConcept;
import com.b2international.snowowl.snomed.core.domain.ISnomedDescription;
import com.b2international.snowowl.snomed.core.domain.SnomedConcepts;
import com.b2international.snowowl.snomed.core.domain.SnomedDescriptions;
import com.b2international.snowowl.snomed.datastore.server.request.SnomedRequests;
public class ValidationDescriptionService implements org.ihtsdo.drools.service.DescriptionService {
private DescriptionService descriptionService;
private String branchPath;
private IEventBus bus;
public ValidationDescriptionService(DescriptionService descriptionService, String branchPath, IEventBus bus) {
this.descriptionService = descriptionService;
this.branchPath = branchPath;
this.bus = bus;
}
final static Logger logger = LoggerFactory.getLogger(ValidationDescriptionService.class);
// Static block of sample case significant words - lower case word -> exact
// word as supplied
// NOTE: This will not handle cases where the same word exists with
// different capitalizations
// However, at this time no further precision is required
public static final Set<String> caseSignificantWords = new HashSet<>();
static {
String fileName = "/opt/termserver/resources/test-resources/cs_words.txt";
File file = new File(fileName);
FileReader fileReader;
BufferedReader bufferedReader;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
// skip header line
bufferedReader.readLine();
while ((line = bufferedReader.readLine()) != null) {
String[] words = line.split("\\s+");
// format: 0: word, 1: type (only use type 1 words)
if (words[1].equals("1")) {
caseSignificantWords.add(words[0]);
}
}
fileReader.close();
logger.info("Loaded " + caseSignificantWords.size() + " case sensitive words into cache from: " + fileName);
} catch (IOException e) {
logger.info("Failed to retrieve case sensitive words file: " + fileName);
}
}
// Static block of sample case significant words
// In non-dev environments, this should initialize on startup
public static final Map<String, Set<String>> refsetToLanguageSpecificWordsMap = new HashMap<>();
static {
loadRefsetSpecificWords(Constants.GB_EN_LANG_REFSET, "/opt/termserver/resources/test-resources/gbTerms.txt");
loadRefsetSpecificWords(Constants.US_EN_LANG_REFSET, "/opt/termserver/resources/test-resources/usTerms.txt");
}
private static void loadRefsetSpecificWords(String refsetId, String fileName) {
Set<String> words = new HashSet<>();
File file = new File(fileName);
FileReader fileReader;
BufferedReader bufferedReader;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
// skip header line
bufferedReader.readLine();
while ((line = bufferedReader.readLine()) != null) {
words.add(line.toLowerCase()); // assumed to be single-word
// lines
}
fileReader.close();
logger.info("Loaded " + words.size() + " language-specific spellings into cache for refset " + refsetId
+ " from: " + fileName);
} catch (IOException e) {
logger.info("Failed to retrieve language-specific terms for refset " + refsetId + " in file " + fileName);
} finally {
refsetToLanguageSpecificWordsMap.put(refsetId, words);
}
}
// On initial load, retrieve the top-level hierarchy roots for hierarchy
// detection
private static Set<String> hierarchyRootIds = null;
@Override
public Set<String> getFSNs(Set<String> conceptIds, String... languageRefsetIds) {
Set<String> fsns = new HashSet<>();
List<ExtendedLocale> locales = new ArrayList<>();
for (String languageRefsetId : languageRefsetIds) {
String languageCode = LanguageCodeReferenceSetIdentifierMapping.getLanguageCode(languageRefsetId);
locales.add(new ExtendedLocale(languageCode, null, languageRefsetId));
}
Map<String, ISnomedDescription> fullySpecifiedNames = descriptionService.getFullySpecifiedNames(conceptIds,
locales);
for (ISnomedDescription description : fullySpecifiedNames.values()) {
fsns.add(description.getTerm());
}
return fsns;
}
@Override
public Set<Description> findActiveDescriptionByExactTerm(String exactTerm) {
final SnomedDescriptions descriptions = SnomedRequests.prepareSearchDescription().filterByActive(true)
.filterByTerm(exactTerm).build(branchPath).executeSync(bus);
Set<Description> matches = new HashSet<>();
for (ISnomedDescription iSnomedDescription : descriptions) {
if (iSnomedDescription.getTerm().equals(exactTerm)) {
matches.add(new ValidationSnomedDescription(iSnomedDescription, iSnomedDescription.getConceptId()));
}
}
return matches;
}
@Override
public Set<Description> findInactiveDescriptionByExactTerm(String exactTerm) {
final SnomedDescriptions descriptions = SnomedRequests.prepareSearchDescription().filterByActive(false)
.filterByTerm(exactTerm).build(branchPath).executeSync(bus);
Set<Description> matches = new HashSet<>();
for (ISnomedDescription iSnomedDescription : descriptions) {
if (iSnomedDescription.getTerm().equals(exactTerm)) {
matches.add(new ValidationSnomedDescription(iSnomedDescription, iSnomedDescription.getConceptId()));
}
}
return matches;
}
private void cacheHierarchyRootConcepts() {
hierarchyRootIds = new HashSet<>();
final SnomedConcepts rootConcepts = SnomedRequests.prepareSearchConcept()
.setComponentIds(Arrays.asList("138875005")).setExpand("descendants(direct:true)").build(branchPath)
.executeSync(bus);
for (ISnomedConcept rootConcept : rootConcepts) {
for (ISnomedConcept childConcept : rootConcept.getDescendants()) {
hierarchyRootIds.add(childConcept.getId());
}
}
logger.info("Cached " + hierarchyRootIds.size() + " hierarchy root ids for validation");
}
private String getHierarchyIdForConcept(ISnomedConcept concept) {
// if concept null, return null
if (concept == null) {
return null;
}
// if not yet retrieved, cache the root concepts
if (hierarchyRootIds == null) {
cacheHierarchyRootConcepts();
}
// check if this concept is a root
for (String rootId : hierarchyRootIds) {
if (rootId.equals(concept.getId())) {
return rootId;
}
}
// otherwise check ancestors
for (ISnomedConcept ancestor : concept.getAncestors()) {
if (hierarchyRootIds.contains(ancestor.getId())) {
return ancestor.getId().toString();
}
}
return null;
}
@Override
public Set<Description> findMatchingDescriptionInHierarchy(Concept concept, Description description) {
System.out.println("Checking for matching description " + description.getTerm());
// on first invocation, cache the hierarchy root ids
if (hierarchyRootIds == null) {
cacheHierarchyRootConcepts();
}
// the return set
Set<Description> matchesInHierarchy = new HashSet<>();
// retrieve partially-matching descriptions
final SnomedDescriptions descriptions = SnomedRequests.prepareSearchDescription().filterByActive(true)
.filterByTerm(description.getTerm()).filterByLanguageCodes(Arrays.asList(description.getLanguageCode()))
.build(branchPath).executeSync(bus);
System.out.println(" Found " + descriptions.getTotal() + " partial matches");
// filter by exact match and save concept ids
Set<String> matchingConceptIds = new HashSet<>();
Set<ISnomedDescription> matchesInSnomed = new HashSet<>();
for (ISnomedDescription iSnomedDescription : descriptions) {
if (iSnomedDescription.getTerm().equals(description.getTerm())) {
matchesInSnomed.add(iSnomedDescription);
matchingConceptIds.add(iSnomedDescription.getConceptId());
}
}
System.out.println(" Found " + matchesInSnomed.size() + " exact matches on concepts " + matchingConceptIds.toString());
// if matches found
if (matchesInSnomed.size() > 0) {
// the concept id used to determine the hierarchy
String lookupId = null;
// if this is a root id, use it as the lookup id
if (hierarchyRootIds.contains(concept.getId())) {
lookupId = concept.getId();
}
// otherwise, use the first active parent as lookup id
else {
Iterator<? extends Relationship> iter = concept.getRelationships().iterator();
while (iter.hasNext()) {
Relationship rel = iter.next();
if (rel.isActive() && Constants.IS_A.equals(rel.getTypeId())) {
lookupId = rel.getDestinationId();
}
}
}
System.out.println(" Lookup id: " + lookupId);
// if id could not be retrieved, cannot determine hierarchy
// either SNOMED CT root concept, or has no active parents
if (lookupId == null) {
return matchesInHierarchy;
}
// use id to retrieve concept for hierarchy detection
ISnomedConcept hierarchyConcept = null;
try {
hierarchyConcept = SnomedRequests.prepareGetConcept().setComponentId(lookupId)
.setExpand(String.format("ancestors(direct:%s,offset:%d,limit:%d)", "false", 0, 1000))
.build(branchPath).executeSync(bus);
System.out.println(" Hierarchy concept " + hierarchyConcept.getId() + " has " + hierarchyConcept.getAncestors().getTotal() + " ancestors with root " + this.getHierarchyIdForConcept(hierarchyConcept));
// back out if cannot determine hierarchy
if (hierarchyConcept == null || getHierarchyIdForConcept(hierarchyConcept) == null) {
return matchesInHierarchy;
}
} catch (Exception e) {
System.out.println(" Exception getting hierarchy concept with ancestors " + e.getMessage() + ", " + e.getStackTrace().toString());
// do nothing, failure should not interrupt
}
// retrieve active concepts from saved concept ids
SnomedConcepts conceptsWithAncestors;
try {
conceptsWithAncestors = SnomedRequests.prepareSearchConcept().filterByActive(true)
.filterByComponentIds(matchingConceptIds)
.setExpand(String.format("ancestors(direct:%s,offset:%d,limit:%d)", "false", 0, 1000))
.build(branchPath).executeSync(bus);
System.out.println(" Concepts with ancestors loaded: " + conceptsWithAncestors.getTotal());
// cycle over matching descriptions and compare to concepts with
// ancestors
for (ISnomedDescription iSnomedDescription : matchesInSnomed) {
System.out.println(" Checking description " + iSnomedDescription.getTerm());
for (ISnomedConcept iSnomedConcept : conceptsWithAncestors) {
System.out.println(" Checking against concept " + iSnomedConcept.getId() + " with " + iSnomedConcept.getAncestors().getTotal() + " ancestors in hierarchy " + this.getHierarchyIdForConcept(iSnomedConcept));
if (iSnomedConcept.getId().equals(iSnomedDescription.getConceptId())) {
if (getHierarchyIdForConcept(hierarchyConcept)
.equals(getHierarchyIdForConcept(iSnomedConcept))) {
matchesInHierarchy.add(new ValidationSnomedDescription(iSnomedDescription,
iSnomedDescription.getConceptId()));
}
}
}
}
} catch (Exception e) {
System.out.println(" Exception retrieving match concept ancestors " + e.getMessage() + e.getCause().toString());
// do nothing -- prevent blocking errors
// TODO Revisit this and similar Drools error handling
}
}
return matchesInHierarchy;
}
@Override
public String getLanguageSpecificErrorMessage(Description description) {
String errorMessage = "";
// null checks
if (description == null || description.getAcceptabilityMap() == null || description.getTerm() == null) {
return errorMessage;
}
String[] words = description.getTerm().split("\\s+");
// convenience variables
String usAcc = description.getAcceptabilityMap().get(Constants.US_EN_LANG_REFSET);
String gbAcc = description.getAcceptabilityMap().get(Constants.GB_EN_LANG_REFSET);
// NOTE: Supports international only at this point
// Only check active synonyms
if (description.isActive() && Constants.SYNONYM.equals(description.getTypeId())) {
for (String word : words) {
// Step 1: Check en-us preferred synonyms for en-gb spellings
if (usAcc != null
&& refsetToLanguageSpecificWordsMap.containsKey(Constants.GB_EN_LANG_REFSET)
&& refsetToLanguageSpecificWordsMap.get(Constants.GB_EN_LANG_REFSET)
.contains(word.toLowerCase())) {
errorMessage += "Synonym is preferred in the en-us refset but refers to a word that has en-gb spelling: "
+ word + "\n";
}
// Step 2: Check en-gb preferred synonyms for en-en spellings
if (gbAcc != null
&& refsetToLanguageSpecificWordsMap.containsKey(Constants.US_EN_LANG_REFSET)
&& refsetToLanguageSpecificWordsMap.get(Constants.US_EN_LANG_REFSET)
.contains(word.toLowerCase())) {
errorMessage += "Synonym is preferred in the en-gb refset but refers to a word that has en-us spelling: "
+ word + "\n";
}
}
}
return errorMessage;
}
@Override
public String getCaseSensitiveWordsErrorMessage(Description description) {
String result = "";
// return immediately if description or term null
if (description == null || description.getTerm() == null) {
return result;
}
String[] words = description.getTerm().split("\\s+");
for (String word : words) {
// NOTE: Simple test to see if a case-sensitive term exists as
// written. Original check for mis-capitalization, but false
// positives, e.g. "oF" appears in list but spuriously reports "of"
// Map preserved for lower-case matching in future
if (caseSignificantWords.contains(word)) {
// term starting with case sensitive word must be ETCS
if (description.getTerm().startsWith(word)
&& !Constants.ENTIRE_TERM_CASE_SENSITIVE.equals(description.getCaseSignificanceId())) {
result += "Description starts with case-sensitive word but is not marked entire term case sensitive: "
+ word + ".\n";
}
// term containing case sensitive word (not at start) must be
// ETCS or OICCI
else if (!Constants.ENTIRE_TERM_CASE_SENSITIVE.equals(description.getCaseSignificanceId())
&& !Constants.ONLY_INITIAL_CHARACTER_CASE_INSENSITIVE
.equals(description.getCaseSignificanceId())) {
result += "Description contains case-sensitive word but is not marked entire term case sensitive or only initial character case insensitive: "
+ word + ".\n";
}
}
}
return result;
}
}
|
package net.ssehub.easy.instantiation.core.model.vilTypes.configuration;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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 net.ssehub.easy.basics.progress.ProgressObserver;
import net.ssehub.easy.instantiation.core.model.artifactModel.ArtifactFactory;
import net.ssehub.easy.instantiation.core.model.artifactModel.FileArtifact;
import net.ssehub.easy.instantiation.core.model.artifactModel.Path;
import net.ssehub.easy.instantiation.core.model.buildlangModel.Script;
import net.ssehub.easy.instantiation.core.model.common.VilException;
import net.ssehub.easy.instantiation.core.model.vilTypes.ArraySequence;
import net.ssehub.easy.instantiation.core.model.vilTypes.ArraySet;
import net.ssehub.easy.instantiation.core.model.vilTypes.IStringValueProvider;
import net.ssehub.easy.instantiation.core.model.vilTypes.Invisible;
import net.ssehub.easy.instantiation.core.model.vilTypes.OperationMeta;
import net.ssehub.easy.instantiation.core.model.vilTypes.Sequence;
import net.ssehub.easy.instantiation.core.model.vilTypes.SetSet;
import net.ssehub.easy.instantiation.core.model.vilTypes.TypeDescriptor;
import net.ssehub.easy.instantiation.core.model.vilTypes.configuration.NameRegExFilter.DataType;
import net.ssehub.easy.reasoning.core.frontend.ReasonerFrontend;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerConfiguration;
import net.ssehub.easy.reasoning.core.reasoner.ReasoningResult;
import net.ssehub.easy.varModel.confModel.ConfigurationException;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.model.AbstractVariable;
import net.ssehub.easy.varModel.model.IvmlException;
import net.ssehub.easy.varModel.model.ModelQuery;
import net.ssehub.easy.varModel.model.Project;
import net.ssehub.easy.varModel.model.datatypes.IDatatype;
import net.ssehub.easy.varModel.model.values.ContainerValue;
import net.ssehub.easy.varModel.model.values.ReferenceValue;
import net.ssehub.easy.varModel.model.values.Value;
import net.ssehub.easy.varModel.persistency.IVMLWriter;
/**
* Represents a variability model and its configuration in VIL. This class provides
* specific methods to filter and select variables, attributes etc. Basically, the idea
* of this configuration class is to contain a filtered set of configurable elements (see {@link IVariableFilter},
* typically one that enables only frozen variables). It is currently
* unsure how much access we actually need to the variable and attribute declarations.
* Shifted this into {@link Utils}.
*
* @author Holger Eichelberger
*/
public class Configuration extends IvmlElement implements IStringValueProvider {
private Script rootScript;
private Project project;
private net.ssehub.easy.varModel.confModel.Configuration configuration;
private DecisionVariable[] variables;
private Attribute[] attributes;
private Map<String, IvmlElement> nameMap = new HashMap<String, IvmlElement>();
private IVariableFilter filter;
private boolean isValid = true;
private ChangeHistory changed;
/**
* Creates a new configuration instance from an EASy configuration based
* on frozen variables.
*
* @param configuration the IVML configuration instance to be wrapped
*/
public Configuration(net.ssehub.easy.varModel.confModel.Configuration configuration) {
this(configuration, FrozenVariablesFilter.INSTANCE);
}
/**
* Creates a new configuration instance from an EASy configuration.
*
* @param configuration the IVML configuration instance to be wrapped
* @param filter the external variable filter, e.g., for frozen variables
*/
public Configuration(net.ssehub.easy.varModel.confModel.Configuration configuration,
IVariableFilter filter) {
this.configuration = configuration;
this.project = configuration.getProject();
this.filter = filter;
this.changed = new ChangeHistory(this);
}
/**
* Creates a configuration from a given set of variables.
*
* @param configuration the IVML configuration instance to be wrapped
* @param variables the variables representing the actual contents of this configuration
* @param filter the external variable filter
*/
Configuration(net.ssehub.easy.varModel.confModel.Configuration configuration, DecisionVariable[] variables,
IVariableFilter filter) {
this.configuration = configuration;
this.variables = variables;
this.project = configuration.getProject();
this.filter = filter;
this.changed = new ChangeHistory(this);
index(variables);
}
/**
* Creates a projected configuration only containing the <code>changed</code> variables.
*
* @param configuration the base configuration
* @param changed the changed variables to be present in the projection
*/
private Configuration(Configuration configuration, Set<AbstractIvmlVariable> changed) {
this.isValid = configuration.isValid;
this.configuration = configuration.configuration;
this.project = configuration.project;
this.changed = configuration.changed;
ConfigurationContextResolver resolver = new ConfigurationContextResolver(this, changed);
resolver.resolve();
this.filter = resolver.filter();
this.variables = resolver.variables();
index(this.variables);
this.attributes = resolver.attributes();
index(this.attributes);
}
/**
* Creates a projected configuration (without explicit project).
*
* @param configuration the base configuration
* @param variablesFilter the filter to apply to variables
* @param filter the external variable filter
*/
private Configuration(Configuration configuration, IConfigurationFilter variablesFilter, IVariableFilter filter) {
this(configuration, null, variablesFilter, filter);
}
/**
* Creates a projected configuration.
*
* @param configuration the base configuration
* @param project the top-level project used for the projection (may be <b>null</b>)
* @param variablesFilter the filter to apply to variables
* @param filter the external variable filter
*/
private Configuration(Configuration configuration, Project project, IConfigurationFilter variablesFilter,
IVariableFilter filter) {
this.isValid = configuration.isValid;
this.filter = filter;
this.configuration = configuration.getConfiguration();
this.changed = configuration.changed;
if (null == project) {
this.project = this.configuration.getProject();
} else {
this.project = project;
}
configuration.initializeNested();
if (null != variablesFilter && variablesFilter != NoFilter.INSTANCE) {
List<DecisionVariable> tmp = new ArrayList<DecisionVariable>();
for (int v = 0; v < configuration.variables.length; v++) {
DecisionVariable var = configuration.variables[v];
if (variablesFilter.include(var)) {
tmp.add(var);
if (this.project.getName().equals(var.getDecisionVariable().getDeclaration().getNameSpace())) {
nameMap.put(var.getName(), var);
}
nameMap.put(var.getQualifiedName(), var);
}
}
variables = new DecisionVariable[tmp.size()];
tmp.toArray(variables);
}
configuration.initializeAttributes();
attributes = configuration.attributes;
index(attributes);
}
/**
* Indexes the names of the given elements.
*
* @param elements the elements to index
*/
private void index(IvmlElement[] elements) {
if (null != elements) {
for (int e = 0; e < elements.length; e++) {
nameMap.put(elements[e].getName(), elements[e]);
nameMap.put(elements[e].getQualifiedName(), elements[e]);
}
}
}
/**
* Returns the underlying EASy configuration. This operation may be required to wrap old-style
* instantiators.
*
* @return the EASy configuration
*/
@Invisible
public net.ssehub.easy.varModel.confModel.Configuration getConfiguration() {
return configuration;
}
@Override
protected void initializeNested() {
// this is not optimal if a configuration is used directly for projection but ok for now
// (re) initializes self and leaves parent untouched where instances may be reused
if (null == variables) {
Project project = configuration.getProject();
VariableCollector collector = new VariableCollector(this, filter);
project.accept(collector);
variables = collector.getCollectedVariables();
index(variables);
}
}
@Override
protected void initializeAttributes() {
// this is not optimal if a configuration is used directly for projection but ok for now
// (re) initializes self and leaves parent untouched where instances may be reused
if (null == attributes) {
Project project = configuration.getProject();
List<Attribute> tmp = new ArrayList<Attribute>();
for (int a = 0; a < project.getAttributesCount(); a++) {
IDecisionVariable var = configuration.getDecision(project.getAttribute(a));
if (null != var && filter.isEnabled(var)) {
Attribute attr = new Attribute(this, var, filter);
tmp.add(attr);
nameMap.put(attr.getQualifiedName(), attr);
}
}
attributes = new Attribute[tmp.size()];
tmp.toArray(attributes);
}
}
/**
* Returns the decision variables represented by this configuration.
*
* @return the decision variables
*/
@OperationMeta(returnGenerics = { DecisionVariable.class } )
public Sequence<DecisionVariable> variables() {
initializeNested();
return new ArraySequence<DecisionVariable>(variables, DecisionVariable.class);
}
/**
* Returns a projected version of this configuration according to the names
* of the variables.
*
* @param namePattern a regular name pattern (or just the full name) all variables
* in the resulting configuration must match
* @return the projected configuration
* @throws VilException in case of an illformed name pattern
*/
public Configuration selectByName(String namePattern) throws VilException {
initializeNested();
NameRegExFilter regexFilter = new NameRegExFilter(namePattern, DataType.NAME);
Configuration newConfig = new Configuration(this, regexFilter, filter);
return newConfig;
}
/**
* Returns a projected version of this configuration according to the type
* of the variables.
*
* @param typePattern a regular pattern (or just the full name) all variables
* in the resulting configuration must match
* @return the projected configuration
* @throws VilException in case of an illformed name pattern
*/
public Configuration selectByType(String typePattern) throws VilException {
initializeNested();
return new Configuration(this, new NameRegExFilter(typePattern, DataType.TYPE), filter);
}
/**
* Returns a projected version of this configuration according to the applied
* annotations.
*
* @param namePattern a regular name pattern (or just the full name) all applied
* annotations of all variables in the resulting configuration must match
* @return the projected configuration
* @throws VilException in case of an illformed name pattern
*/
public Configuration selectByAnnotation(String namePattern) throws VilException {
initializeAttributes();
return new Configuration(this, new NameRegExFilter(namePattern, DataType.ATTRIBUTE), filter);
}
/**
* Returns a projected version of this configuration according to the applied
* annotations.
*
* @param namePattern a regular name pattern (or just the full name) all applied
* annotations of all variables in the resulting configuration must match
* @return the projected configuration
* @throws VilException in case of an illformed name pattern
*/
public Configuration selectByAttribute(String namePattern) throws VilException {
return selectByAnnotation(namePattern);
} // TODO cleanup -> annotation
/**
* Returns a projected version of this configuration according to variables defined for
* the specified project.
*
* @param name the name of the project
* @param considerImports whether imports of projects shall be considered
* @return the projected configuration
*/
public Configuration selectByProject(String name, boolean considerImports) {
Project project = ModelQuery.findProject(configuration.getProject(), name);
if (null == project) {
project = new Project(name); // tolerance, but no contents
}
return new Configuration(this, project, new ProjectFilter(project, considerImports), filter);
}
/**
* Returns a projected version of this configuration according to variables defined for
* the specified project. Imports are considered by default.
*
* @param name the name of the project
* @return the projected configuration
*/
public Configuration selectByProject(String name) {
return selectByProject(name, true);
}
/**
* Returns a projected version of this configuration according to the applied
* annotations.
*
* @param name the name of the annotation (may be <b>null</b>)
* @param value the value as an IVML identifier (may be <b>null</b>)
* @return the projected configuration
* @throws VilException in case of an illformed name pattern
*/
public Configuration selectByAnnotation(String name, Object value) throws VilException {
initializeAttributes();
Configuration result;
if (null == name) {
result = new Configuration(this, AllFilter.INSTANCE, filter);
} else {
result = new Configuration(this,
new NameRegExFilter(name, DataType.ATTRIBUTE,
new ValueFilter(value, Attribute.class)), filter);
}
return result;
}
/**
* Returns a projected version of this configuration according to the applied
* annotations.
*
* @param name the name of the annotation (may be <b>null</b>)
* @param value the value as an IVML identifier (may be <b>null</b>)
* @return the projected configuration
* @throws VilException in case of an illformed name pattern
*/
public Configuration selectByAttribute(String name, Object value) throws VilException {
return selectByAnnotation(name, value);
}
/**
* Returns whether this configuration is empty.
*
* @return <code>true</code> if there are no decision variables to be configured,
* <code>false</code> else
*/
public boolean isEmpty() {
int count = 0;
if (null != variables || null != attributes) {
// if filtered/initialized
count += null != variables ? variables.length : 0;
count += null != attributes ? attributes.length : 0;
} else {
// fallback
count = configuration.getProject().getElementCount();
}
return count == 0;
}
@Override
public String getStringValue(StringComparator comparator) {
return "<config>"; // currently a pseudo value for testing
}
@Override
public String getName() {
return project.getName();
}
@Override
public String getQualifiedName() {
return project.getQualifiedName();
}
@Override
public TypeDescriptor<?> getType() {
return getTypeDescriptor(project.getType());
}
@Override
public String getTypeName() {
return project.getType().getName();
}
@Override
public String getQualifiedType() {
return project.getType().getQualifiedName();
}
/**
* Returns the specified attribute.
*
* @param index the 0-based index of the attribute to return
* @return the specified attribute
* @throws IndexOutOfBoundsException if <code>index < 0 || index >= {@link #getAttributeCount()}</code>
*/
Attribute getAttribute(int index) {
initializeAttributes();
if (null == attributes) {
throw new IndexOutOfBoundsException();
}
return attributes[index];
}
/**
* Returns the number of attributes.
*
* @return the number of attributes
*/
int getAttributeCount() {
initializeAttributes();
return null == attributes ? 0 : attributes.length;
}
@Invisible
@Override
public Object getValue() {
return null;
}
/**
* Returns the attributes of this configuration.
*
* @return the attributes
*/
@OperationMeta(returnGenerics = { Attribute.class } )
public Sequence<Attribute> attributes() {
initializeAttributes();
return new ArraySequence<Attribute>(attributes, Attribute.class);
}
/**
* Returns the decision variable with the given (qualified) name.
*
* @param name the name of the variable to return
* @return the variable or <b>null</b> if not found
*/
public DecisionVariable getByName(String name) {
IvmlElement elt = getElement(name);
DecisionVariable result;
if (elt instanceof DecisionVariable) {
result = (DecisionVariable) elt;
} else {
result = null;
}
return result;
}
/**
* Returns the element matching the given (qualified) name.
*
* @param name the name to search for
* @return the matching element or <b>null</b> if not found
*/
@Invisible
public IvmlElement getElement(String name) {
initializeAttributes();
initializeNested();
String key = name;
int pos = name.indexOf("::");
if (pos > 0) {
pos = name.indexOf("::", pos + 2);
if (pos > 0) {
// project::element
key = name.substring(0, pos);
}
}
IvmlElement match = nameMap.get(key);
if (null != match && key.length() < name.length()) {
match = match.getElement(name);
}
if (null == match) { // FQN match
match = nameMap.get(name);
}
if (null == match) {
Project project = configuration.getProject();
try {
AbstractVariable var = (AbstractVariable) ModelQuery.findElementByName(
project, name, AbstractVariable.class);
if (null != var) {
match = new IvmlDeclaration(var);
}
} catch (IvmlException e) {
}
try {
Value eVal = ModelQuery.enumLiteralAsValue(project, name);
if (eVal instanceof net.ssehub.easy.varModel.model.values.EnumValue) {
match = new EnumValue((net.ssehub.easy.varModel.model.values.EnumValue) eVal);
}
} catch (IvmlException e) {
}
}
return match;
}
@Invisible
@Override
public String getStringValue() {
return null;
}
@Invisible
@Override
public Integer getIntegerValue() {
return null;
}
@Invisible
@Override
public Double getRealValue() {
return null;
}
@Invisible
@Override
public Boolean getBooleanValue() {
return null;
}
@Invisible
@Override
public EnumValue getEnumValue() {
return null;
}
/**
* Stores a hint to the root executing script (for VTL-by-name resolution).
*
* @return the hint to the executing script
*/
@Invisible
public Script getRootScript() {
return rootScript;
}
/**
* Stores a hint to the root executing script (for VTL-by-name resolution).
*
* @param rootScript the hint to the executing script
*/
@Invisible
public void setRootScript(Script rootScript) {
this.rootScript = rootScript;
}
/**
* Stores the underlying (unprojected) configuration to <code>path</code>.
*
* @param path the target path
* @return the created/modified file artifact
* @throws VilException in case that storing the configuration fails
*/
public FileArtifact store(Path path) throws VilException {
return store(path, true);
}
/**
* Stores the underlying (unprojected) configuration to <code>path</code>.
*
* @param path the target path
* @param userValuesOnly store only user defined values (<code>true</code>) or the full
* configuration (<code>false</code>)
* @return the created/modified file artifact
* @throws VilException in case that storing the configuration fails
*/
public FileArtifact store(Path path, boolean userValuesOnly) throws VilException {
File target = path.getAbsolutePath();
FileWriter out = null;
try {
Project project = configuration.toProject(true, userValuesOnly);
out = new FileWriter(target);
IVMLWriter writer = new IVMLWriter(out);
project.accept(writer);
IVMLWriter.releaseInstance(writer);
out.close();
} catch (ConfigurationException e) {
throw new VilException(e, VilException.ID_RUNTIME_EXECUTION);
} catch (IOException e) {
if (null != out) {
try {
out.close();
} catch (IOException e1) {
}
}
throw new VilException(e, VilException.ID_IO);
}
return ArtifactFactory.createArtifact(FileArtifact.class, target, null);
}
/**
* Re-reasons on the variable settings of this configuration. This operation is intended
* for runtime reasoning, in particular of changed variables only.
*
* @return a projection of this configuration containing the variables changed by reasoning or
* <b>this</b> if the reasoner does not provide information on affected variables
*/
public Configuration reason() {
Configuration result;
ReasoningResult tmp = ReasonerFrontend.getInstance().propagate(configuration,
new ReasonerConfiguration(), ProgressObserver.NO_OBSERVER);
if (tmp.providesInformationOnAffectedVariables()) {
int aCount = tmp.getAffectedVariablesCount();
final HashSet<String> affected = new HashSet<String>();
for (int a = 0; a < aCount; a++) {
affected.add(tmp.getAffectedVariable(a).getDeclaration().getQualifiedName());
}
IConfigurationFilter reasoningFilter = new IConfigurationFilter() {
@Override
public boolean include(IvmlElement element) {
return affected.contains(element.getQualifiedName());
}
};
result = new Configuration(this, reasoningFilter, filter);
result.isValid = !tmp.hasConflict();
} else {
result = this;
}
return result;
}
/**
* Projects this configuration to the frozen variables. This method is intended to support runtime
* variability, i.e., to explicitly separate between pre-runtime instantiation and runtime instantiation.
* Please note that a configuration projected to frozen variables (in particular in pre-runtime instantiation) will
* remain frozen.
*
* @return a projection of this configuration containing frozen variables only
*/
public Configuration selectFrozen() {
Configuration result;
if (filter == FrozenVariablesFilter.INSTANCE) {
result = this;
} else {
result = new Configuration(configuration, FrozenVariablesFilter.INSTANCE);
result.isValid = isValid;
}
return result;
}
/**
* Returns a projection of this configuration returning all variables, including non-frozen
* runtime variables. Please note that a configuration projected to frozen variables (in particular in
* pre-runtime instantiation) will remain frozen.
*
* @return the projected configuration
*/
public Configuration selectAll() {
return this;
}
/**
* Copies this configuration into a new configuration instance. This method is intended for instantiating runtime
* variabilities.
*
* @return a copy of the configuration
*/
public Configuration copy() {
Configuration result = new Configuration(
new net.ssehub.easy.varModel.confModel.Configuration(configuration), filter);
result.isValid = isValid;
return result;
}
/**
* Returns whether this configuration is valid, in particular after {@link #reason()}.
*
* @return <code>true</code> if this configuration is valid, <code>false</code> else
*/
public boolean isValid() {
return isValid;
}
/**
* Projects to the changed variables only.
*
* @return a projects of the changed variables only, may be empty
* @see #selectChangedWithContext()
*/
public Configuration selectChanged() {
return new Configuration(configuration, changed.changedFilter());
}
/**
* Projects to the changed variables with their context.
*
* @return a projects of the changed variables only, may be empty
* @see #selectChanged()
*/
public Configuration selectChangedWithContext() {
return new Configuration(this, changed.changed());
}
/**
* Is called to notify the configuration about a changed variable value.
*
* @param variable the variable the value has changed for
* @param oldValue the value of the variable before the change
*/
@Invisible
public void notifyValueChanged(AbstractIvmlVariable variable, Value oldValue) {
changed.notifyChanged(variable, oldValue);
// don't rely on the qualified name here due to changing pseudo names for collections
}
/**
* Returns the mapped IVML element for <code>name</code>.
*
* @param name the name
* @return the mapped element (may be <b>null</b>)
*/
@Invisible
IvmlElement get(String name) {
return nameMap.get(name);
}
/**
* Returns the change history.
*
* @return the change history
*/
public ChangeHistory getChangeHistory() {
return changed;
}
/**
* Searches for the VIL instance holding <code>var</code>.
*
* @param var the variable
* @return the VIL instance holding <code>var</code>
*/
@Invisible
public DecisionVariable findVariable(IDecisionVariable var) {
DecisionVariable result = getByName(net.ssehub.easy.varModel.confModel.Configuration.getInstanceName(var));
for (int v = 0; null == result && v < variables.length; v++) {
result = findVariable(var, variables[v]);
}
return result;
}
/**
* Searches for <code>var</code> in <code>dVar</code>, i.e., whether <code>dVar</code> or
* one of its contained variables holdes <code>var</code>.
*
* @param var the variable to search for
* @param dVar the VIL variable wrapper to look into
* @return the VIL wrapper representing <code>dVar</code> or <b>null</b> if not found
*/
private DecisionVariable findVariable(IDecisionVariable var, DecisionVariable dVar) {
DecisionVariable result = null;
if (dVar.isVariable(var)) {
result = dVar;
} else {
Sequence<DecisionVariable> vars = dVar.variables();
for (int v = 0; null == result && v < vars.size(); v++) {
DecisionVariable tmp = vars.get(v);
if (tmp.isVariable(var)) {
result = tmp;
}
}
}
return result;
}
/**
* Returns all instances of the given <code>type</code>.
*
* @param type the type to look for
* @return all instances (may be empty)
*/
public net.ssehub.easy.instantiation.core.model.vilTypes.Set<?> allInstances(TypeDescriptor<?> type) {
net.ssehub.easy.instantiation.core.model.vilTypes.Set<?> result = null;
if (type instanceof IvmlTypeDescriptor) {
IDatatype ivmlType = ((IvmlTypeDescriptor) type).getIvmlType();
Value val = configuration.getAllInstances(ivmlType);
if (val instanceof ContainerValue) {
ContainerValue cValue = (ContainerValue) val;
Set<Object> tmp = new HashSet<Object>(cValue.getElementSize());
for (int v = 0; v < cValue.getElementSize(); v++) {
resolveAndAddValue(cValue.getElement(v), tmp);
}
if (!tmp.isEmpty()) {
result = new SetSet<Object>(tmp, type);
}
}
}
if (null == result) {
result = new ArraySet<Object>(new Object[0], type);
}
return result;
}
/**
* Resolves the VIL decision variable object for <code>value</code> and adds it to <code>result</code>.
*
* @param value the value
* @param result the result (to be modified as a side effect)
*/
private void resolveAndAddValue(Value value, Set<Object> result) {
if (value instanceof ReferenceValue) { // always the case, just to be sure
AbstractVariable var = ((ReferenceValue) value).getValue();
if (var != null) {
IDecisionVariable decVar = configuration.getDecision(var);
if (null != decVar) {
DecisionVariable dVar = findVariable(decVar);
if (null != dVar) {
result.add(dVar);
}
}
}
}
}
}
|
package org.deviceconnect.android.profile;
import android.content.Intent;
import android.os.Bundle;
import org.deviceconnect.android.message.MessageUtils;
import org.deviceconnect.profile.MediaStreamRecordingProfileConstants;
import java.util.List;
/**
* MediaStream Recording .
*
* <p>
* API.<br/>
* API <br/>
* </p>
*
* <h1>API</h1>
* <p>
* MediaStream Profile API<br/>
* API<br/>
* API
* </p>
* <ul>
* <li>MediaStreamRecording MediaRecorder API [GET] :
* {@link MediaStreamRecordingProfile#onGetMediaRecorder(Intent, Intent, String)}
* </li>
* <li>MediaStreamRecording Take Photo API [POST] :
* {@link MediaStreamRecordingProfile#onPostTakePhoto(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Record API [POST] :
* {@link MediaStreamRecordingProfile#onPostRecord(Intent, Intent, String, String, Long)}
* </li>
* <li>MediaStreamRecording Pause API [PUT] :
* {@link MediaStreamRecordingProfile#onPutPause(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Resume API [PUT] :
* {@link MediaStreamRecordingProfile#onPutResume(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Stop API [PUT] :
* {@link MediaStreamRecordingProfile#onPutStop(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Mute Track API [PUT] :
* {@link MediaStreamRecordingProfile#onPutMuteTrack(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Unmute Track API [PUT] :
* {@link MediaStreamRecordingProfile#onPutUnmuteTrack(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Options API [GET] :
* {@link MediaStreamRecordingProfile#onGetOptions(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Options API [PUT] :
* {@link MediaStreamRecordingProfile#onPutOptions(Intent, Intent, String, String, Integer, Integer, Integer, Integer, Double, String)}
* </li>
* <li>MediaStreamRecording Preview API [PUT] :
* {@link MediaStreamRecordingProfile#onPutPreview(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Preview API [DELETE] :
* {@link MediaStreamRecordingProfile#onPutPreview(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Take a Picture Event API [Register] :
* {@link MediaStreamRecordingProfile#onPutOnPhoto(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Take a Picture Event API [Unregister] :
* {@link MediaStreamRecordingProfile#onDeleteOnPhoto(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Recording Change Event API [Register] :
* {@link MediaStreamRecordingProfile#onPutOnRecordingChange(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Recording Change Event API [Unregister] :
* {@link MediaStreamRecordingProfile#onDeleteOnRecordingChange(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Data Available Event API [Register] :
* {@link MediaStreamRecordingProfile#onPutOnDataAvailable(Intent, Intent, String, String)}
* </li>
* <li>MediaStreamRecording Data Available Event API [Unregister] :
* {@link MediaStreamRecordingProfile#onDeleteOnDataAvailable(Intent, Intent, String, String)}
* </li>
* </ul>
* @author NTT DOCOMO, INC.
*/
public class MediaStreamRecordingProfile extends DConnectProfile implements MediaStreamRecordingProfileConstants {
@Override
public final String getProfileName() {
return PROFILE_NAME;
}
@Override
protected boolean onGetRequest(final Intent request, final Intent response) {
String attribute = getAttribute(request);
boolean result = true;
if (attribute == null) {
setUnsupportedError(response);
} else {
String serviceId = getServiceID(request);
if (attribute.equals(ATTRIBUTE_MEDIARECORDER)) {
result = onGetMediaRecorder(request, response, serviceId);
} else if (attribute.equals(ATTRIBUTE_OPTIONS)) {
String target = getTarget(request);
result = onGetOptions(request, response, serviceId, target);
} else {
setUnsupportedError(response);
}
}
return result;
}
@Override
protected boolean onPostRequest(final Intent request, final Intent response) {
String attribute = getAttribute(request);
boolean result = true;
if (attribute == null) {
setUnsupportedError(response);
} else {
String target = getTarget(request);
String serviceId = getServiceID(request);
if (attribute.equals(ATTRIBUTE_TAKE_PHOTO)) {
result = onPostTakePhoto(request, response, serviceId, target);
} else if (attribute.equals(ATTRIBUTE_RECORD)) {
try {
Long timeslice = getTimeSlice(request);
result = onPostRecord(request, response, serviceId, target, timeslice);
} catch (NumberFormatException e) {
MessageUtils.setInvalidRequestParameterError(response);
}
} else {
setUnsupportedError(response);
}
}
return result;
}
@SuppressWarnings("deprecation")
@Override
protected boolean onPutRequest(final Intent request, final Intent response) {
String attribute = getAttribute(request);
boolean result = true;
if (attribute == null) {
MessageUtils.setUnknownAttributeError(response);
} else {
String serviceId = getServiceID(request);
String target = getTarget(request);
String sessionKey = getSessionKey(request);
if (attribute.equals(ATTRIBUTE_PAUSE)) {
result = onPutPause(request, response, serviceId, target);
} else if (attribute.equals(ATTRIBUTE_RESUME)) {
result = onPutResume(request, response, serviceId, target);
} else if (attribute.equals(ATTRIBUTE_STOP)) {
result = onPutStop(request, response, serviceId, target);
} else if (attribute.equals(ATTRIBUTE_MUTETRACK)) {
result = onPutMuteTrack(request, response, serviceId, target);
} else if (attribute.equals(ATTRIBUTE_UNMUTETRACK)) {
result = onPutUnmuteTrack(request, response, serviceId, target);
} else if (attribute.equals(ATTRIBUTE_OPTIONS)) {
Integer imageWidth = getImageWidth(request);
Integer imageHeight = getImageHeight(request);
Integer previewWidth = getPreviewWidth(request);
Integer previewHeight = getPreviewHeight(request);
Double previewMaxFrameRate = getPreviewMaxFrameRate(request);
String mimeType = getMIMEType(request);
result = onPutOptions(request, response, serviceId, target, imageWidth, imageHeight,
previewWidth, previewHeight, previewMaxFrameRate, mimeType);
} else if (attribute.equals(ATTRIBUTE_ON_PHOTO)) {
result = onPutOnPhoto(request, response, serviceId, sessionKey);
} else if (attribute.equals(ATTRIBUTE_ON_RECORDING_CHANGE)) {
result = onPutOnRecordingChange(request, response, serviceId, sessionKey);
} else if (attribute.equals(ATTRIBUTE_ON_DATA_AVAILABLE)) {
result = onPutOnDataAvailable(request, response, serviceId, sessionKey);
} else if (attribute.equals(ATTRIBUTE_PREVIEW)) {
result = onPutPreview(request, response, serviceId, target);
} else {
MessageUtils.setUnknownAttributeError(response);
}
}
return result;
}
@SuppressWarnings("deprecation")
@Override
protected boolean onDeleteRequest(final Intent request, final Intent response) {
String attribute = getAttribute(request);
boolean result = true;
if (attribute == null) {
MessageUtils.setUnknownAttributeError(response);
} else {
String serviceId = getServiceID(request);
String target = getTarget(request);
String sessionKey = getSessionKey(request);
if (attribute.equals(ATTRIBUTE_ON_PHOTO)) {
result = onDeleteOnPhoto(request, response, serviceId, sessionKey);
} else if (attribute.equals(ATTRIBUTE_ON_RECORDING_CHANGE)) {
result = onDeleteOnRecordingChange(request, response, serviceId, sessionKey);
} else if (attribute.equals(ATTRIBUTE_ON_DATA_AVAILABLE)) {
result = onDeleteOnDataAvailable(request, response, serviceId, sessionKey);
} else if (attribute.equals(ATTRIBUTE_PREVIEW)) {
result = onDeletePreview(request, response, serviceId, target);
} else {
MessageUtils.setUnknownAttributeError(response);
}
}
return result;
}
// GET
/**
* .<br/>
*
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @return
*/
protected boolean onGetMediaRecorder(final Intent request, final Intent response, final String serviceId) {
setUnsupportedError(response);
return true;
}
/**
* .<br/>
*
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target IDnull
* @return
*/
protected boolean onGetOptions(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
// POST
/**
* .<br/>
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target IDnull
* @return
*/
protected boolean onPostTakePhoto(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
/**
* .<br/>
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @param timeslice
* @return
*/
protected boolean onPostRecord(final Intent request, final Intent response, final String serviceId,
final String target, final Long timeslice) {
setUnsupportedError(response);
return true;
}
// PUT
/**
* .<br/>
*
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @return
*/
protected boolean onPutPause(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
/**
* .<br/>
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @return
*/
protected boolean onPutResume(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
/**
* .<br/>
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @return
*/
protected boolean onPutStop(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
/**
* .<br/>
*
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @return
*/
protected boolean onPutMuteTrack(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
/**
* .<br/>
*
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @return
*/
protected boolean onPutUnmuteTrack(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
/**
* .<br/>
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @param imageWidth
* @param imageHeight
* @param previewWidth
* @param previewHeight
* @param previewMaxFrameRate
* @param mimeType MIME
* @return
*/
protected boolean onPutOptions(final Intent request, final Intent response, final String serviceId,
final String target, final Integer imageWidth, final Integer imageHeight,
final Integer previewWidth, final Integer previewHeight, final Double previewMaxFrameRate,
final String mimeType) {
setUnsupportedError(response);
return true;
}
/**
* onphoto.<br/>
* onphoto
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param sessionKey
* @return
*/
protected boolean onPutOnPhoto(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* onrecordingchange.<br/>
* onrecordingchange
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param sessionKey
* @return
*/
protected boolean onPutOnRecordingChange(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* ondataavailable.<br/>
* ondataavailable
* true
* false
*
* @deprecated This method is deprecated.
*
* @param request
* @param response
* @param serviceId ID
* @param sessionKey
* @return
*/
protected boolean onPutOnDataAvailable(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* .
* <p>
* URI<br/>
* true
* false
* </p>
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @return
*/
protected boolean onPutPreview(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
// DELETE
/**
* onphoto.<br/>
* onphoto
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param sessionKey
* @return
*/
protected boolean onDeleteOnPhoto(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* onrecordingchange.<br/>
* onPutOnRecordingChange
* true
* false
*
* @param request
* @param response
* @param serviceId ID
* @param sessionKey
* @return
*/
protected boolean onDeleteOnRecordingChange(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* ondataavailable.<br/>
* ondataavailable
* true
* false
*
* @deprecated This method is deprecated.
*
* @param request
* @param response
* @param serviceId ID
* @param sessionKey
* @return
*/
protected boolean onDeleteOnDataAvailable(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* .
* <p>
* <br/>
* true
* false
* </p>
* @param request
* @param response
* @param serviceId ID
* @param target ID
* @return
*/
protected boolean onDeletePreview(final Intent request, final Intent response, final String serviceId,
final String target) {
setUnsupportedError(response);
return true;
}
/**
* ID.
*
* @param request
* @return IDnull
*/
public static String getTarget(final Intent request) {
String target = request.getStringExtra(PARAM_TARGET);
return target;
}
/**
* .
*
* @param request
* @return -1
*/
public static Long getTimeSlice(final Intent request) {
Bundle b = request.getExtras();
if (b == null) {
return null;
}
try {
String slice = b.getString(PARAM_TIME_SLICE);
if (slice == null) {
return null;
}
Long res = Long.valueOf(slice);
return res;
} catch (NumberFormatException e) {
throw e;
}
}
/**
* .
*
* @param request
* @return <code>null</code>
*/
public static Integer getImageWidth(final Intent request) {
return parseInteger(request, PARAM_IMAGE_WIDTH);
}
/**
* .
*
* @param request
* @return <code>null</code>
*/
public static Integer getImageHeight(final Intent request) {
return parseInteger(request, PARAM_IMAGE_HEIGHT);
}
/**
* .
*
* @param request
* @return <code>null</code>
*/
public static Integer getPreviewWidth(final Intent request) {
return parseInteger(request, PARAM_PREVIEW_WIDTH);
}
/**
* .
*
* @param request
* @return <code>null</code>
*/
public static Integer getPreviewHeight(final Intent request) {
return parseInteger(request, PARAM_PREVIEW_HEIGHT);
}
/**
* .
*
* @param request
* @return <code>null</code>
*/
public static Double getPreviewMaxFrameRate(final Intent request) {
return parseDouble(request, PARAM_PREVIEW_MAX_FRAME_RATE);
}
/**
* MIME.
*
* @param request
* @return MIME
*/
public static String getMIMEType(final Intent request) {
String mime = request.getStringExtra(PARAM_MIME_TYPE);
return mime;
}
/**
* .
*
* @param response
* @param recorders
*/
public static void setRecorders(final Intent response, final Bundle[] recorders) {
response.putExtra(PARAM_RECORDERS, recorders);
}
/**
* .
*
* @param response
* @param path
*/
public static void setPath(final Intent response, final String path) {
response.putExtra(PARAM_PATH, path);
}
/**
* .
*
* @param photo
* @param path
*/
public static void setPath(final Bundle photo, final String path) {
photo.putString(PARAM_PATH, path);
}
/**
* .
*
* @param response
* @param recorders
*/
public static void setRecorders(final Intent response, final List<Bundle> recorders) {
setRecorders(response, recorders.toArray(new Bundle[recorders.size()]));
}
/**
* ID.
*
* @param recorder
* @param id ID
*/
public static void setRecorderId(final Bundle recorder, final String id) {
recorder.putString(PARAM_ID, id);
}
/**
* .
*
* @param recorder
* @param name
*/
public static void setRecorderName(final Bundle recorder, final String name) {
recorder.putString(PARAM_NAME, name);
}
/**
* .
*
* @param recorder
* @param state
*/
public static void setRecorderState(final Bundle recorder, final RecorderState state) {
recorder.putString(PARAM_STATE, state.getValue());
}
/**
* .
*
* @param recorder
* @param imageWidth
*/
public static void setRecorderImageWidth(final Bundle recorder, final int imageWidth) {
recorder.putInt(PARAM_IMAGE_WIDTH, imageWidth);
}
/**
* .
*
* @param recorder
* @param imageHeight
*/
public static void setRecorderImageHeight(final Bundle recorder, final int imageHeight) {
recorder.putInt(PARAM_IMAGE_HEIGHT, imageHeight);
}
/**
* .
*
* @param recorder
* @param previewWidth
*/
public static void setRecorderPreviewWidth(final Bundle recorder, final int previewWidth) {
recorder.putInt(PARAM_PREVIEW_WIDTH, previewWidth);
}
/**
* .
*
* @param recorder
* @param previewHeight
*/
public static void setRecorderPreviewHeight(final Bundle recorder, final int previewHeight) {
recorder.putInt(PARAM_PREVIEW_HEIGHT, previewHeight);
}
/**
* .
*
* @param recorder
* @param maxFrameRate
*/
public static void setRecorderPreviewMaxFrameRate(final Bundle recorder, final double maxFrameRate) {
recorder.putDouble(PARAM_PREVIEW_MAX_FRAME_RATE, maxFrameRate);
}
/**
* .
*
* @param recorder
* @param audio
*/
public static void setRecorderAudio(final Bundle recorder, final Bundle audio) {
recorder.putBundle(PARAM_AUDIO, audio);
}
/**
* .
*
* @param audio
* @param channels
*/
public static void setAudioChannels(final Bundle audio, final int channels) {
audio.putInt(PARAM_CHANNELS, channels);
}
/**
* .
*
* @param audio
* @param sampleRate
*/
public static void setAudioSampleRate(final Bundle audio, final int sampleRate) {
audio.putInt(PARAM_SAMPLE_RATE, sampleRate);
}
/**
* .
*
* @param audio
* @param sampleSize
*/
public static void setAudioSampleSize(final Bundle audio, final int sampleSize) {
audio.putInt(PARAM_SAMPLE_SIZE, sampleSize);
}
/**
* .
*
* @param audio
* @param blockSize
*/
public static void setAudioBlockSize(final Bundle audio, final int blockSize) {
audio.putInt(PARAM_BLOCK_SIZE, blockSize);
}
/**
* .
*
* @param message
* @param audio
*/
public static void setAudio(final Intent message, final Bundle audio) {
message.putExtra(PARAM_AUDIO, audio);
}
/**
* URI.
*
* @param audio
* @param uri URI
*/
public static void setAudioUri(final Bundle audio, final String uri) {
audio.putString(PARAM_URI, uri);
}
/**
* MIME.
*
* @param recorder
* @param mime MIME
*/
public static void setRecorderMIMEType(final Bundle recorder, final String mime) {
recorder.putString(PARAM_MIME_TYPE, mime);
}
/**
* .
*
* @param recorder
* @param config
*/
public static void setRecorderConfig(final Bundle recorder, final String config) {
recorder.putString(PARAM_CONFIG, config);
}
/**
* .
*
* @param message
* @param photo
*/
public static void setPhoto(final Intent message, final Bundle photo) {
message.putExtra(PARAM_PHOTO, photo);
}
/**
* .
*
* @param message
* @param media
*/
public static void setMedia(final Intent message, final Bundle media) {
message.putExtra(PARAM_MEDIA, media);
}
/**
* URI.
*
* @param response
* @param uri URI
*/
public static void setUri(final Intent response, final String uri) {
response.putExtra(PARAM_URI, uri);
}
/**
* URI.
*
* @param media
* @param uri URI
*/
public static void setUri(final Bundle media, final String uri) {
media.putString(PARAM_URI, uri);
}
/**
* .
*
* @param media
* @param errorMessage
*/
public static void setErrorMessage(final Bundle media, final String errorMessage) {
media.putString(PARAM_ERROR_MESSAGE, errorMessage);
}
/**
* .
*
* @param media
* @param state
*/
public static void setStatus(final Bundle media, final RecordingState state) {
media.putString(PARAM_STATUS, state.getValue());
}
/**
* .
*
* @param media
* @param state
*/
public static void setStatus(final Bundle media, final String state) {
media.putString(PARAM_STATUS, state);
}
/**
* .
*
* @param response
* @param imageSizes
*/
public static void setImageSizes(final Intent response, final Bundle[] imageSizes) {
response.putExtra(PARAM_IMAGE_SIZES, imageSizes);
}
/**
* .
*
* @param response
* @param previewSizes
*/
public static void setPreviewSizes(final Intent response, final Bundle[] previewSizes) {
response.putExtra(PARAM_PREVIEW_SIZES, previewSizes);
}
/**
* .
* @param size
* @param width
*/
public static void setWidth(final Bundle size, final int width) {
size.putInt(PARAM_WIDTH, width);
}
/**
* .
* @param size
* @param height
*/
public static void setHeight(final Bundle size, final int height) {
size.putInt(PARAM_HEIGHT, height);
}
/**
* .
* @param size
* @param min
* @param max
* @deprecated
*/
public static void setSize(final Bundle size, final int min, final int max) {
size.putInt(PARAM_MIN, min);
size.putInt(PARAM_MAX, max);
}
/**
* .
* @param response
* @param min
* @param max
* @deprecated
*/
public static void setImageWidth(final Intent response, final int min, final int max) {
Bundle size = new Bundle();
setSize(size, min, max);
setImageWidth(response, size);
}
/**
* .
* @param response
* @param size
* @deprecated
*/
public static void setImageWidth(final Intent response, final Bundle size) {
response.putExtra(PARAM_IMAGE_WIDTH, size);
}
/**
* .
* @param response
* @param min
* @param max
* @deprecated
*/
public static void setImageHeight(final Intent response, final int min, final int max) {
Bundle size = new Bundle();
setSize(size, min, max);
setImageHeight(response, size);
}
/**
* .
* @param response
* @param size
* @deprecated
*/
public static void setImageHeight(final Intent response, final Bundle size) {
response.putExtra(PARAM_IMAGE_HEIGHT, size);
}
/**
* MIME.
*
* @param response
* @param mimeType MIME
*/
public static void setMIMEType(final Intent response, final String[] mimeType) {
response.putExtra(PARAM_MIME_TYPE, mimeType);
}
/**
* MIME.
*
* @param param
* @param mimeType MIME
*/
public static void setMIMEType(final Bundle param, final String mimeType) {
param.putString(PARAM_MIME_TYPE, mimeType);
}
/**
* MIME.
*
* @param param
* @param mimeType MIME
*/
public static void setMIMEType(final Bundle param, final String[] mimeType) {
param.putStringArray(PARAM_MIME_TYPE, mimeType);
}
/**
* MIME.
*
* @param param
* @param mimeType MIME
*/
public static void setMIMEType(final Bundle param, final List<String> mimeType) {
param.putStringArray(PARAM_MIME_TYPE, mimeType.toArray(new String[mimeType.size()]));
}
}
|
package se.callista.microservices.composite.product;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/*@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ProductCompositeServiceApplication.class)
@WebAppConfiguration
public class ProductCompositeServiceApplicationTests {
@Test
public void contextLoads() {
}
}*/
|
package org.nuxeo.ecm.platform.annotations.gwt.client.view;
import org.nuxeo.ecm.platform.annotations.gwt.client.controler.AnnotationController;
import org.nuxeo.ecm.platform.annotations.gwt.client.view.i18n.TranslationConstants;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ToggleButton;
/**
* @author <a href="mailto:troger@nuxeo.com">Thomas Roger</a>
*
*/
public class HideShowAnnotationsButton extends Composite {
public HideShowAnnotationsButton(
final AnnotationController annotationController) {
final TranslationConstants translationConstants = GWT.create(TranslationConstants.class);
final ToggleButton button = new ToggleButton(
translationConstants.showAnnotations(),
translationConstants.hideAnnotations());
button.setStyleName("annotation-hide-show-button");
button.setDown(annotationController.isAnnotationsVisible());
button.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (button.isDown()) {
showAnnotations();
} else {
hideAnnotations();
}
}
});
initWidget(button);
}
private native void showAnnotations() /*-{
if (typeof top['showAnnotations'] != "undefined") {
top['showAnnotations']();
}
}-*/;
private native void hideAnnotations() /*-{
if (typeof top['hideAnnotations'] != "undefined") {
top['hideAnnotations']();
}
}-*/;
}
|
package com.ge.research.sadl.jena.translator;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ge.research.sadl.model.ModelError;
import com.ge.research.sadl.model.gp.BuiltinElement;
import com.ge.research.sadl.model.gp.BuiltinElement.BuiltinType;
import com.ge.research.sadl.model.gp.ConstantNode;
import com.ge.research.sadl.model.gp.Equation;
import com.ge.research.sadl.model.gp.FunctionSignature;
import com.ge.research.sadl.model.gp.GraphPatternElement;
import com.ge.research.sadl.model.gp.Junction;
import com.ge.research.sadl.model.gp.Junction.JunctionType;
import com.ge.research.sadl.model.gp.KnownNode;
import com.ge.research.sadl.model.gp.Literal;
import com.ge.research.sadl.model.gp.NamedNode;
import com.ge.research.sadl.model.gp.NamedNode.NodeType;
import com.ge.research.sadl.model.gp.NegatedExistentialQuantifier;
import com.ge.research.sadl.model.gp.Node;
import com.ge.research.sadl.model.gp.ProxyNode;
import com.ge.research.sadl.model.gp.Query;
import com.ge.research.sadl.model.gp.Query.Order;
import com.ge.research.sadl.model.gp.Query.OrderingPair;
import com.ge.research.sadl.model.gp.RDFTypeNode;
import com.ge.research.sadl.model.gp.Rule;
import com.ge.research.sadl.model.gp.TripleElement;
import com.ge.research.sadl.model.gp.TripleElement.TripleModifierType;
import com.ge.research.sadl.processing.SadlConstants;
import com.ge.research.sadl.model.gp.VariableNode;
import com.ge.research.sadl.reasoner.ConfigurationException;
import com.ge.research.sadl.reasoner.ConfigurationItem;
import com.ge.research.sadl.reasoner.ConfigurationItem.ConfigurationType;
import com.ge.research.sadl.reasoner.ConfigurationOption;
import com.ge.research.sadl.reasoner.FunctionNotSupportedException;
import com.ge.research.sadl.reasoner.IConfigurationManager;
import com.ge.research.sadl.reasoner.IConfigurationManagerForEditing;
import com.ge.research.sadl.reasoner.ITranslator;
import com.ge.research.sadl.reasoner.InvalidNameException;
import com.ge.research.sadl.reasoner.ModelError.ErrorType;
import com.ge.research.sadl.reasoner.TranslationException;
import com.ge.research.sadl.reasoner.utils.SadlUtils;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.ontology.Ontology;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.reasoner.rulesys.Builtin;
import com.hp.hpl.jena.reasoner.rulesys.BuiltinRegistry;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
public class JenaTranslatorPlugin implements ITranslator {
protected static final Logger logger = LoggerFactory.getLogger(JenaTranslatorPlugin.class);
private static final String TranslatorCategory = "Basic_Jena_Translator";
private static final String ReasonerFamily="Jena-Based";
protected IConfigurationManager configurationMgr;
public enum TranslationTarget {RULE_TRIPLE, RULE_BUILTIN, QUERY_TRIPLE, QUERY_FILTER}
private enum SpecialBuiltin {NOVALUE, NOVALUESPECIFIC, NOTONLY, ONLY, ISKNOWN}
private enum RulePart {PREMISE, CONCLUSION, NOT_A_RULE}
private Map<String, String> prefixes = new HashMap<String, String>();
private boolean saveRuleFileAfterModelSave = true; // unless set to false because an explicit list of rules are
private Rule ruleInTranslation = null;
private Query queryInTranslation = null;
private int nextQueryVarNum = 1;
private OntModel theModel;
private String modelName;
protected List<ModelError> errors = null;
// provided, we need to look for rule files in
// imported models and if there are any create a rule file
// for this model so that the imported rule files will be loaded
public List<ModelError> translateAndSaveModel(OntModel model, String translationFolder,
String modelName, List<String> orderedImports, String saveFilename) throws TranslationException, IOException, URISyntaxException {
// Jena models have been saved to the OwlModels folder by the ModelManager prior to calling the translator. For Jena
// reasoners, no additional saving of OWL models is need so we can continue on to rule translation and saving.
if (errors != null) {
errors.clear();
}
if (model == null) {
return addError("Cannot save model in file '" + saveFilename + "' as it has no model.");
}
if (modelName == null) {
return addError("Cannot save model in file '" + saveFilename + "' as it has no name.");
}
if (saveRuleFileAfterModelSave) {
String ruleFilename = createDerivedFilename(saveFilename, "rules");
String fullyQualifiedRulesFilename = translationFolder + File.separator + ruleFilename;
translateAndSaveRules(model, null, modelName, fullyQualifiedRulesFilename);
}
saveRuleFileAfterModelSave = false; // reset
return (errors != null && errors.size() > 0) ? errors : null;
}
public List<ModelError> translateAndSaveModel(OntModel model, List<Rule> ruleList,
String translationFolder, String modelName, List<String> orderedImports, String saveFilename)
throws TranslationException, IOException, URISyntaxException {
if (errors != null) {
errors.clear();
}
saveRuleFileAfterModelSave = false;
// a Jena model simply writes out the OWL file
translateAndSaveModel(model, translationFolder, modelName, orderedImports, saveFilename);
String ruleFilename = createDerivedFilename(saveFilename, "rules");
String fullyQualifiedRulesFilename = translationFolder + File.separator + ruleFilename;
if (ruleList != null && ruleList.size() > 0) {
translateAndSaveRules(model, ruleList, modelName, fullyQualifiedRulesFilename);
}
else {
// there isn't a rules file but make sure there isn't an old one around that needs to be deleted
File oldRuleFile = new File(fullyQualifiedRulesFilename);
if (oldRuleFile.exists() && oldRuleFile.isFile()) {
try {
oldRuleFile.delete();
}
catch (Exception e) {
addError("Failed to delete old rules file '" + fullyQualifiedRulesFilename + "'.");
logger.error("Failed to delete old rule file '" + fullyQualifiedRulesFilename + "': " + e.getLocalizedMessage());
}
}
}
return (errors != null && errors.size() > 0) ? errors : null;
}
public String translateRule(OntModel model, Rule rule)
throws TranslationException {
setRuleInTranslation(rule);
boolean translateToBackwardRule = false;
StringBuilder sb = new StringBuilder();
// put annotations (if any) in the rule
if (rule.getAnnotations() != null) {
Iterator<String[]> annItr = rule.getAnnotations().iterator();
sb.append("#/**\n");
while (annItr.hasNext()) {
String[] annNVP = annItr.next();
sb.append("# * @");
sb.append(annNVP[0]);
sb.append("\t");
String val = annNVP[1];
String linesep =System.lineSeparator();
String[] valLines = val.split(linesep);
for (int i = 0; i < valLines.length; i++) {
if (i > 0) {
sb.append("# * ");
}
sb.append(valLines[i]);
sb.append("\n");
}
}
sb.append("# */\n");
}
if (translateToBackwardRule) {
sb.append("[");
sb.append(rule.getRuleName());
sb.append(": ");
List<GraphPatternElement> thens = rule.getThens();
String thenStr = graphPatternElementsToJenaRuleString(thens, RulePart.CONCLUSION);
if (thenStr != null) {
sb.append(thenStr);
}
sb.append(" <- ");
List<GraphPatternElement> givens = rule.getGivens();
String givenStr = graphPatternElementsToJenaRuleString(givens, RulePart.PREMISE);
if (givenStr != null) {
sb.append(givenStr);
}
List<GraphPatternElement> ifs = rule.getIfs();
String ifStr = graphPatternElementsToJenaRuleString(ifs, RulePart.PREMISE);
if (ifStr != null) {
if (givenStr != null) {
sb.append(", ");
}
sb.append(ifStr);
}
sb.append("]");
}
else {
sb.append("[");
sb.append(rule.getRuleName());
sb.append(": ");
List<GraphPatternElement> givens = rule.getGivens();
String givenStr = graphPatternElementsToJenaRuleString(givens, RulePart.PREMISE);
if (givenStr != null) {
sb.append(givenStr);
}
List<GraphPatternElement> ifs = rule.getIfs();
String ifStr = graphPatternElementsToJenaRuleString(ifs, RulePart.PREMISE);
if (ifStr != null) {
if (givenStr != null) {
sb.append(", ");
}
sb.append(ifStr);
}
sb.append(" -> ");
List<GraphPatternElement> thens = rule.getThens();
String thenStr = graphPatternElementsToJenaRuleString(thens, RulePart.CONCLUSION);
if (thenStr != null) {
sb.append(thenStr);
}
sb.append("]");
}
setRuleInTranslation(null);
return (sb.length() > 0 ? sb.toString() : null);
}
private String graphPatternElementsToJenaRuleString(List<GraphPatternElement> elements, RulePart rulePart) throws TranslationException {
int cnt = 0;
if (elements != null && elements.size() > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; elements != null && i < elements.size(); i++) {
if (cnt > 0) sb.append(", ");
SpecialBuiltin spb = processSpecialBuiltins(elements, i); // check for special handling required for some built-ins
if (spb != null) {
// get the triple in question
TripleElement trel = null;
if (elements.get(i) instanceof TripleElement) {
trel = (TripleElement)elements.get(i);
}
else {
logger.error("Unhandled graph pattern element detected as special builtin: " + elements.get(i).toString());
}
// translate based on type of spb
if (spb.equals(SpecialBuiltin.NOVALUE)) {
sb.append(createNoValue(trel, TranslationTarget.RULE_BUILTIN));
}
else if (spb.equals(SpecialBuiltin.ISKNOWN)) {
sb.append(graphPatternElementToJenaRuleString(trel, rulePart));
sb.append(", ");
sb.append("bound(" + nodeToString(trel.getObject(), TranslationTarget.RULE_BUILTIN) + ")");
}
else {
if (spb.equals(SpecialBuiltin.NOVALUESPECIFIC)) {
sb.append(createNoValueSpecific(trel, TranslationTarget.RULE_BUILTIN));
}
else if (spb.equals(SpecialBuiltin.NOTONLY)) {
sb.append(createNotOnly(trel, TranslationTarget.RULE_BUILTIN));
}
else if (spb.equals(SpecialBuiltin.ONLY)) {
sb.append(createOnly((TripleElement)elements.get(i), TranslationTarget.RULE_BUILTIN));
}
else {
logger.error("Unhandled special builtin: " + elements.toString());
}
}
}
else {
sb.append(graphPatternElementToJenaRuleString(elements.get(i), rulePart));
}
cnt++;
}
return sb.toString();
}
return null;
}
/**
* Look for special built-ins and if found process them, modifying the element list as needed.
* @param elements
* @param index
* @return
*/
private SpecialBuiltin processSpecialBuiltins(List<GraphPatternElement> elements, int index) {
if (elements.get(index) instanceof TripleElement) {
if (!((TripleElement)elements.get(index)).getModifierType().equals(TripleModifierType.None)) {
TripleElement trel = (TripleElement)elements.get(index);
if (trel.getModifierType().equals(TripleModifierType.Not)) {
if (trel.getObject() instanceof KnownNode) {
return SpecialBuiltin.NOVALUE;
}
else {
return SpecialBuiltin.NOVALUESPECIFIC;
}
}
else if (trel.getModifierType().equals(TripleModifierType.NotOnly)) {
return SpecialBuiltin.NOTONLY;
}
else if (trel.getModifierType().equals(TripleModifierType.Only)) {
return SpecialBuiltin.ONLY;
}
}
else if (elements.size() > (index + 1) && elements.get(index + 1) instanceof BuiltinElement) {
// these special builtins will be of the form:
// x predicate y, op(y,z)
// or in other words, the first argument of the operation will be the object of the triple
// (is that restrictive enough??)
BuiltinElement be = (BuiltinElement) elements.get(index + 1);
BuiltinType bt = be.getFuncType();
List<Node> args = be.getArguments();
Node biarg1 = (args.size() > 0) ? args.get(0) : null; // builtin 0th argument node
Node trobj = ((TripleElement)elements.get(index)).getObject(); // triple object node
if (biarg1 != null && trobj != null && biarg1 instanceof NamedNode && trobj instanceof NamedNode
&& ((NamedNode)biarg1).getName().equals(((NamedNode)trobj).getName())) {
if (bt.equals(BuiltinType.NotEqual) && args.size() == 2) {
Node arg2 = args.get(1);
if (arg2 instanceof KnownNode) {
// this case: (x pred y), !=(y, known)
// just drop the i+1 builtin
elements.remove(index + 1);
return SpecialBuiltin.NOVALUE;
}
else {
// this case: (x pred y), !=(y, z)
// move the z to the object of the triple and drop the i+1 builtin
if (args.size() > 1) {
Node biarg2 = args.get(1);
Node trsubj = ((TripleElement)elements.get(index)).getSubject();
if (biarg2 instanceof NamedNode && !(biarg2 instanceof VariableNode) && trsubj instanceof NamedNode &&
!(((NamedNode)biarg2).getName().equals(((NamedNode)trsubj).getName()))) {
((TripleElement)elements.get(index)).setObject(args.get(1));
elements.remove(index + 1);
return SpecialBuiltin.NOVALUESPECIFIC;
}
}
}
}
else if (bt.equals(BuiltinType.NotOnly)) {
((TripleElement)elements.get(index)).setObject(args.get(1));
elements.remove(index + 1);
return SpecialBuiltin.NOTONLY;
}
else if (bt.equals(BuiltinType.Only)) {
((TripleElement)elements.get(index)).setObject(args.get(1));
elements.remove(index + 1);
return SpecialBuiltin.ONLY;
}
}
}
else if (((TripleElement)elements.get(index)).getObject() instanceof KnownNode) {
Node var = new VariableNode("v" + System.currentTimeMillis());
((TripleElement)elements.get(index)).setObject(var);
return SpecialBuiltin.ISKNOWN;
}
}
return null;
}
private String createNoValue(TripleElement trel, TranslationTarget target) throws TranslationException {
Node arg1 = trel.getSubject();
Node arg2 = trel.getPredicate();
return "noValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ")";
}
private Object createNoValueSpecific(TripleElement trel, TranslationTarget target) throws TranslationException {
Node arg1 = trel.getSubject();
Node arg2 = trel.getPredicate();
Node arg3 = trel.getObject();
return "noValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")";
}
private Object createOnly(TripleElement trel, TranslationTarget target) throws TranslationException {
Node arg1 = trel.getSubject();
Node arg2 = trel.getPredicate();
Node arg3 = trel.getObject();
return "noValuesOtherThan(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")";
}
private Object createNotOnly(TripleElement trel, TranslationTarget target) throws TranslationException {
Node arg1 = trel.getSubject();
Node arg2 = trel.getPredicate();
Node arg3 = trel.getObject();
return "notOnlyValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")";
}
public String translateQuery(OntModel model, Query query)
throws TranslationException, InvalidNameException {
boolean isEval = false;
setTheModel(model);
setModelName(modelName);
if (query == null) {
throw new TranslationException("Invalid query: query is null!");
}
if (query.getPatterns() != null) {
GraphPatternElement gpe1 = query.getPatterns().get(0);
if (gpe1 instanceof Junction) {
Object gperhs = ((Junction)gpe1).getRhs();
if (gperhs instanceof BuiltinElement && ((BuiltinElement)gperhs).getFuncName().equalsIgnoreCase("eval")) {
isEval = true;
Object gpelhs = ((Junction)gpe1).getLhs();
if (gpelhs instanceof GraphPatternElement) {
query.getPatterns().set(0, (GraphPatternElement) gpelhs);
query.setToBeEvaluated(true);
}
}
}
}
if (query.getSparqlQueryString() != null) {
return prepareQuery(model, query.getSparqlQueryString());
}
if (query.getKeyword() == null) {
if (query.getVariables() == null) {
query.setKeyword("ask");
}
else {
query.setKeyword("select");
}
}
if (!query.getKeyword().equals("ask") && query.getVariables() == null) {
throw new TranslationException("Invalid query (" + query.toString() + "): must be a valid structure with specified variable(s).");
}
setQueryInTranslation(query);
StringBuilder sbmain = new StringBuilder();
StringBuilder sbfilter = new StringBuilder();
sbmain.append(query.getKeyword());
if (query.isDistinct()) {
sbmain.append("distinct ");
}
List<String> vars = query.getVariables();
List<GraphPatternElement> elements = query.getPatterns();
for (int i = 0; vars != null && i < vars.size(); i++) {
if (i > 0) sbmain.append(" ");
sbmain.append("?" + vars.get(i));
}
sbmain.append(" where {");
int tripleCtr = 0;
int builtinCtr = 0;
for (int i = 0; elements != null && i < elements.size(); i++) {
GraphPatternElement gpe = elements.get(i);
// need to handle or, and
if (gpe instanceof Junction) {
if (tripleCtr++ > 0) sbmain.append(" . ");
String junctionStr = junctionToQueryString((Junction)gpe, sbfilter);
sbmain.append(junctionStr);
}
else if (gpe instanceof TripleElement) {
if (tripleCtr++ > 0) sbmain.append(" . ");
String jenaStr = graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE);
sbmain.append(jenaStr);
}
else if (gpe instanceof BuiltinElement) {
// if (builtinCtr++ > 0) {
// sbfilter.append(" && ");
// else {
// sbfilter.append("FILTER (");
// sbfilter.append(graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_FILTER));
// the filter string will be added in the method
graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE);
}
}
if (sbfilter.length() > 0) {
sbfilter.insert(0, "FILTER ("); sbfilter.append(")");
if (!sbmain.toString().trim().endsWith(".")) {
sbmain.append(" . ");
}
sbmain.append(sbfilter.toString());
}
sbmain.append("}");
if (query.getOrderBy() != null) {
List<OrderingPair> ops = query.getOrderBy();
if (ops.size() > 0) {
sbmain.append(" order by");
for (int i = 0; i < ops.size(); i++) {
sbmain.append(" ");
OrderingPair op = ops.get(i);
boolean explicitOrder = false;
if (op.getOrder() != null && op.getOrder().equals(Order.DESC)) {
sbmain.append("DESC(");
explicitOrder = true;
}
sbmain.append("?");
sbmain.append(op.getVariable());
if (explicitOrder) {
sbmain.append(")");
}
}
}
}
return prepareQuery(model, sbmain.toString());
}
/**
* Convert a junction to a query string. Filter stuff goes to the sbfilter StringBuilder, triple stuff gets returned.
*
* @param gpe
* @param sbfilter
* @return
* @throws TranslationException
*/
private String junctionToQueryString(Junction gpe, StringBuilder sbfilter) throws TranslationException {
// We have a junction, could be one of
// 1. triple junction filter, e.g., ... x prop y and y < 3
// 2. filter junction triple, e.g., ... y < 3 and x prop z
// 3. filter junction filter, e.g., ... x > 0 and x < 3
// 4. triple junction triple, e.g., ... x prop1 y and y prop2 z
JunctionType jtype = ((Junction)gpe).getJunctionType();
boolean lhsFilter = false;
boolean rhsFilter = false;
Object lhsobj = ((Junction)gpe).getLhs();
Object rhsobj = ((Junction)gpe).getRhs();
if (lhsobj instanceof BuiltinElement) {
lhsFilter = true;
}
if (rhsobj instanceof BuiltinElement) {
rhsFilter = true;
}
StringBuilder sbjunct = new StringBuilder();
String connector = null;
boolean wrapInCurleyBrackets = false;
if (lhsFilter || rhsFilter) {
if (lhsFilter && rhsFilter) {
// this is a junction within the filter, case 3
connector = junctionToFilterString(jtype);
sbfilter.append("(");
graphPatternElementToJenaQueryString((GraphPatternElement)lhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE);
sbfilter.append(connector);
graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE);
sbfilter.append(")");
}
else {
// Note: junctions between a triple and a built-in filter are ignored, cases 1 & 2
if (lhsFilter) {
graphPatternElementToJenaQueryString((GraphPatternElement)lhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE);
if (rhsobj instanceof BuiltinElement) {
sbfilter.append(junctionToFilterString(jtype));
}
sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE));
}
else { // rhsFilter
sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) lhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE));
if (lhsobj instanceof BuiltinElement) {
sbfilter.append(junctionToFilterString(jtype));
}
graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE);
}
}
}
else {
// this is a junction between triple patterns, case 4
if (jtype.equals(JunctionType.Conj)) { // (and)
connector = " . ";
}
else {
// must be Disj (or)
wrapInCurleyBrackets = true;
connector = "} UNION {";
}
if (wrapInCurleyBrackets) {
sbjunct.append("{");
}
sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) lhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE));
sbjunct.append(connector);
sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE));
if (wrapInCurleyBrackets) {
sbjunct.append("}");
}
}
return sbjunct.toString();
}
private String junctionToFilterString(JunctionType jtype) {
if (jtype.equals(JunctionType.Conj)) { // and
return " && ";
}
else {
// must be Disj (or)
return " || ";
}
}
private String builtinToFilterFunctionString(BuiltinElement gpe) throws TranslationException {
List<Node> args = gpe.getArguments();
if (args.size() < 2) {
throw new TranslationException("Filter '" + gpe.getFuncName() + "' must take two arguments.");
}
if (gpe.getFuncType().equals(BuiltinType.Equal)) {
gpe.setFuncName("="); // there are several possibilities here that all map to "=" in SPARQL
}
if (gpe.getFuncType().equals(BuiltinType.Not)) {
gpe.setFuncName("!=");
}
switch(gpe.getFuncType()) {
case Equal:
case GT:
case GTE:
case LT:
case LTE:
case NotEqual:
case Not:
String filter = nodeToString(args.get(0), TranslationTarget.QUERY_FILTER) + " " + gpe.getFuncName() + " " + nodeToString(args.get(1), TranslationTarget.QUERY_FILTER);
return filter; // nodeToString(args.get(0), TranslationTarget.QUERY_FILTER) + " " + gpe.getFuncName() + " " + nodeToString(args.get(1), TranslationTarget.QUERY_FILTER);
default:
throw new TranslationException("Unhandled filter type: " + gpe.getFuncName());
}
}
private boolean translateAndSaveRules(OntModel model, List<Rule> ruleList, String modelName, String filename) throws TranslationException, IOException {
if (ruleList == null || ruleList.size() < 1) {
throw new TranslationException("No rules provided to rule translation.");
}
// Open file and output header and imports
File ruleFile = new File(filename);
if (ruleFile.exists()) {
boolean success = ruleFile.delete();
if (!success) {
addError("Failed to delete old rules file '" + filename + "'.");
logger.error("Failed to delete old rule file '" + filename + "'.");
if (ruleList == null || ruleList.size() == 0) {
setTheModel(null);
setModelName(null);
return false;
}
// else don't return--maybe we can open it for output anyway
}
}
String jenaRules = translateAndSaveRules(model, ruleList, modelName) ;
SadlUtils su = new SadlUtils();
su.stringToFile(ruleFile, jenaRules, true);
return (errors== null || errors.size() == 0) ? true : false;
}
/**
* Save the
* @param model
* @param ruleList
* @param modelName
* @return
* @throws TranslationException
*/
public String translateAndSaveRules(OntModel model, List<Rule> ruleList, String modelName) throws TranslationException {
if (ruleList == null) {
return null;
}
setTheModel(model);
setModelName(modelName);
StringBuilder contents = new StringBuilder();
contents.append("# Jena Rules file generated by SADL IDE -- Do not edit! Edit the SADL model and regenerate.\n");
contents.append("# Created from SADL model '" + modelName + "'\n\n");
StringBuilder ruleContent = new StringBuilder();
for (int i = 0; i < ruleList.size(); i++) {
Rule rule = ruleList.get(i);
ruleContent.append(translateRule(model, rule));
ruleContent.append("\n");
}
// now add prefix info to rule file output
Iterator<String> itr2 = prefixes.keySet().iterator();
while (itr2.hasNext()) {
String prefix = itr2.next();
String ns = prefixes.get(prefix);
contents.append("@prefix ");
contents.append(prefix);
contents.append(": <");
contents.append(ns);
contents.append(">\n");
}
contents.append("\n");
// Because rule files are loaded for each sub-model, there is no need to put in includes
if (ruleContent.length() > 0) {
contents.append(ruleContent);
}
setTheModel(null);
setModelName(null);
return contents.toString();
}
public String modelNsToRuleNs(String modelNs) {
return modelNs + ".rules";
}
/**
* Convert GraphPatternElement to String in the context of a Rule
*
* @param gpe
* @return
* @throws TranslationException
*/
private String graphPatternElementToJenaRuleString(GraphPatternElement gpe, RulePart rulePart) throws TranslationException {
StringBuilder sb = null;
if (gpe instanceof TripleElement) {
if (!((TripleElement)gpe).getModifierType().equals(TripleModifierType.None)) {
sb = new StringBuilder();
TripleModifierType type = ((TripleElement)gpe).getModifierType();
if (type.equals(TripleModifierType.Not)) {
sb.append("noValue(");
}
else if (type.equals(TripleModifierType.Only)) {
sb.append("notOnlyValue(");
}
else {
sb.append("noValueOtherThan(");
}
sb.append(nodeToString(((TripleElement)gpe).getSubject(),TranslationTarget.RULE_BUILTIN));
sb.append(", ");
Node pn = ((TripleElement)gpe).getPredicate();
checkPredicateSpecial(pn);
sb.append(nodeToString(pn, TranslationTarget.RULE_BUILTIN));
if (!(((TripleElement)gpe).getObject() instanceof KnownNode)) {
sb.append(", ");
sb.append(nodeToString(((TripleElement)gpe).getObject(), TranslationTarget.RULE_BUILTIN));
}
sb.append(")");
}
else {
sb = tripleElementToRawJenaString((TripleElement) gpe, TranslationTarget.RULE_TRIPLE, rulePart, null); // 2/16/2011 false);
}
}
else if (gpe instanceof BuiltinElement) {
sb = new StringBuilder();
List<Node> args = ((BuiltinElement)gpe).getArguments();
sb.append(builtinTypeToString((BuiltinElement)gpe));
sb.append("(");
for (int i = 0; args != null && i < args.size(); i++) {
Node arg = args.get(i);
if (i > 0) sb.append(", ");
if (arg instanceof ProxyNode) {
Object pfor = ((ProxyNode)arg).getProxyFor();
if (pfor instanceof GraphPatternElement) {
sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) pfor, rulePart));
}
else {
throw new TranslationException("Non-graph element proxy-for in ProxyNode '" + arg.toFullyQualifiedString() + "'");
}
}
else {
sb.append(nodeToString(arg, TranslationTarget.RULE_BUILTIN));
}
}
sb.append(")");
}
else if (gpe instanceof Junction) {
sb = new StringBuilder();
JunctionType jtype = ((Junction)gpe).getJunctionType();
if (jtype.equals(JunctionType.Conj)) {
Object lhs = ((Junction)gpe).getLhs();
if (lhs instanceof List<?>) {
sb.append(graphPatternElementsToJenaRuleString((List<GraphPatternElement>)lhs, rulePart));
}
else if (lhs instanceof GraphPatternElement) {
sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) lhs, rulePart));
}
else {
throw new TranslationException("Unexpected junction lhs type: " + lhs.getClass());
}
Object rhs = ((Junction)gpe).getRhs();
if (rhs instanceof List<?>) {
sb.append(", ");
sb.append(graphPatternElementsToJenaRuleString((List<GraphPatternElement>)rhs, rulePart));
}
else if (rhs instanceof GraphPatternElement) {
sb.append(", ");
sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) rhs, rulePart));
}
else {
throw new TranslationException("Unexpected junction rhs type: " + rhs.getClass());
}
}
else {
System.err.println("Encountered unhandled OR in rule '" + ruleInTranslation.getRuleName() + "'");
// throw new TranslationException("Jena rules do not currently support disjunction (OR).");
}
}
else if (gpe instanceof NegatedExistentialQuantifier) {
throw new TranslationException("Existential quantification with negation is not supported by the Jena reasoner.");
}
else {
throw new TranslationException("GraphPatternElement '" + gpe.toString() + "' cannot be translated to Jena rule.");
}
return sb.toString();
}
private String graphPatternElementToJenaQueryString(GraphPatternElement gpe, StringBuilder sbfilter,
TranslationTarget target, RulePart rulePart) throws TranslationException {
if (gpe instanceof TripleElement) {
StringBuilder sb = tripleElementToRawJenaString((TripleElement) gpe, target, rulePart, sbfilter);
return sb.toString();
}
else if (gpe instanceof Junction) {
String junctStr = junctionToQueryString((Junction)gpe, sbfilter);
return junctStr;
}
else if (gpe instanceof BuiltinElement) {
String bistr = builtinToFilterFunctionString((BuiltinElement)gpe);
if (sbfilter.length() > 0) {
String tmp = sbfilter.toString().trim();
if (!tmp.endsWith("(") && !tmp.endsWith("&&") && !tmp.endsWith("||")) {
sbfilter.append(" && ");
}
}
sbfilter.append(bistr);
return null;
}
else {
throw new TranslationException("GraphPatternElement '" + gpe.toString() + "' not yet handled in Jena query.");
}
}
/**
* Method to convert a TripleElement to a Jena String without delimiters
*
* @param gpe
* @param sbfilter
* @return
* @throws TranslationException
*/
private StringBuilder tripleElementToRawJenaString(TripleElement gpe, TranslationTarget target, RulePart rulePart, StringBuilder sbfilter) throws TranslationException {
StringBuilder sb = new StringBuilder();
Node subj = gpe.getSubject();
Node pred = gpe.getPredicate();
checkPredicateSpecial(pred);
Node obj = gpe.getObject();
boolean moveObjectToEqualityTest = false;
if (target.equals(TranslationTarget.RULE_TRIPLE)) {
sb.insert(0, '(');
}
sb.append(nodeToString(subj, target));
sb.append(" ");
sb.append(nodeToString(pred, target));
sb.append(" ");
String newVar = null;
if (rulePart.equals(RulePart.PREMISE) && target.equals(TranslationTarget.RULE_TRIPLE) && tripleHasDecimalObject(gpe)) {
// this would be a triple match on a float or double value, which is not reliable
// move the object to a separate equality test
moveObjectToEqualityTest = true;
newVar = getNewVariableForRule();
sb.append("?");
sb.append(newVar);
}
else {
if (rulePart.equals(RulePart.NOT_A_RULE)) {
if (obj instanceof KnownNode) {
newVar = "?" + getNewVariableForQuery();
if (gpe.getModifierType().equals(TripleModifierType.Not)) {
sb.append(newVar);
sb.insert(0, "OPTIONAL {");
sb.append("}");
if (sbfilter != null) {
if (sbfilter.length() > 0) {
sbfilter.append(" && ");
}
sbfilter.append("!bound(");
sbfilter.append(newVar);
sbfilter.append(")");
}
}
else {
sb.append(newVar);
}
}
else if (tripleHasDecimalObject(gpe)) {
newVar = "?" + getNewVariableForQuery();
sb.append(newVar);
if (sbfilter != null) {
if (sbfilter.length() > 0) {
sbfilter.append(" && ");
}
sbfilter.append(newVar);
if (gpe.getModifierType().equals(TripleModifierType.Not)) {
sbfilter.append(" != ");
}
else {
sbfilter.append(" = ");
}
sbfilter.append(nodeToString(obj, TranslationTarget.RULE_BUILTIN));
}
else {
sb.append(newVar);
}
}
else {
sb.append(nodeToString(obj, target));
}
}
else {
sb.append(nodeToString(obj, target));
}
}
if (target.equals(TranslationTarget.RULE_TRIPLE)) {
sb.append(")");
}
else {
// this is a query
if (gpe.getModifierType() != null && gpe.getModifierType().equals(TripleModifierType.Not)) {
// this is negation--translate into a filter on !exits
sb.insert(0, "!EXISTS { ");
sb.append(" }");
sbfilter.append(sb);
sb.setLength(0);
}
}
if (moveObjectToEqualityTest) {
// now add the equality test. (this is only for rules)
sb.append(" equal(?");
sb.append(newVar);
sb.append(", ");
sb.append(nodeToString(obj, TranslationTarget.RULE_BUILTIN));
sb.append(")");
}
return sb;
}
private String getNewVariableForRule() {
int cntr = 1;
Rule rule = getRuleInTranslation();
if (rule != null) {
String rulestr = rule.toString();
String varName;
do {
varName = "v" + cntr++;
} while (rulestr.indexOf(varName) > 0);
return varName;
}
else {
return "v1";
}
}
private String getNewVariableForQuery() {
int cntr = nextQueryVarNum;
Query query = getQueryInTranslation();
String querystr = query.toString();
String varName;
do {
varName = "v" + cntr++;
} while (querystr.indexOf(varName) > 0);
nextQueryVarNum = cntr;
return varName;
}
private boolean tripleHasDecimalObject(TripleElement gpe) {
Node pred = gpe.getPredicate();
Node obj = gpe.getObject();
if (!(obj instanceof NamedNode) && pred instanceof NamedNode && ((NamedNode)pred).getNamespace() != null) {
OntProperty prop = getTheModel().getOntProperty(((NamedNode)pred).toFullyQualifiedString());
if (prop != null && prop.isDatatypeProperty()) {
Resource rng = prop.getRange();
if (rng.toString().contains("double") || rng.toString().contains("float")) {
return true;
}
}
}
if (obj instanceof Literal) {
Object objval = ((Literal)obj).getValue();
if (objval instanceof Double || objval instanceof Float) {
return true;
}
}
return false;
}
private void checkPredicateSpecial(Node predNode) {
if (predNode instanceof NamedNode) {
if (((NamedNode)predNode).getNamespace() == null &&
((NamedNode)predNode).getName() != null &&
((NamedNode)predNode).getName().equals(RDFS.comment.getLocalName()) ) {
((NamedNode)predNode).setNamespace(RDFS.getURI());
}
}
}
private Object builtinTypeToString(BuiltinElement bin) throws TranslationException {
BuiltinType ftype = bin.getFuncType();
if (ftype.equals(BuiltinType.Divide)) {
// return "quotient";
bin.setFuncName("quotient");
}
else if (ftype.equals(BuiltinType.Equal)) {
// return "equal";
bin.setFuncName("equal");
}
else if (ftype.equals(BuiltinType.GT)) {
// return "greaterThan";
bin.setFuncName("greaterThan");
}
else if (ftype.equals(BuiltinType.GTE)) {
// return "ge";
bin.setFuncName("ge");
}
else if (ftype.equals(BuiltinType.LT)) {
// return "lessThan";
bin.setFuncName("lessThan");
}
else if (ftype.equals(BuiltinType.LTE)) {
// return "le";
bin.setFuncName("le");
}
else if (ftype.equals(BuiltinType.Minus)) {
// return "difference";
bin.setFuncName("difference");
}
else if (ftype.equals(BuiltinType.Modulus)) {
// return "mod";
bin.setFuncName("mod");
}
else if (ftype.equals(BuiltinType.Multiply)) {
// return "product";
bin.setFuncName("product");
}
else if (ftype.equals(BuiltinType.Negative)) {
// return "negative";
bin.setFuncName("negative");
}
else if (ftype.equals(BuiltinType.Not)) {
// return "noValue";
bin.setFuncName("noValue");
}
else if (ftype.equals(BuiltinType.NotEqual)) {
// return "notEqual";
bin.setFuncName("notEqual");
}
else if (ftype.equals(BuiltinType.NotOnly)) {
// return "notOnlyValue";
bin.setFuncName("notOnlyValue");
}
else if (ftype.equals(BuiltinType.Only)) {
// return "noValuesOtherThan";
bin.setFuncName("noValuesOtherThan");
}
else if (ftype.equals(BuiltinType.Plus)) {
// return "sum";
bin.setFuncName("sum");
}
else if (ftype.equals(BuiltinType.Power)) {
// return "pow";
bin.setFuncName("pow");
}
else if (ftype.equals(BuiltinType.Assign)) {
// return "assign";
bin.setFuncName("assign");
}
String builtinName = bin.getFuncName();
// Note: the order here allows any built-in which overrides the ones in Jena to be picked up preferentially
// see if it is known to the ConfigurationManager or if we can find it in the services registry
boolean status = findOrAddBuiltin(builtinName);
if (!status) {
// if not see if it is one already registered
Builtin bltin = BuiltinRegistry.theRegistry.getImplementation(builtinName);
if (bltin == null) {
logger.error("Something went wrong finding/loading Builtin '" + builtinName + "'");
addError("Unable to resolve built-in '" + builtinName + "'");
}
}
return builtinName;
}
private boolean findOrAddBuiltin(String builtinName) {
int cnt = 0;
// is it known to the ConfigurationManager?
String[] categories = new String[2];
try {
categories[0] = configurationMgr.getReasoner().getReasonerFamily();
categories[1] = IConfigurationManager.BuiltinCategory;
List<ConfigurationItem> knownBuiltins = configurationMgr.getConfiguration(categories, false);
for (int i = 0; knownBuiltins != null && i < knownBuiltins.size(); i++) {
ConfigurationItem item = knownBuiltins.get(i);
Object itemName = item.getNamedValue("name");
if (itemName != null && itemName instanceof String && ((String)itemName).equals(builtinName)) {
logger.debug("Built-in '" + builtinName + "' found in configuration.");
return true;
}
}
} catch (ConfigurationException e) {
// this is ok--new ones won't be found
// e.printStackTrace();
// logger.error("Unable to find Builtin '" + builtinName + "' in current configuration: " + e.getLocalizedMessage());
}
// Use ServiceLoader to find an implementation of Builtin that has this name
ServiceLoader<Builtin> serviceLoader = ServiceLoader.load(Builtin.class);
if( serviceLoader != null ){
logger.debug("ServiceLoader is OK");
for( Iterator<Builtin> itr = serviceLoader.iterator(); itr.hasNext() ; ){
try {
Builtin bltin = itr.next();
cnt++;
if (bltin.getName().equals(builtinName)) {
String clsname = bltin.getClass().getCanonicalName();
// TODO is there a reasonable check here?
if (1 > 0) {
if (configurationMgr instanceof IConfigurationManagerForEditing) {
ConfigurationItem newItem = new ConfigurationItem(categories);
newItem.addNameValuePair(newItem.new NameValuePair("name", builtinName, ConfigurationType.Bag));
newItem.addNameValuePair(newItem.new NameValuePair("class", clsname, ConfigurationType.Bag));
((IConfigurationManagerForEditing) configurationMgr).addConfiguration(newItem);
((IConfigurationManagerForEditing) configurationMgr).saveConfiguration();
logger.info("Built-in '" + builtinName + "' found in service registry and added to configuration.");
}
}
else {
logger.info("Built-in '" + builtinName + "' found in service registry.");
}
BuiltinRegistry.theRegistry.register(builtinName, bltin);
return true;
}
}
catch (Throwable t) {
t.printStackTrace();
logger.error(t.getLocalizedMessage());
}
}
} else {
logger.debug("ServiceLoader is null");
}
logger.debug("Failed to find Builtin with name '" + builtinName + "' after examining " + cnt + " registered Builtins.");
return false;
}
private String nodeToString(Node node, TranslationTarget target) throws TranslationException {
if (node instanceof NamedNode) {
NodeType ntype = ((NamedNode)node).getNodeType();
if (ntype.equals(NodeType.VariableNode)) {
// double-check this; if a concept was declared after reference in a rule or query
// it may have been parsed as a variable but actually be a defined concept
OntResource r = getTheModel().getOntResource(getModelName() + "#" + ((NamedNode)node).getName());
if (r == null) {
return "?" + ((NamedNode)node).getName();
}
// it appears that at time of parsing of the rule or query the named concept was not defined but
// was subsequently. Warn user of this apparent error: concepts must be defined before they are
// used in a rule or query.
String msg = "The concept '" + ((NamedNode)node).getName() + "' ";
if (ruleInTranslation != null) {
msg += "in rule '" + ruleInTranslation.getRuleName() + "' ";
}
msg += " in model '" + getModelName() + "' is used before it is defined. Please define the concept before referencing it in a query or rule.";
addError(msg);
logger.error(msg);
}
if (node instanceof RDFTypeNode) {
// registerPrefix("rdf", ""); I don't think these need an explicit prefix awc 11/23/2010
if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) {
return "<rdf:type>";
}
else {
return "rdf:type";
}
}
else {
String nts;
if (((NamedNode)node).getNamespace() != null) {
String prefix = ((NamedNode)node).getPrefix();
if (prefix != null) {
registerPrefix(prefix, ((NamedNode)node).getNamespace());
}
else {
// this must be the default namespace
((NamedNode)node).setPrefix("");
}
nts = ((NamedNode)node).getNamespace() + ((NamedNode)node).getName();
}
else {
nts = ((NamedNode)node).getName();
}
if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) {
return "<" + nts + ">";
}
else {
return nts;
}
}
}
else if (node instanceof ConstantNode) {
Literal litval = constantToLiteral((ConstantNode)node);
return literalValueToString(litval, target);
}
else if (node instanceof Literal) {
Object litObj = ((Literal)node).getValue();
return literalValueToString(litObj, target);
}
else if (node instanceof KnownNode) {
return "?" + getNewVariableForRule();
}
else if (node == null) {
throw new TranslationException("Encountered null node in nodeToString; this indicates incorrect intermediate form and should not happen");
}
else {
throw new TranslationException("Nnode '" + node.toString() + "' cannot be translated to Jena format.");
}
}
private Literal constantToLiteral(ConstantNode node) throws TranslationException {
if (node.getName().equals("PI")) {
Literal lit = new Literal();
lit.setValue(Math.PI);
lit.setOriginalText(node.getName());
return lit;
}
throw new TranslationException("Unknown constant '" + node.getName() + "' cannot be translated");
}
public static synchronized String literalValueToString(Object litObj, TranslationTarget target) {
if (litObj instanceof String) {
if (target.equals(TranslationTarget.RULE_BUILTIN)) {
return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#string";
}
else {
litObj = "\"" + litObj + "\"";
return (String)litObj;
}
}
else if (litObj instanceof Boolean) {
if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) {
return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#boolean>";
}
else {
return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#boolean";
}
}
else if (litObj instanceof Long) {
if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) {
return litObj.toString().trim();
}
else if (target.equals(TranslationTarget.QUERY_TRIPLE)) {
return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#long>";
}
else {
return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#long";
}
}
else if (litObj instanceof Integer) {
if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) {
return litObj.toString().trim();
}
else if (target.equals(TranslationTarget.QUERY_TRIPLE)) {
return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#int>";
}
else {
return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#int";
}
}
else if (litObj instanceof Double) {
if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) {
return litObj.toString().trim();
}
else if (target.equals(TranslationTarget.QUERY_TRIPLE)) {
return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#double>";
}
else {
return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#double";
}
}
else if (litObj instanceof Float) {
if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) {
return litObj.toString().trim();
}
else if (target.equals(TranslationTarget.QUERY_TRIPLE)) {
return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#float>";
}
else {
return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#float";
}
}
else {
return litObj.toString();
}
}
private void registerPrefix(String prefix, String namespace) {
if (prefix == null) {
logger.error("Prefix is null in registerPrefix");
}
if (!prefixes.containsKey(prefix)) {
prefixes.put(prefix, namespace);
}
}
protected String createDerivedFilename(String filename, String newext) {
int lastDot = filename.lastIndexOf('.');
if (lastDot > 0) {
return filename.substring(0, lastDot + 1) + newext;
}
return filename + "." + newext;
}
/**
* Method to prepare a query by expanding the URIs of concepts to be complete URIs
*
* @param model
* @param q
* @return
* @throws InvalidNameException
*/
public String prepareQuery(OntModel model, String q) throws InvalidNameException {
int openBracket = q.indexOf('<');
if (openBracket > 0) {
int closeBracket = q.indexOf('>', openBracket);
if (closeBracket <= openBracket) {
// this could be a comparison in a FILTER...
return q;
}
String before = q.substring(0, openBracket + 1);
String url = q.substring(openBracket + 1, closeBracket);
String rest = q.substring(closeBracket);
rest = prepareQuery(model, rest);
if (url.indexOf('
return before + url + rest;
}
else if (url.indexOf(':') > 0) {
url = expandPrefixedUrl(model, url);
}
else if (isValidLocalName(url)){
url = findNameNs(model, url);
}
return before + url + rest;
}
return q;
}
protected boolean isValidLocalName(String name) {
if (name == null || name.indexOf(" ") >= 0 || name.indexOf("?") >= 0) {
return false;
}
return true;
}
/**
* This method takes an OntModel and a concept name and tries to find the concept in the model or
* one of the models imported by the model.
*
* @param model -- the OntModel at the root of the search
* @param name -- the concept name
* @return -- the fuly-qualified name of the concept as found in some model
*
* @throws InvalidNameException -- the concept was not found
*/
public static synchronized String findNameNs(OntModel model, String name) throws InvalidNameException {
String uri = findConceptInSomeModel(model, name);
if (uri != null) {
return uri;
}
Iterator<String> impitr = model.listImportedOntologyURIs(true).iterator();
while (impitr.hasNext()) {
String impuri = impitr.next();
if (!impuri.endsWith("
impuri += "
}
impuri = getUriInModel(model, impuri, name);
if (impuri != null) {
logger.debug("found concept with URI '" + impuri + "'");
return impuri;
}
}
ExtendedIterator<Ontology> oitr = model.listOntologies();
while (oitr.hasNext()) {
Ontology onto = oitr.next();
if (onto != null) {
ExtendedIterator<OntResource> importsItr = onto.listImports();
while (importsItr.hasNext()) {
OntResource or = importsItr.next();
String ns = or.getURI();
if (!ns.endsWith("
ns = ns + "
}
String muri = getUriInModel(model, or.getURI(), name);
if (muri != null) {
logger.debug("found concept with URI '" + muri + "'");
return muri;
}
}
// try this ontology--maybe it wasn't in the map used by findConceptInSomeModel
String muri = getUriInModel(model, onto.getURI() + "#", name);
if (muri != null) {
logger.debug("found concept with URI '" + muri + "'");
return muri;
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Failed to find '" + name + "' in any model.");
ByteArrayOutputStream sos = new ByteArrayOutputStream();
model.write(sos);
logger.debug(sos.toString());
}
throw new InvalidNameException("'" + name + "' not found in any model.");
}
private static synchronized String findConceptInSomeModel(OntModel model, String name) {
Map<String, String> map = model.getNsPrefixMap();
Iterator<String> uriitr = map.values().iterator();
while (uriitr.hasNext()) {
String ns = uriitr.next();
String uri = getUriInModel(model, ns, name);
if (uri != null) {
logger.debug("found concept with URI '" + uri + "'");
return uri;
}
}
logger.debug("did not find concept with name '" + name + "'");
return null;
}
private static synchronized String getUriInModel(OntModel model, String ns, String name) {
Resource r = model.getAnnotationProperty(ns + name);
if (r != null) {
return r.getURI();
}
r = model.getDatatypeProperty(ns + name);
if (r != null) {
return r.getURI();
}
r = model.getObjectProperty(ns + name);
if (r != null) {
return r.getURI();
}
r = model.getOntClass(ns + name);
if (r != null) {
return r.getURI();
}
r = model.getIndividual(ns + name);
if (r != null) {
return r.getURI();
}
if (RDF.type.getURI().equals(ns + name)) {
return RDF.type.getURI();
}
return null;
}
protected String expandPrefixedUrl(OntModel model, String name) {
String prefix = name.substring(0, name.indexOf(':'));
String lname = name.substring(name.indexOf(':') + 1);
String ns = model.getNsPrefixURI(prefix);
if (ns != null) {
name = ns + lname;
}
return name;
}
protected List<ModelError> addError(String msg) {
if (errors == null) {
errors = new ArrayList<ModelError>();
}
errors.add(new ModelError(msg, ErrorType.ERROR));
return errors;
}
protected List<ModelError> addError(String msg, ErrorType errType) {
if (errors == null) {
errors = new ArrayList<ModelError>();
}
errors.add(new ModelError(msg, errType));
return errors;
}
protected List<ModelError> addError(ModelError err) {
if (errors == null) {
errors = new ArrayList<ModelError>();
}
errors.add(err);
return errors;
}
public String getReasonerFamily() {
return ReasonerFamily;
}
public String getConfigurationCategory() {
return TranslatorCategory;
}
private void setRuleInTranslation(Rule ruleInTranslation) {
this.ruleInTranslation = ruleInTranslation;
}
private Rule getRuleInTranslation() {
return ruleInTranslation;
}
private void setTheModel(OntModel theModel) {
this.theModel = theModel;
}
private OntModel getTheModel() {
return theModel;
}
public Map<String, ConfigurationOption> getTranslatorConfigurationOptions() {
// This translator doesn't have any configuration items
return null;
}
public boolean configure(ConfigurationItem configItem) {
// This translator doesn't have any configuration items
return false;
}
public boolean configure(List<ConfigurationItem> configItems) {
// This translator doesn't have any configuration items
return false;
}
public List<ConfigurationItem> discoverOptimalConfiguration(
String translationFolder, String modelName, IConfigurationManager configMgr, List<Query> queries) throws FunctionNotSupportedException, ConfigurationException, TranslationException {
throw new FunctionNotSupportedException(this.getClass().getCanonicalName() + " does not support discovery of optimal configuration.");
}
private Query getQueryInTranslation() {
return queryInTranslation;
}
private void setQueryInTranslation(Query queryInTranslation) {
this.queryInTranslation = queryInTranslation;
}
public void setConfigurationManager(IConfigurationManager configMgr) throws ConfigurationException {
// if ((configMgr instanceof IConfigurationManagerForEditing)) {
// ((IConfigurationManagerForEditing) configMgr).setTranslatorClassName(this.getClass().getCanonicalName());
configurationMgr = configMgr;
}
private String getModelName() {
return modelName;
}
private void setModelName(String modelName) {
this.modelName = modelName;
}
@Override
public List<ModelError> translateAndSaveModelWithOtherStructure(
OntModel model, Object otherStructure, String translationFolder,
String modelName, List<String> orderedImports, String saveFilename) throws TranslationException,
IOException, URISyntaxException {
if (otherStructure instanceof List<?>) {
OntModel eqModel = null; // get model
// remove all equations in this namespace
for (Object os: (List<?>)otherStructure) {
if (os instanceof Equation) {
addError(new ModelError(this.getClass().getCanonicalName() + " does not currently translate equations", ErrorType.ERROR));
// add equations
// System.out.println("Jena translator ready to save equation '" + os.toString() + "'");
}
}
// save eqModel
}
return (errors != null && errors.size() > 0) ? errors : null;
}
public List<ModelError> validateRule(com.ge.research.sadl.model.gp.Rule rule) {
List<ModelError> errors = null;
// conclusion binding tests
List<GraphPatternElement> thens = rule.getThens();
for (int i = 0; thens != null && i < thens.size(); i++) {
GraphPatternElement gpe = thens.get(i);
if (gpe instanceof BuiltinElement) {
List<Node> args = ((BuiltinElement)gpe).getArguments();
if (args == null) {
ModelError me = new ModelError("Built-in '" + ((BuiltinElement)gpe).getFuncName() +
"' with no arguments not legal in rule conclusion", ErrorType.ERROR);
if (errors == null) {
errors = new ArrayList<ModelError>();
}
errors.add(me);
}
else {
for (int j = 0; j < args.size(); j++) {
Node arg = args.get(j);
if (arg instanceof VariableNode) {
if (!variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, arg) &&
!variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, arg)) {
ModelError me = new ModelError("Conclusion built-in '" + ((BuiltinElement)gpe).getFuncName() +
"', variable argument '" + arg.toString() + "' is not bound in rule premises", ErrorType.ERROR);
if (errors == null) {
errors = new ArrayList<ModelError>();
}
errors.add(me);
}
}
}
}
}
else if (gpe instanceof TripleElement) {
if (((TripleElement)gpe).getSubject() instanceof VariableNode &&
!variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, ((TripleElement)gpe).getSubject())
&& !variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, ((TripleElement)gpe).getSubject())) {
ModelError me = new ModelError("Subject of conclusion triple '" + gpe.toString() +
"' is not bound in rule premises", ErrorType.ERROR);
addError(me);
}
if (((TripleElement)gpe).getObject() instanceof VariableNode &&
!variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, ((TripleElement)gpe).getObject())
&& !variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, ((TripleElement)gpe).getObject())) {
ModelError me = new ModelError("Object of conclusion triple '" + gpe.toString() +
"' is not bound in rule premises", ErrorType.ERROR);
if (errors == null) {
errors = new ArrayList<ModelError>();
}
errors.add(me);
}
}
}
return errors;
}
private Map<String, NamedNode> getTypedVars(com.ge.research.sadl.model.gp.Rule rule) {
Map<String, NamedNode> results = getTypedVars(rule.getGivens());
Map<String, NamedNode> moreResults = getTypedVars(rule.getIfs());
if (moreResults != null) {
if (results == null) {
results = moreResults;
}
else {
results.putAll(moreResults);
}
}
moreResults = getTypedVars(rule.getThens());
if (moreResults != null) {
if (results == null) {
results = moreResults;
}
else {
results.putAll(moreResults);
}
}
return results;
}
private Map<String, NamedNode> getTypedVars(List<GraphPatternElement> gpes) {
Map<String, NamedNode> results = null;
for (int i = 0; gpes != null && i < gpes.size(); i++) {
GraphPatternElement gpe = gpes.get(i);
if (gpe instanceof TripleElement &&
(((TripleElement)gpe).getModifierType() == null ||
((TripleElement)gpe).getModifierType().equals(TripleModifierType.None) ||
((TripleElement)gpe).getModifierType().equals(TripleModifierType.Not)) &&
((TripleElement)gpe).getSubject() instanceof VariableNode &&
((TripleElement)gpe).getPredicate() instanceof RDFTypeNode &&
((TripleElement)gpe).getObject() instanceof NamedNode) {
if (results == null) {
results = new HashMap<String, NamedNode>();
}
String varName = ((VariableNode)((TripleElement)gpe).getSubject()).getName();
NamedNode varType = (NamedNode) ((TripleElement)gpe).getObject();
if (results.containsKey(varName)) {
NamedNode nn = results.get(varName);
if (!nn.equals(varType) && !(nn instanceof VariableNode || varType instanceof VariableNode)) {
addError(new ModelError("Variable '" + varName + "' is typed more than once in the rule.", ErrorType.WARNING));
}
}
results.put(varName, varType);
}
else if (gpe instanceof Junction) {
Object lobj = ((Junction)gpe).getLhs();
Object robj = ((Junction)gpe).getRhs();
if (lobj instanceof GraphPatternElement || robj instanceof GraphPatternElement) {
List<GraphPatternElement> junctgpes = new ArrayList<GraphPatternElement>();
if (lobj instanceof GraphPatternElement) {
junctgpes.add((GraphPatternElement) lobj);
}
if (robj instanceof GraphPatternElement) {
junctgpes.add((GraphPatternElement) robj);
}
if (results == null) {
results = getTypedVars(junctgpes);
}
else {
Map<String, NamedNode> moreresults = getTypedVars(junctgpes);
if (moreresults != null) {
results.putAll(moreresults);
}
}
}
}
}
return results;
}
/**
* This method checks the list of GraphPatternElements to see if the specified variable is bound in these elements
*
* @param gpes - list of GraphPatternElements to check
* @param startingIndex - where to start in the list
* @param gp - the element in which this variable appears
* @param boundIfEqual - use the current element for test?
* @param matchMustBeAfter - must the binding be after the current element
* @param v - the variable Node being checked
* @return - true if the variable is bound else false
*/
public boolean variableIsBoundInOtherElement(List<GraphPatternElement> gpes, int startingIndex, GraphPatternElement gp,
boolean boundIfEqual, boolean matchMustBeAfter, Node v) {
boolean reachedSame = false;
for (int i = startingIndex; gpes != null && i < gpes.size(); i++) {
GraphPatternElement gpe = gpes.get(i);
while (gpe != null) {
boolean same = gp == null ? false : gp.equals(gpe);
if (same) {
reachedSame = true;
}
boolean okToTest = false;
if (matchMustBeAfter && reachedSame && !same) {
okToTest = true;
}
if (!matchMustBeAfter && (!same || (same && boundIfEqual))) {
okToTest = true;
}
if (okToTest && variableIsBound(gpe, v)) {
return true;
}
gpe = gpe.getNext();
}
}
return false;
}
private boolean variableIsBound(GraphPatternElement gpe, Node v) {
if (gpe instanceof TripleElement) {
if ((((TripleElement)gpe).getSubject() != null &&((TripleElement)gpe).getSubject().equals(v)) ||
(((TripleElement)gpe).getObject() != null && ((TripleElement)gpe).getObject().equals(v))) {
return true;
}
}
else if (gpe instanceof BuiltinElement) {
List<Node> args = ((BuiltinElement)gpe).getArguments();
// TODO built-ins can actually have more than the last argument as output, but we can only tell this
// if we have special knowledge of the builtin. Current SADL grammar doesn't allow this to occur.
if (args != null && args.get(args.size() - 1) != null && args.get(args.size() - 1).equals(v)) {
return true;
}
}
else if (gpe instanceof Junction) {
Object lhsobj = ((Junction)gpe).getLhs();
if (lhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)lhsobj, v)) {
return true;
}
else if (lhsobj instanceof VariableNode && ((VariableNode)lhsobj).equals(v)) {
return true;
}
Object rhsobj = ((Junction)gpe).getRhs();
if (rhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)rhsobj, v)) {
return true;
}
else if (rhsobj instanceof VariableNode && ((VariableNode)rhsobj).equals(v)) {
return true;
}
}
return false;
}
@Override
public String translateEquation(OntModel model, Equation equation) throws TranslationException {
throw new TranslationException("Equation translation not yet implemented in " + this.getClass().getCanonicalName());
}
@Override
public String getBuiltinFunctionModel(){
StringBuilder sb = new StringBuilder();
sb.append("uri \"");
sb.append(SadlConstants.SADL_BUILTIN_FUNCTIONS_URI);
sb.append("\" alias ");
sb.append(SadlConstants.SADL_BUILTIN_FUNCTIONS_ALIAS);
sb.append(".\n\n");
return sb.toString();
}
@Override
public boolean isBuiltinFunction(String builtinName){
// is it known to the ConfigurationManager?
String[] categories = new String[2];
try {
categories[0] = configurationMgr.getReasoner().getReasonerFamily();
categories[1] = IConfigurationManager.BuiltinCategory;
List<ConfigurationItem> knownBuiltins = configurationMgr.getConfiguration(categories, false);
if (knownBuiltins != null) {
for (ConfigurationItem item : knownBuiltins) {
Object itemName = item.getNamedValue("name");
if (itemName != null && itemName instanceof String && ((String)itemName).equals(builtinName)) {
return true;
}
}
}
} catch (ConfigurationException e) {
// this is ok--one more check to go.
}
// Use ServiceLoader to find an implementation of Builtin that has this name
ServiceLoader<Builtin> serviceLoader = ServiceLoader.load(Builtin.class);
if( serviceLoader != null ){
for( Iterator<Builtin> itr = serviceLoader.iterator(); itr.hasNext() ; ){
try {
Builtin bltin = itr.next();
if (bltin.getName().equals(builtinName)) {
return true;
}
}
catch (Throwable t) {
t.printStackTrace();
logger.error(t.getLocalizedMessage());
}
}
}
return false;
}
@Override
public Enum isBuiltinFunctionTypeCheckingAvailable(){
return SadlConstants.SADL_BUILTIN_FUNCTIONS_TYPE_CHECKING_AVAILABILITY.NAME_ONLY;
}
}
|
package org.xwiki.tool.enforcer;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
/**
* Performs checks on the type specified for dependencies in pom.xml files. For example in XWiki Standard we want to
* prevent extension with package {@code jar} and {@code webjar} to depend on {@code xar} extensions. To achieve this
* you would use:
*
* <pre>
* <code>
* <rules>
* <validateDependencyVersion implementation="org.xwiki.tool.enforcer.BannedDependencyType">
* <projectPackaging>jar</projectPackaging>
* <dependencyType>xar</dependencyType>
* </validateDependencyVersion>
* <validateDependencyVersion implementation="org.xwiki.tool.enforcer.BannedDependencyType">
* <projectPackaging>webjar</projectPackaging>
* <dependencyType>xar</dependencyType>
* </validateDependencyVersion>
* </rules>
* </code>
* </pre>
*
* @version $Id$
* @since 14.5RC1
* @since 14.4.3
* @since 13.10.8
*/
public class BannedDependencyType extends AbstractPomCheck
{
/**
* The packaging of the project to check.
*/
private String projectPackaging;
private String dependencyType;
@Override
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException
{
Model model = getModel(helper);
if (this.projectPackaging == null || model.getPackaging().equals(projectPackaging)) {
for (Dependency dependency : model.getDependencies()) {
if (isRuntime(dependency) && getType(dependency).equals(this.dependencyType)) {
StringBuilder builder = new StringBuilder("Found dependency with banned type [");
builder.append(this.dependencyType);
builder.append("]");
if (this.projectPackaging != null) {
builder.append(" for a project with packaging [");
builder.append(this.projectPackaging);
builder.append("]");
}
builder.append(": ");
builder.append(dependency);
throw new EnforcerRuleException(builder.toString());
}
}
}
}
private boolean isRuntime(Dependency dependency)
{
return dependency.getScope() == null || dependency.getScope().equals("runtime");
}
private String getType(Dependency dependency)
{
return dependency.getType() != null ? dependency.getType() : "jar";
}
}
|
package org.csstudio.archive.common.service.mysqlimpl.sample;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.csstudio.archive.common.service.ArchiveConnectionException;
import org.csstudio.archive.common.service.channel.ArchiveChannelId;
import org.csstudio.archive.common.service.channel.IArchiveChannel;
import org.csstudio.archive.common.service.controlsystem.IArchiveControlSystem;
import org.csstudio.archive.common.service.mysqlimpl.batch.BatchQueueHandlerSupport;
import org.csstudio.archive.common.service.mysqlimpl.channel.IArchiveChannelDao;
import org.csstudio.archive.common.service.mysqlimpl.dao.AbstractArchiveDao;
import org.csstudio.archive.common.service.mysqlimpl.dao.ArchiveConnectionHandler;
import org.csstudio.archive.common.service.mysqlimpl.dao.ArchiveDaoException;
import org.csstudio.archive.common.service.mysqlimpl.persistengine.PersistEngineDataManager;
import org.csstudio.archive.common.service.mysqlimpl.requesttypes.DesyArchiveRequestType;
import org.csstudio.archive.common.service.sample.ArchiveMinMaxSample;
import org.csstudio.archive.common.service.sample.IArchiveMinMaxSample;
import org.csstudio.archive.common.service.sample.IArchiveSample;
import org.csstudio.archive.common.service.sample.SampleMinMaxAggregator;
import org.csstudio.archive.common.service.util.ArchiveTypeConversionSupport;
import org.csstudio.domain.desy.epics.typesupport.EpicsSystemVariableSupport;
import org.csstudio.domain.desy.system.ControlSystem;
import org.csstudio.domain.desy.system.ISystemVariable;
import org.csstudio.domain.desy.system.SystemVariableSupport;
import org.csstudio.domain.desy.time.TimeInstant;
import org.csstudio.domain.desy.time.TimeInstant.TimeInstantBuilder;
import org.csstudio.domain.desy.typesupport.BaseTypeConversionSupport;
import org.csstudio.domain.desy.typesupport.TypeSupportException;
import org.joda.time.Duration;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
/**
* Archive sample dao implementation.
*
* @author bknerr
* @since 11.11.2010
*/
public class ArchiveSampleDaoImpl extends AbstractArchiveDao implements IArchiveSampleDao {
public static final String TAB_SAMPLE = "sample";
public static final String TAB_SAMPLE_M = "sample_m";
public static final String TAB_SAMPLE_H = "sample_h";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_CHANNEL_ID = "channel_id";
public static final String COLUMN_VALUE = "value";
public static final String COLUMN_AVG = "avg_val";
public static final String COLUMN_MIN = "min_val";
public static final String COLUMN_MAX = "max_val";
private static final String ARCH_TABLE_PLACEHOLDER = "<arch.table>";
private static final String RETRIEVAL_FAILED = "Sample retrieval from archive failed.";
private static final String SELECT_RAW_PREFIX =
"SELECT " + Joiner.on(",").join(COLUMN_CHANNEL_ID, COLUMN_TIME, COLUMN_VALUE) + " ";
private final String _selectSamplesStmt =
SELECT_RAW_PREFIX +
"FROM " + getDatabaseName() + "." + ARCH_TABLE_PLACEHOLDER + " WHERE " + COLUMN_CHANNEL_ID + "=? " +
"AND " + COLUMN_TIME + " BETWEEN ? AND ?";
private final String _selectOptSamplesStmt =
"SELECT " + Joiner.on(",").join(COLUMN_CHANNEL_ID, COLUMN_TIME, COLUMN_AVG, COLUMN_MIN, COLUMN_MAX) + " " +
"FROM " + getDatabaseName() + "."+ ARCH_TABLE_PLACEHOLDER + " WHERE " + COLUMN_CHANNEL_ID + "=? " +
"AND " + COLUMN_TIME + " BETWEEN ? AND ?";
private final String _selectLatestSampleBeforeTimeStmt =
SELECT_RAW_PREFIX +
"FROM " + getDatabaseName() + "." + TAB_SAMPLE + " WHERE " + COLUMN_CHANNEL_ID + "=? " +
"AND " + COLUMN_TIME + "<? ORDER BY " + COLUMN_TIME + " DESC LIMIT 1";
private final Map<ArchiveChannelId, SampleMinMaxAggregator> _reducedDataMapForMinutes =
Maps.newConcurrentMap();
private final Map<ArchiveChannelId, SampleMinMaxAggregator> _reducedDataMapForHours =
Maps.newConcurrentMap();
private final IArchiveChannelDao _channelDao;
/**
* Constructor.
*/
@Inject
public ArchiveSampleDaoImpl(@Nonnull final ArchiveConnectionHandler handler,
@Nonnull final PersistEngineDataManager persister,
@Nonnull final IArchiveChannelDao channelDao) {
super(handler, persister);
_channelDao = channelDao;
ArchiveTypeConversionSupport.install();
EpicsSystemVariableSupport.install();
BatchQueueHandlerSupport.installHandlerIfNotExists(new ArchiveSampleBatchQueueHandler(getDatabaseName()));
BatchQueueHandlerSupport.installHandlerIfNotExists(new MinuteReducedDataSampleBatchQueueHandler(getDatabaseName()));
BatchQueueHandlerSupport.installHandlerIfNotExists(new HourReducedDataSampleBatchQueueHandler(getDatabaseName()));
}
/**
* {@inheritDoc}
*/
@Override
public <V extends Serializable, T extends ISystemVariable<V>>
void createSamples(@Nonnull final Collection<IArchiveSample<V, T>> samples) throws ArchiveDaoException {
try {
getEngineMgr().submitToBatch(samples);
final List<? extends AbstractReducedDataSample> minuteSamples;
minuteSamples = generatePerMinuteSamples(samples, _reducedDataMapForMinutes);
if (minuteSamples.isEmpty()) {
return;
}
getEngineMgr().submitToBatch(minuteSamples);
final List<? extends AbstractReducedDataSample> hourSamples =
generatePerHourSamples(minuteSamples, _reducedDataMapForHours);
if (hourSamples.isEmpty()) {
return;
}
getEngineMgr().submitToBatch(hourSamples);
} catch (final TypeSupportException e) {
throw new ArchiveDaoException("Type support for sample type could not be found.", e);
}
}
@Nonnull
private List<? extends AbstractReducedDataSample>
generatePerHourSamples(@Nonnull final Collection<? extends AbstractReducedDataSample> samples,
@Nonnull final Map<ArchiveChannelId, SampleMinMaxAggregator> aggregatorMap) throws ArchiveDaoException {
if (samples.isEmpty()) {
return Collections.emptyList();
}
final List<HourReducedDataSample> hourSamples = Lists.newLinkedList();
for (final AbstractReducedDataSample sample : samples) {
final ArchiveChannelId channelId = sample.getChannelId();
final Double newValue = sample.getAvg();
final Double minValue = sample.getMin();
final Double maxValue = sample.getMax();
final TimeInstant time = sample.getTimestamp();
final SampleMinMaxAggregator agg = retrieveAndInitializeAggregator(channelId,
aggregatorMap,
newValue,
minValue,
maxValue,
time);
processHourSampleOnTimeCondition(hourSamples, channelId, newValue, time, agg);
}
return hourSamples;
}
private void processHourSampleOnTimeCondition(@Nonnull final List<HourReducedDataSample> hourSamples,
@Nonnull final ArchiveChannelId channelId,
@Nonnull final Double newValue,
@Nonnull final TimeInstant time,
@Nonnull final SampleMinMaxAggregator agg) {
if (isReducedDataWriteDueAndHasChanged(newValue, agg, time, Hours.ONE.toStandardDuration())) {
final Double avg = agg.getAvg();
final Double min = agg.getMin();
final Double max = agg.getMax();
if (avg != null && min != null && max != null) {
hourSamples.add(new HourReducedDataSample(channelId, time, avg, min, max));
}
agg.reset();
}
}
@Nonnull
private <V extends Serializable, T extends ISystemVariable<V>>
List<? extends AbstractReducedDataSample> generatePerMinuteSamples(@Nonnull final Collection<IArchiveSample<V, T>> samples,
@Nonnull final Map<ArchiveChannelId, SampleMinMaxAggregator> aggregatorMap)
throws TypeSupportException, ArchiveDaoException {
if (samples.isEmpty()) {
return Collections.emptyList();
}
final List<MinuteReducedDataSample> minuteSamples = Lists.newLinkedList();
for (final IArchiveSample<V, T> sample : samples) {
final T sysVar = sample.getSystemVariable();
final V data = sysVar.getData();
if (ArchiveTypeConversionSupport.isDataTypeOptimizable(data.getClass())) {
final Double newValue =
BaseTypeConversionSupport.createDoubleFromValueOrNull(sysVar);
if (newValue == null) {
continue;
}
final ArchiveChannelId channelId = sample.getChannelId();
final Double minValue = newValue;
final Double maxValue = newValue;
final TimeInstant time = sample.getSystemVariable().getTimestamp();
final SampleMinMaxAggregator agg = retrieveAndInitializeAggregator(channelId,
aggregatorMap,
newValue,
minValue,
maxValue,
time);
processMinuteSampleOnTimeCondition(minuteSamples, newValue, channelId, time, agg);
}
}
return minuteSamples;
}
private void processMinuteSampleOnTimeCondition(@Nonnull final List<MinuteReducedDataSample> minuteSamples,
@Nonnull final Double newValue,
@Nonnull final ArchiveChannelId channelId,
@Nonnull final TimeInstant time,
@Nonnull final SampleMinMaxAggregator agg) {
if (isReducedDataWriteDueAndHasChanged(newValue, agg, time, Minutes.ONE.toStandardDuration())) {
final Double avg = agg.getAvg();
final Double min = agg.getMin();
final Double max = agg.getMax();
if (avg != null && min != null && max != null) {
minuteSamples.add(new MinuteReducedDataSample(channelId, time, avg, min, max));
}
agg.reset();
}
}
@Nonnull
private SampleMinMaxAggregator retrieveAndInitializeAggregator(@Nonnull final ArchiveChannelId channelId,
@Nonnull final Map<ArchiveChannelId, SampleMinMaxAggregator> aggMap,
@Nonnull final Double value,
@Nonnull final Double min,
@Nonnull final Double max,
@Nonnull final TimeInstant time) throws ArchiveDaoException {
SampleMinMaxAggregator aggregator = aggMap.get(channelId);
if (aggregator == null) {
aggregator = new SampleMinMaxAggregator();
initAggregatorToLastKnownSample(channelId, time, aggregator);
aggMap.put(channelId, aggregator);
}
aggregator.aggregate(value, min, max, time);
return aggregator;
}
private void initAggregatorToLastKnownSample(@Nonnull final ArchiveChannelId channelId,
@Nonnull final TimeInstant time,
@Nonnull final SampleMinMaxAggregator aggregator) throws ArchiveDaoException {
final IArchiveChannel channel = _channelDao.retrieveChannelById(channelId);
if (channel == null) {
throw new ArchiveDaoException("Init sample aggregator failed. Channel with id " + channelId.intValue() +
" does not exist.", null);
}
final IArchiveSample<Serializable, ISystemVariable<Serializable>> sample =
retrieveLatestSampleBeforeTime(channel, time);
if (sample != null) {
final Double lastWrittenValue =
BaseTypeConversionSupport.createDoubleFromValueOrNull(sample.getSystemVariable());
if (lastWrittenValue != null) {
final TimeInstant lastWriteTime = sample.getSystemVariable().getTimestamp();
aggregator.aggregate(lastWrittenValue, lastWriteTime);
}
}
}
private boolean isReducedDataWriteDueAndHasChanged(@Nonnull final Double newVal,
@Nonnull final SampleMinMaxAggregator agg,
@Nonnull final TimeInstant timestamp,
@Nonnull final Duration duration) {
final TimeInstant lastWriteTime = agg.getResetTimestamp();
if (lastWriteTime == null) {
return true;
}
final TimeInstant dueTime = lastWriteTime.plusMillis(duration.getMillis());
if (timestamp.isBefore(dueTime)) {
return false; // not yet due, don't write
}
final Double lastWrittenValue = agg.getAverageBeforeReset();
if (lastWrittenValue != null && lastWrittenValue.compareTo(newVal) == 0) {
return false; // hasn't changed much TODO (bknerr) : consider a sort of 'deadband' here, too
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
@Nonnull
public <V extends Serializable, T extends ISystemVariable<V>>
Collection<IArchiveSample<V, T>> retrieveSamples(@Nullable final DesyArchiveRequestType type,
@Nonnull final IArchiveChannel channel,
@Nonnull final TimeInstant s,
@Nonnull final TimeInstant e) throws ArchiveDaoException {
PreparedStatement stmt = null;
ResultSet result = null;
try {
DesyArchiveRequestType reqType = determineRequestType(type, channel.getDataType(), s, e);
do {
stmt = createReadSamplesStatement(channel, s, e, reqType);
result = stmt.executeQuery();
if (result.next()) {
return createRetrievedSamplesContainer(channel, reqType, result);
} else if (type == null) { // type == null means use automatic lookup
reqType = reqType.getNextLowerOrderRequestType();
}
} while (type == null && reqType != null); // no other request type of lower order
} catch (final Exception ex) {
handleExceptions(RETRIEVAL_FAILED, ex);
} finally {
closeStatement(result, stmt, "Closing of statement failed.");
}
return Collections.emptyList();
}
@Nonnull
private <V extends Serializable, T extends ISystemVariable<V>>
Collection<IArchiveSample<V, T>> createRetrievedSamplesContainer(@Nonnull final IArchiveChannel channel,
@Nonnull final DesyArchiveRequestType reqType,
@CheckForNull final ResultSet result)
throws SQLException,
ArchiveDaoException,
TypeSupportException {
final List<IArchiveSample<V, T>> samples = Lists.newArrayList();
while (result != null && !result.isAfterLast()) {
final IArchiveSample<V, T> sample =
createSampleFromQueryResult(reqType, channel, result);
samples.add(sample);
result.next();
}
return samples;
}
@Nonnull
private PreparedStatement createReadSamplesStatement(@Nonnull final IArchiveChannel channel,
@Nonnull final TimeInstant s,
@Nonnull final TimeInstant e,
@Nonnull final DesyArchiveRequestType reqType)
throws SQLException,
ArchiveConnectionException {
final PreparedStatement stmt = dispatchRequestTypeToStatement(reqType);
stmt.setInt(1, channel.getId().intValue());
stmt.setLong(2, s.getNanos());
stmt.setLong(3, e.getNanos());
return stmt;
}
@Nonnull
private PreparedStatement dispatchRequestTypeToStatement(@Nonnull final DesyArchiveRequestType type)
throws SQLException,
ArchiveConnectionException {
PreparedStatement stmt = null;
switch (type) {
case RAW :
System.out.println(_selectSamplesStmt.replaceFirst(ARCH_TABLE_PLACEHOLDER, TAB_SAMPLE));
stmt = getConnection().prepareStatement(_selectSamplesStmt.replaceFirst(ARCH_TABLE_PLACEHOLDER, TAB_SAMPLE));
break;
case AVG_PER_MINUTE :
stmt = getConnection().prepareStatement(_selectOptSamplesStmt.replaceFirst(ARCH_TABLE_PLACEHOLDER, TAB_SAMPLE_M));
break;
case AVG_PER_HOUR :
stmt = getConnection().prepareStatement(_selectOptSamplesStmt.replaceFirst(ARCH_TABLE_PLACEHOLDER, TAB_SAMPLE_H));
break;
default :
}
return stmt;
}
@SuppressWarnings("unchecked")
@Nonnull
private <V extends Serializable, T extends ISystemVariable<V>>
IArchiveMinMaxSample<V, T> createSampleFromQueryResult(@Nonnull final DesyArchiveRequestType type,
@Nonnull final IArchiveChannel channel,
@Nonnull final ResultSet result) throws SQLException,
ArchiveDaoException,
TypeSupportException {
final String dataType = channel.getDataType();
V value = null;
V min = null;
V max = null;
switch (type) {
case RAW : {
// (..., value)
value = ArchiveTypeConversionSupport.fromArchiveString(dataType, result.getString(COLUMN_VALUE));
break;
}
case AVG_PER_MINUTE :
case AVG_PER_HOUR : {
// (..., avg_val, min_val, max_val)
value = ArchiveTypeConversionSupport.fromDouble(dataType, result.getDouble(COLUMN_AVG));
min = ArchiveTypeConversionSupport.fromDouble(dataType, result.getDouble(COLUMN_MIN));
max = ArchiveTypeConversionSupport.fromDouble(dataType, result.getDouble(COLUMN_MAX));
break;
}
default:
throw new ArchiveDaoException("Archive request type unknown. Sample could not be created from query", null);
}
final long time = result.getLong(COLUMN_TIME);
final TimeInstant timeInstant = TimeInstantBuilder.fromNanos(time);
final IArchiveControlSystem cs = channel.getControlSystem();
final ISystemVariable<V> sysVar = SystemVariableSupport.create(channel.getName(),
value,
ControlSystem.valueOf(cs.getName(), cs.getType()),
timeInstant);
final ArchiveMinMaxSample<V, T> sample =
new ArchiveMinMaxSample<V, T>(channel.getId(), (T) sysVar, null, min, max);
return sample;
}
@Nonnull
private DesyArchiveRequestType determineRequestType(@CheckForNull final DesyArchiveRequestType type,
@Nonnull final String dataType,
@Nonnull final TimeInstant s,
@Nonnull final TimeInstant e) throws TypeSupportException {
if (DesyArchiveRequestType.RAW.equals(type) || !ArchiveTypeConversionSupport.isDataTypeOptimizable(dataType)) {
return DesyArchiveRequestType.RAW;
} else if (type != null) {
return type;
} else {
DesyArchiveRequestType reqType;
final Duration d = new Duration(s.getInstant(), e.getInstant());
if (d.isLongerThan(Duration.standardDays(45))) {
reqType = DesyArchiveRequestType.AVG_PER_HOUR;
} else if (d.isLongerThan(Duration.standardDays(1))) {
reqType = DesyArchiveRequestType.AVG_PER_MINUTE;
} else {
reqType = DesyArchiveRequestType.RAW;
}
return reqType;
}
}
/**
* {@inheritDoc}
*/
@Override
@CheckForNull
public <V extends Serializable, T extends ISystemVariable<V>>
IArchiveSample<V, T> retrieveLatestSampleBeforeTime(@Nonnull final IArchiveChannel channel,
@Nonnull final TimeInstant time) throws ArchiveDaoException {
PreparedStatement stmt = null;
ResultSet result = null;
try {
stmt = getConnection().prepareStatement(_selectLatestSampleBeforeTimeStmt);
stmt.setInt(1, channel.getId().intValue());
stmt.setLong(2, time.getNanos());
result = stmt.executeQuery();
if (result.next()) {
return createSampleFromQueryResult(DesyArchiveRequestType.RAW, channel, result);
}
} catch(final Exception e) {
handleExceptions(RETRIEVAL_FAILED, e);
} finally {
closeStatement(result, stmt, "Closing of statement failed.");
}
return null;
}
}
|
//$HeadURL: svn+ssh://lbuesching@svn.wald.intevation.de/deegree/base/trunk/resources/eclipse/files_template.xml $
package org.deegree.services.wps.provider.jrxml.contentprovider;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.getAsCodeType;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.getAsLanguageStringType;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stax.StAXSource;
import net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory;
import net.sf.jasperreports.engine.util.JRXmlUtils;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.commons.io.IOUtils;
import org.deegree.commons.tom.ows.CodeType;
import org.deegree.commons.xml.NamespaceBindings;
import org.deegree.commons.xml.XMLAdapter;
import org.deegree.commons.xml.XPath;
import org.deegree.commons.xml.stax.XMLStreamUtils;
import org.deegree.process.jaxb.java.ComplexFormatType;
import org.deegree.process.jaxb.java.ComplexInputDefinition;
import org.deegree.process.jaxb.java.ProcessletInputDefinition;
import org.deegree.services.wps.ProcessletException;
import org.deegree.services.wps.ProcessletInputs;
import org.deegree.services.wps.input.ComplexInput;
import org.deegree.services.wps.input.ProcessletInput;
import org.deegree.services.wps.provider.jrxml.JrxmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
public class DataTableContentProvider implements JrxmlContentProvider {
private static final Logger LOG = LoggerFactory.getLogger( DataTableContentProvider.class );
static final String SCHEMA = "http:
final static String MIME_TYPE = "text/xml";
static final String TABLE_PREFIX = "xml";
static final String DETAIL_SUFFIX = "DetailEntry";
static final String HEADER_SUFFIX = "HeaderEntry";
private static final NamespaceBindings nsContext;
static {
nsContext = JrxmlUtils.nsContext.addNamespace( "tbl", SCHEMA );
}
@Override
public void inspectInputParametersFromJrxml( List<JAXBElement<? extends ProcessletInputDefinition>> inputs,
XMLAdapter jrxmlAdapter, Map<String, String> parameters,
List<String> handledParameters ) {
List<String> tableIds = new ArrayList<String>();
List<OMElement> fieldElements = jrxmlAdapter.getElements( jrxmlAdapter.getRootElement(),
new XPath( "/jasper:jasperReport/jasper:field",
nsContext ) );
for ( OMElement fieldElement : fieldElements ) {
String fieldName = fieldElement.getAttributeValue( new QName( "name" ) );
if ( isTableParameter( fieldName ) ) {
String identifier = getIdentifierFromParameter( fieldName );
if ( !tableIds.contains( identifier ) ) {
tableIds.add( identifier );
}
}
}
for ( String tableId : tableIds ) {
LOG.debug( "Found table component with id " + tableId );
ComplexInputDefinition comp = new ComplexInputDefinition();
comp.setTitle( getAsLanguageStringType( tableId ) );
comp.setIdentifier( getAsCodeType( tableId ) );
ComplexFormatType format = new ComplexFormatType();
format.setEncoding( "UTF-8" );
format.setMimeType( MIME_TYPE );
format.setSchema( SCHEMA );
comp.setDefaultFormat( format );
comp.setMaxOccurs( BigInteger.valueOf( 1 ) );
comp.setMinOccurs( BigInteger.valueOf( 0 ) );
inputs.add( new JAXBElement<ComplexInputDefinition>( new QName( "ProcessInput" ),
ComplexInputDefinition.class, comp ) );
}
}
private String getIdentifierFromParameter( String fieldName ) {
return fieldName.substring( TABLE_PREFIX.length(), fieldName.indexOf( "_" ) );
}
private boolean isTableParameter( String paramName ) {
return paramName != null ? paramName.matches( TABLE_PREFIX + "[a-zA-Z0-9]*_(" + DETAIL_SUFFIX + "|"
+ HEADER_SUFFIX + ")1" ) : false;
}
@Override
public InputStream prepareJrxmlAndReadInputParameters( InputStream jrxml, Map<String, Object> params,
ProcessletInputs in, List<CodeType> processedIds,
Map<String, String> parameters )
throws ProcessletException {
for ( ProcessletInput input : in.getParameters() ) {
if ( !processedIds.contains( input ) && input instanceof ComplexInput ) {
ComplexInput complexIn = (ComplexInput) input;
if ( SCHEMA.equals( complexIn.getSchema() ) && MIME_TYPE.equals( complexIn.getMimeType() ) ) {
String tableId = complexIn.getIdentifier().getCode();
LOG.debug( "Found input parameter " + tableId + " representing a xml datasource!" );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
// TODO: read number of headerentries
// XMLAdapter tableAdapter = new XMLAdapter( complexIn.getValueAsXMLStream() );
// List<OMElement> elements = tableAdapter.getElements( tableAdapter.getRootElement(),
// new XPath(
// "/tbl:XMLDataSource/tbl:Header/tbl:HeaderEntry",
// nsContext ) );
int numberOfEntries = 4; // elements.size();
if ( numberOfEntries > 1 ) {
XMLAdapter jrxmlAdapter = new XMLAdapter( jrxml );
OMElement root = jrxmlAdapter.getRootElement();
List<OMElement> fieldElements = jrxmlAdapter.getElements( root,
new XPath(
"/jasper:jasperReport/jasper:field",
nsContext ) );
OMFactory factory = OMAbstractFactory.getOMFactory();
for ( OMElement fieldElement : fieldElements ) {
String fieldName = fieldElement.getAttributeValue( new QName( "name" ) );
if ( isTableParameter( fieldName )
&& tableId.equals( getIdentifierFromParameter( fieldName ) ) ) {
OMElement textFieldElement = jrxmlAdapter.getElement( root,
new XPath(
".//jasper:textField[jasper:textFieldExpression/text()='$F{"
+ fieldName
+ "}']",
nsContext ) );
for ( int i = 2; i < numberOfEntries + 1; i++ ) {
OMElement newFieldElement = fieldElement.cloneOMElement();
String newFieldName = fieldName.substring( 0, fieldName.length() - 1 ) + i;
newFieldElement.addAttribute( "name", newFieldName, null );
OMElement fieldDesc = jrxmlAdapter.getElement( newFieldElement,
new XPath(
"jasper:fieldDescription",
nsContext ) );
String text = fieldDesc.getText();
text = text.replace( "[1]", "[" + i + "]" );
setText( factory, fieldDesc, text );
fieldElement.insertSiblingAfter( newFieldElement );
// reference
if ( textFieldElement != null ) {
int width = jrxmlAdapter.getRequiredNodeAsInteger( textFieldElement,
new XPath(
"jasper:reportElement/@width",
nsContext ) );
int x = jrxmlAdapter.getRequiredNodeAsInteger( textFieldElement,
new XPath(
"jasper:reportElement/@x",
nsContext ) );
OMElement newDetailTextField = textFieldElement.cloneOMElement();
jrxmlAdapter.getElement( newDetailTextField,
new XPath( "jasper:reportElement", nsContext ) ).addAttribute( "x",
Integer.toString( x
+ width
* ( i - 1 ) ),
null );
OMElement newTextFieldExpr = jrxmlAdapter.getElement( newDetailTextField,
new XPath(
"jasper:textFieldExpression",
nsContext ) );
setText( factory, newTextFieldExpr, "$F{" + newFieldName + "}" );
textFieldElement.insertSiblingAfter( newDetailTextField );
}
}
}
}
if ( LOG.isDebugEnabled() ) {
LOG.debug( "Adjusted jrxml: " + root );
}
// reset xml
root.serialize( bos );
jrxml = new ByteArrayInputStream( bos.toByteArray() );
}
// add complete input xml
XMLStreamReader xmlIs = complexIn.getValueAsXMLStream();
Document document = XMLStreamUtils.getAsDocument (xmlIs);
params.put( JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, document );
} catch ( Exception e ) {
String msg = "Could not process data table content: " + e.getMessage();
LOG.error( msg, e );
throw new ProcessletException( msg );
} finally {
IOUtils.closeQuietly( bos );
}
processedIds.add( complexIn.getIdentifier() );
}
}
}
return jrxml;
}
private void setText( OMFactory factory, OMElement txtElement, String text ) {
// this does not work:
// e.setText( layer );
// it attaches the text, but does not replace
txtElement.getFirstOMChild().detach();
txtElement.addChild( factory.createOMText( txtElement, text ) );
}
}
|
package org.xwiki.uiextension;
import java.io.StringWriter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.velocity.VelocityContext;
import org.junit.jupiter.api.Test;
import org.xwiki.component.internal.multi.DelegateComponentManager;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.wiki.WikiComponent;
import org.xwiki.component.wiki.WikiComponentException;
import org.xwiki.component.wiki.internal.bridge.ContentParser;
import org.xwiki.job.event.status.JobProgressManager;
import org.xwiki.logging.LoggerConfiguration;
import org.xwiki.model.ModelContext;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.ObjectReference;
import org.xwiki.rendering.async.AsyncContext;
import org.xwiki.rendering.async.internal.block.BlockAsyncRendererExecutor;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.transformation.RenderingContext;
import org.xwiki.rendering.transformation.Transformation;
import org.xwiki.rendering.util.ErrorBlockGenerator;
import org.xwiki.test.annotation.BeforeComponent;
import org.xwiki.test.junit5.mockito.InjectMockComponents;
import org.xwiki.test.junit5.mockito.MockComponent;
import org.xwiki.test.mockito.MockitoComponentManager;
import org.xwiki.uiextension.internal.WikiUIExtensionComponentBuilder;
import org.xwiki.uiextension.internal.WikiUIExtensionConstants;
import org.xwiki.velocity.VelocityEngine;
import org.xwiki.velocity.VelocityManager;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseObjectReference;
import com.xpn.xwiki.test.MockitoOldcore;
import com.xpn.xwiki.test.junit5.mockito.OldcoreTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@OldcoreTest
public class WikiUIExtensionComponentBuilderTest implements WikiUIExtensionConstants
{
@MockComponent
private JobProgressManager jobProgressManager;
@MockComponent
private ErrorBlockGenerator errorBlockGenerator;
@MockComponent
private AsyncContext asyncContext;
@MockComponent
private BlockAsyncRendererExecutor blockAsyncRendererExecutor;
@MockComponent
private RenderingContext renderingContext;
@MockComponent
private ContentParser contentParser;
@MockComponent
private LoggerConfiguration loggerConfiguration;
@InjectMockComponents
private WikiUIExtensionComponentBuilder builder;
private static final DocumentReference DOC_REF =
new DocumentReference("xwiki", "XWiki", "MyUIExtension", Locale.ROOT);
private static final DocumentReference AUTHOR_REFERENCE = new DocumentReference("xwiki", "XWiki", "Admin");
private XWikiDocument componentDoc;
@BeforeComponent
public void configure(MockitoComponentManager componentManager, MockitoOldcore oldcore) throws Exception
{
// Required by BaseObjectReference
DocumentReferenceResolver<String> resolver =
componentManager.registerMockComponent(DocumentReferenceResolver.TYPE_STRING);
when(resolver.resolve("XWiki.UIExtension"))
.thenReturn(new DocumentReference("xwiki", "XWiki", "UIExtensionClass"));
DelegateComponentManager wikiComponentManager = new DelegateComponentManager();
wikiComponentManager.setComponentManager(componentManager);
componentManager.registerComponent(ComponentManager.class, "wiki", wikiComponentManager);
// Components accessed through dynamic lookup.
VelocityManager velocityManager = componentManager.registerMockComponent(VelocityManager.class);
when(velocityManager.getVelocityEngine()).thenReturn(mock(VelocityEngine.class));
when(velocityManager.getVelocityContext()).thenReturn(mock(VelocityContext.class));
ModelContext modelContext = componentManager.registerMockComponent(ModelContext.class);
when(modelContext.getCurrentEntityReference()).thenReturn(DOC_REF);
componentManager.registerMockComponent(RenderingContext.class);
componentManager.registerMockComponent(Transformation.class, "macro");
componentManager.registerMockComponent(ContentParser.class);
// The document holding the UI extension object.
this.componentDoc = mock(XWikiDocument.class, "xwiki:XWiki.MyUIExtension");
when(this.componentDoc.getDocumentReference()).thenReturn(DOC_REF);
when(this.componentDoc.getAuthorReference()).thenReturn(AUTHOR_REFERENCE);
when(this.componentDoc.getContentAuthorReference()).thenReturn(AUTHOR_REFERENCE);
when(this.componentDoc.getSyntax()).thenReturn(Syntax.XWIKI_2_1);
oldcore.getDocuments().put(DOC_REF, componentDoc);
}
@Test
public void buildGlobalComponentsWithoutPR()
{
BaseObject extensionObject = createExtensionObject("id", "extensionPointId", "content", "parameters", "global");
Throwable exception = assertThrows(WikiComponentException.class, () -> {
this.builder.buildComponents(extensionObject);
});
assertEquals("Registering global UI extensions requires programming rights", exception.getMessage());
}
@Test
public void buildWikiLevelComponentsWithoutAdminRights()
{
BaseObject extensionObject = createExtensionObject("id", "extensionPointId", "content", "parameters", "wiki");
Throwable exception = assertThrows(WikiComponentException.class, () -> {
this.builder.buildComponents(extensionObject);
});
assertEquals("Registering UI extensions at wiki level requires wiki administration rights",
exception.getMessage());
}
@Test
public void buildComponents(ComponentManager componentManager) throws Exception
{
BaseObject extensionObject = createExtensionObject("name", "extensionPointId", "content",
"key=value=foo\nkey2=value2\nempty=\n\n=invalid", "user");
ContentParser contentParser = componentManager.getInstance(ContentParser.class);
VelocityManager velocityManager = componentManager.getInstance(VelocityManager.class);
List<WikiComponent> components = this.builder.buildComponents(extensionObject);
assertEquals(1, components.size());
verify(contentParser).parse("content", Syntax.XWIKI_2_1, DOC_REF);
UIExtension uiExtension = (UIExtension) components.get(0);
Map<String, String> parameters = uiExtension.getParameters();
assertEquals(3, parameters.size());
verify(velocityManager.getVelocityEngine()).evaluate(any(VelocityContext.class), any(StringWriter.class),
eq("name:key"), eq("value=foo"));
verify(velocityManager.getVelocityEngine()).evaluate(any(VelocityContext.class), any(StringWriter.class),
eq("name:key2"), eq("value2"));
verify(velocityManager.getVelocityEngine()).evaluate(any(VelocityContext.class), any(StringWriter.class),
eq("name:empty"), eq(""));
}
private BaseObject createExtensionObject(String id, String extensionPointId, String content, String parameters,
String scope)
{
BaseObject extensionObject = mock(BaseObject.class, id);
when(extensionObject.getStringValue(ID_PROPERTY)).thenReturn(id);
when(extensionObject.getStringValue(EXTENSION_POINT_ID_PROPERTY)).thenReturn(extensionPointId);
when(extensionObject.getStringValue(CONTENT_PROPERTY)).thenReturn(content);
when(extensionObject.getStringValue(PARAMETERS_PROPERTY)).thenReturn(parameters);
when(extensionObject.getStringValue(SCOPE_PROPERTY)).thenReturn(scope);
BaseObjectReference objectReference =
new BaseObjectReference(new ObjectReference("XWiki.UIExtensionClass[0]", DOC_REF));
when(extensionObject.getReference()).thenReturn(objectReference);
when(extensionObject.getOwnerDocument()).thenReturn(this.componentDoc);
return extensionObject;
}
}
|
package io.quarkus.resteasy.server.common.deployment;
import static io.quarkus.runtime.annotations.ConfigPhase.BUILD_TIME;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import javax.ws.rs.core.Application;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationTarget.Kind;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.MethodParameterInfo;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
import org.jboss.resteasy.api.validation.ResteasyConstraintViolation;
import org.jboss.resteasy.api.validation.ViolationReport;
import org.jboss.resteasy.microprofile.config.FilterConfigSource;
import org.jboss.resteasy.microprofile.config.ServletConfigSource;
import org.jboss.resteasy.microprofile.config.ServletContextConfigSource;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.resteasy.spi.ResteasyDeployment;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import io.quarkus.arc.ArcUndeclaredThrowableException;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.AnnotationsTransformerBuildItem;
import io.quarkus.arc.deployment.AutoInjectAnnotationBuildItem;
import io.quarkus.arc.deployment.BeanArchiveIndexBuildItem;
import io.quarkus.arc.deployment.BeanDefiningAnnotationBuildItem;
import io.quarkus.arc.deployment.BuildTimeConditionBuildItem;
import io.quarkus.arc.deployment.CustomScopeAnnotationsBuildItem;
import io.quarkus.arc.deployment.UnremovableBeanBuildItem;
import io.quarkus.arc.deployment.UnremovableBeanBuildItem.BeanClassNameExclusion;
import io.quarkus.arc.processor.AnnotationsTransformer;
import io.quarkus.arc.processor.BuiltinScope;
import io.quarkus.arc.processor.DotNames;
import io.quarkus.arc.processor.Transformation;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.nativeimage.NativeImageConfigBuildItem;
import io.quarkus.deployment.builditem.nativeimage.NativeImageProxyDefinitionBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveHierarchyBuildItem;
import io.quarkus.deployment.util.JandexUtil;
import io.quarkus.gizmo.Gizmo;
import io.quarkus.resteasy.common.deployment.JaxrsProvidersToRegisterBuildItem;
import io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.ResteasyCommonConfig;
import io.quarkus.resteasy.common.runtime.QuarkusInjectorFactory;
import io.quarkus.resteasy.common.spi.ResteasyDotNames;
import io.quarkus.resteasy.server.common.runtime.QuarkusResteasyDeployment;
import io.quarkus.resteasy.server.common.spi.AdditionalJaxRsResourceDefiningAnnotationBuildItem;
import io.quarkus.resteasy.server.common.spi.AdditionalJaxRsResourceMethodAnnotationsBuildItem;
import io.quarkus.resteasy.server.common.spi.AdditionalJaxRsResourceMethodParamAnnotations;
import io.quarkus.resteasy.server.common.spi.AllowedJaxRsAnnotationPrefixBuildItem;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigRoot;
import io.quarkus.runtime.annotations.ConvertWith;
import io.quarkus.runtime.configuration.NormalizeRootHttpPathConverter;
/**
* Processor that builds the RESTEasy server configuration.
*/
public class ResteasyServerCommonProcessor {
private static final Logger log = Logger.getLogger("io.quarkus.resteasy");
private static final String JAX_RS_APPLICATION_PARAMETER_NAME = "javax.ws.rs.Application";
private static final DotName JSONB_ANNOTATION = DotName.createSimple("javax.json.bind.annotation.JsonbAnnotation");
private static final List<DotName> METHOD_ANNOTATIONS = List.of(
ResteasyDotNames.GET,
ResteasyDotNames.HEAD,
ResteasyDotNames.DELETE,
ResteasyDotNames.OPTIONS,
ResteasyDotNames.PATCH,
ResteasyDotNames.POST,
ResteasyDotNames.PUT);
private static final List<DotName> RESTEASY_PARAM_ANNOTATIONS = List.of(
ResteasyDotNames.RESTEASY_QUERY_PARAM,
ResteasyDotNames.RESTEASY_FORM_PARAM,
ResteasyDotNames.RESTEASY_COOKIE_PARAM,
ResteasyDotNames.RESTEASY_PATH_PARAM,
ResteasyDotNames.RESTEASY_HEADER_PARAM,
ResteasyDotNames.RESTEASY_MATRIX_PARAM);
/**
* JAX-RS configuration.
*/
ResteasyConfig resteasyConfig;
ResteasyCommonConfig commonConfig;
@ConfigRoot(phase = BUILD_TIME)
static final class ResteasyConfig {
@ConfigItem(defaultValue = "true")
boolean singletonResources;
/**
* Set this to override the default path for JAX-RS resources if there are no
* annotated application classes. This path is specified with a leading {@literal /}, but is resolved relative
* to {@literal quarkus.http.root-path}.
* <ul>
* <li>If {@literal quarkus.http.root-path=/} and {@code quarkus.resteasy.path=/bar}, the JAX-RS resource path will be
* {@literal /bar}</li>
* <li>If {@literal quarkus.http.root-path=/foo} and {@code quarkus.resteasy.path=/bar}, the JAX-RS resource path will
* be {@literal /foo/bar}</li>
* </ul>
*/
@ConfigItem(defaultValue = "/")
@ConvertWith(NormalizeRootHttpPathConverter.class)
String path;
@Deprecated(forRemoval = true)
@ConfigItem(name = "metrics.enabled")
public Optional<Boolean> metricsEnabled;
/**
* Ignore all explicit JAX-RS {@link Application} classes.
* As multiple JAX-RS applications are not supported, this can be used to effectively merge all JAX-RS applications.
*/
@ConfigItem(defaultValue = "false")
boolean ignoreApplicationClasses;
/**
* Whether or not annotations such `@IfBuildTimeProfile`, `@IfBuildTimeProperty` and friends will be taken
* into account when used on JAX-RS classes.
*/
@ConfigItem(defaultValue = "true")
boolean buildTimeConditionAware;
}
@BuildStep
NativeImageConfigBuildItem config() {
return NativeImageConfigBuildItem.builder()
.addResourceBundle("messages")
.build();
}
@BuildStep
public void build(
BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy,
BuildProducer<NativeImageProxyDefinitionBuildItem> proxyDefinition,
BuildProducer<BytecodeTransformerBuildItem> transformers,
BuildProducer<ResteasyServerConfigBuildItem> resteasyServerConfig,
BuildProducer<ResteasyDeploymentBuildItem> resteasyDeployment,
BuildProducer<UnremovableBeanBuildItem> unremovableBeans,
BuildProducer<AnnotationsTransformerBuildItem> annotationsTransformer,
List<BuildTimeConditionBuildItem> buildTimeConditions,
List<AutoInjectAnnotationBuildItem> autoInjectAnnotations,
List<AdditionalJaxRsResourceDefiningAnnotationBuildItem> additionalJaxRsResourceDefiningAnnotations,
List<AdditionalJaxRsResourceMethodAnnotationsBuildItem> additionalJaxRsResourceMethodAnnotations,
List<AdditionalJaxRsResourceMethodParamAnnotations> additionalJaxRsResourceMethodParamAnnotations,
List<AllowedJaxRsAnnotationPrefixBuildItem> friendlyJaxRsAnnotationPrefixes,
List<ResteasyDeploymentCustomizerBuildItem> deploymentCustomizers,
JaxrsProvidersToRegisterBuildItem jaxrsProvidersToRegisterBuildItem,
CombinedIndexBuildItem combinedIndexBuildItem,
BeanArchiveIndexBuildItem beanArchiveIndexBuildItem,
Optional<ResteasyServletMappingBuildItem> resteasyServletMappingBuildItem,
CustomScopeAnnotationsBuildItem scopes) throws Exception {
IndexView index = combinedIndexBuildItem.getIndex();
Collection<AnnotationInstance> applicationPaths = Collections.emptySet();
final Set<String> allowedClasses;
final Set<String> excludedClasses;
if (resteasyConfig.buildTimeConditionAware) {
excludedClasses = getExcludedClasses(buildTimeConditions);
} else {
excludedClasses = Collections.emptySet();
}
if (resteasyConfig.ignoreApplicationClasses) {
allowedClasses = Collections.emptySet();
} else {
applicationPaths = index.getAnnotations(ResteasyDotNames.APPLICATION_PATH);
allowedClasses = getAllowedClasses(index);
jaxrsProvidersToRegisterBuildItem = getFilteredJaxrsProvidersToRegisterBuildItem(
jaxrsProvidersToRegisterBuildItem, allowedClasses, excludedClasses);
}
boolean filterClasses = !allowedClasses.isEmpty() || !excludedClasses.isEmpty();
// currently we only examine the first class that is annotated with @ApplicationPath so best
// fail if the user code has multiple such annotations instead of surprising the user
// at runtime
if (applicationPaths.size() > 1) {
throw createMultipleApplicationsException(applicationPaths);
}
Set<AnnotationInstance> additionalPaths = new HashSet<>();
for (AdditionalJaxRsResourceDefiningAnnotationBuildItem annotation : additionalJaxRsResourceDefiningAnnotations) {
additionalPaths.addAll(beanArchiveIndexBuildItem.getIndex().getAnnotations(annotation.getAnnotationClass()));
}
Collection<AnnotationInstance> paths = beanArchiveIndexBuildItem.getIndex().getAnnotations(ResteasyDotNames.PATH);
final Collection<AnnotationInstance> allPaths;
if (filterClasses) {
allPaths = paths.stream().filter(
annotationInstance -> keepAnnotation(beanArchiveIndexBuildItem.getIndex(), allowedClasses, excludedClasses,
annotationInstance))
.collect(Collectors.toList());
} else {
allPaths = new ArrayList<>(paths);
}
allPaths.addAll(additionalPaths);
if (allPaths.isEmpty()) {
// no detected @Path, bail out
return;
}
final String rootPath;
final String path;
final String appClass;
if (!applicationPaths.isEmpty()) {
AnnotationInstance applicationPath = applicationPaths.iterator().next();
rootPath = "/";
path = applicationPath.value().asString();
appClass = applicationPath.target().asClass().name().toString();
} else {
if (resteasyServletMappingBuildItem.isPresent()) {
/**
* @param buildTimeConditions the build time conditions from which the excluded classes are extracted.
* @return the set of classes that have been annotated with unsuccessful build time conditions.
*/
private static Set<String> getExcludedClasses(List<BuildTimeConditionBuildItem> buildTimeConditions) {
return buildTimeConditions.stream()
.filter(item -> !item.isEnabled())
.map(BuildTimeConditionBuildItem::getTarget)
.filter(target -> target.kind() == Kind.CLASS)
.map(target -> target.asClass().toString())
.collect(Collectors.toSet());
}
/**
* @param index the Jandex index view from which the class information is extracted.
* @param allowedClasses the classes to keep provided by the methods {@link Application#getClasses()} and
* {@link Application#getSingletons()}.
* @param excludedClasses the classes that have been annotated with unsuccessful build time conditions and that
* need to be excluded from the list of paths.
* @param annotationInstance the annotation instance to test.
* @return {@code true} if the enclosing class of the annotation is a concrete class and is part of the allowed
* classes, or is an interface and at least one concrete implementation is included, or is an abstract class
* and at least one concrete sub class is included, or is not part of the excluded classes, {@code false} otherwise.
*/
private static boolean keepAnnotation(IndexView index, Set<String> allowedClasses, Set<String> excludedClasses,
AnnotationInstance annotationInstance) {
final ClassInfo classInfo = JandexUtil.getEnclosingClass(annotationInstance);
final String className = classInfo.toString();
if (allowedClasses.isEmpty()) {
// No allowed classes have been set, meaning that only excluded classes have been provided.
// Keep the enclosing class only if not excluded
return !excludedClasses.contains(className);
} else if (Modifier.isAbstract(classInfo.flags())) {
// Only keep the annotation if a concrete implementation or a sub class has been included
return (Modifier.isInterface(classInfo.flags()) ? index.getAllKnownImplementors(classInfo.name())
: index.getAllKnownSubclasses(classInfo.name()))
.stream()
.filter(clazz -> !Modifier.isAbstract(clazz.flags()))
.map(Objects::toString)
.anyMatch(allowedClasses::contains);
}
return allowedClasses.contains(className);
}
/**
* @param allowedClasses the classes returned by the methods {@link Application#getClasses()} and
* {@link Application#getSingletons()} to keep.
* @param excludedClasses the classes that have been annotated wih unsuccessful build time conditions and that
* need to be excluded from the list of providers.
* @param jaxrsProvidersToRegisterBuildItem the initial {@code jaxrsProvidersToRegisterBuildItem} before being
* filtered
* @return an instance of {@link JaxrsProvidersToRegisterBuildItem} that has been filtered to take into account
* the classes returned by the methods {@link Application#getClasses()} and {@link Application#getSingletons()}
* if at least one of those methods return a non empty {@code Set}, the provided instance of
* {@link JaxrsProvidersToRegisterBuildItem} otherwise.
*/
private static JaxrsProvidersToRegisterBuildItem getFilteredJaxrsProvidersToRegisterBuildItem(
JaxrsProvidersToRegisterBuildItem jaxrsProvidersToRegisterBuildItem, Set<String> allowedClasses,
Set<String> excludedClasses) {
if (allowedClasses.isEmpty() && excludedClasses.isEmpty()) {
return jaxrsProvidersToRegisterBuildItem;
}
Set<String> providers = new HashSet<>(jaxrsProvidersToRegisterBuildItem.getProviders());
Set<String> contributedProviders = new HashSet<>(jaxrsProvidersToRegisterBuildItem.getContributedProviders());
Set<String> annotatedProviders = new HashSet<>(jaxrsProvidersToRegisterBuildItem.getAnnotatedProviders());
providers.removeAll(annotatedProviders);
contributedProviders.removeAll(annotatedProviders);
if (allowedClasses.isEmpty()) {
annotatedProviders.removeAll(excludedClasses);
} else {
annotatedProviders.retainAll(allowedClasses);
}
providers.addAll(annotatedProviders);
contributedProviders.addAll(annotatedProviders);
return new JaxrsProvidersToRegisterBuildItem(
providers, contributedProviders, annotatedProviders, jaxrsProvidersToRegisterBuildItem.useBuiltIn());
}
/**
* @param index the index to use to find the existing {@link Application}.
* @return the set of classes returned by the methods {@link Application#getClasses()} and
* {@link Application#getSingletons()}.
*/
private static Set<String> getAllowedClasses(IndexView index) {
final Collection<ClassInfo> applications = index.getAllKnownSubclasses(ResteasyDotNames.APPLICATION);
final Set<String> allowedClasses = new HashSet<>();
Application application;
ClassInfo selectedAppClass = null;
for (ClassInfo applicationClassInfo : applications) {
if (Modifier.isAbstract(applicationClassInfo.flags())) {
continue;
}
if (selectedAppClass != null) {
throw new RuntimeException("More than one Application class: " + applications);
}
selectedAppClass = applicationClassInfo;
// FIXME: yell if there's more than one
String applicationClass = applicationClassInfo.name().toString();
try {
Class<?> appClass = Thread.currentThread().getContextClassLoader().loadClass(applicationClass);
application = (Application) appClass.getConstructor().newInstance();
Set<Class<?>> classes = application.getClasses();
if (!classes.isEmpty()) {
for (Class<?> klass : classes) {
allowedClasses.add(klass.getName());
}
}
classes = application.getSingletons().stream().map(Object::getClass).collect(Collectors.toSet());
if (!classes.isEmpty()) {
for (Class<?> klass : classes) {
allowedClasses.add(klass.getName());
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
| InvocationTargetException e) {
throw new RuntimeException("Unable to handle class: " + applicationClass, e);
}
}
return allowedClasses;
}
}
|
package picodedTests.jCache;
import java.lang.Exception;
import picodedTests.TestConfig;
import redis.embedded.*;
import com.hazelcast.core.*;
import com.hazelcast.config.*;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
/// Test utiltiy function, used to setup a local Redis / hazelCast cache instance
public class LocalCacheSetup {
/// Redis server
/// The redis server instance
private static RedisServer rServer = null;
/// The generate redis port
public static int rPort = 6379;
/// Starts up redis at the default port
static public int setupRedisServer() {
if (rServer != null) {
return rPort;
//throw new RuntimeException("Local Redis server already started");
}
try {
rServer = new RedisServer(6379); //default port
rServer.start();
return 6379;
} catch (Exception e) {
throw new RuntimeException("Local Redis server setup error", e);
}
//return -1;
}
/// Tears down the redis test server
static public void teardownRedisServer() {
if (rServer == null) {
return; // throw new RuntimeException("No local Redis server to 'teardown'");
}
rServer.stop();
rServer = null;
}
/// SimpleDB
/// @TODO implement SimpleDB support for unit testing, followed by jCache implementation
/// The generate redis port
//public static int sDB_port = 6379;
/// Hazelcast server
/// The hazelcast server instance
private static HazelcastInstance hcServer = null;
/// The generated hazel0cast name
public static String hcClusterName = null;
/// Starts up redis at the default port
static public String setupHazelcastServer() {
if (hcServer != null) {
return hcClusterName;
//throw new RuntimeException("Local hazelcast server already started");
}
String clusterName = TestConfig.randomTablePrefix();
hcClusterName = clusterName;
try {
Config clusterConfig = new Config();
clusterConfig.getGroupConfig().setName(clusterName);
clusterConfig.setProperty("hazelcast.logging.type", "none");
hcServer = Hazelcast.newHazelcastInstance(clusterConfig);
return clusterName;
} catch (Exception e) {
throw new RuntimeException("Local hazelcast server setup error", e);
}
//return -1;
}
/// Tears down the redis test server
static public void teardownHazelcastServer() {
if (hcServer == null) {
return; // throw new RuntimeException("No local hazelcast server to 'teardown'");
}
hcServer.shutdown();
rServer = null;
}
}
|
package org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational;
import java.util.Iterator;
import java.util.List;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.DescriptorEvent;
import org.eclipse.persistence.descriptors.DescriptorQueryManager;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping;
import org.eclipse.persistence.queries.DeleteObjectQuery;
import org.eclipse.persistence.queries.InsertObjectQuery;
import org.eclipse.persistence.queries.ReadAllQuery;
import org.eclipse.persistence.queries.ReadObjectQuery;
import org.eclipse.persistence.queries.UpdateObjectQuery;
import org.eclipse.persistence.tools.workbench.mappingsmodel.MWModel;
import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.relational.MWRelationalTransactionalPolicy;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.MWQueryManager;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.MWReadAllQuery;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.MWReadObjectQuery;
import org.eclipse.persistence.tools.workbench.utility.node.Node;
/**
* This class holds any custom sql the user has created.
*/
public final class MWRelationalQueryManager extends MWQueryManager {
private volatile MWInsertQuery insertQuery;
public final static String INSERT_QUERY_PROPERTY = "insertQuery";
private volatile MWUpdateQuery updateQuery;
public final static String UPDATE_QUERY_PROPERTY = "updateQuery";
private volatile MWDeleteQuery deleteQuery;
public final static String DELETE_QUERY_PROPERTY = "deleteQuery";
private volatile MWCustomReadObjectQuery readObjectQuery;
public final static String READ_OBJECT_QUERY_PROPERTY = "readObjectQuery";
private volatile MWCustomReadAllQuery readAllQuery;
public final static String READ_ALL_QUERY_PROPERTY = "readAllQuery";
private String legacyDescriptorAlias;
//Toplink persistence use only please
private MWRelationalQueryManager() {
super();
}
public MWRelationalQueryManager(MWRelationalTransactionalPolicy descriptor) {
super(descriptor);
}
@Override
protected void initialize() {
super.initialize();
this.insertQuery = new MWInsertQuery(this);
this.deleteQuery = new MWDeleteQuery(this);
this.updateQuery = new MWUpdateQuery(this);
this.readObjectQuery = new MWCustomReadObjectQuery(this);
this.readAllQuery = new MWCustomReadAllQuery(this);
}
@Override
protected void addChildrenTo(List children) {
super.addChildrenTo(children);
children.add(this.insertQuery);
children.add(this.deleteQuery);
children.add(this.updateQuery);
children.add(this.readObjectQuery);
children.add(this.readAllQuery);
}
//Persistence
public static XMLDescriptor buildDescriptor() {
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setJavaClass(MWRelationalQueryManager.class);
descriptor.getInheritancePolicy().setParentClass(MWQueryManager.class);
//custom queries
XMLCompositeObjectMapping insertQueryMapping = new XMLCompositeObjectMapping();
insertQueryMapping.setAttributeName("insertQuery");
insertQueryMapping.setGetMethodName("getInsertQueryForTopLink");
insertQueryMapping.setSetMethodName("setInsertQueryForTopLink");
insertQueryMapping.setReferenceClass(MWInsertQuery.class);
insertQueryMapping.setXPath("insert-query");
descriptor.addMapping(insertQueryMapping);
XMLCompositeObjectMapping deleteQueryMapping = new XMLCompositeObjectMapping();
deleteQueryMapping.setAttributeName("deleteQuery");
deleteQueryMapping.setGetMethodName("getDeleteQueryForTopLink");
deleteQueryMapping.setSetMethodName("setDeleteQueryForTopLink");
deleteQueryMapping.setReferenceClass(MWDeleteQuery.class);
deleteQueryMapping.setXPath("delete-query");
descriptor.addMapping(deleteQueryMapping);
XMLCompositeObjectMapping updateQueryMapping = new XMLCompositeObjectMapping();
updateQueryMapping.setAttributeName("updateQuery");
updateQueryMapping.setGetMethodName("getUpdateQueryForTopLink");
updateQueryMapping.setSetMethodName("setUpdateQueryForTopLink");
updateQueryMapping.setReferenceClass(MWUpdateQuery.class);
updateQueryMapping.setXPath("update-query");
descriptor.addMapping(updateQueryMapping);
XMLCompositeObjectMapping readObjectQueryMapping = new XMLCompositeObjectMapping();
readObjectQueryMapping.setAttributeName("readObjectQuery");
readObjectQueryMapping.setGetMethodName("getReadObjectQueryForTopLink");
readObjectQueryMapping.setSetMethodName("setReadObjectQueryForTopLink");
readObjectQueryMapping.setReferenceClass(MWCustomReadObjectQuery.class);
readObjectQueryMapping.setXPath("read-object-query");
descriptor.addMapping(readObjectQueryMapping);
XMLCompositeObjectMapping readAllQueryMapping = new XMLCompositeObjectMapping();
readAllQueryMapping.setAttributeName("readAllQuery");
readAllQueryMapping.setGetMethodName("getReadAllQueryForTopLink");
readAllQueryMapping.setSetMethodName("setReadAllQueryForTopLink");
readAllQueryMapping.setReferenceClass(MWCustomReadAllQuery.class);
readAllQueryMapping.setXPath("read-all-query");
descriptor.addMapping(readAllQueryMapping);
return descriptor;
}
public static XMLDescriptor buildStandalone60Descriptor() {
XMLDescriptor descriptor = MWModel.legacy60BuildStandardDescriptor();
descriptor.setJavaClass(MWRelationalQueryManager.class);
descriptor.getInheritancePolicy().setParentClass(MWQueryManager.class);
descriptor.addDirectMapping("insertSQLString", "legacyGetInsertSQLString", "legacySetInsertSQLString", "insert-string/text()");
descriptor.addDirectMapping("updateSQLString", "legacyGetUpdateSQLString", "legacySetUpdateSQLString", "update-string/text()");
descriptor.addDirectMapping("deleteSQLString", "legacyGetDeleteSQLString", "legacySetDeleteSQLString", "delete-string/text()");
descriptor.addDirectMapping("readObjectSQLString", "legacyGetReadObjectSQLString", "legacySetReadObjectSQLString", "read-object-string/text()");
descriptor.addDirectMapping("readAllSQLString", "legacyGetReadAllSQLString", "legacySetReadAllSQLString", "read-all-string/text()");
return descriptor;
}
public MWReportQuery addReportQuery(String queryName) {
return (MWReportQuery) this.addQuery(new MWReportQuery(this, queryName));
}
public MWReadAllQuery buildReadAllQuery(String queryName) {
return new MWRelationalReadAllQuery(this, queryName);
}
public MWReadObjectQuery buildReadObjectQuery(String queryName) {
return new MWRelationalReadObjectQuery(this, queryName);
}
public boolean supportsReportQueries() {
return true;
}
public MWDeleteQuery getDeleteQuery() {
return this.deleteQuery;
}
public MWInsertQuery getInsertQuery() {
return this.insertQuery;
}
public MWCustomReadAllQuery getReadAllQuery() {
return this.readAllQuery;
}
public MWCustomReadObjectQuery getReadObjectQuery(){
return this.readObjectQuery;
}
public MWUpdateQuery getUpdateQuery() {
return this.updateQuery;
}
public void setDeleteQuery(MWDeleteQuery delete) {
MWDeleteQuery oldDelete = getDeleteQuery();
this.deleteQuery = delete;
firePropertyChanged(DELETE_QUERY_PROPERTY, oldDelete, delete);
}
public void setDeleteSQLString(String sqlString) {
this.deleteQuery.setSQLString(sqlString);
}
public void setInsertQuery(MWInsertQuery insert) {
MWInsertQuery oldInsert = getInsertQuery();
this.insertQuery = insert;
firePropertyChanged(INSERT_QUERY_PROPERTY, oldInsert, insert);
}
public void setInsertSQLString(String sqlString) {
this.insertQuery.setSQLString(sqlString);
}
public void setReadAllQuery(MWCustomReadAllQuery readAll) {
MWCustomReadAllQuery oldReadAll = getReadAllQuery();
this.readAllQuery = readAll;
firePropertyChanged(READ_ALL_QUERY_PROPERTY, oldReadAll, readAll);
}
public void setReadAllSQLString(String sqlString) {
this.readAllQuery.setSQLString(sqlString);
}
public void setReadObjectQuery(MWCustomReadObjectQuery readObject) {
MWCustomReadObjectQuery oldReadObject = getReadObjectQuery();
this.readObjectQuery = readObject;
firePropertyChanged(READ_OBJECT_QUERY_PROPERTY, oldReadObject, readObject);
}
public void setReadObjectSQLString(String sqlString) {
this.readObjectQuery.setSQLString(sqlString);
}
public void setUpdateQuery(MWUpdateQuery update) {
MWUpdateQuery oldUpdate = getUpdateQuery();
this.updateQuery = update;
firePropertyChanged(UPDATE_QUERY_PROPERTY, oldUpdate, update);
}
public void setUpdateSQLString(String sqlString) {
this.updateQuery.setSQLString(sqlString);
}
public void notifyExpressionsToRecalculateQueryables(){
for (Iterator queries = queries(); queries.hasNext();) {
((MWRelationalQuery) queries.next()).notifyExpressionsToRecalculateQueryables();
}
}
//TopLink use only
private MWInsertQuery getInsertQueryForTopLink() {
return this.insertQuery;
}
//TopLink use only
private MWDeleteQuery getDeleteQueryForTopLink() {
return this.deleteQuery;
}
//TopLink use only
private MWUpdateQuery getUpdateQueryForTopLink() {
return this.updateQuery;
}
//TopLink use only
private MWCustomReadObjectQuery getReadObjectQueryForTopLink() {
return this.readObjectQuery;
}
//TopLink use only
private MWCustomReadAllQuery getReadAllQueryForTopLink() {
return this.readAllQuery;
}
//TopLink use only
private void setInsertQueryForTopLink(MWInsertQuery query) {
if (query != null) {
this.insertQuery = query;
}
}
//TopLink use only
private void setDeleteQueryForTopLink(MWDeleteQuery query) {
if (query != null) {
this.deleteQuery = query;
}
}
//TopLink use only
private void setUpdateQueryForTopLink(MWUpdateQuery query) {
if (query != null) {
this.updateQuery = query;
}
}
//TopLink use only
private void setReadObjectQueryForTopLink(MWCustomReadObjectQuery query) {
if (query != null) {
this.readObjectQuery = query;
}
}
//TopLink use only
private void setReadAllQueryForTopLink(MWCustomReadAllQuery query) {
if (query != null) {
this.readAllQuery = query;
}
}
@Override
protected void legacy60PostBuild(DescriptorEvent event) {
super.legacy60PostBuild(event);
// Checks null since in cases where sql was specified,
// these object will be not null.
if (this.deleteQuery == null) {
this.deleteQuery = new MWDeleteQuery(this);
}
if (this.insertQuery == null) {
this.insertQuery = new MWInsertQuery(this);
}
if (this.readAllQuery == null) {
this.readAllQuery = new MWCustomReadAllQuery(this);
}
if (this.readObjectQuery == null) {
this.readObjectQuery = new MWCustomReadObjectQuery(this);;
}
if (this.updateQuery == null) {
this.updateQuery = new MWUpdateQuery(this);
}
}
//for legacy TopLink use only
private String legacyGetInsertSQLString() {
//this should never be called
throw new IllegalStateException();
}
//for legacy TopLink use only
private String legacyGetUpdateSQLString() {
//this should never be called
throw new IllegalStateException();
}
//for legacy TopLink use only
private String legacyGetDeleteSQLString() {
//this should never be called
throw new IllegalStateException();
}
//for legacy TopLink use only
private String legacyGetReadObjectSQLString() {
//this should never be called
throw new IllegalStateException();
}
//for legacy TopLink use only
private String legacyGetReadAllSQLString() {
//this should never be called
throw new IllegalStateException();
}
//for legacy TopLink use only
private void legacySetInsertSQLString(String sql) {
if (sql != null) {
this.insertQuery = new MWInsertQuery(this);
this.insertQuery.setQueryFormatType(MWRelationalQuery.SQL_FORMAT);
MWSQLQueryFormat queryFormat = (MWSQLQueryFormat)this.insertQuery.getQueryFormat();
queryFormat.legacySetQueryStringForTopLink(sql);
}
}
//for legacy TopLink use only
private void legacySetUpdateSQLString(String sql) {
if (sql != null) {
this.updateQuery = new MWUpdateQuery(this);
this.updateQuery.setQueryFormatType(MWRelationalQuery.SQL_FORMAT);
MWSQLQueryFormat queryFormat = (MWSQLQueryFormat)this.updateQuery.getQueryFormat();
queryFormat.legacySetQueryStringForTopLink(sql);
}
}
//for legacy TopLink use only
private void legacySetDeleteSQLString(String sql) {
if (sql != null) {
this.deleteQuery = new MWDeleteQuery(this);
this.deleteQuery.setQueryFormatType(MWRelationalQuery.SQL_FORMAT);
MWSQLQueryFormat queryFormat = (MWSQLQueryFormat)this.deleteQuery.getQueryFormat();
queryFormat.legacySetQueryStringForTopLink(sql);
}
}
//for legacy TopLink use only
private void legacySetReadObjectSQLString(String sql) {
if (sql != null) {
this.readObjectQuery = new MWCustomReadObjectQuery(this);
this.readObjectQuery.setQueryFormatType(MWRelationalQuery.SQL_FORMAT);
MWSQLQueryFormat queryFormat = (MWSQLQueryFormat)this.readObjectQuery.getQueryFormat();
queryFormat.legacySetQueryStringForTopLink(sql);
}
}
//for legacy TopLink use only
private void legacySetReadAllSQLString(String sql) {
if (sql != null) {
this.readAllQuery = new MWCustomReadAllQuery(this);
this.readAllQuery.setQueryFormatType(MWRelationalQuery.SQL_FORMAT);
MWSQLQueryFormat queryFormat = (MWSQLQueryFormat)this.readAllQuery.getQueryFormat();
queryFormat.legacySetQueryStringForTopLink(sql);
}
}
//Conversion methods
public void adjustRuntimeDescriptor(ClassDescriptor runtimeDescriptor) {
super.adjustRuntimeDescriptor(runtimeDescriptor);
DescriptorQueryManager rtQueryManager = (DescriptorQueryManager) runtimeDescriptor.getQueryManager();
// Custom Calls
if (!this.deleteQuery.isContentEmpty()) {
DeleteObjectQuery rtDeleteQuery = (DeleteObjectQuery)this.deleteQuery.buildRuntimeQuery();
this.deleteQuery.adjustRuntimeQuery(rtDeleteQuery);
rtQueryManager.setDeleteQuery(rtDeleteQuery);
}
if (!this.insertQuery.isContentEmpty()) {
InsertObjectQuery rtInsertQuery = (InsertObjectQuery)this.insertQuery.buildRuntimeQuery();
this.insertQuery.adjustRuntimeQuery(rtInsertQuery);
rtQueryManager.setInsertQuery(rtInsertQuery);
}
if (!this.updateQuery.isContentEmpty()) {
UpdateObjectQuery rtUpdateQuery = (UpdateObjectQuery)this.updateQuery.buildRuntimeQuery();
this.updateQuery.adjustRuntimeQuery(rtUpdateQuery);
rtQueryManager.setUpdateQuery(rtUpdateQuery);
}
if (!this.readAllQuery.isContentEmpty()) {
ReadAllQuery rtReadAllQuery = (ReadAllQuery)this.readAllQuery.buildRuntimeQuery();
this.readAllQuery.adjustRuntimeQuery(rtReadAllQuery);
rtQueryManager.setReadAllQuery(rtReadAllQuery);
}
if (!this.readObjectQuery.isContentEmpty()) {
ReadObjectQuery rtReadObjectQuery = (ReadObjectQuery)this.readObjectQuery.buildRuntimeQuery();
this.readObjectQuery.adjustRuntimeQuery(rtReadObjectQuery);
rtQueryManager.setReadObjectQuery(rtReadObjectQuery);
}
}
public void adjustFromRuntimeDescriptor(ClassDescriptor runtimeDescriptor) {
super.adjustFromRuntime(runtimeDescriptor);
DescriptorQueryManager rtQueryManager = (DescriptorQueryManager) runtimeDescriptor.getQueryManager();
// Custom Calls
DeleteObjectQuery rtDeleteQuery = (DeleteObjectQuery)this.deleteQuery.buildRuntimeQuery();
this.deleteQuery.adjustRuntimeQuery(rtDeleteQuery);
rtQueryManager.setDeleteQuery(rtDeleteQuery);
InsertObjectQuery rtInsertQuery = (InsertObjectQuery)this.insertQuery.buildRuntimeQuery();
this.insertQuery.adjustRuntimeQuery(rtInsertQuery);
rtQueryManager.setInsertQuery(rtInsertQuery);
UpdateObjectQuery rtUpdateQuery = (UpdateObjectQuery)this.updateQuery.buildRuntimeQuery();
this.updateQuery.adjustRuntimeQuery(rtUpdateQuery);
rtQueryManager.setUpdateQuery(rtUpdateQuery);
ReadAllQuery rtReadAllQuery = (ReadAllQuery)this.readAllQuery.buildRuntimeQuery();
this.readAllQuery.adjustRuntimeQuery(rtReadAllQuery);
rtQueryManager.setReadAllQuery(rtReadAllQuery);
ReadObjectQuery rtReadObjectQuery = (ReadObjectQuery)this.readObjectQuery.buildRuntimeQuery();
this.readObjectQuery.adjustRuntimeQuery(rtReadObjectQuery);
rtQueryManager.setReadObjectQuery(rtReadObjectQuery);
}
public static XMLDescriptor legacy60BuildDescriptor() {
XMLDescriptor descriptor = MWModel.legacy60BuildStandardDescriptor();
descriptor.setJavaClass(MWRelationalQueryManager.class);
descriptor.getInheritancePolicy().setParentClass(MWQueryManager.class);
descriptor.addDirectMapping("insertSQLString", "legacyGetInsertSQLString", "legacySetInsertSQLString", "insert-string/text()");
descriptor.addDirectMapping("updateSQLString", "legacyGetUpdateSQLString", "legacySetUpdateSQLString", "update-string/text()");
descriptor.addDirectMapping("deleteSQLString", "legacyGetDeleteSQLString", "legacySetDeleteSQLString", "delete-string/text()");
descriptor.addDirectMapping("readObjectSQLString", "legacyGetReadObjectSQLString", "legacySetReadObjectSQLString", "read-object-string/text()");
descriptor.addDirectMapping("readAllSQLString", "legacyGetReadAllSQLString", "legacySetReadAllSQLString", "read-all-string/text()");
return descriptor;
}
}
|
package pl.wurmonline.deedplanner.data;
import pl.wurmonline.deedplanner.data.bridges.BridgePart;
import java.util.*;
import java.util.Map.Entry;
import javax.media.opengl.GL2;
import org.w3c.dom.*;
import pl.wurmonline.deedplanner.*;
import pl.wurmonline.deedplanner.data.storage.Data;
import pl.wurmonline.deedplanner.logic.Tab;
import pl.wurmonline.deedplanner.logic.TileFragment;
import pl.wurmonline.deedplanner.logic.symmetry.Symmetry;
import pl.wurmonline.deedplanner.util.*;
public final class Tile implements XMLSerializable {
private static final float[] deformMatrix = new float[] {1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
private final Map map;
private final int x;
private final int y;
private int height = 0;
private Ground ground;
private final HashMap<EntityData, TileEntity> entities;
private Label label;
private BridgePart bridgePart;
private int caveHeight = 5;
private int caveSize = 30;
private CaveData cave = Data.caves.get("sw");
private Label caveLabel;
public Tile(Map map, int x, int y, Element tile) {
this.map = map;
this.x = x;
this.y = y;
height = (int) Float.parseFloat(tile.getAttribute("height"));
if (!tile.getAttribute("caveHeight").equals("")) {
caveHeight = (int) Float.parseFloat(tile.getAttribute("caveHeight"));
}
if (!tile.getAttribute("caveSize").equals("")) {
caveSize = (int) Float.parseFloat(tile.getAttribute("caveSize"));
}
ground = new Ground((Element) tile.getElementsByTagName("ground").item(0));
if (tile.getElementsByTagName("cave").getLength()!=0) {
cave = CaveData.get((Element) tile.getElementsByTagName("cave").item(0));
}
NodeList labels = tile.getElementsByTagName("label");
if (labels.getLength()!=0) {
label = new Label((Element) labels.item(0));
}
NodeList caveLabels = tile.getElementsByTagName("caveLabel");
if (caveLabels.getLength()!=0) {
caveLabel = new Label((Element) caveLabels.item(0));
}
entities = new HashMap<>();
NodeList list = tile.getElementsByTagName("level");
for (int i=0; i<list.getLength(); i++) {
Element level = (Element) list.item(i);
int floor = Integer.parseInt(level.getAttribute("value"));
NodeList childNodes = level.getElementsByTagName("*");
for (int i2=0; i2<childNodes.getLength(); i2++) {
Element entity = (Element) childNodes.item(i2);
switch (entity.getNodeName().toLowerCase()) {
case "floor":
entities.put(new EntityData(floor, EntityType.FLOORROOF), new Floor(entity));
break;
case "hwall":
if (x == map.getWidth()) {
Log.out(this, "Detected wall on the edge of visible area, deleting");
continue;
}
Wall hwall = new Wall(entity);
if (hwall.data.houseWall) {
entities.put(new EntityData(floor, EntityType.HWALL), hwall);
}
else {
entities.put(new EntityData(floor, EntityType.HFENCE), hwall);
}
break;
case "vwall":
if (y == map.getHeight()) {
Log.out(this, "Detected wall on the edge of visible area, deleting");
continue;
}
Wall vwall = new Wall(entity);
if (vwall.data.houseWall) {
entities.put(new EntityData(floor, EntityType.VWALL), vwall);
}
else {
entities.put(new EntityData(floor, EntityType.VFENCE), vwall);
}
break;
case "hborder":
entities.put(new EntityData(0, EntityType.HBORDER), BorderData.get(entity));
break;
case "vborder":
entities.put(new EntityData(0, EntityType.VBORDER), BorderData.get(entity));
break;
case "roof":
entities.put(new EntityData(floor, EntityType.FLOORROOF), new Roof(entity));
break;
case "object":
if (x == map.getWidth() || y == map.getHeight()) {
Log.out(this, "Detected object on the edge of visible area, deleting");
continue;
}
ObjectLocation loc = ObjectLocation.parse(entity.getAttribute("position"));
entities.put(new ObjectEntityData(floor, loc), new GameObject(entity));
break;
case "cave":
cave = CaveData.get(entity);
break;
}
}
}
}
public Tile(Map map, int x, int y) {
this.map = map;
this.x = x;
this.y = y;
if (!Data.grounds.isEmpty()) {
ground = new Ground(Data.grounds.get("gr"));
}
entities = new HashMap<>();
}
public Tile(Tile tile) {
this(tile.map, tile, tile.x, tile.y);
}
public Tile(Map map, Tile tile, int x, int y) {
this.map = map;
this.x = x;
this.y = y;
this.height = tile.height;
this.ground = tile.ground;
this.cave = tile.cave;
this.label = tile.label;
this.caveLabel = tile.caveLabel;
this.bridgePart = tile.bridgePart;
HashMap<EntityData, TileEntity> entities = new HashMap<>();
for (Entry<EntityData, TileEntity> entrySet : tile.entities.entrySet()) {
EntityData key = entrySet.getKey();
TileEntity value = entrySet.getValue();
entities.put(key, value.deepCopy());
}
this.entities = new HashMap(tile.entities);
}
public void render3d(GL2 g, boolean edge) {
if (!edge) {
if (Globals.floor>=0) {
renderGround(g);
}
else {
renderUnderground(g);
}
}
renderEntities(g);
}
private void renderGround(GL2 g) {
if (bridgePart != null) {
g.glColor3f(1, 1, 1);
bridgePart.render(g, this);
}
if ((Globals.upCamera && Globals.floor>=0 && Globals.floor<3) || !Globals.upCamera) {
if (Globals.upCamera && Globals.floor>=0 && Globals.floor<3) {
switch (Globals.floor) {
case 0:
g.glColor3f(1, 1, 1);
break;
case 1:
g.glColor3f(0.6f, 0.6f, 0.6f);
break;
case 2:
g.glColor3f(0.25f, 0.25f, 0.25f);
break;
}
}
ground.render(g, this);
}
}
private void renderEntities(GL2 g) {
for (Entry<EntityData, TileEntity> e : entities.entrySet()) {
EntityData key = e.getKey();
final int floor = key.getFloor();
if (!MathUtils.isSameSign(floor, Globals.floor)) {
continue;
}
float colorMod = 1;
if (Globals.upCamera) {
// in case of negative floors (cave dwellings) color modifier will be reversed
switch (Math.abs(Globals.floor) - Math.abs(floor)) {
case 0:
colorMod = 1;
break;
case 1:
colorMod = 0.6f;
break;
case 2:
colorMod = 0.25f;
break;
default:
continue;
}
}
TileEntity entity = e.getValue();
g.glPushMatrix();
renderEntity(g, key, entity, colorMod);
g.glPopMatrix();
g.glColor3f(1, 1, 1);
}
}
private void renderEntity(GL2 g, EntityData data, TileEntity entity, float colorMod) {
int floor = data.getFloor();
int floorOffset = getFloorOffset(floor);
switch (data.getType()) {
case FLOORROOF:
g.glTranslatef(4, 0, floorOffset + getFloorHeight()/Constants.HEIGHT_MOD);
g.glColor3f(colorMod, colorMod, colorMod);
entity.render(g, this);
break;
case VWALL: case VFENCE:
float verticalWallHeight = getVerticalWallHeight();
float verticalWallHeightDiff = getVerticalWallHeightDiff();
renderWall(g, (Wall) entity, floorOffset, colorMod, verticalWallHeight, verticalWallHeightDiff, true);
break;
case HWALL: case HFENCE:
float horizontalWallHeight = getHorizontalWallHeight();
float horizontalWallHeightDiff = getHorizontalWallHeightDiff();
renderWall(g, (Wall) entity, floorOffset, colorMod, horizontalWallHeight, horizontalWallHeightDiff, false);
break;
case OBJECT:
ObjectEntityData objData = (ObjectEntityData) data;
ObjectLocation loc = objData.getLocation();
GameObject obj = (GameObject) entity;
GameObjectData goData = obj.getData();
boolean isTree = goData.type.equals(Constants.TREE_TYPE);
boolean treeRenderingAllowed = (Globals.renderTrees2d && Globals.upCamera) || (Globals.renderTrees3d && !Globals.upCamera);
if (!isTree || (isTree && treeRenderingAllowed)) {
g.glColor3f(colorMod, colorMod, colorMod);
g.glTranslatef(loc.getHorizontalAlign(), loc.getVerticalAlign(), floorOffset + getHeight(loc.getHorizontalAlign()/4f, loc.getVerticalAlign()/4f)/Constants.HEIGHT_MOD);
obj.render(g, this);
}
break;
}
}
private int getFloorOffset(int floor) {
if (floor < 0) {
floor = Math.abs(floor) - 1;
}
return 3 * floor;
}
private void renderWall(GL2 g, Wall wall, int floorOffset, float colorMod, float wallElevation, float wallHeightDiff, boolean isVertical) {
g.glTranslatef(0, 0, floorOffset + wallElevation / Constants.HEIGHT_MOD);
if (isVertical) {
g.glRotatef(90, 0, 0, 1);
}
float diff = wallHeightDiff / 47f;
if (diff<0) {
g.glTranslatef(0, 0, -diff*4f);
}
deform(g, diff);
if (Globals.upCamera) {
wall.data.color.use(g, colorMod);
}
else {
g.glColor3f(1, 1, 1);
}
wall.render(g, this);
g.glColor3f(1, 1, 1);
}
private void renderUnderground(GL2 g) {
cave.render(g, this);
}
public void render2d(GL2 g) {
for (Entry<EntityData, TileEntity> e : entities.entrySet()) {
EntityData key = e.getKey();
TileEntity entity = e.getValue();
g.glPushMatrix();
switch (key.getType()) {
case VBORDER:
g.glRotatef(90, 0, 0, 1);
BorderData vBorder = (BorderData) entity;
if (Globals.upCamera) {
vBorder.render(g, this);
}
g.glColor3f(1, 1, 1);
break;
case HBORDER:
BorderData hBorder = (BorderData) entity;
if (Globals.upCamera) {
hBorder.render(g, this);
}
g.glColor3f(1, 1, 1);
break;
}
g.glPopMatrix();
g.glColor3f(1, 1, 1);
}
}
private float getFloorHeight() {
float h00 = getCurrentLayerHeight();
float h10 = getMap().getTile(this, 1, 0)!=null ? getMap().getTile(this, 1, 0).getCurrentLayerHeight(): 0;
float h01 = getMap().getTile(this, 0, 1)!=null ? getMap().getTile(this, 0, 1).getCurrentLayerHeight() : 0;
float h11 = getMap().getTile(this, 1, 1)!=null ? getMap().getTile(this, 1, 1).getCurrentLayerHeight() : 0;
return Math.max(Math.max(h00, h10), Math.max(h01, h11));
}
private float getVerticalWallHeight() {
return Math.min(getCurrentLayerHeight(), getMap().getTile(this, 0, 1).getCurrentLayerHeight());
}
private float getVerticalWallHeightDiff() {
return getMap().getTile(this, 0, 1).getCurrentLayerHeight() - getCurrentLayerHeight();
}
private float getHorizontalWallHeight() {
return Math.min(getCurrentLayerHeight(), getMap().getTile(this, 1, 0).getCurrentLayerHeight());
}
private float getHorizontalWallHeightDiff() {
return getMap().getTile(this, 1, 0).getCurrentLayerHeight() - getCurrentLayerHeight();
}
private void deform(GL2 g, float scale) {
deformMatrix[2] = scale;
g.glMultMatrixf(deformMatrix, 0);
}
public void renderSelection(GL2 g) {
if ((Globals.tab == Tab.labels || Globals.tab == Tab.height || Globals.tab == Tab.symmetry || Globals.tab == Tab.bridges)) {
g.glDisable(GL2.GL_ALPHA_TEST);
g.glEnable(GL2.GL_BLEND);
g.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA);
double color = System.currentTimeMillis();
color%=2000d; color-=1000d; color = Math.abs(color); color/=1000d;
g.glColor4d(1, 1, 0, 0.1d+0.2d*color);
g.glBegin(GL2.GL_QUADS);
g.glVertex2f(0, 0);
g.glVertex2f(0, 4);
g.glVertex2f(4, 4);
g.glVertex2f(4, 0);
g.glEnd();
g.glColor4f(1, 1, 1, 1);
g.glDisable(GL2.GL_BLEND);
g.glEnable(GL2.GL_ALPHA_TEST);
}
}
public void renderSymmetry(GL2 g) {
Symmetry sym = getMap().getSymmetry();
switch(sym.getType()) {
case TILE:
sym.renderTiles(g);
break;
case BORDER:
case CORNER:
if(getX() == sym.getX() && Globals.xSymLock)
sym.renderXBorder(g);
if(getY() == sym.getY() && Globals.ySymLock)
sym.renderYBorder(g);
break;
}
}
public void renderLabel(GL2 g) {
if (label!=null) {
label.render(g, this);
}
}
public void renderCaveLabel(GL2 g) {
if (caveLabel!=null) {
caveLabel.render(g, this);
}
}
public void serialize(Document doc, Element root) {
Element tile = doc.createElement("tile");
tile.setAttribute("x", Integer.toString(x));
tile.setAttribute("y", Integer.toString(y));
tile.setAttribute("height", Float.toString(height));
tile.setAttribute("caveHeight", Float.toString(caveHeight));
tile.setAttribute("caveSize", Float.toString(caveSize));
root.appendChild(tile);
ground.serialize(doc, tile);
cave.serialize(doc, tile);
if (label!=null) {
label.serialize(doc, tile, false);
}
if (caveLabel!=null) {
caveLabel.serialize(doc, tile, true);
}
final HashMap<Integer, Element> levels = new HashMap<>();
for (Entry<EntityData, TileEntity> e : entities.entrySet()) {
final EntityData key = e.getKey();
final TileEntity entity = e.getValue();
final int floor = key.getFloor();
Element level = levels.get(floor);
if (level==null) {
level = doc.createElement("level");
level.setAttribute("value", Integer.toString(key.getFloor()));
levels.put(key.getFloor(), level);
tile.appendChild(level);
}
switch (key.getType()) {
case FLOORROOF:
entity.serialize(doc, level);
break;
case HWALL: case HFENCE:
Element hWall = doc.createElement("hWall");
entity.serialize(doc, hWall);
level.appendChild(hWall);
break;
case VWALL: case VFENCE:
Element vWall = doc.createElement("vWall");
entity.serialize(doc, vWall);
level.appendChild(vWall);
break;
case HBORDER:
Element hDeco = doc.createElement("hBorder");
entity.serialize(doc, hDeco);
level.appendChild(hDeco);
break;
case VBORDER:
Element vDeco = doc.createElement("vBorder");
entity.serialize(doc, vDeco);
level.appendChild(vDeco);
break;
case OBJECT:
ObjectEntityData objectData = (ObjectEntityData) key;
Element objectElement = doc.createElement("object");
objectElement.setAttribute("position", objectData.getLocation().toString());
entity.serialize(doc, objectElement);
level.appendChild(objectElement);
break;
}
}
}
protected int getEntityFloor(TileEntity entity) {
for (Entry<EntityData, TileEntity> entry : entities.entrySet()) {
if (entry.getValue() == entity) {
return entry.getKey().getFloor();
}
}
throw new DeedPlannerRuntimeException("Cannot find entity: "+entity);
}
public Map getMap() {
return map;
}
public Ground getGround() {
return ground;
}
public void setGround(GroundData data, RoadDirection dir) {
setGround(data, dir, true);
}
public void setGround(GroundData data) {
setGround(data, Globals.roadDirection, true);
}
void setGround(GroundData data, RoadDirection dir, boolean undo) {
if (!new Ground(data).equals(ground)) {
Tile oldTile = new Tile(this);
if (!data.diagonal) {
dir = RoadDirection.CENTER;
}
ground = new Ground(data, dir);
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setHeight(int height) {
if (Globals.floor>=0) {
setHeight(height, true);
}
else if (!Globals.editSize) {
setCaveHeight(height, true);
}
else {
setCaveSize(height, true);
}
}
void setHeight(int height, boolean undo) {
if (this.height!=height) {
Tile oldTile = new Tile(this);
this.height = height;
map.recalculateHeight();
if (undo) {
map.addUndo(this, oldTile);
for (int i = -1; i <= 0; i++) {
for (int i2 = -1; i2 <= 0; i2++) {
Tile tile = map.getTile(this, i, i2);
if (tile != null) {
tile.destroyBridge();
}
}
}
}
}
}
public float getHeight(final float xPart, final float yPart) {
final float xPartRev = 1f - xPart;
final float yPartRev = 1f - yPart;
final float h00 = getCurrentLayerHeight();
final float h10 = x!=map.getWidth() ? map.getTile(this, 1, 0).getCurrentLayerHeight() : 0;
final float h01 = y!=map.getHeight() ? map.getTile(this, 0, 1).getCurrentLayerHeight() : 0;
final float h11 = (x!=map.getWidth() && y!=map.getHeight()) ? map.getTile(this, 1, 1).getCurrentLayerHeight() : 0;
final float x0 = (h00*xPartRev + h10*xPart);
final float x1 = (h01*xPartRev + h11*xPart);
return (x0*yPartRev + x1*yPart);
}
public int getHeight() {
return height;
}
void setCaveHeight(int height, boolean undo) {
if (this.caveHeight!=height) {
Tile oldTile = new Tile(this);
this.caveHeight = height;
map.recalculateHeight();
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public int getCaveHeight() {
return caveHeight;
}
private int getCurrentLayerHeight() {
if (Globals.floor < 0) {
return caveHeight;
}
else {
return height;
}
}
void setCaveSize(int size, boolean undo) {
if (size<30 || size>300) {
return;
}
if (this.caveSize!=size) {
Tile oldTile = new Tile(this);
this.caveSize = size;
map.recalculateHeight();
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public int getCaveSize() {
return caveSize;
}
public void setCaveEntity(CaveData entity) {
setCaveEntity(entity, true);
}
void setCaveEntity(CaveData entity, boolean undo) {
if (this.cave != entity) {
Tile oldTile = new Tile(this);
this.cave = entity;
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public CaveData getCaveEntity() {
return cave;
}
public boolean isFlat() {
return map.getTile(this, 1, 1)!=null && getHeight()==map.getTile(this, 1, 1).getHeight() &&
map.getTile(this, 1, 0)!=null && getHeight()==map.getTile(this, 1, 0).getHeight() &&
map.getTile(this, 0, 1)!=null && getHeight()==map.getTile(this, 0, 1).getHeight();
}
public void setTileContent(TileEntity entity, int level) {
setTileContent(entity, level, true);
}
void setTileContent(TileEntity entity, int level, boolean undo) {
if (!isFlat()) {
return;
}
if (entity instanceof Roof) {
for (TileEntity e : entities.values()) {
if (e instanceof Roof) {
return;
}
}
}
final EntityData entityData = new EntityData(level, EntityType.FLOORROOF);
if (entity!=entities.get(entityData)) {
Tile oldTile = new Tile(this);
if (entity!=null) {
entities.put(entityData, entity);
}
else {
entities.remove(entityData);
}
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public TileEntity getTileContent(int level) {
return entities.get(new EntityData(level, EntityType.FLOORROOF));
}
public void setHorizontalWall(WallData wall, int level) {
setHorizontalWall(wall, level, true);
}
void setHorizontalWall(WallData wall, int level, boolean undo) {
if (wall!=null && wall.houseWall) {
if (!(isFlat() || (map.getTile(this, 0, -1)!=null && map.getTile(this, 0, -1).isFlat()))) {
return;
}
}
final EntityData entityData;
if (wall!=null && wall.houseWall) {
entityData = new EntityData(level, EntityType.HWALL);
}
else if (wall!=null) {
entityData = new EntityData(level, EntityType.HFENCE);
}
else {
entityData = null;
}
final EntityData wallEntity = new EntityData(level, EntityType.HWALL);
final EntityData fenceEntity = new EntityData(level, EntityType.HFENCE);
final Wall currentWall = (Wall) entities.get(wallEntity);
final Wall currentFence = (Wall) entities.get(fenceEntity);
boolean reversed;
if (wall!=null && wall.houseWall) {
if (Globals.autoReverseWall) {
reversed = getTileContent(level)!=null && map.getTile(this, 0, -1).getTileContent(level)==null;
if (reversed == false) {
reversed = Globals.reverseWall;
}
}
else {
reversed = Globals.reverseWall;
}
}
else {
reversed = false;
}
if (!(new Wall(wall, reversed).equals(entities.get(entityData)))) {
Tile oldTile = new Tile(this);
if (wall!=null) {
entities.put(entityData, new Wall(wall, reversed));
if (wall.houseWall && !(wall.arch && currentFence!=null && currentFence.data.archBuildable)) {
entities.remove(fenceEntity);
}
else if (!wall.houseWall && !(wall.archBuildable && currentWall!=null && currentWall.data.arch)) {
entities.remove(wallEntity);
}
}
else {
entities.remove(wallEntity);
entities.remove(fenceEntity);
}
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public Wall getHorizontalWall(int level) {
return (Wall) entities.get(new EntityData(level, EntityType.HWALL));
}
public Wall getHorizontalFence(int level) {
return (Wall) entities.get(new EntityData(level, EntityType.HFENCE));
}
public void clearHorizontalWalls() {
for (int i = 0; i < Constants.FLOORS_LIMIT; i++) {
clearHorizontalWalls(i);
}
}
public void clearHorizontalWalls(int level) {
entities.remove(new EntityData(level, EntityType.HWALL));
entities.remove(new EntityData(level, EntityType.HFENCE));
}
public void setVerticalWall(WallData wall, int level) {
setVerticalWall(wall, level, true);
}
void setVerticalWall(WallData wall, int level, boolean undo) {
if (wall!=null && wall.houseWall) {
if (!(isFlat() || map.getTile(this, -1, 0).isFlat())) {
return;
}
}
final EntityData entityData;
if (wall!=null && wall.houseWall) {
entityData = new EntityData(level, EntityType.VWALL);
}
else if (wall!=null) {
entityData = new EntityData(level, EntityType.VFENCE);
}
else {
entityData = null;
}
final EntityData wallEntity = new EntityData(level, EntityType.VWALL);
final EntityData fenceEntity = new EntityData(level, EntityType.VFENCE);
final Wall currentWall = (Wall) entities.get(wallEntity);
final Wall currentFence = (Wall) entities.get(fenceEntity);
boolean reversed;
if (wall!=null && wall.houseWall) {
if (Globals.autoReverseWall) {
reversed = getTileContent(level)==null && map.getTile(this, -1, 0).getTileContent(level)!=null;
if (reversed == false) {
reversed = Globals.reverseWall;
}
}
else {
reversed = Globals.reverseWall;
}
}
else {
reversed = false;
}
if (!(new Wall(wall, reversed).equals(entities.get(entityData)))) {
Tile oldTile = new Tile(this);
if (wall!=null) {
entities.put(entityData, new Wall(wall, reversed));
if (wall.houseWall && !(wall.arch && currentFence!=null && currentFence.data.archBuildable)) {
entities.remove(fenceEntity);
}
else if (!wall.houseWall && !(wall.archBuildable && currentWall!=null && currentWall.data.arch)) {
entities.remove(wallEntity);
}
}
else {
entities.remove(wallEntity);
entities.remove(fenceEntity);
}
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public Wall getVerticalWall(int level) {
return (Wall) entities.get(new EntityData(level, EntityType.VWALL));
}
public Wall getVerticalFence(int level) {
return (Wall) entities.get(new EntityData(level, EntityType.VFENCE));
}
public void clearVerticalWalls() {
for (int i = 0; i < Constants.FLOORS_LIMIT; i++) {
clearVerticalWalls(i);
}
}
public void clearVerticalWalls(int level) {
entities.remove(new EntityData(level, EntityType.VWALL));
entities.remove(new EntityData(level, EntityType.VFENCE));
}
public void setHorizontalBorder(BorderData border) {
setHorizontalBorder(border, true);
}
void setHorizontalBorder(BorderData border, boolean undo) {
final EntityData entityData = new EntityData(0, EntityType.HBORDER);
if (border!=entities.get(entityData)) {
Tile oldTile = new Tile(this);
if (border!=null) {
entities.put(entityData, border);
}
else {
entities.remove(entityData);
}
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public BorderData getHorizontalBorder() {
return (BorderData) entities.get(new EntityData(0, EntityType.HBORDER));
}
public void setVerticalBorder(BorderData border) {
setVerticalBorder(border, true);
}
void setVerticalBorder(BorderData border, boolean undo) {
final EntityData entityData = new EntityData(0, EntityType.VBORDER);
if (border!=entities.get(entityData)) {
Tile oldTile = new Tile(this);
if (border!=null) {
entities.put(entityData, border);
}
else {
entities.remove(entityData);
}
if (undo) {
map.addUndo(this, oldTile);
}
}
}
public BorderData getVerticalBorder() {
return (BorderData) entities.get(new EntityData(0, EntityType.VBORDER));
}
public void setLabel(Label label) {
setLabel(label, true);
}
void setLabel(Label label, boolean undo) {
Tile oldTile = new Tile(this);
this.label = label;
if (undo) {
map.addUndo(this, oldTile);
}
}
public Label getLabel() {
return label;
}
public void setCaveLabel(Label caveLabel) {
setCaveLabel(caveLabel, true);
}
void setCaveLabel(Label caveLabel, boolean undo) {
Tile oldTile = new Tile(this);
this.caveLabel = caveLabel;
if (undo) {
map.addUndo(this, oldTile);
}
}
public Label getCaveLabel() {
return caveLabel;
}
public void setGameObject(GameObjectData data, ObjectLocation location, int floor) {
setGameObject(data, location, floor, true);
}
void setGameObject(GameObjectData data, ObjectLocation location, int floor, boolean undo) {
Tile oldTile = new Tile(this);
if (data!=null) {
entities.put(new ObjectEntityData(floor, location), new GameObject(data));
}
else {
for (ObjectLocation loc : ObjectLocation.values()) {
entities.remove(new ObjectEntityData(floor, loc));
}
}
if (undo) {
map.addUndo(this, oldTile);
}
}
public GameObject getGameObject(int level, ObjectLocation location) {
//assumption - ObjectEntityData key always have GameObject value.
return (GameObject) entities.get(new ObjectEntityData(level, location));
}
public void destroyBridge() {
if (bridgePart != null) {
bridgePart.destroy();
}
}
/**
* This method shouldn't be called to destroy bridge manually - use destroyBridge() instead!
*/
public void setBridgePart(BridgePart bridgePart) {
this.bridgePart = bridgePart;
}
public BridgePart getBridgePart() {
return bridgePart;
}
public Materials getMaterials() {
return getMaterials(false, false);
}
public Materials getMaterials(boolean withRight, boolean withTop) {
Materials materials = new Materials();
entities.values().stream().forEach((entity) -> {
materials.put(entity.getMaterials());
});
if (bridgePart != null) {
materials.put(bridgePart.getMaterials());
}
if (withRight) {
for (int i = 0; i<Constants.FLOORS_LIMIT; i++) {
Wall wall = map.getTile(this, 1, 0).getVerticalWall(i);
Wall fence = map.getTile(this, 1, 0).getVerticalFence(i);
if (wall!=null) {
materials.put(wall.getMaterials());
}
if (fence!=null) {
materials.put(fence.getMaterials());
}
}
}
if (withTop) {
for (int i = 0; i<Constants.FLOORS_LIMIT; i++) {
Wall wall = map.getTile(this, 0, 1).getHorizontalWall(i);
Wall fence = map.getTile(this, 0, 1).getHorizontalFence(i);
if (wall!=null) {
materials.put(wall.getMaterials());
}
if (fence!=null) {
materials.put(fence.getMaterials());
}
}
}
return materials;
}
public boolean isPassable(TileBorder border) {
switch (border) {
case SOUTH:
return getHorizontalWall(0)==null;
case NORTH:
return map.getTile(this, 0, 1)!=null &&
map.getTile(this, 0, 1).getHorizontalWall(0)==null;
case WEST:
return getVerticalWall(0)==null;
case EAST:
return map.getTile(this, 1, 0)!=null &&
map.getTile(this, 1, 0).getVerticalWall(0)==null;
default:
return false;
}
}
public String toString() {
return "Tile: ("+x+"; "+y+")";
}
public Tile[] getAffectedTiles(TileFragment frag) {
final Tile[] tiles;
if (null != frag) switch (frag) {
case CENTER:
tiles = new Tile[4];
tiles[0] = this;
tiles[1] = this.getMap().getTile(this, 1, 0);
tiles[2] = this.getMap().getTile(this, 1, 1);
tiles[3] = this.getMap().getTile(this, 0, 1);
return tiles;
case S:
tiles = new Tile[2];
tiles[0] = this;
tiles[1] = this.getMap().getTile(this, 1, 0);
return tiles;
case N:
tiles = new Tile[2];
tiles[0] = this.getMap().getTile(this, 0, 1);
tiles[1] = this.getMap().getTile(this, 1, 1);
return tiles;
case W:
tiles = new Tile[2];
tiles[0] = this;
tiles[1] = this.getMap().getTile(this, 0, 1);
return tiles;
case E:
tiles = new Tile[2];
tiles[0] = this.getMap().getTile(this, 1, 0);
tiles[1] = this.getMap().getTile(this, 1, 1);
return tiles;
case SW:
return new Tile[]{this};
case SE:
return new Tile[]{this.getMap().getTile(this, 1, 0)};
case NW:
return new Tile[]{this.getMap().getTile(this, 0, 1)};
case NE:
return new Tile[]{this.getMap().getTile(this, 1, 1)};
default:
throw new DeedPlannerRuntimeException("Illegal argument");
}
return null;
}
}
|
package org.xwiki.eventstream.internal;
import java.util.Date;
import java.util.List;
import org.xwiki.job.AbstractRequest;
import org.xwiki.job.Request;
/**
* The request used to configure {@link LegacyEventMigrationJob}.
*
* @version $Id$
* @since 12.6
*/
public class LegacyEventMigrationRequest extends AbstractRequest
{
/**
* Serialization identifier.
*/
private static final long serialVersionUID = 1L;
private static final String SINCE_ID = "after";
/**
* The default constructor.
*/
public LegacyEventMigrationRequest()
{
}
/**
* @param request the request to copy
*/
public LegacyEventMigrationRequest(Request request)
{
super(request);
}
/**
* @param since the date after which to copy the events
* @param id the identifier used to access the job
*/
public LegacyEventMigrationRequest(Date since, List<String> id)
{
setSince(since);
setId(id);
}
/**
* @return the date after which to copy the events
*/
public Date getSince()
{
return this.getProperty(SINCE_ID);
}
/**
* @param since the date after which to copy the events
*/
public void setSince(Date since)
{
setProperty(SINCE_ID, since);
}
}
|
package io.airlift.log;
public enum Level
{
OFF(java.util.logging.Level.OFF),
DEBUG(java.util.logging.Level.FINE),
INFO(java.util.logging.Level.INFO),
WARN(java.util.logging.Level.WARNING),
ERROR(java.util.logging.Level.SEVERE);
private final java.util.logging.Level julLevel;
Level(java.util.logging.Level julLevel)
{
this.julLevel = julLevel;
}
java.util.logging.Level toJulLevel()
{
return julLevel;
}
static Level fromJulLevel(java.util.logging.Level level)
{
// Convert any implementation of Level based on the int value
int levelValue = level.intValue();
if (levelValue == java.util.logging.Level.OFF.intValue()) {
return OFF;
}
if (levelValue >= java.util.logging.Level.SEVERE.intValue()) {
return ERROR;
}
if (levelValue >= java.util.logging.Level.WARNING.intValue()) {
return WARN;
}
if (levelValue >= java.util.logging.Level.INFO.intValue()) {
return INFO;
}
return DEBUG;
}
}
|
package org.csstudio.opibuilder.converter.writer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.csstudio.opibuilder.converter.EdmConverterTest;
import org.csstudio.opibuilder.converter.model.EdmColor;
import org.csstudio.opibuilder.converter.model.EdmDisplay;
import org.csstudio.opibuilder.converter.model.EdmException;
import org.csstudio.opibuilder.converter.model.EdmModel;
import org.csstudio.opibuilder.converter.model.Edm_activeXTextClass;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Opi_activeXTextClassTest {
@Test
public void testOpi_activeXTextClass() throws EdmException {
System.setProperty("edm2xml.robustParsing", "false");
System.setProperty("edm2xml.colorsFile", EdmConverterTest.COLOR_LIST_FILE);
Document doc = XMLFileHandler.createDomDocument();
Element root = doc.createElement("root");
doc.appendChild(root);
String edlFile = EdmConverterTest.RESOURCES_LOCATION + "EDMDisplayParser_example.edl";
EdmModel.getInstance();
EdmDisplay d = EdmModel.getDisplay(edlFile);
assertTrue(d.getSubEntity(6) instanceof Edm_activeXTextClass);
Edm_activeXTextClass t = (Edm_activeXTextClass)d.getSubEntity(6);
Context context = new Context(doc, root, d, 0, 0);
Opi_activeXTextClass o = new Opi_activeXTextClass(context, t);
assertTrue(o instanceof OpiWidget);
Element e = (Element)doc.getElementsByTagName("widget").item(0);
assertEquals("org.csstudio.opibuilder.widgets.Label", e.getAttribute("typeId"));
assertEquals("1.0", e.getAttribute("version"));
XMLFileHandler.isElementEqual("EDM Label", "name", e);
XMLFileHandler.isElementEqual("123", "x", e);
XMLFileHandler.isElementEqual("50", "y", e);
XMLFileHandler.isElementEqual("42", "width", e);
XMLFileHandler.isElementEqual("13", "height", e);
XMLFileHandler.isFontElementEqual("helvetica-bold-r-12.0", "font", e);
XMLFileHandler.isColorElementEqual(new EdmColor(10), "foreground_color", e);
XMLFileHandler.isColorElementEqual(new EdmColor(3), "background_color", e);
XMLFileHandler.isElementEqual("At low", "text", e);
XMLFileHandler.isElementEqual("true", "auto_size", e);
XMLFileHandler.isElementEqual("1", "border_style", e);
XMLFileHandler.isElementEqual("2", "border_width", e);
//XMLFileHandler.isElementEqual("true", "transparency", e);
//XMLFileHandler.writeXML(doc);
}
}
|
package com.arun.parallel;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Supplier;
public class SupplierFactory {
public static Supplier<Boolean> createSupplier(BooleanConsumer consumer) {
return consumer::accept;
}
public static Supplier<Boolean> createObjectSupplier(Serializable s, ObjectConsumer consumer) {
return () -> {
return consumer.accept(s);
};
}
public static Supplier<Boolean> createReflectionSupplier(Object obj, String methodName) throws NoSuchMethodException, SecurityException {
Method method = obj.getClass().getMethod(methodName);
return () -> {
try {
return (Boolean) method.invoke(obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return false;
};
}
public static <T> Supplier<T> createGenericReflectionSupplier(Object obj, String methodName, Class<? extends Object> type, Signature signature) throws NoSuchMethodException, SecurityException {
if (signature.getArgs() != null && signature.getArgs().size() > 0) {
return createGenericReflectionSupplierWithArgs(obj, methodName, type, signature.getArgs(), signature.getArgTypes().toArray(new Class[signature.getArgTypes().size()]));
} else {
return createGenericReflectionSupplierNoArgs(obj, methodName, type);
}
}
public static <T,E> Supplier<T> createGenericReflectionSupplierWithArgs(Object obj, String methodName, Class<? extends Object> type, List<? extends Object> args, Class<E>... argTypes) throws NoSuchMethodException, SecurityException {
Method argsMethod = obj.getClass().getMethod(methodName, argTypes);
return () -> {
T t = null;
try {
return (T)type.cast(argsMethod.invoke(obj, args.toArray(new Object[args.size()])));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return t;
};
}
public static <T> Supplier<T> createGenericReflectionSupplierNoArgs(Object obj, String methodName, Class<? extends Object> type) throws NoSuchMethodException, SecurityException {
Method noArgsMethod = obj.getClass().getMethod(methodName);
return () -> {
T t = null;
try {
return (T)type.cast(noArgsMethod.invoke(obj));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return t;
};
}
}
|
package com.biermacht.brews.recipe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.biermacht.brews.ingredient.Fermentable;
import com.biermacht.brews.ingredient.Hop;
import com.biermacht.brews.ingredient.Ingredient;
import com.biermacht.brews.ingredient.Misc;
import com.biermacht.brews.ingredient.Water;
import com.biermacht.brews.ingredient.Yeast;
import com.biermacht.brews.utils.BrewCalculator;
import com.biermacht.brews.utils.Utils;
import com.biermacht.brews.utils.comparators.InstructionComparator;
public class Recipe {
private String name; // Recipe name
private int version; // XML Version -- 1
private String type; // Extract, Grain, Mash
private String style; // Stout, Pilsner, etc.
private String brewer; // Brewer's name
private double batchSize; // Target size (L)
private double boilSize; // Pre-boil vol (L)
private int boilTime; // In Minutes
private double efficiency; // 100 for extract
private ArrayList<Hop> hops; // Hops used
private ArrayList<Fermentable> fermentables; // Fermentables used
private ArrayList<Yeast> yeasts; // Yeasts used
private ArrayList<Misc> miscs; // Misc ingredients used
private ArrayList<Water> waters; // Waters used
// TODO: ADD MASH PROFILES
private double OG; // Original Gravity
private double FG; // Final Gravity
private int fermentationStages; // # of Fermentation stages
private long id; // id for use in database
private String description; // User input description
private int batchTime; // Total length in weeks
private double ABV; // Alcohol by volume
private double bitterness; // Bitterness in IBU
private double color; // Color - SRM
private ArrayList<Instruction> instructionList;
public static final String EXTRACT = "Extract";
public static final String ALL_GRAIN = "All Grain";
public static final String PARTIAL_MASH = "Partial Mash";
// Public constructors
public Recipe(String s)
{
this.name = s;
this.setVersion(1);
this.setType(EXTRACT);
this.style = Utils.BEERSTYLE_OTHER.toString();
this.setBrewer("Unknown Brewer");
this.batchSize = -1;
this.setBoilSize(-1);
this.boilTime = -1;
this.efficiency = 100;
this.hops = new ArrayList<Hop>();
this.fermentables = new ArrayList<Fermentable>();
this.yeasts = new ArrayList<Yeast>();
this.miscs = new ArrayList<Misc>();
this.waters = new ArrayList<Water>();
this.OG = 1;
this.setFG(1);
this.setFermentationStages(1);
this.id = -1;
this.description = "No description provided";
this.batchTime = 60;
this.ABV = 0;
this.bitterness = 0;
this.color = 0;
instructionList = new ArrayList<Instruction>();
}
// Public methods
public void update()
{
setColor(BrewCalculator.calculateColorFromRecipe(this));
setOG(BrewCalculator.calculateOriginalGravityFromRecipe(this));
setBitterness(BrewCalculator.calculateIbuFromRecipe(this));
setFG(BrewCalculator.estimateFinalGravityFromRecipe(this));
setABV(BrewCalculator.calculateAbvFromRecipe(this));
}
public void setRecipeName(String name)
{
this.name = name;
}
public String getRecipeName()
{
return this.name;
}
public void addIngredient(Ingredient i)
{
if (i.getType().equals(Ingredient.HOP))
addHop(i);
else if (i.getType().equals(Ingredient.FERMENTABLE))
addFermentable(i);
else if (i.getType().equals(Ingredient.MISC))
addMisc(i);
else if (i.getType().equals(Ingredient.YEAST))
addYeast(i);
else if (i.getType().equals(Ingredient.WATER))
addWater(i);
update();
}
public void removeIngredient(String i)
{
for (Ingredient ingredient : getIngredientList())
{
if(i.equals(ingredient.toString()));
{
removeIngredient(ingredient);
}
}
update();
}
private void removeIngredient(Ingredient i)
{
if (i.getType().equals(Ingredient.HOP))
hops.remove((Hop) i);
else if (i.getType().equals(Ingredient.FERMENTABLE))
fermentables.remove((Fermentable) i);
else if (i.getType().equals(Ingredient.MISC))
miscs.remove((Misc) i);
else if (i.getType().equals(Ingredient.YEAST))
yeasts.remove((Yeast) i);
else if (i.getType().equals(Ingredient.WATER))
waters.remove((Water) i);
}
public void addInstruction(Instruction i)
{
instructionList.add(i);
}
public void removeInstruction(String i)
{
}
public String getDescription() {
return description;
}
public void setDescription(String description)
{
if (description.isEmpty())
this.description = "No description provided.";
else
this.description = description;
}
public String getStyle() {
return style;
}
public void setStyle(String beerStyle) {
this.style = beerStyle;
}
public ArrayList<Ingredient> getIngredientList()
{
ArrayList<Ingredient> list = new ArrayList<Ingredient>();
list.addAll(hops);
list.addAll(fermentables);
list.addAll(yeasts);
list.addAll(waters);
Collections.sort(list, new IngredientComparator());
return list;
}
public void setIngredientsList(ArrayList<Ingredient> ingredientsList) {
for (Ingredient i : ingredientsList)
{
if (i.getType().equals(Ingredient.HOP))
addHop(i);
else if (i.getType().equals(Ingredient.FERMENTABLE))
addFermentable(i);
else if (i.getType().equals(Ingredient.MISC))
addMisc(i);
else if (i.getType().equals(Ingredient.YEAST))
addYeast(i);
else if (i.getType().equals(Ingredient.WATER))
addWater(i);
}
update();
}
private void addWater(Ingredient i) {
Water w = (Water) i;
waters.add(w);
}
private void addYeast(Ingredient i) {
Yeast y = (Yeast) i;
yeasts.add(y);
}
private void addMisc(Ingredient i) {
Misc m = (Misc) i;
miscs.add(m);
}
private void addFermentable(Ingredient i) {
Fermentable f = (Fermentable) i;
fermentables.add(f);
}
private void addHop(Ingredient i) {
Hop h = (Hop) i;
hops.add(h);
}
public ArrayList<Instruction> getInstructionList()
{
return generateInstructionsFromIngredients(); //instructionList;
}
// Comparator for sorting ingredients list
private class IngredientComparator implements Comparator<Ingredient>
{
public int compare(Ingredient i1, Ingredient i2) {
return i1.getType().compareTo(i2.getType());
}
}
public double getOG() {
return OG;
}
public void setOG(double gravity) {
gravity = (double) Math.round(gravity * 1000) / 1000;
this.OG = gravity;
}
public double getBitterness() {
bitterness = (double) Math.round(bitterness * 10) / 10;
return bitterness;
}
public void setBitterness(double bitterness) {
bitterness = (double) Math.round(bitterness * 10) / 10;
this.bitterness = bitterness;
}
public double getColor() {
color = (double) Math.round(color * 10) / 10;
return color;
}
public void setColor(double color) {
color = (double) Math.round(color * 10) / 10;
this.color = color;
}
public double getABV() {
ABV = (double) Math.round(ABV * 10) / 10;
return ABV;
}
public void setABV(double aBV) {
ABV = (double) Math.round(ABV * 10) / 10;
ABV = aBV;
}
public int getBatchTime() {
return batchTime;
}
public void setBatchTime(int batchTime) {
this.batchTime = batchTime;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getBatchSize() {
return this.batchSize;
}
public void setBatchSize(double v)
{
this.batchSize = v;
}
public int getBoilTime() {
return boilTime;
}
public void setBoilTime(int boilTime) {
this.boilTime = boilTime;
}
public double getEfficiency() {
return efficiency;
}
public void setEfficiency(double efficiency) {
this.efficiency = efficiency;
}
@Override
public String toString()
{
return this.getRecipeName();
}
private ArrayList<Instruction> generateInstructionsFromIngredients()
{
ArrayList<Instruction> list = new ArrayList<Instruction>();
String steeps = "";
String extract_adds = "";
String yeasts = "";
Instruction inst;
// Extract recipe
if (true)
{
// Generate steep and extract add instructions
for(Fermentable f : getFermentablesList())
{
if (f.getFermentableType().equals(Fermentable.GRAIN))
{
steeps += f.getName() + "\n";
}
else
{
extract_adds += f.getName() + "\n";
}
}
// Boil hops instructions
for(Hop h : getHopsList())
{
inst = new Instruction();
if (h.getUse().equals(Hop.USE_BOIL))
{
inst.setInstructionType(Instruction.TYPE_BOIL);
inst.setInstructionText("Boil " + h.getName());
}
else if (h.getUse().equals(Hop.USE_DRY_HOP))
{
inst.setInstructionType(Instruction.TYPE_DRY_HOP);
inst.setInstructionText("Dry hop " + h.getName());
}
inst.setStartTime(h.getStartTime());
inst.setEndTime(h.getEndTime());
list.add(inst);
}
for (Yeast y : getYeastsList())
{
yeasts += y.getName() + " yeast";
}
}
// Build up the instruction list
if (steeps.length() > 0)
{
// Remove trailing newline character
steeps = steeps.substring(0, steeps.length()-1);
inst = new Instruction();
inst.setInstructionText(steeps);
inst.setInstructionType(Instruction.TYPE_STEEP);
inst.setStartTime(-2);
inst.setEndTime(0);
list.add(inst);
}
if (extract_adds.length() > 0)
{
// Remove trailing newline character
extract_adds = extract_adds.substring(0, extract_adds.length()-1);
inst = new Instruction();
inst.setInstructionType(Instruction.TYPE_ADD);
inst.setInstructionText(extract_adds);
inst.setStartTime(-1);
inst.setEndTime(getBoilTime());
list.add(inst);
}
if (list.size() > 0)
{
// Add a cool wort stage
inst = new Instruction();
inst.setInstructionType(Instruction.TYPE_COOL);
inst.setInstructionText("Cool wort to 70F");
inst.setStartTime(getBoilTime());
inst.setEndTime(getBoilTime());
list.add(inst);
}
if (yeasts.length() > 0)
{
inst = new Instruction();
inst.setInstructionType(Instruction.TYPE_ADD);
inst.setInstructionText(yeasts);
inst.setStartTime(getBoilTime() + 1);
inst.setEndTime(getBoilTime() + 1);
list.add(inst);
}
if (list.size() > 0)
{
inst = new Instruction();
inst.setInstructionType(Instruction.TYPE_FERMENT);
inst.setInstructionText("Ferment till FG = " + getFG());
inst.setStartTime(getBoilTime() + 1);
inst.setEndTime(getBoilTime() + 1);
list.add(inst);
}
// Sort based on start time
Collections.sort(list, new InstructionComparator<Instruction>());
return list;
}
/**
* @return the brewer
*/
public String getBrewer() {
return brewer;
}
/**
* @param brewer the brewer to set
*/
public void setBrewer(String brewer) {
this.brewer = brewer;
}
/**
* @return the boilSize
*/
public double getBoilSize() {
return boilSize;
}
/**
* @param boilSize the boilSize to set
*/
public void setBoilSize(double boilSize) {
this.boilSize = boilSize;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the fG
*/
public double getFG() {
this.FG = (double) Math.round(FG * 1000) / 1000;
return this.FG;
}
/**
* @param fG the fG to set
*/
public void setFG(double fG) {
fG = (double) Math.round(fG * 1000) / 1000;
this.FG = fG;
}
/**
* @return the fermentationStages
*/
public int getFermentationStages() {
return fermentationStages;
}
/**
* @param fermentationStages the fermentationStages to set
*/
public void setFermentationStages(int fermentationStages) {
this.fermentationStages = fermentationStages;
}
/**
* @return the version
*/
public int getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(int version) {
this.version = version;
}
public ArrayList<Fermentable> getFermentablesList()
{
return fermentables;
}
public ArrayList<Hop> getHopsList()
{
return hops;
}
public ArrayList<Yeast> getYeastsList()
{
return yeasts;
}
}
|
package org.deeplearning4j.models.sequencevectors.transformers.impl.iterables;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.sequencevectors.transformers.impl.SentenceTransformer;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.deeplearning4j.text.documentiterator.LabelAwareIterator;
import org.deeplearning4j.text.documentiterator.LabelledDocument;
import java.util.Iterator;
/**
* @author raver119@gmail.com
*/
@Slf4j
public class BasicTransformerIterator implements Iterator<Sequence<VocabWord>> {
protected final LabelAwareIterator iterator;
protected boolean allowMultithreading;
protected final SentenceTransformer sentenceTransformer;
public BasicTransformerIterator(@NonNull LabelAwareIterator iterator, @NonNull SentenceTransformer transformer) {
this.iterator = iterator;
this.allowMultithreading = false;
this.sentenceTransformer = transformer;
this.iterator.reset();
}
@Override
public boolean hasNext() {
return this.iterator.hasNextDocument();
}
@Override
public Sequence<VocabWord> next() {
LabelledDocument document = iterator.nextDocument();
if (document == null || document.getContent() == null) return new Sequence<>();
Sequence<VocabWord> sequence = sentenceTransformer.transformToSequence(document.getContent());
if (document.getLabels() != null)
for (String label: document.getLabels()) {
if (label != null && !label.isEmpty())
sequence.addSequenceLabel(new VocabWord(1.0, label));
}
/*
if (document.getLabel() != null && !document.getLabel().isEmpty()) {
sequence.setSequenceLabel(new VocabWord(1.0, document.getLabel()));
}*/
return sequence;
}
public void reset() {
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
package com.brein.api;
import com.brein.domain.BreinConfig;
import com.brein.domain.results.BreinRecommendationResult;
import com.brein.util.BreinMapUtil;
import com.brein.util.BreinUtil;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BreinRecommendation extends BreinBase<BreinRecommendation>
implements IExecutable<BreinRecommendationResult> {
public static final int DEF_NUM_RESULTS = 3;
public static final String ATTR_REC_CATEGORIES = "recommendationCategories";
public static final String ATTR_REC_CATEGORIES_BLACKLISTED = "recommendationCategoriesBlacklist";
public static final String ATTR_REC_SUB_RECOMMENDERS = "recommendationSubRecommenders";
public static final String ATTR_REC_SUB_INHIBITORS = "recommendationSubInhibitors";
public static final String ATTR_REC_SUB_BLOCKERS = "recommendationSubBlockers";
public static final String ATTR_REC_AT_TIME = "recommendationAtTime";
public static final String ATTR_REC_UNTIL_TIME = "recommendationUntilTime";
public static final String ATTR_REC_DISABLE_CACHE = "recommendationDisableCache";
public static final String ATTR_REC_FOR_ITEMS = "recommendationForItems";
public static final String ATTR_REC_QUERY_NAME = "recommendationQueryName";
public static final String ATTR_REC_MIN_QUANTITY = "recommendationMinQuantity";
public static final String ATTR_REC_NUM_RESULTS = "numRecommendations";
public static final String ATTR_REC_ADDITIONAL_PARAMETERS = "recommendationAdditionalParameters";
/**
* Recommends a user items that are similar to what they previously interacted with
*/
public static final String SUB_RECOMMENDER_SIMILAR_ITEMS = "itemSearch";
/**
* Recommends items based on the currently popular items
*/
public static final String SUB_RECOMMENDER_POPULAR_ITEMS = "topN";
/**
* Recommends items that similar users have bought
*/
public static final String SUB_RECOMMENDER_USERS_LIKE_YOU = "usersLikeYou";
/**
* Recommends previously purchased items
*/
public static final String SUB_RECOMMENDER_RECENTLY_PURCHASED = "purchaseHistory";
/**
* Recommends items that have historically trended during similar times
*/
public static final String SUB_RECOMMENDER_TEMPORAL = "temporal";
/**
* Recommends items that have are ordered through some config-defined manner
*/
public static final String SUB_RECOMMENDER_CUSTOM_SORT = "customSort";
/**
* contains the number of recommendations - default is 3
*/
private int numberOfRecommendations = -1;
/**
* contains the category for the recommendation
*/
private List<String> categories = null;
/**
* contains the category for the recommendation
*/
private List<String> categoriesBlacklist = null;
/**
* an optional list of subrecommenders to run
*/
private List<String> subRecommenders = null;
/**
* an optional list of subrecommenders to use to inhibit recs
*/
private List<String> subInhibitors = null;
/**
* an optional list of blockers to use to block recs
*/
private List<String> blockers = null;
/**
* Should result caching be disabled
*/
private boolean disableCaching = false;
/**
* An optional start time for recommendations
*/
private long recStartTime = -1;
/**
* An optional end time for recommendations
*/
private long recEndTime = -1;
/**
* A list of items to get a recommendation for
*/
private List<String> itemToItemRecs = null;
/**
* Used to keep track of different locations for requests of recommendations
*/
private String recommendationQueryName = null;
/**
* Minimum number of items in stock for a returned recommendation
*/
private Double minQuantity = null;
/**
* Additional parameters to be passed into the sub recommenders
*/
private Map<String, Object> recommendationAdditionalParameters = null;
/**
* A base map for the recommendation-request (more specific values will override these parameters)
*/
private Map<String, Object> recommendationRequest = null;
public Map<String, Object> getRecommendationRequest() {
return recommendationRequest;
}
public BreinRecommendation setRecommendationRequest(final Map<String, Object> recommendationRequest) {
this.recommendationRequest = recommendationRequest;
return this;
}
public BreinRecommendation addRecommendationRequest(final String name, final Object value) {
if (this.recommendationRequest == null) {
this.recommendationRequest = new HashMap<>();
}
this.recommendationRequest.put(name, value);
return this;
}
/**
* get the number of recommendations
*
* @return number
*/
public int getNumberOfRecommendations() {
return numberOfRecommendations;
}
/**
* set the number of recommendations
*
* @param numberOfRecommendations number of recommendations
*
* @return self
*/
public BreinRecommendation setNumberOfRecommendations(final int numberOfRecommendations) {
this.numberOfRecommendations = numberOfRecommendations;
return this;
}
/**
* get the recommendation category
*
* @return category
*/
public List<String> getCategories() {
return categories;
}
/**
* set the recommendation category
*
* @param category contains the category
*
* @return self
*/
public BreinRecommendation setCategories(final String... category) {
this.categories = Arrays.asList(category);
return this;
}
/**
* gets categories that should not be returned
*
* @return the blacklisted categories
*/
public List<String> getCategoriesBlacklist() {
return categoriesBlacklist;
}
/**
* set the categories that should not be returned
*
* @param category the blacklisted categories
*
* @return self
*/
public BreinRecommendation setCategoriesBlacklist(final String... category) {
this.categoriesBlacklist = Arrays.asList(category);
return this;
}
public BreinRecommendation setSubRecommenders(final List<String> subRecommenders) {
this.subRecommenders = subRecommenders;
return this;
}
public BreinRecommendation setSubRecommenders(final String... subRecomenders) {
setSubRecommenders(Arrays.asList(subRecomenders));
return this;
}
public List<String> getSubRecommenders() {
return subRecommenders;
}
public BreinRecommendation setMinQuantity(final Double minQuantity) {
this.minQuantity = minQuantity;
return this;
}
public Double getMinQuantity() {
return minQuantity;
}
/**
* Should this request disable caching?
*
* @return if caching should be disabled
*/
public boolean isDisableCaching() {
return disableCaching;
}
/**
* Set if we want to disable caching
*
* @param disableCaching the caching state
*/
public BreinRecommendation setDisableCaching(final boolean disableCaching) {
this.disableCaching = disableCaching;
return this;
}
/**
* @return When recommendations should start
*/
public long getRecStartTime() {
return recStartTime;
}
/**
* @param recStartTime When recommendations should start
*/
public BreinRecommendation setRecStartTime(final long recStartTime) {
this.recStartTime = recStartTime;
return this;
}
/**
* @return When recommendations should end
*/
public long getRecEndTime() {
return recEndTime;
}
/**
* @param recEndTime When recommendations should end
*/
public BreinRecommendation setRecEndTime(final long recEndTime) {
this.recEndTime = recEndTime;
return this;
}
/**
* @return Items for an item(s) to items recommendation
*/
public List<String> getItemToItemRecs() {
return itemToItemRecs;
}
/**
* @param itemToItemRecs the item(s) that an item to item recommendation should be done for
*/
public BreinRecommendation setItemToItemRecs(final List<String> itemToItemRecs) {
this.itemToItemRecs = itemToItemRecs;
return this;
}
public String getRecommendationQueryName() {
return recommendationQueryName;
}
public BreinRecommendation setRecommendationQueryName(final String recommendationQueryName) {
this.recommendationQueryName = recommendationQueryName;
return this;
}
@Override
public BreinRecommendationResult execute() {
return Breinify.recommendation(this);
}
public List<String> getSubInhibitors() {
return subInhibitors;
}
public BreinRecommendation setSubInhibitors(final List<String> subInhibitors) {
this.subInhibitors = subInhibitors;
return this;
}
public List<String> getBlockers() {
return blockers;
}
public BreinRecommendation setBlockers(final List<String> blockers) {
this.blockers = blockers;
return this;
}
public Map<String, Object> getRecommendationAdditionalParameters() {
return this.recommendationAdditionalParameters;
}
public BreinRecommendation setRecommendationAdditionalParameters(final Map<String, Object> params) {
this.recommendationAdditionalParameters = params;
return this;
}
@Override
public String getEndPoint(final BreinConfig config) {
return config.getRecommendationEndpoint();
}
@Override
public void prepareRequestData(final BreinConfig config, final Map<String, Object> requestData) {
// recommendation data
final Map<String, Object> recommendation = new HashMap<>();
if (this.recommendationRequest != null) {
recommendation.putAll(this.recommendationRequest);
}
// check optional field
if (BreinUtil.containsValue(getCategories())) {
recommendation.put(ATTR_REC_CATEGORIES, getCategories());
}
if (BreinUtil.containsValue(getCategories())) {
recommendation.put(ATTR_REC_CATEGORIES_BLACKLISTED, getCategoriesBlacklist());
}
if (BreinUtil.containsValue(getSubRecommenders())) {
recommendation.put(ATTR_REC_SUB_RECOMMENDERS, getSubRecommenders());
}
if (BreinUtil.containsValue(getSubInhibitors())) {
recommendation.put(ATTR_REC_SUB_INHIBITORS, getSubInhibitors());
}
if (BreinUtil.containsValue(getBlockers())) {
recommendation.put(ATTR_REC_SUB_BLOCKERS, getBlockers());
}
if (getRecStartTime() >= 0) {
recommendation.put(ATTR_REC_AT_TIME, getRecStartTime());
}
if (getRecEndTime() >= 0) {
recommendation.put(ATTR_REC_UNTIL_TIME, getRecEndTime());
}
if (isDisableCaching()) {
recommendation.put(ATTR_REC_DISABLE_CACHE, true);
}
if (getItemToItemRecs() != null && !getItemToItemRecs().isEmpty()) {
recommendation.put(ATTR_REC_FOR_ITEMS, getItemToItemRecs());
}
if (getRecommendationQueryName() != null) {
recommendation.put(ATTR_REC_QUERY_NAME, getRecommendationQueryName());
}
if (getMinQuantity() != null) {
recommendation.put(ATTR_REC_MIN_QUANTITY, getMinQuantity());
}
// mandatory field
if (getNumberOfRecommendations() > -1) {
recommendation.put(ATTR_REC_NUM_RESULTS, getNumberOfRecommendations());
} else if (!recommendation.containsKey(ATTR_REC_NUM_RESULTS)) {
recommendation.put(ATTR_REC_NUM_RESULTS, DEF_NUM_RESULTS);
}
final Object objAdditional = recommendation.get(ATTR_REC_ADDITIONAL_PARAMETERS);
final Map<String, Object> additional = Map.class.isInstance(objAdditional) ?
Map.class.cast(objAdditional) : new HashMap<>();
// next handle the additional
if (BreinUtil.containsValue(getRecommendationAdditionalParameters())) {
additional.putAll(getRecommendationAdditionalParameters());
}
recommendation.put(ATTR_REC_ADDITIONAL_PARAMETERS, getRecommendationAdditionalParameters());
requestData.put("recommendation", recommendation);
}
/**
* Generates the signature for the request
*
* @return full signature
*/
@Override
public String createSignature(final BreinConfig config, final Map<String, Object> requestData) {
final long unixTimestamp = BreinMapUtil.getNestedValue(requestData, UNIX_TIMESTAMP_FIELD);
final String message = String.format("%d", unixTimestamp);
return BreinUtil.generateSignature(message, config.getSecret());
}
}
|
package cn.cerc.core;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*
* @author
*/
public class TDate extends TDateTime {
private static final long serialVersionUID = 1L;
public TDate(Date date) {
this.setData(date);
}
public TDate(String date) {
TDateTime val = TDateTime.fromDate(date);
if (val == null) {
throw new RuntimeException(String.format("%s ", date));
}
this.setData(val.getData());
}
public static TDate Today() {
return today();
}
public static TDate today() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String str = sdf.format(date);
try {
date = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("");
}
return new TDate(date);
}
public static void main(String[] args) {
TDate val;
val = new TDate(TDateTime.now().incMonth(-13).getData());
System.out.println(val.getShortValue());
val = TDate.Today();
System.out.println(val.getShortValue());
}
@Override
public String toString() {
return this.getDate();
}
public String getShortValue() {
String year = this.getYearMonth().substring(2, 4);
int month = this.getMonth();
int day = this.getDay();
if (TDateTime.now().compareYear(this) != 0) {
return String.format("%s%d", year, month);
} else {
return String.format("%d%d", month, day);
}
}
}
|
package com.edinarobotics.zeke;
import com.edinarobotics.zeke.subsystems.Collector;
import com.edinarobotics.zeke.subsystems.Drivetrain;
import com.edinarobotics.zeke.subsystems.DrivetrainRotation;
import com.edinarobotics.zeke.subsystems.DrivetrainStrafe;
import com.edinarobotics.zeke.subsystems.Shooter;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.DigitalInput;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class Components {
private static Components instance;
// Subsystems
public final Drivetrain drivetrain;
public final DrivetrainStrafe drivetrainStrafe;
public final DrivetrainRotation drivetrainRotation;
public final Shooter shooter;
public final Collector collector;
// END Subsystems
// Compressor
public final Compressor compressor;
// Analog Inputs
private static final int GYRO = 1;
private static final int ULTRASONIC_SENSOR = 4;
private static final int SHOOTER_POT_PORT = 3;
// END Analog Inputs
// Digital IO Constants
// Drivetrain Encoders
/*
private static final DigitalInput FRONT_LEFT_A = new DigitalInput(1, 1);
private static final DigitalInput FRONT_LEFT_B = new DigitalInput(2, 1);
private static final DigitalInput REAR_LEFT_A = new DigitalInput(1, 2);
private static final DigitalInput REAR_LEFT_B = new DigitalInput(2, 2);
private static final DigitalInput FRONT_RIGHT_A = new DigitalInput(1, 3);
private static final DigitalInput FRONT_RIGHT_B = new DigitalInput(2, 3);
private static final DigitalInput REAR_RIGHT_A = new DigitalInput(1, 4);
private static final DigitalInput REAR_RIGHT_B = new DigitalInput(2, 4);
*/
// Limit Switches
private static final int SHOOTER_LOWER_LIMIT = 6;
private static final int COLLECTOR_UPPER_LIMIT = 7;
// Compressor Switch
private static final int COMPRESSOR_PRESSURE_SWITCH = 5;
// END Digital IO constants
// PWM constants
// Drivetrain
private static final int FRONT_LEFT_DRIVE = 4;
private static final int REAR_LEFT_DRIVE = 3;
private static final int FRONT_RIGHT_DRIVE = 2;
private static final int REAR_RIGHT_DRIVE = 1;
private static final int WINCH_TALON = 5;
private static final int COLLECTOR_FRONT_TALON = 6;
private static final int COLLECTOR_BACK_TALON = 7;
// END PWM constants
// Solenoid constants
// Collector
private static final int COLLECTOR_DOUBLESOLENOID_FORWARD = 2;
private static final int COLLECTOR_DOUBLESOLENOID_REVERSE = 1;
// Shooter
private static final int SHOOTER_DOUBLESOLENOID_FORWARD = 3;
private static final int SHOOTER_DOUBLESOLENOID_REVERSE = 4;
// Pusher
private static final int PUSHER_DOUBLESOLENOID_FORWARD = 6;
private static final int PUSHER_DOUBLESOLENOID_REVERSE = 5;
// END Solenoid constants
// Relay constats
// Compressor
private static final int COMPRESSOR_RELAY = 1;
// END Relay constants
/**
* Private constructor for the Components singleton. This constructor
* is only called once and handles creating all the robot subsystems.
*/
private Components(){
drivetrain = new Drivetrain(FRONT_LEFT_DRIVE, REAR_LEFT_DRIVE,
FRONT_RIGHT_DRIVE, REAR_RIGHT_DRIVE, ULTRASONIC_SENSOR);
drivetrainStrafe = new DrivetrainStrafe(drivetrain);
drivetrainRotation = new DrivetrainRotation(drivetrain, GYRO);
shooter = new Shooter(WINCH_TALON, SHOOTER_DOUBLESOLENOID_FORWARD, SHOOTER_DOUBLESOLENOID_REVERSE,
PUSHER_DOUBLESOLENOID_FORWARD, PUSHER_DOUBLESOLENOID_REVERSE,
SHOOTER_POT_PORT, SHOOTER_LOWER_LIMIT);
collector = new Collector(COLLECTOR_FRONT_TALON, COLLECTOR_BACK_TALON,
COLLECTOR_DOUBLESOLENOID_FORWARD, COLLECTOR_DOUBLESOLENOID_REVERSE,
COLLECTOR_UPPER_LIMIT);
compressor = new Compressor(COMPRESSOR_PRESSURE_SWITCH, COMPRESSOR_RELAY);
compressor.start();
}
/**
* Returns a new instance of {@link Components}, creating one if null.
* @return {@link Components}
*/
public static Components getInstance() {
if(instance == null){
instance = new Components();
}
return instance;
}
}
|
package com.example.mystocks;
import java.util.Arrays;
import java.util.HashMap;
import com.example.mystocks.info.AbstractOnXMLParseAction;
import com.example.mystocks.info.AsyncTaskGetAndParseXML;
import com.example.mystocks.info.EStockAttributes;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener
{
public final static String STOCK_SYMBOL = "com.example.stockquotes.STOCK";
protected static final int ADD_STOCK_WINDOW = 1;
private SharedPreferences stockSymbolsEntered;
private TableLayout stockTableScrollView;
Button deleteStocksdata;
Button addNew;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stockSymbolsEntered = getSharedPreferences("stockList", MODE_PRIVATE);
stockTableScrollView = (TableLayout) findViewById(R.id.stockTableScrollView);
deleteStocksdata = (Button) findViewById(R.id.deleteStocksButton);
deleteStocksdata.setOnClickListener(this);
addNew = (Button) findViewById(R.id.addNew);
addNew.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
Intent intent = new Intent(MainActivity.this, AddStockActivity.class);
startActivityForResult(intent, ADD_STOCK_WINDOW);
}
});
((Button) findViewById(R.id.refresh)).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
refreshStocksAsync();
}
});
updateSavedStockList(null);
}
private void refreshStocksAsync()
{
String[] stocks = stockSymbolsEntered.getAll().keySet().toArray(new String[0]);
for (int i = 0; i < stocks.length; i++)
{
View row = stockTableScrollView.getChildAt(i);
TextView sym = (TextView) row.findViewById(R.id.stockSymbolTextView);
TextView lastVal = (TextView) row.findViewById(R.id.stockSymbolLastValue);
TextView compName = (TextView) row.findViewById(R.id.stockSymCompanyName);
execAsyncAndUpdateValues(sym.getText().toString(), compName, lastVal);
}
}
private void execAsyncAndUpdateValues(String symbol, final TextView companyName, final TextView lastValue)
{
String yahooURLFirst = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22";
String yahooURLSecond = "%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
final String yqlURL = yahooURLFirst + symbol + yahooURLSecond;
new AsyncTaskGetAndParseXML(new AbstractOnXMLParseAction()
{
@Override
public void doAction(HashMap<EStockAttributes, String> xmlPullParserResults)
{
lastValue.setText(xmlPullParserResults.get(EStockAttributes.LastTradePriceOnly));
companyName.setText(xmlPullParserResults.get(EStockAttributes.Name));
}
}).execute(yqlURL);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (null != data)
{
saveStockSymbol(data.getStringExtra("result"));
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateSavedStockList(String newStockSymbol)
{
String[] stocks = stockSymbolsEntered.getAll().keySet().toArray(new String[0]);
Arrays.sort(stocks, String.CASE_INSENSITIVE_ORDER);
if (newStockSymbol != null)
{
insertStockInScrollView(newStockSymbol, Arrays.binarySearch(stocks, newStockSymbol));
}
else
{
for (int i = 0; i < stocks.length; ++i)
{
insertStockInScrollView(stocks[i], i);
}
}
}
private void saveStockSymbol(String newStock)
{
String isTheStockNew = stockSymbolsEntered.getString(newStock, null);
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.putString(newStock, newStock);
preferencesEditor.apply();
if (isTheStockNew == null)
{
updateSavedStockList(newStock);
}
}
private void insertStockInScrollView(String stock, int arrayIndex)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newStockRow = inflater.inflate(R.layout.stock_quote, null);
TextView newStockTextView = (TextView) newStockRow.findViewById(R.id.stockSymbolTextView);
newStockTextView.setText(stock);
Button stockQuoteButton = (Button) newStockRow.findViewById(R.id.stockQuoteButton);
stockQuoteButton.setOnClickListener(getStockActivityListener);
stockTableScrollView.addView(newStockRow, arrayIndex);
execAsyncAndUpdateValues(stock, (TextView) newStockRow.findViewById(R.id.stockSymCompanyName), (TextView) newStockRow.findViewById(R.id.stockSymbolLastValue));
}
private void deleteAllStocks()
{
stockTableScrollView.removeAllViews();
}
public OnClickListener getStockActivityListener = new OnClickListener()
{
public void onClick(View v)
{
TableRow tableRow = (TableRow) v.getParent();
TextView stockTextView = (TextView) tableRow.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stockTextView.getText().toString();
Intent intent = new Intent(MainActivity.this, StockInfoActivity.class);
intent.putExtra(STOCK_SYMBOL, stockSymbol);
startActivity(intent);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
switch (arg0.getId())
{
// case R.id.enterStockSymbolButton:
// if (stockSymbolEditText.getText().length() > 0)
// saveStockSymbol(stockSymbolEditText.getText().toString());
// stockSymbolEditText.setText(""); // Clear EditText box
// InputMethodManager imm = (InputMethodManager)
// getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(stockSymbolEditText.getWindowToken(), 0);
// else
// // Create an alert dialog box
// AlertDialog.Builder builder = new
// AlertDialog.Builder(MainActivity.this);
// builder.setTitle(R.string.invalid_stock_symbol);
// builder.setMessage(R.string.missing_stock_symbol);
// AlertDialog theAlertDialog = builder.create();
// theAlertDialog.show();
// break;
case R.id.deleteStocksButton:
deleteAllStocks();
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.clear();
preferencesEditor.apply();
break;
}
}
}
|
package com.haxademic.core.app;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.sound.midi.InvalidMidiDataException;
import com.haxademic.core.audio.analysis.input.AudioInputBeads;
import com.haxademic.core.audio.analysis.input.AudioInputESS;
import com.haxademic.core.audio.analysis.input.AudioInputMinim;
import com.haxademic.core.audio.analysis.input.AudioStreamData;
import com.haxademic.core.audio.analysis.input.IAudioInput;
import com.haxademic.core.constants.AppSettings;
import com.haxademic.core.constants.PRenderers;
import com.haxademic.core.data.store.AppStore;
import com.haxademic.core.debug.DebugUtil;
import com.haxademic.core.debug.DebugView;
import com.haxademic.core.debug.Stats;
import com.haxademic.core.draw.context.DrawUtil;
import com.haxademic.core.draw.context.OpenGLUtil;
import com.haxademic.core.draw.image.MovieBuffer;
import com.haxademic.core.file.FileUtil;
import com.haxademic.core.hardware.browser.BrowserInputState;
import com.haxademic.core.hardware.keyboard.KeyboardState;
import com.haxademic.core.hardware.kinect.IKinectWrapper;
import com.haxademic.core.hardware.kinect.KinectWrapperV1;
import com.haxademic.core.hardware.kinect.KinectWrapperV2;
import com.haxademic.core.hardware.kinect.KinectWrapperV2Mac;
import com.haxademic.core.hardware.midi.MidiState;
import com.haxademic.core.hardware.osc.OscWrapper;
import com.haxademic.core.hardware.webcam.WebCamWrapper;
import com.haxademic.core.render.AnimationLoop;
import com.haxademic.core.render.GifRenderer;
import com.haxademic.core.render.ImageSequenceRenderer;
import com.haxademic.core.render.JoonsWrapper;
import com.haxademic.core.render.MIDISequenceRenderer;
import com.haxademic.core.render.Renderer;
import com.haxademic.core.system.AppUtil;
import com.haxademic.core.system.JavaInfo;
import com.haxademic.core.system.P5Properties;
import com.haxademic.core.system.SecondScreenViewer;
import com.haxademic.core.system.SystemUtil;
import com.haxademic.core.ui.PrefsSliders;
import de.voidplus.leapmotion.LeapMotion;
import krister.Ess.AudioInput;
import processing.core.PApplet;
import processing.core.PGraphics;
import processing.core.PSurface;
import processing.opengl.PJOGL;
import processing.video.Movie;
import themidibus.MidiBus;
/**
* PAppletHax is a starting point for interactive visuals, giving you a unified
* environment for both realtime and rendering modes. It loads several Java
* libraries and wraps them up to play nicely with each other.
*
* @author cacheflowe
*
*/
public class PAppletHax
extends PApplet
{
// Simplest launch:
// public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }
// Fancier launch:
// public static void main(String args[]) {
// PAppletHax.main(P.concat(args, new String[] { "--hide-stop", "--bgcolor=000000", Thread.currentThread().getStackTrace()[1].getClassName() }));
// PApplet.main(new String[] { "--hide-stop", "--bgcolor=000000", "--location=1920,0", "--display=1", ElloMotion.class.getName() });
// public static String arguments[];
// public static void main(String args[]) {
// arguments = args;
// PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName());
// app
protected static PAppletHax p; // Global/static ref to PApplet - any audio-reactive object should be passed this reference, or grabbed from this static ref.
protected PGraphics pg; // Offscreen buffer that matches the app size
public P5Properties appConfig; // Loads the project .properties file to configure several app properties externally.
protected String customPropsFile = null; // Loads an app-specific project .properties file.
protected String renderer; // The current rendering engine
protected Robot _robot;
// audio
public IAudioInput audioInput;
public AudioStreamData audioData = new AudioStreamData();
public PGraphics audioInputDebugBuffer;
// rendering
public Renderer movieRenderer;
public MIDISequenceRenderer _midiRenderer;
public GifRenderer _gifRenderer;
public ImageSequenceRenderer imageSequenceRenderer;
protected Boolean _isRendering = true;
protected Boolean _isRenderingAudio = true;
protected Boolean _isRenderingMidi = true;
protected JoonsWrapper joons;
public AnimationLoop loop = null;
// input
public WebCamWrapper webCamWrapper = null;
public MidiState midiState = null;
public MidiBus midiBus;
public KeyboardState keyboardState;
public IKinectWrapper kinectWrapper = null;
public LeapMotion leapMotion = null;
public OscWrapper oscState = null;
public BrowserInputState browserInputState = null;
public int lastMouseTime = 0;
public boolean mouseShowing = true;
// debug
public int _fps;
public Stats _stats;
public boolean showDebug = false;
public DebugView debugView;
public PrefsSliders prefsSliders;
public SecondScreenViewer appViewerWindow;
// INIT
public void settings() {
P.p = p = this;
P.store = AppStore.instance();
AppUtil.setFrameBackground(p,0,255,0);
loadAppConfig();
overridePropsFile();
setAppIcon();
setRenderer();
setSmoothing();
setRetinaScreen();
}
protected void loadAppConfig() {
appConfig = new P5Properties(p);
if( customPropsFile != null ) appConfig.loadPropertiesFile( customPropsFile );
customPropsFile = null;
}
public void setAppIcon() {
String appIconFile = p.appConfig.getString(AppSettings.APP_ICON, "haxademic/images/haxademic-logo.png");
PJOGL.setIcon(FileUtil.getFile(appIconFile));
}
public void setup () {
if(customPropsFile != null) DebugUtil.printErr("Make sure to load custom .properties files in settings()");
setAppletProps();
checkScreenManualPosition();
if(renderer != PRenderers.PDF) {
debugView = new DebugView( p );
prefsSliders = new PrefsSliders();
}
_stats = new Stats( p );
}
// INIT GRAPHICS
protected void setRetinaScreen() {
if(p.appConfig.getBoolean(AppSettings.RETINA, false) == true) {
if(p.displayDensity() == 2) {
p.pixelDensity(2);
} else {
DebugUtil.printErr("Error: Attempting to set retina drawing on a non-retina screen");
}
}
}
protected void setSmoothing() {
if(p.appConfig.getInt(AppSettings.SMOOTHING, AppSettings.SMOOTH_HIGH) == 0) {
p.noSmooth();
} else {
p.smooth(p.appConfig.getInt(AppSettings.SMOOTHING, AppSettings.SMOOTH_HIGH));
}
}
protected void setRenderer() {
PJOGL.profile = 4;
renderer = p.appConfig.getString(AppSettings.RENDERER, P.P3D);
if(p.appConfig.getBoolean(AppSettings.SPAN_SCREENS, false) == true) {
// run fullscreen across all screens
p.fullScreen(renderer, P.SPAN);
} else if(p.appConfig.getBoolean(AppSettings.FULLSCREEN, false) == true) {
// run fullscreen - default to screen #1 unless another is specified
p.fullScreen(renderer, p.appConfig.getInt(AppSettings.FULLSCREEN_SCREEN_NUMBER, 1));
} else if(p.appConfig.getBoolean(AppSettings.FILLS_SCREEN, false) == true) {
// fills the screen, but not fullscreen
p.size(displayWidth,displayHeight,renderer);
} else {
if(renderer == PRenderers.PDF) {
// set headless pdf output file
p.size(p.appConfig.getInt(AppSettings.WIDTH, 800),p.appConfig.getInt(AppSettings.HEIGHT, 600), renderer, p.appConfig.getString(AppSettings.PDF_RENDERER_OUTPUT_FILE, "output/output.pdf"));
} else {
// run normal P3D renderer
p.size(p.appConfig.getInt(AppSettings.WIDTH, 800),p.appConfig.getInt(AppSettings.HEIGHT, 600), renderer);
}
}
}
protected void checkScreenManualPosition() {
boolean isFullscreen = p.appConfig.getBoolean(AppSettings.FULLSCREEN, false);
// check for additional screen_x params to manually place the screen
if(p.appConfig.getInt("screen_x", -1) != -1) {
if(isFullscreen == false) {
DebugUtil.printErr("Error: Manual screen positioning requires AppSettings.FULLSCREEN = true");
return;
}
surface.setSize(p.appConfig.getInt(AppSettings.WIDTH, 800), p.appConfig.getInt(AppSettings.HEIGHT, 600));
surface.setLocation(p.appConfig.getInt("screen_x", 0), p.appConfig.getInt("screen_y", 0)); // location has to happen after size, to break it out of fullscreen
}
}
// INIT OBJECTS
protected void setAppletProps() {
_isRendering = p.appConfig.getBoolean(AppSettings.RENDERING_MOVIE, false);
if( _isRendering == true ) DebugUtil.printErr("When rendering, make sure to call super.keyPressed(); for esc key shutdown");
_isRenderingAudio = p.appConfig.getBoolean(AppSettings.RENDER_AUDIO, false);
_isRenderingMidi = p.appConfig.getBoolean(AppSettings.RENDER_MIDI, false);
_fps = p.appConfig.getInt(AppSettings.FPS, 60);
p.showDebug = p.appConfig.getBoolean(AppSettings.SHOW_DEBUG, false);
if(p.appConfig.getInt(AppSettings.FPS, 60) != 60) frameRate(_fps);
}
protected void initHaxademicObjects() {
// create offscreen buffer
pg = p.createGraphics(p.width, p.height, P.P3D);
DrawUtil.setTextureRepeat(pg, true);
// audio input
initAudioInput();
// animation loop
if(p.appConfig.getFloat(AppSettings.LOOP_FRAMES, 0) != 0) loop = new AnimationLoop(p.appConfig.getFloat(AppSettings.LOOP_FRAMES, 0));
// save single reference for other objects
if( appConfig.getInt(AppSettings.WEBCAM_INDEX, -1) >= 0 ) webCamWrapper = new WebCamWrapper(appConfig.getInt(AppSettings.WEBCAM_INDEX, -1), appConfig.getBoolean(AppSettings.WEBCAM_THREADED, true));
movieRenderer = new Renderer( p, _fps, Renderer.OUTPUT_TYPE_MOVIE, p.appConfig.getString( "render_output_dir", FileUtil.getHaxademicOutputPath() ) );
if(appConfig.getBoolean(AppSettings.RENDERING_GIF, false) == true) {
_gifRenderer = new GifRenderer(appConfig.getInt(AppSettings.RENDERING_GIF_FRAMERATE, 45), appConfig.getInt(AppSettings.RENDERING_GIF_QUALITY, 15));
}
if(appConfig.getBoolean(AppSettings.RENDERING_IMAGE_SEQUENCE, false) == true) {
imageSequenceRenderer = new ImageSequenceRenderer();
}
if( p.appConfig.getBoolean( AppSettings.KINECT_V2_WIN_ACTIVE, false ) == true ) {
kinectWrapper = new KinectWrapperV2( p, p.appConfig.getBoolean( "kinect_depth", true ), p.appConfig.getBoolean( "kinect_rgb", true ), p.appConfig.getBoolean( "kinect_depth_image", true ) );
} else if( p.appConfig.getBoolean( AppSettings.KINECT_V2_MAC_ACTIVE, false ) == true ) {
kinectWrapper = new KinectWrapperV2Mac( p, p.appConfig.getBoolean( "kinect_depth", true ), p.appConfig.getBoolean( "kinect_rgb", true ), p.appConfig.getBoolean( "kinect_depth_image", true ) );
} else if( p.appConfig.getBoolean( AppSettings.KINECT_ACTIVE, false ) == true ) {
kinectWrapper = new KinectWrapperV1( p, p.appConfig.getBoolean( "kinect_depth", true ), p.appConfig.getBoolean( "kinect_rgb", true ), p.appConfig.getBoolean( "kinect_depth_image", true ) );
}
if(kinectWrapper != null) {
kinectWrapper.setMirror( p.appConfig.getBoolean( "kinect_mirrored", true ) );
kinectWrapper.setFlipped( p.appConfig.getBoolean( "kinect_flipped", false ) );
}
if( p.appConfig.getInt(AppSettings.MIDI_DEVICE_IN_INDEX, -1) >= 0 ) {
MidiBus.list(); // List all available Midi devices on STDOUT. This will show each device's index and name.
midiBus = new MidiBus(
this,
p.appConfig.getInt(AppSettings.MIDI_DEVICE_IN_INDEX, 0),
p.appConfig.getInt(AppSettings.MIDI_DEVICE_OUT_INDEX, 0)
);
}
midiState = new MidiState();
keyboardState = new KeyboardState();
browserInputState = new BrowserInputState();
if( p.appConfig.getBoolean( "leap_active", false ) == true ) leapMotion = new LeapMotion(this);
if( p.appConfig.getBoolean( AppSettings.OSC_ACTIVE, false ) == true ) oscState = new OscWrapper();
joons = ( p.appConfig.getBoolean(AppSettings.SUNFLOW, false ) == true ) ?
new JoonsWrapper( p, width, height, ( p.appConfig.getString(AppSettings.SUNFLOW_QUALITY, "low" ) == AppSettings.SUNFLOW_QUALITY_HIGH ) ? JoonsWrapper.QUALITY_HIGH : JoonsWrapper.QUALITY_LOW, ( p.appConfig.getBoolean(AppSettings.SUNFLOW_ACTIVE, true ) == true ) ? true : false )
: null;
try { _robot = new Robot(); } catch( Exception error ) { println("couldn't init Robot for screensaver disabling"); }
if(p.appConfig.getBoolean(AppSettings.APP_VIEWER_WINDOW, false) == true) appViewerWindow = new SecondScreenViewer(p.g, p.appConfig.getFloat(AppSettings.APP_VIEWER_SCALE, 0.5f));
// check for always on top
boolean isFullscreen = p.appConfig.getBoolean(AppSettings.FULLSCREEN, false);
if(isFullscreen == true) {
if(p.appConfig.getBoolean(AppSettings.ALWAYS_ON_TOP, true)) surface.setAlwaysOnTop(true);
}
}
protected void initAudioInput() {
if(appConfig.getBoolean(AppSettings.AUDIO_DEBUG, false) == true) JavaInfo.debugInfo();
if( appConfig.getBoolean(AppSettings.INIT_MINIM_AUDIO, false) == true ) {
audioInput = new AudioInputMinim();
} else if( appConfig.getBoolean(AppSettings.INIT_BEADS_AUDIO, false) == true ) {
DebugUtil.printErr("Fix AudioInputBeads passthrough output");
audioInput = new AudioInputBeads();
} else if( appConfig.getBoolean(AppSettings.INIT_ESS_AUDIO, true) == true ) {
// Default to ESS being on, unless a different audio library is selected
try {
audioInput = new AudioInputESS();
DebugUtil.printErr("Fix AudioInputESS amp: audioStreamData.setAmp(fft.max);");
} catch (IllegalArgumentException e) {
DebugUtil.printErr("ESS Audio not initialized. Check your sound card settings.");
}
}
// if we've initialized an audio input, let's build an audio buffer
if(audioInput != null) {
audioInputDebugBuffer = p.createGraphics((int)AudioStreamData.debugW, (int)AudioStreamData.debugW, PRenderers.P3D);
debugView.setTexture(audioInputDebugBuffer);
}
}
protected void initializeOn1stFrame() {
if( p.frameCount == 1 ) {
P.println("Using Java version: " + SystemUtil.getJavaVersion() + " and GL version: " + OpenGLUtil.getGlVersion(p.g));
initHaxademicObjects();
setupFirstFrame();
}
}
// OVERRIDES
protected void overridePropsFile() {
if( customPropsFile == null ) P.println("YOU SHOULD OVERRIDE overridePropsFile(). Using run.properties");
}
protected void setupFirstFrame() {
// YOU SHOULD OVERRIDE setupFirstFrame() to avoid 5000ms Processing/Java timeout in setup()
}
protected void drawApp() {
P.println("YOU MUST OVERRIDE drawApp()");
}
// GETTERS
// app surface
public PSurface getSurface() {
return surface;
}
public void setAlwaysOnTop() {
surface.setAlwaysOnTop(false);
surface.setAlwaysOnTop(true);
}
// audio
public float[] audioFreqs() {
return audioInput.audioData().frequencies();
}
public float audioFreq(int index) {
return audioFreqs()[index % audioFreqs().length];
}
// DRAW
public void draw() {
initializeOn1stFrame();
killScreensaver();
if(loop != null) loop.update();
updateAudioData();
handleRenderingStepthrough();
midiState.update();
if( kinectWrapper != null ) kinectWrapper.update();
p.pushMatrix();
if( joons != null ) joons.startFrame();
drawApp();
if( joons != null ) joons.endFrame( p.appConfig.getBoolean(AppSettings.SUNFLOW_SAVE_IMAGES, false) == true );
p.popMatrix();
renderFrame();
keyboardState.update();
browserInputState.update();
autoHideMouse();
if(oscState != null) oscState.update();
showStats();
setAppDockIconAndTitle();
if(renderer == PRenderers.PDF) finishPdfRender();
}
// UPDATE OBJECTS
protected void updateAudioData() {
if(audioInput != null) {
PGraphics audioBuffer = (showDebug == true) ? audioInputDebugBuffer : null; // only draw if debugging
if(audioBuffer != null) {
audioBuffer.beginDraw();
audioBuffer.background(0);
}
audioInput.update(audioBuffer);
audioData = audioInput.audioData();
if(audioBuffer != null) audioBuffer.endDraw();
}
}
protected void showStats() {
p.noLights();
_stats.update();
if(showDebug) debugView.draw();
prefsSliders.update();
}
protected void setAppDockIconAndTitle() {
if(p.frameCount == 1 && renderer != PRenderers.PDF) {
AppUtil.setTitle(p, p.appConfig.getString(AppSettings.APP_NAME, "Haxademic"));
AppUtil.setAppToDockIcon(p);
}
}
// RENDERING
protected void finishPdfRender() {
P.println("Finished PDF render.");
p.exit();
}
protected void handleRenderingStepthrough() {
// step through midi file if set
if( _isRenderingMidi == true ) {
if( p.frameCount == 1 ) {
try {
_midiRenderer = new MIDISequenceRenderer(p);
_midiRenderer.loadMIDIFile( p.appConfig.getString(AppSettings.RENDER_MIDI_FILE, ""), p.appConfig.getFloat(AppSettings.RENDER_MIDI_BPM, 150f), _fps, p.appConfig.getFloat(AppSettings.RENDER_MIDI_OFFSET, -8f) );
} catch (InvalidMidiDataException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
}
}
// analyze & init audio if stepping through a render
if( _isRendering == true ) {
if( p.frameCount == 1 ) {
if( _isRenderingAudio == true ) {
movieRenderer.startRendererForAudio( p.appConfig.getString(AppSettings.RENDER_AUDIO_FILE, "") );
} else {
movieRenderer.startRenderer();
}
}
// if( p.frameCount > 1 ) {
// have renderer step through audio, then special call to update the single WaveformData storage object
if( _isRenderingAudio == true ) {
movieRenderer.analyzeAudio();
}
if( _midiRenderer != null ) {
boolean doneCheckingForMidi = false;
boolean triggered = false;
while( doneCheckingForMidi == false ) {
int rendererNote = _midiRenderer.checkForCurrentFrameNoteEvents();
if( rendererNote != -1 ) {
midiState.noteOn( 0, rendererNote, 100 );
triggered = true;
} else {
doneCheckingForMidi = true;
}
}
// if( triggered == false && midi != null ) midi.allOff();
}
}
if(_gifRenderer != null && appConfig.getBoolean(AppSettings.RENDERING_GIF, false) == true) {
if(appConfig.getInt(AppSettings.RENDERING_GIF_START_FRAME, 1) == p.frameCount) {
_gifRenderer.startGifRender(this);
}
}
if(imageSequenceRenderer != null && appConfig.getBoolean(AppSettings.RENDERING_IMAGE_SEQUENCE, false) == true) {
if(appConfig.getInt(AppSettings.RENDERING_IMAGE_SEQUENCE_START_FRAME, 1) == p.frameCount) {
imageSequenceRenderer.startImageSequenceRender();;
}
}
}
protected void renderFrame() {
// gives the app 1 frame to shutdown after the movie rendering stops
if( _isRendering == true ) {
if(p.frameCount >= appConfig.getInt(AppSettings.RENDERING_MOVIE_START_FRAME, 1)) {
movieRenderer.renderFrame();
}
// check for movie rendering stop frame
if(p.frameCount == appConfig.getInt(AppSettings.RENDERING_MOVIE_STOP_FRAME, 5000)) {
movieRenderer.stop();
P.println("shutting down renderer");
}
}
// check for gifrendering stop frame
if(_gifRenderer != null && appConfig.getBoolean(AppSettings.RENDERING_GIF, false) == true) {
if(appConfig.getInt(AppSettings.RENDERING_GIF_START_FRAME, 1) == p.frameCount) {
_gifRenderer.startGifRender(this);
}
DrawUtil.setColorForPImage(p);
_gifRenderer.renderGifFrame(p.g);
if(appConfig.getInt(AppSettings.RENDERING_GIF_STOP_FRAME, 100) == p.frameCount) {
_gifRenderer.finish();
}
}
// check for image sequence stop frame
if(imageSequenceRenderer != null && appConfig.getBoolean(AppSettings.RENDERING_IMAGE_SEQUENCE, false) == true) {
if(p.frameCount >= appConfig.getInt(AppSettings.RENDERING_IMAGE_SEQUENCE_START_FRAME, 1)) {
imageSequenceRenderer.renderImageFrame(p.g);
}
if(p.frameCount == appConfig.getInt(AppSettings.RENDERING_IMAGE_SEQUENCE_STOP_FRAME, 500)) {
imageSequenceRenderer.finish();
}
}
}
// INPUT
protected void autoHideMouse() {
// show mouse
if(p.mouseX != p.pmouseX || p.mouseY != p.pmouseY) {
lastMouseTime = p.millis();
if(p.mouseShowing == false) {
p.mouseShowing = true;
p.cursor();
}
}
// hide mouse
if(p.mouseShowing == true) {
if(p.millis() > lastMouseTime + 5000) {
p.noCursor();
mouseShowing = false;
}
}
}
protected void killScreensaver() {
// keep screensaver off - hit shift every 1000 frames
if( p.frameCount % 1000 == 10 ) _robot.keyPress(KeyEvent.VK_SHIFT);
if( p.frameCount % 1000 == 11 ) _robot.keyRelease(KeyEvent.VK_SHIFT);
}
public void keyPressed() {
// disable esc key - subclass must call super.keyPressed()
if( p.key == P.ESC && ( p.appConfig.getBoolean(AppSettings.DISABLE_ESC_KEY, false) == true ) ) { // || p.appConfig.getBoolean(AppSettings.RENDERING_MOVIE, false) == true )
key = 0;
// renderShutdownBeforeExit();
}
keyboardState.setKeyOn(p.keyCode);
// special core app key commands
// audio input gain
if ( p.key == '.' ) {
p.audioData.setGain(p.audioData.gain() + 0.05f);
p.debugView.setValue("audioData.gain()", p.audioData.gain());
}
if ( p.key == ',' ) {
p.audioData.setGain(p.audioData.gain() - 0.05f);
p.debugView.setValue("audioData.gain()", p.audioData.gain());
}
// show debug & prefs sliders
if (p.key == '/') showDebug = !showDebug;
if (p.key == '\\') prefsSliders.active(!prefsSliders.active());
}
public void keyReleased() {
keyboardState.setKeyOff(p.keyCode);
}
public float mousePercentX() {
return P.map(p.mouseX, 0, p.width, 0, 1);
}
public float mousePercentY() {
return P.map(p.mouseY, 0, p.height, 0, 1);
}
// SHUTDOWN
public void stop() {
if(p.webCamWrapper != null) p.webCamWrapper.dispose();
if( kinectWrapper != null ) {
kinectWrapper.stop();
kinectWrapper = null;
}
if( leapMotion != null ) leapMotion.dispose();
super.stop();
}
// PAPPLET LISTENERS
// Movie playback
public void movieEvent(Movie m) {
m.read();
MovieBuffer.moviesEventFrames.put(m, p.frameCount);
}
// ESS audio input
public void audioInputData(AudioInput theInput) {
if(audioInput instanceof AudioInputESS) {
((AudioInputESS) audioInput).audioInputCallback(theInput);
}
}
// LEAP MOTION EVENTS
void leapOnInit(){
// println("Leap Motion Init");
}
void leapOnConnect(){
// println("Leap Motion Connect");
}
void leapOnFrame(){
// println("Leap Motion Frame");
}
void leapOnDisconnect(){
// println("Leap Motion Disconnect");
}
void leapOnExit(){
// println("Leap Motion Exit");
}
}
|
package org.xwiki.security.authorization.internal;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.security.authorization.AuthorizationManager;
import org.xwiki.security.authorization.Right;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.user.api.XWikiRightService;
import com.xpn.xwiki.user.api.XWikiUser;
import com.xpn.xwiki.web.Utils;
/**
* Legacy bridge aimed to replace the current RightService until the new API is used in all places.
* @version $Id$
*/
public class XWikiCachingRightService implements XWikiRightService
{
/** Logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(XWikiCachingRightService.class);
/** The login action. */
private static final String DELETE_ACTION = "delete";
/** The delete action. */
private static final String LOGIN_ACTION = "login";
/**
* Map containing all known actions.
*/
private static final ActionMap ACTION_MAP = new ActionMap();
static {
ACTION_MAP
.putAction(LOGIN_ACTION, Right.LOGIN)
.putAction("view", Right.VIEW)
.putAction(DELETE_ACTION, Right.DELETE)
.putAction("admin", Right.ADMIN)
.putAction("programing", Right.PROGRAM)
.putAction("edit", Right.EDIT)
.putAction("register", Right.REGISTER)
.putAction("logout", Right.LOGIN)
.putAction("loginerror", Right.LOGIN)
.putAction("loginsubmit", Right.LOGIN)
.putAction("viewrev", Right.VIEW)
.putAction("get", Right.VIEW)
// .putAction("downloadrev", "download"); Huh??
.putAction("downloadrev", Right.VIEW)
.putAction("plain", Right.VIEW)
.putAction("raw", Right.VIEW)
.putAction("attach", Right.VIEW)
.putAction("charting", Right.VIEW)
.putAction("skin", Right.VIEW)
.putAction("download", Right.VIEW)
.putAction("dot", Right.VIEW)
.putAction("svg", Right.VIEW)
.putAction("pdf", Right.VIEW)
.putAction("deleteversions", Right.ADMIN)
// .putAction("undelete", "undelete"); Huh??
.putAction("undelete", Right.EDIT)
.putAction("reset", Right.DELETE)
.putAction("commentadd", Right.COMMENT)
.putAction("redirect", Right.VIEW)
.putAction("export", Right.VIEW)
.putAction("import", Right.ADMIN)
.putAction("jsx", Right.VIEW)
.putAction("ssx", Right.VIEW)
.putAction("tex", Right.VIEW)
.putAction("unknown", Right.VIEW)
.putAction("save", Right.EDIT)
.putAction("preview", Right.EDIT)
.putAction("lock", Right.EDIT)
.putAction("cancel", Right.EDIT)
.putAction("delattachment", Right.EDIT)
.putAction("inline", Right.EDIT)
.putAction("propadd", Right.EDIT)
.putAction("propupdate", Right.EDIT)
.putAction("propdelete", Right.EDIT)
.putAction("objectadd", Right.EDIT)
.putAction("objectremove", Right.EDIT)
.putAction("objectsync", Right.EDIT)
.putAction("rollback", Right.EDIT)
.putAction("upload", Right.EDIT)
.putAction("create", Right.EDIT);
}
/** Resolver for document references. */
@SuppressWarnings("unchecked")
private DocumentReferenceResolver<String> documentReferenceResolver
= Utils.getComponent(DocumentReferenceResolver.class);
/** Resolver for user and group document references. */
@SuppressWarnings("unchecked")
private DocumentReferenceResolver<String> userAndGroupReferenceResolver
= Utils.getComponent(DocumentReferenceResolver.class, "user");
/** The authorization manager used to really do the job. */
private final AuthorizationManager authorizationManager
= Utils.getComponent(AuthorizationManager.class);
/**
* Specialized map with a chainable put action to avoid exceeding code complexity during initialization.
*/
private static class ActionMap extends HashMap<String, Right>
{
/** Serialization identifier for conformance to Serializable. */
private static final long serialVersionUID = 1;
/** Allow filling the map in the initializer without exceeding code complexity.
* @param action the action name
* @param right the corresponding right required
* @return this action map to allow code chaining
*/
public ActionMap putAction(String action, Right right)
{
put(action, right);
return this;
}
}
public static Right actionToRight(String action)
{
Right right = ACTION_MAP.get(action);
if (right == null) {
return Right.ILLEGAL;
}
return right;
}
/**
* @param username name as a string.
* @param wikiReference default wiki, if not explicitly specified in the username.
* @return A document reference that uniquely identifies the user.
*/
private DocumentReference resolveUserName(String username, WikiReference wikiReference)
{
return userAndGroupReferenceResolver.resolve(username, wikiReference);
}
/**
* @param docname name of the document as string.
* @param wikiReference the default wiki where the document will be
* assumed do be located, unless explicitly specified in docname.
* @return the document reference.
*/
private DocumentReference resolveDocName(String docname, WikiReference wikiReference)
{
return documentReferenceResolver.resolve(docname, wikiReference);
}
/**
* Show the login page, unless the wiki is configured otherwise.
* @param context the context
*/
private void showLogin(XWikiContext context)
{
try {
if (context.getRequest() != null
&& !context.getWiki().Param("xwiki.hidelogin", "false").equalsIgnoreCase("true")) {
context.getWiki().getAuthService().showLogin(context);
}
} catch (XWikiException e) {
LOGGER.error("Failed to show login page.", e);
}
}
/**
* @param right Right to authenticate.
* @param entityReference Document that is being accessed.
* @param context current {@link XWikiContext}
* @return a {@link DocumentReference} that uniquely identifies
* the user, if the authentication was successful. {@code null}
* on failure.
*/
private DocumentReference authenticateUser(Right right, EntityReference entityReference, XWikiContext context)
{
XWikiUser user = context.getXWikiUser();
boolean needsAuth;
if (user == null) {
needsAuth = needsAuth(right, context);
try {
if (context.getMode() != XWikiContext.MODE_XMLRPC) {
user = context.getWiki().checkAuth(context);
} else {
user = new XWikiUser(XWikiConstants.GUEST_USER_FULLNAME);
}
if ((user == null) && (needsAuth)) {
LOGGER.info("Authentication needed for right " + right + " and entity " + entityReference + '.');
return null;
}
} catch (XWikiException e) {
LOGGER.error("Caught exception while authenticating user.", e);
}
String username;
if (user == null) {
username = XWikiConstants.GUEST_USER_FULLNAME;
} else {
username = user.getUser();
}
context.setUser(username);
return resolveUserName(username, new WikiReference(context.getDatabase()));
} else {
return resolveUserName(user.getUser(), new WikiReference(context.getDatabase()));
}
}
/**
* @param value a {@code String} value
* @return a {@code Boolean} value
*/
private Boolean checkNeedsAuthValue(String value)
{
if (value != null && !value.equals("")) {
if (value.toLowerCase().equals("yes")) {
return true;
}
try {
if (Integer.parseInt(value) > 0) {
return true;
}
} catch (NumberFormatException e) {
Formatter f = new Formatter();
LOGGER.warn(f.format("Failed to parse preference value: '%s'", value).toString());
}
}
return null;
}
/**
* @param right the right to check.
* @param context current {@link XWikiContext}
* @return {@code true} if the given right requires authentication.
*/
private boolean needsAuth(Right right, XWikiContext context)
{
String prefName = "authenticate_" + right.getName();
String value = context.getWiki().getXWikiPreference(prefName, "", context);
Boolean result = checkNeedsAuthValue(value);
if (result != null) {
return result;
}
value = context.getWiki().getSpacePreference(prefName, "", context).toLowerCase();
result = checkNeedsAuthValue(value);
if (result != null) {
return result;
}
return false;
}
@Override
public boolean checkAccess(String action, XWikiDocument doc, XWikiContext context)
throws XWikiException
{
Right right = actionToRight(action);
EntityReference entityReference = doc.getDocumentReference();
LOGGER.debug("checkAccess for action " + right + " on entity " + entityReference + '.');
DocumentReference userReference = authenticateUser(right, entityReference, context);
if (userReference == null) {
showLogin(context);
return false;
}
if (authorizationManager.hasAccess(right, userReference, entityReference)) {
return true;
}
// If the right has been denied, and we have guest user, redirect the user to login page
// unless the denied is on the login action, which could cause infinite redirection.
// FIXME: The hasAccessLevel is broken (do not allow document creator) on the delete action in the old
// implementation, so code that simply want to verify if a user can delete (but is not actually deleting)
// has to call checkAccess. This happen really often, and this why we should not redirect to login on failed
// delete, since it would prevent most user to do anything.
if (context.getUserReference() == null && !DELETE_ACTION.equals(action) && !LOGIN_ACTION.equals(action)) {
LOGGER.debug("Redirecting guest user to login, since it have been denied " + right + " on "
+ entityReference + '.');
showLogin(context);
}
return false;
}
@Override
public boolean hasAccessLevel(String right, String username, String docname, XWikiContext context)
throws XWikiException
{
WikiReference wikiReference = new WikiReference(context.getDatabase());
DocumentReference document = resolveDocName(docname, wikiReference);
LOGGER.debug("Resolved '" + docname + "' into " + document);
DocumentReference user = resolveUserName(username, wikiReference);
return authorizationManager.hasAccess(Right.toRight(right), user, document);
}
@Override
public boolean hasProgrammingRights(XWikiContext context)
{
XWikiDocument sdoc = (XWikiDocument) context.get("sdoc");
return hasProgrammingRights((sdoc != null) ? sdoc : context.getDoc(), context);
}
@Override
public boolean hasProgrammingRights(XWikiDocument doc, XWikiContext context)
{
DocumentReference user;
WikiReference wiki;
if (doc != null) {
user = doc.getContentAuthorReference();
wiki = doc.getDocumentReference().getWikiReference();
} else {
user = context.getUserReference();
wiki = new WikiReference(context.getDatabase());
}
return authorizationManager.hasAccess(Right.PROGRAM, user, wiki);
}
@Override
public boolean hasAdminRights(XWikiContext context)
{
DocumentReference user = context.getUserReference();
DocumentReference document = context.getDoc().getDocumentReference();
return authorizationManager.hasAccess(Right.ADMIN, user, document);
}
@Override
public boolean hasWikiAdminRights(XWikiContext context)
{
DocumentReference user = context.getUserReference();
WikiReference wiki = new WikiReference(context.getDatabase());
return authorizationManager.hasAccess(Right.ADMIN, user, wiki);
}
@Override
public List<String> listAllLevels(XWikiContext context)
throws XWikiException
{
return Right.getAllRightsAsString();
}
}
|
package com.ibm.nmon.parser;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import com.ibm.nmon.data.PerfmonDataSet;
import com.ibm.nmon.data.DataRecord;
import com.ibm.nmon.data.DataType;
import com.ibm.nmon.data.SubDataType;
import com.ibm.nmon.data.ProcessDataType;
import com.ibm.nmon.data.Process;
import com.ibm.nmon.data.transform.WindowsBytesTransform;
import com.ibm.nmon.data.transform.WindowsNetworkPostProcessor;
import com.ibm.nmon.data.transform.WindowsProcessPostProcessor;
import com.ibm.nmon.util.DataHelper;
public final class PerfmonParser {
private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(PerfmonParser.class);
private static final SimpleDateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// older versions of Windows output CSV without "
private static final Pattern DATA_SPLITTER = Pattern.compile(",");
private static final Pattern DATA_SPLITTER_QUOTES = Pattern.compile("\",\"");
private static final Pattern SUBCATEGORY_SPLITTER = Pattern.compile(":");
// "\\hostname\category (optional subcategory)\metric"
// note storing a matcher vs a pattern is _NOT_ thread safe
// first group is non-greedy (.*?) to allow proper parsing of strings like
// \\SYSTEM\Paging File(\??\D:\pagefile.sys)\% Usage
private static final Matcher METRIC_MATCHER = Pattern.compile("\\\\\\\\(.*?)\\\\(.*)\\\\(.*)\"?").matcher("");
private LineNumberReader in = null;
private PerfmonDataSet data = null;
private final WindowsBytesTransform bytesTransform = new WindowsBytesTransform();
// builders for each column
private DataTypeBuilder[] buildersByColumn;
// builders by type id
private Map<String, DataTypeBuilder> buildersById = new java.util.HashMap<String, DataTypeBuilder>();
public PerfmonDataSet parse(File file, boolean scaleProcessesByCPU) throws IOException, ParseException {
return parse(file.getAbsolutePath(), scaleProcessesByCPU);
}
public PerfmonDataSet parse(String filename, boolean scaleProcessesByCPU) throws IOException, ParseException {
long start = System.nanoTime();
data = new PerfmonDataSet(filename);
data.setMetadata("OS", "Perfmon");
try {
in = new LineNumberReader(new FileReader(filename));
String line = in.readLine();
// assume all columns will be quoted if the first one is
Pattern splitter = null;
if (line.startsWith("\"")) {
splitter = DATA_SPLITTER_QUOTES;
}
else {
splitter = DATA_SPLITTER;
}
parseHeader(splitter.split(line));
while ((line = in.readLine()) != null) {
parseData(splitter.split(line));
}
long postProcessStart = System.nanoTime();
// post process after parsing all the data since DataTypes are built lazily
WindowsNetworkPostProcessor networkPostProcessor = new WindowsNetworkPostProcessor();
WindowsProcessPostProcessor processPostProcessor = null;
networkPostProcessor.addDataTypes(data);
if (scaleProcessesByCPU) {
processPostProcessor = new WindowsProcessPostProcessor();
processPostProcessor.addDataTypes(data);
}
for (DataRecord record : data.getRecords()) {
networkPostProcessor.postProcess(data, record);
if (scaleProcessesByCPU) {
processPostProcessor.postProcess(data, record);
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Post processing" + " complete for {} in {}ms", data.getSourceFile(),
(System.nanoTime() - postProcessStart) / 1000000.0d);
}
DataHelper.aggregateProcessData(data, LOGGER);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parse" + " complete for {} in {}ms", data.getSourceFile(),
(System.nanoTime() - start) / 1000000.0d);
}
return data;
}
finally {
in.close();
data = null;
// columnTypes.clear();
buildersById.clear();
// processes.clear();
buildersByColumn = null;
bytesTransform.reset();
}
}
private void parseHeader(String[] header) {
buildersByColumn = new DataTypeBuilder[header.length];
// remove trailing " or ,
String lastData = header[header.length - 1];
if (lastData.endsWith("\"")) {
header[header.length - 1] = lastData.substring(0, lastData.length() - 1);
}
else if (lastData.endsWith(",")) {
header[header.length - 1] = lastData.substring(0, lastData.length() - 2);
}
// parse out the timezone in a format like (PDH-CSV 4.0) (GMT Daylight Time)(-60)
int idx = header[0].lastIndexOf('(');
if (idx == -1) {
LOGGER.warn("version header '{0}' is not in the right format, the time zone will default to UTC",
header[0]);
TIMESTAMP_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
else {
String temp = header[0].substring(idx + 1, header[0].length() - 1);
try {
// timezone format in negative minutes from UTC
double offset = Integer.parseInt(temp) / -60.0d;
TIMESTAMP_FORMAT.setTimeZone(new java.util.SimpleTimeZone((int) (offset * 3600000), temp));
}
catch (NumberFormatException nfe) {
LOGGER.warn("version header '{0}' is not in the right format, the time zone will default to UTC",
header[0]);
TIMESTAMP_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
}
// timestamp does not belong to a category
// columnTypes.add(null);
buildersByColumn[0] = null;
// read the first column to get the hostname
METRIC_MATCHER.reset(header[1]);
if (METRIC_MATCHER.matches()) {
// assume hostname does not change
data.setHostname(METRIC_MATCHER.group(1).toLowerCase());
}
else {
throw new IllegalArgumentException("hostname not found in '" + header[1] + "'");
}
for (int i = 1; i < header.length; i++) {
METRIC_MATCHER.reset(header[i]);
if (!METRIC_MATCHER.matches()) {
LOGGER.warn("'{}' is not a valid header column", header[i]);
buildersByColumn[i] = null;
continue;
}
// looking for type id (sub type id)
String toParse = METRIC_MATCHER.group(2);
String uniqueId = null;
String id = null;
String subId = null;
idx = toParse.indexOf('(');
if (idx != -1) { // has sub type
int endIdx = toParse.indexOf(')', idx + 1);
if (endIdx == -1) {
LOGGER.warn("no end parentheses found in header column '{}'", toParse);
// columnTypes.add(null);
buildersByColumn[i] = null;
continue;
}
else {
id = DataHelper.newString(toParse.substring(0, idx));
subId = DataHelper.newString(parseSubId(id, toParse.substring(idx + 1, endIdx)));
uniqueId = SubDataType.buildId(id, subId);
}
}
else {
id = uniqueId = DataHelper.newString(toParse);
}
String field = parseField(id, METRIC_MATCHER.group(3));
DataTypeBuilder builder = buildersById.get(uniqueId);
if (builder == null) {
builder = new DataTypeBuilder(uniqueId, id, subId);
buildersById.put(uniqueId, builder);
}
if (data.getTypeIdPrefix().equals(id)) { // Process
// skip Total and Idle processes
if ("Idle".equals(subId) || "Total".equals(subId)) {
buildersByColumn[i] = null;
}
// skip ID Process field but use is as the process id
else if ("ID Process".equals(field)) {
buildersByColumn[i] = null;
builder.setProcessIdColumn(i);
}
else {
buildersByColumn[i] = builder;
builder.addField(field);
}
}
else {
buildersByColumn[i] = builder;
builder.addField(field);
}
}
}
private void parseData(String[] rawData) {
if (rawData.length != buildersByColumn.length) {
LOGGER.warn("invalid number of data columns at line {}, this data will be skipped", in.getLineNumber());
return;
}
// remove trailing " or ,
String lastData = rawData[rawData.length - 1];
if (lastData.endsWith("\"")) {
rawData[rawData.length - 1] = lastData.substring(0, lastData.length() - 1);
}
else if (lastData.endsWith(",")) {
rawData[rawData.length - 1] = lastData.substring(0, lastData.length() - 2);
}
// remove leading " on timestamp
String timestamp = DataHelper.newString(rawData[0].substring(1));
long time = 0;
try {
time = TIMESTAMP_FORMAT.parse(timestamp).getTime();
}
catch (ParseException pe) {
LOGGER.warn("invalid timestamp format at line {}, this data will be skipped", in.getLineNumber());
return;
}
Map<String, DataHolder> dataByType = new java.util.HashMap<String, DataHolder>();
for (int i = 1; i < rawData.length; i++) {
DataTypeBuilder builder = buildersByColumn[i];
if (builder == null) {
continue;
}
else {
DataHolder holder = dataByType.get(builder.unique);
if (holder == null) {
holder = new DataHolder(builder.fields.size());
dataByType.put(builder.unique, holder);
}
try {
holder.add(parseDouble(rawData[i]));
}
catch (NumberFormatException nfe) {
LOGGER.warn("invalid double '{}' at line {}, column {}; it will be NaN", rawData[i],
in.getLineNumber(), i + 1);
holder.add(Double.NaN);
}
}
}
DataRecord record = new DataRecord(time, timestamp);
for (String unique : dataByType.keySet()) {
DataTypeBuilder builder = buildersById.get(unique);
DataHolder holder = dataByType.get(unique);
DataType type = builder.build(time, rawData);
double[] values = holder.data;
if (bytesTransform.isValidFor(builder.id, builder.subId)) {
if (type.hasField("% Used Space")) {
int idx = type.getFieldIndex("% Used Space");
values[idx] = 100 - values[idx];
}
values = bytesTransform.transform(type, values);
}
record.addData(type, values);
}
data.addRecord(record);
}
private String parseSubId(String id, String toParse) {
// some ESXTop data need special handling
if ("Interrupt Vector".equals(id)) {
String[] split = SUBCATEGORY_SPLITTER.split(toParse);
// interrupt id
return split[0];
}
else if (id.startsWith("Group")) {
// remove leading process id
String[] split = SUBCATEGORY_SPLITTER.split(toParse);
return split[1];
}
else if ("Vcpu".equals(id)) {
// remove leading process id
String[] split = SUBCATEGORY_SPLITTER.split(toParse);
return split[1];
}
else if (toParse.charAt(0) == '_') {
// _Total = Total
return toParse.substring(1);
}
else {
return toParse;
}
}
private double parseDouble(String value) {
// assume start with space, whole string is space (i.e. empty)
if (value.isEmpty() || (value.charAt(0) == ' ')) {
return Double.NaN;
}
else {
return Double.parseDouble(value);
}
}
private String parseField(String id, String toParse) {
if ("Interrupt Vector".equals(id)) {
String[] split = SUBCATEGORY_SPLITTER.split(toParse);
// total stats for interrupt
if (split.length > 1) {
return DataHelper.newString(split[1]);
}
else {
return toParse;
}
}
else {
return toParse;
}
}
// builder class for DataTypes
// needed due to Perfmon interleaving Process data columns
// Processes also need to be created with a start time and pid are unknown until data is parsed
private final class DataTypeBuilder {
// id + subId, used for hashCode and equals
private final String unique;
private final String id;
private final String subId;
// possible column mapping for ID Process column
private int processIdColumn = -1;
private final List<String> fields = new java.util.ArrayList<String>();
private DataType type;
DataTypeBuilder(String unique, String id, String subId) {
this.unique = unique;
this.id = id;
this.subId = subId;
}
void addField(String field) {
// assume no duplicates will happen
fields.add(field);
}
void setProcessIdColumn(int processIdColumn) {
this.processIdColumn = processIdColumn;
}
@Override
public int hashCode() {
return unique.hashCode();
}
@Override
public boolean equals(Object o) {
return unique.equals(o);
}
DataType build(long startTime, String[] rawData) {
if (type != null) {
return type;
}
String[] fieldsArray = new String[fields.size()];
fields.toArray(fieldsArray);
if (data.getTypeIdPrefix().equals(id)) { // Process
int pid = (int) (processIdColumn != -1 ? parseDouble(rawData[processIdColumn]) : 0);
String processName = subId; // store processes with full name
// parse out pid, if available via
// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance
// ProcessNameFormat=2
int idx = processName.indexOf('_');
if (idx != -1) {
String temp = processName.substring(idx + 1, processName.length());
try {
pid = Integer.parseInt(temp);
processName = DataHelper.newString(processName.substring(0, idx));
}
catch (NumberFormatException nfe) {
// process name might contain _
// ignore and continue parsing pid using other methods
}
}
idx = processName.indexOf('
if (idx != -1) {
processName = DataHelper.newString(processName.substring(0, idx));
}
if (pid == 0) {
// artificial process id
pid = data.getProcessCount() + 1;
}
Process process = new Process(pid, startTime, processName, data.getTypeIdPrefix() + " " + processName);
data.addProcess(process);
type = new ProcessDataType(process, fieldsArray);
}
else {
String name = SubDataType.buildId(id, subId);
if (bytesTransform.isValidFor(id, subId)) {
// cannot use a DataTransform for disk free -> disk used since disks also need
// to have WindowsBytesTransform applied
if ("LogicalDisk".equals(id) || "PhysicalDisk".equals(id)) {
for (int i = 0; i < fieldsArray.length; i++) {
String field = fieldsArray[i];
if ("% Free Space".equals(field)) {
fieldsArray[i] = "% Used Space";
}
}
}
type = bytesTransform.buildDataType(id, subId, name, fieldsArray);
}
else {
if (subId == null) {
type = new DataType(id, name, fieldsArray);
}
else {
type = new SubDataType(id, subId, name, fieldsArray);
}
}
}
data.addType(type);
return type;
}
}
// simple holder for field data as it is being read
private final class DataHolder {
private int nextIdx = 0;
private final double[] data;
DataHolder(int size) {
data = new double[size];
}
void add(double d) {
data[nextIdx++] = d;
}
}
}
|
package com.inet.lib.less;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.WritableRaster;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import javax.imageio.ImageIO;
class CustomFunctions {
static void colorizeImage( CssFormatter formatter, List<Expression> parameters ) throws IOException {
if( parameters.size() < 4 ) {
throw new LessException( "error evaluating function colorize-image expects url, main_color, contrast_color " );
}
String relativeURL = parameters.get( 0 ).stringValue( formatter );
String urlString = parameters.get( 1 ).stringValue( formatter );
URL url = new URL( formatter.getBaseURL(), relativeURL );
String urlStr = UrlUtils.removeQuote( urlString );
url = new URL( url, urlStr );
int mainColor = ColorUtils.argb( UrlUtils.getColor( parameters.get( 2 ), formatter ) );
int contrastColor = ColorUtils.argb( UrlUtils.getColor( parameters.get( 3 ), formatter ) );
BufferedImage loadedImage = ImageIO.read( url.openStream() );
// convert the image in a standard color model
int width = loadedImage.getWidth( null );
int height = loadedImage.getHeight( null );
BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
Graphics2D bGr = image.createGraphics();
bGr.drawImage( loadedImage, 0, 0, null );
bGr.dispose();
final float[] mainColorHsb = Color.RGBtoHSB( (mainColor >> 16) & 0xFF, (mainColor >> 8) & 0xFF, mainColor & 0xFF, null );
final float[] contrastColorHsb = Color.RGBtoHSB( (contrastColor >> 16) & 0xFF, (contrastColor >> 8) & 0xFF, contrastColor & 0xFF, null );
// get the pixel data
WritableRaster raster = image.getRaster();
DataBufferInt buffer = (DataBufferInt)raster.getDataBuffer();
int[] data = buffer.getData();
float[] hsb = new float[3];
int hsbColor = 0;
int lastRgb = data[0] + 1;
for( int i = 0; i < data.length; i++ ) {
int rgb = data[i];
if( rgb == lastRgb ) {
data[i] = hsbColor;
continue;
}
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
Color.RGBtoHSB( r, g, b, hsb );
float[] hsbColorize;
if( hsb[1] == 1.0f ) {
hsbColorize = hsb;
hsb[0] = hsb[0] * 3f / 4f + mainColorHsb[0] / 4f;
hsb[1] = hsb[1] * 3f / 4f + mainColorHsb[1] / 4f;
hsb[2] = hsb[2] * 3f / 4f + mainColorHsb[2] / 4f;
} else {
if( hsb[2] == 1.0f ) {
hsbColorize = contrastColorHsb;
} else {
hsbColorize = mainColorHsb;
}
}
lastRgb = rgb;
hsbColor = Color.HSBtoRGB( hsbColorize[0], hsbColorize[1], hsbColorize[2] );
hsbColor = (rgb & 0xFF000000) | (hsbColor & 0xFFFFFF);
data[i] = hsbColor;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write( image, "PNG", out );
UrlUtils.dataUri( formatter, out.toByteArray(), urlString, "image/png;base64" );
}
}
|
package com.maddyhome.idea.vim;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.ActionPlan;
import com.intellij.openapi.editor.actionSystem.DocCommandGroupId;
import com.intellij.openapi.editor.actionSystem.TypedActionHandler;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.maddyhome.idea.vim.action.DuplicableOperatorAction;
import com.maddyhome.idea.vim.action.change.VimRepeater;
import com.maddyhome.idea.vim.action.macro.ToggleRecordingAction;
import com.maddyhome.idea.vim.action.motion.search.SearchEntryFwdAction;
import com.maddyhome.idea.vim.action.motion.search.SearchEntryRevAction;
import com.maddyhome.idea.vim.command.*;
import com.maddyhome.idea.vim.extension.VimExtensionHandler;
import com.maddyhome.idea.vim.group.ChangeGroup;
import com.maddyhome.idea.vim.group.RegisterGroup;
import com.maddyhome.idea.vim.group.visual.VimSelection;
import com.maddyhome.idea.vim.group.visual.VisualGroupKt;
import com.maddyhome.idea.vim.handler.EditorActionHandlerBase;
import com.maddyhome.idea.vim.helper.*;
import com.maddyhome.idea.vim.key.*;
import com.maddyhome.idea.vim.listener.SelectionVimListenerSuppressor;
import com.maddyhome.idea.vim.listener.VimListenerSuppressor;
import com.maddyhome.idea.vim.option.OptionsManager;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.intellij.openapi.actionSystem.CommonDataKeys.*;
import static com.intellij.openapi.actionSystem.PlatformDataKeys.PROJECT_FILE_DIRECTORY;
/**
* This handlers every keystroke that the user can argType except those that are still valid hotkeys for various Idea
* actions. This is a singleton.
*/
public class KeyHandler {
/**
* Returns a reference to the singleton instance of this class
*
* @return A reference to the singleton
*/
@NotNull
public static KeyHandler getInstance() {
if (instance == null) {
instance = new KeyHandler();
}
return instance;
}
/**
* Creates an instance
*/
private KeyHandler() {
}
/**
* Sets the original key handler
*
* @param origHandler The original key handler
*/
public void setOriginalHandler(TypedActionHandler origHandler) {
this.origHandler = origHandler;
}
/**
* Gets the original key handler
*
* @return The original key handler
*/
public TypedActionHandler getOriginalHandler() {
return origHandler;
}
public static void executeVimAction(@NotNull Editor editor,
@NotNull EditorActionHandlerBase cmd,
DataContext context) {
CommandProcessor.getInstance()
.executeCommand(editor.getProject(), () -> cmd.execute(editor, getProjectAwareDataContext(editor, context)),
cmd.getId(), DocCommandGroupId.noneGroupId(editor.getDocument()), UndoConfirmationPolicy.DEFAULT,
editor.getDocument());
}
/**
* Execute an action
*
* @param action The action to execute
* @param context The context to run it in
*/
public static boolean executeAction(@NotNull AnAction action, @NotNull DataContext context) {
final AnActionEvent event =
new AnActionEvent(null, context, ActionPlaces.ACTION_SEARCH, action.getTemplatePresentation(),
ActionManager.getInstance(), 0);
if (action instanceof ActionGroup && !((ActionGroup)action).canBePerformed(context)) {
// Some of the AcitonGroups should not be performed, but shown as a popup
ListPopup popup = JBPopupFactory.getInstance()
.createActionGroupPopup(event.getPresentation().getText(), (ActionGroup)action, context, false, null, -1);
Component component = context.getData(PlatformDataKeys.CONTEXT_COMPONENT);
if (component != null) {
Window window = SwingUtilities.getWindowAncestor(component);
if (window != null) {
popup.showInCenterOf(window);
}
return true;
}
popup.showInFocusCenter();
return true;
}
else {
// beforeActionPerformedUpdate should be called to update the action. It fixes some rider-specific problems
// because rider use async update method. See VIM-1819
action.beforeActionPerformedUpdate(event);
if (event.getPresentation().isEnabled()) {
action.actionPerformed(event);
return true;
}
}
return false;
}
public void startDigraphSequence(@NotNull Editor editor) {
final CommandState editorState = CommandState.getInstance(editor);
editorState.startDigraphSequence();
}
public void startLiteralSequence(@NotNull Editor editor) {
final CommandState editorState = CommandState.getInstance(editor);
editorState.startLiteralSequence();
}
/**
* This is the main key handler for the Vim plugin. Every keystroke not handled directly by Idea is sent here for
* processing.
*
* @param editor The editor the key was typed into
* @param key The keystroke typed by the user
* @param context The data context
*/
public void handleKey(@NotNull Editor editor, @NotNull KeyStroke key, @NotNull DataContext context) {
handleKey(editor, key, context, true);
}
/**
* Invoked before acquiring a write lock and actually handling the keystroke.
* <p>
* Drafts an optional {@link ActionPlan} that will be used as a base for zero-latency rendering in editor.
*
* @param editor The editor the key was typed into
* @param key The keystroke typed by the user
* @param context The data context
* @param plan The current action plan
*/
public void beforeHandleKey(@NotNull Editor editor,
@NotNull KeyStroke key,
@NotNull DataContext context,
@NotNull ActionPlan plan) {
final CommandState.Mode mode = CommandState.getInstance(editor).getMode();
if (mode == CommandState.Mode.INSERT || mode == CommandState.Mode.REPLACE) {
VimPlugin.getChange().beforeProcessKey(editor, context, key, plan);
}
}
public void handleKey(@NotNull Editor editor,
@NotNull KeyStroke key,
@NotNull DataContext context,
boolean allowKeyMappings) {
VimPlugin.clearError();
// All the editor actions should be performed with top level editor!!!
// Be careful: all the EditorActionHandler implementation should correctly process InjectedEditors
editor = HelperKt.getTopLevelEditor(editor);
final CommandState editorState = CommandState.getInstance(editor);
// If this is a "regular" character keystroke, get the character
char chKey = key.getKeyChar() == KeyEvent.CHAR_UNDEFINED ? 0 : key.getKeyChar();
final boolean isRecording = editorState.isRecording();
boolean shouldRecord = true;
if (allowKeyMappings && handleKeyMapping(editor, key, context)) {
if (editorState.getMappingMode() != MappingMode.OP_PENDING ||
currentCmd.isEmpty() ||
currentCmd.peek().getArgument() == null ||
Objects.requireNonNull(currentCmd.peek().getArgument()).getType() != Argument.Type.OFFSETS) {
return;
}
}
else if (isCommandCount(chKey, editorState)) {
editorState.setCount((editorState.getCount() * 10) + (chKey - '0'));
}
else if (isDeleteCommandCount(key, editorState)) {
editorState.setCount(editorState.getCount() / 10);
}
else if (isEditorReset(key, editorState)) {
handleEditorReset(editor, key, context, editorState);
}
// If we got this far the user is entering a command or supplying an argument to an entered command.
// First let's check to see if we are at the point of expecting a single character argument to a command.
else if (editorState.getCurrentArgumentType() == Argument.Type.CHARACTER) {
handleCharArgument(key, chKey);
}
// If we are this far, then the user must be entering a command or a non-single-character argument
// to an entered command. Let's figure out which it is
else {
// For debugging purposes we track the keys entered for this command
editorState.addKey(key);
if (handleDigraph(editor, key, context, editorState)) return;
// Ask the key/action tree if this is an appropriate key at this point in the command and if so,
// return the node matching this keystroke
Node node = editorState.getCurrentNode().get(key);
node = mapOpCommand(key, node, editorState);
if (node instanceof CommandNode) {
handleCommandNode(editor, context, key, (CommandNode) node, editorState);
}
else if (node instanceof CommandPartNode) {
editorState.setCurrentNode((CommandPartNode) node);
}
else {
// If we are in insert/replace mode send this key in for processing
if (editorState.getMode() == CommandState.Mode.INSERT || editorState.getMode() == CommandState.Mode.REPLACE) {
if (!VimPlugin.getChange().processKey(editor, context, key)) {
shouldRecord = false;
}
}
else if (editorState.getMode() == CommandState.Mode.SELECT) {
if (!VimPlugin.getChange().processKeyInSelectMode(editor, context, key)) {
shouldRecord = false;
}
}
else if (editorState.getMappingMode() == MappingMode.CMD_LINE) {
if (!VimPlugin.getProcess().processExKey(editor, key)) {
shouldRecord = false;
}
}
// If we get here then the user has entered an unrecognized series of keystrokes
else {
state = State.BAD_COMMAND;
}
partialReset(editor);
}
}
// Do we have a fully entered command at this point? If so, lets execute it
if (state == State.READY) {
executeCommand(editor, key, context, editorState);
}
else if (state == State.BAD_COMMAND) {
if (editorState.getMappingMode() == MappingMode.OP_PENDING) {
editorState.popState();
}
VimPlugin.indicateError();
reset(editor);
}
else if (isRecording && shouldRecord) {
VimPlugin.getRegister().recordKeyStroke(key);
}
}
/**
* See the description for {@link com.maddyhome.idea.vim.action.DuplicableOperatorAction}
*/
private Node mapOpCommand(KeyStroke key, Node node, @NotNull CommandState editorState) {
if (editorState.getMappingMode() == MappingMode.OP_PENDING && !currentCmd.empty()) {
EditorActionHandlerBase action = currentCmd.peek().getAction();
if (action instanceof DuplicableOperatorAction &&
((DuplicableOperatorAction)action).getDuplicateWith() == key.getKeyChar()) {
return editorState.getCurrentNode().get(KeyStroke.getKeyStroke('_'));
}
}
return node;
}
private static <T> boolean isPrefix(@NotNull List<T> list1, @NotNull List<T> list2) {
if (list1.size() > list2.size()) {
return false;
}
for (int i = 0; i < list1.size(); i++) {
if (!list1.get(i).equals(list2.get(i))) {
return false;
}
}
return true;
}
private void handleEditorReset(@NotNull Editor editor, @NotNull KeyStroke key, @NotNull final DataContext context, CommandState editorState) {
if (editorState.getCount() == 0 && editorState.getCurrentArgumentType() == null && currentCmd.size() == 0) {
RegisterGroup register = VimPlugin.getRegister();
if (register.getCurrentRegister() == register.getDefaultRegister()) {
if (key.getKeyCode() == KeyEvent.VK_ESCAPE) {
CommandProcessor.getInstance()
.executeCommand(editor.getProject(), () -> KeyHandler.executeAction("EditorEscape", context), "", null);
}
VimPlugin.indicateError();
}
}
reset(editor);
ChangeGroup.resetCaret(editor, false);
}
private boolean handleKeyMapping(@NotNull final Editor editor,
@NotNull final KeyStroke key,
@NotNull final DataContext context) {
final CommandState commandState = CommandState.getInstance(editor);
if (state == State.CHAR_OR_DIGRAPH
|| isBuildingMultiKeyCommand(commandState)
|| isMappingDisabledForKey(key, commandState)) {
return false;
}
commandState.stopMappingTimer();
final MappingMode mappingMode = commandState.getMappingMode();
final List<KeyStroke> previouslyUnhandledKeySequence = commandState.getMappingKeys();
final List<KeyStroke> currentlyUnhandledKeySequence = new ArrayList<>(previouslyUnhandledKeySequence);
currentlyUnhandledKeySequence.add(key);
final KeyMapping mapping = VimPlugin.getKey().getKeyMapping(mappingMode);
// Returns true if any of these methods handle the key. False means that the key is unrelated to mapping and should
// be processed as normal.
return handleUnfinishedMappingSequence(editor, mapping, currentlyUnhandledKeySequence, key)
|| handleCompleteMappingSequence(editor, context, mapping, previouslyUnhandledKeySequence, currentlyUnhandledKeySequence, key)
|| handleAbandonedMappingSequence(editor, commandState, context, previouslyUnhandledKeySequence, currentlyUnhandledKeySequence);
}
private boolean isBuildingMultiKeyCommand(CommandState commandState) {
// Don't apply mapping if we're in the middle of building a multi-key command.
// E.g. given nmap s v, don't try to map <C-W>s to <C-W>v
// Similarly, nmap <C-W>a <C-W>s should not try to map the second <C-W> in <C-W><C-W>
// Note that we might still be at RootNode if we're handling a prefix, because we might be buffering keys until we
// get a match. This means we'll still process the rest of the keys of the prefix.
return !(commandState.getCurrentNode() instanceof RootNode);
}
private boolean isMappingDisabledForKey(@NotNull KeyStroke key, @NotNull CommandState commandState) {
// "0" can be mapped, but the mapping isn't applied when entering a count. Other digits are always mapped, even when
// entering a count.
// See `:help :map-modes`
return key.getKeyChar() == '0' && commandState.getCount() > 0;
}
private boolean handleUnfinishedMappingSequence(@NotNull Editor editor,
@NotNull KeyMapping mapping,
@NotNull List<KeyStroke> currentlyUnhandledKeySequence,
@NotNull KeyStroke key) {
// Is there at least one mapping that starts with the current sequence? This does not include complete matches,
// unless a sequence is also a prefix for another mapping. We eagerly evaluate the shortest mapping, so even if a
// mapping is a prefix, it will get evaluated when the next character is entered.
// Note that currentlyUnhandledKeySequence is the same as the state after commandState.getMappingKeys().add(key). It
// would be nice to tidy ths up
if (!mapping.isPrefix(currentlyUnhandledKeySequence)) {
return false;
}
// Save the unhandled key strokes until we either complete or abandon the sequence.
final CommandState commandState = CommandState.getInstance(editor);
commandState.getMappingKeys().add(key);
// If the timeout option is set, set a timer that will abandon the sequence and replay the unhandled keys unmapped.
// Every time a key is pressed and handled, the timer is stopped. E.g. if there is a mapping for "dweri", and the
// user has typed "dw" wait for the timeout, and then replay "d" and "w" without any mapping (which will of course
// delete a word)
final Application application = ApplicationManager.getApplication();
if (!application.isUnitTestMode() && OptionsManager.INSTANCE.getTimeout().isSet()) {
commandState.startMappingTimer(actionEvent -> application.invokeLater(() -> {
final List<KeyStroke> unhandledKeys = new ArrayList<>(commandState.getMappingKeys());
commandState.getMappingKeys().clear();
// TODO: I'm not sure why we abandon plugin commands here
// Would be useful to have a comment or a helpfully named helper method here
if (editor.isDisposed() || unhandledKeys.get(0).equals(StringHelper.PlugKeyStroke)) {
return;
}
for (KeyStroke keyStroke : unhandledKeys) {
handleKey(editor, keyStroke, new EditorDataContext(editor), false);
}
}, ModalityState.stateForComponent(editor.getComponent())));
}
return true;
}
private boolean handleCompleteMappingSequence(@NotNull Editor editor,
DataContext context, @NotNull KeyMapping mapping,
@NotNull List<KeyStroke> previouslyUnhandledKeySequence,
@NotNull List<KeyStroke> currentlyUnhandledKeySequence, KeyStroke key) {
// If the current sequence is a complete mapping, then evaluate it. If not, check if the previous sequence was a
// mapping which was also a prefix, and evaluate it if so.
final MappingInfo previousMappingInfo = mapping.get(previouslyUnhandledKeySequence);
final MappingInfo currentMappingInfo = mapping.get(currentlyUnhandledKeySequence);
final MappingInfo mappingInfo = currentMappingInfo != null ? currentMappingInfo : previousMappingInfo;
if (mappingInfo == null) {
return false;
}
final CommandState commandState = CommandState.getInstance(editor);
commandState.getMappingKeys().clear();
final EditorDataContext currentContext = new EditorDataContext(editor);
final List<KeyStroke> toKeys = mappingInfo.getToKeys();
final VimExtensionHandler extensionHandler = mappingInfo.getExtensionHandler();
if (toKeys != null) {
final boolean fromIsPrefix = isPrefix(mappingInfo.getFromKeys(), toKeys);
boolean first = true;
for (KeyStroke keyStroke : toKeys) {
final boolean recursive = mappingInfo.isRecursive() && !(first && fromIsPrefix);
handleKey(editor, keyStroke, currentContext, recursive);
first = false;
}
}
else if (extensionHandler != null) {
final CommandProcessor processor = CommandProcessor.getInstance();
final boolean isPendingMode = CommandState.getInstance(editor).getMappingMode() == MappingMode.OP_PENDING;
Map<Caret, Integer> startOffsets =
editor.getCaretModel().getAllCarets().stream().collect(Collectors.toMap(Function.identity(), Caret::getOffset));
if (extensionHandler.isRepeatable()) {
VimRepeater.Extension.INSTANCE.clean();
}
processor.executeCommand(editor.getProject(), () -> extensionHandler.execute(editor, context),
"Vim " + extensionHandler.getClass().getSimpleName(), null);
if (extensionHandler.isRepeatable()) {
VimRepeater.Extension.INSTANCE.setLastExtensionHandler(extensionHandler);
VimRepeater.Extension.INSTANCE.setArgumentCaptured(null);
VimRepeater.INSTANCE.setRepeatHandler(true);
}
if (isPendingMode &&
!currentCmd.isEmpty() &&
currentCmd.peek().getArgument() == null) {
Map<Caret, VimSelection> offsets = new HashMap<>();
for (Caret caret : editor.getCaretModel().getAllCarets()) {
@Nullable Integer startOffset = startOffsets.get(caret);
if (caret.hasSelection()) {
final VimSelection vimSelection = VimSelection.Companion
.create(UserDataManager.getVimSelectionStart(caret), caret.getOffset(),
SelectionType.fromSubMode(CommandStateHelper.getSubMode(editor)), editor);
offsets.put(caret, vimSelection);
commandState.popState();
}
else if (startOffset != null && startOffset != caret.getOffset()) {
// Command line motions are always characterwise exclusive
int endOffset = caret.getOffset();
if (startOffset < endOffset) {
endOffset -= 1;
} else {
startOffset -= 1;
}
final VimSelection vimSelection = VimSelection.Companion
.create(startOffset, endOffset, SelectionType.CHARACTER_WISE, editor);
offsets.put(caret, vimSelection);
try (VimListenerSuppressor.Locked ignored = SelectionVimListenerSuppressor.INSTANCE.lock()) {
// Move caret to the initial offset for better undo action
// This is not a necessary thing, but without it undo action look less convenient
editor.getCaretModel().moveToOffset(startOffset);
}
}
}
if (!offsets.isEmpty()) {
currentCmd.peek().setArgument(new Argument(offsets));
state = State.READY;
}
}
}
// If we've just evaluated the previous key sequence, make sure to also handle the current key
if (previousMappingInfo == mappingInfo) {
handleKey(editor, key, currentContext, true);
}
return true;
}
private boolean handleAbandonedMappingSequence(@NotNull Editor editor,
@NotNull CommandState commandState,
DataContext context,
@NotNull List<KeyStroke> previouslyUnhandledKeySequence,
@NotNull List<KeyStroke> currentlyUnhandledKeySequence) {
// The user has terminated a mapping sequence with an unexpected key
// E.g. if there is a mapping for "hello" and user enters command "help" the processing of "h", "e" and "l" will be
// prevented by this handler. Make sure the currently unhandled keys are processed as normal.
// If there are no previous keys to handle, do nothing
if (previouslyUnhandledKeySequence.isEmpty()) {
return false;
}
// Okay, look at the code below. Why is the first key handled separately?
// Let's assume the next mappings:
// - map ds j
// - map I 2l
// If user enters `dI`, the first `d` will be caught be this handler because it's a prefix for `ds` command.
// After the user enters `I`, the caught `d` should be processed without mapping and the rest of keys
// should be processed with mappings (to make I work)
// Additionally, the <Plug>mappings are not executed if the are failed to map to somethings.
// - map <Plug>iA someAction
// - map I <Plug>i
// For `IA` someAction should be executed.
// But if the user types `Ib`, `<Plug>i` won't be executed again. Only `b` will be passed to keyHandler.
commandState.getMappingKeys().clear();
if (currentlyUnhandledKeySequence.get(0).equals(StringHelper.PlugKeyStroke)) {
handleKey(editor, currentlyUnhandledKeySequence.get(currentlyUnhandledKeySequence.size() - 1), context, true);
} else {
handleKey(editor, currentlyUnhandledKeySequence.get(0), context, false);
for (KeyStroke keyStroke : currentlyUnhandledKeySequence.subList(1, currentlyUnhandledKeySequence.size())) {
handleKey(editor, keyStroke, context, true);
}
}
return true;
}
private boolean isDeleteCommandCount(@NotNull KeyStroke key, @NotNull CommandState editorState) {
// See `:help N<Del>`
return (editorState.getMode() == CommandState.Mode.COMMAND || editorState.getMode() == CommandState.Mode.VISUAL) &&
state == State.NEW_COMMAND &&
editorState.getCurrentArgumentType() != Argument.Type.CHARACTER &&
editorState.getCurrentArgumentType() != Argument.Type.DIGRAPH &&
key.getKeyCode() == KeyEvent.VK_DELETE &&
editorState.getCount() != 0;
}
private boolean isEditorReset(@NotNull KeyStroke key, @NotNull CommandState editorState) {
return (editorState.getMode() == CommandState.Mode.COMMAND) && StringHelper.isCloseKeyStroke(key);
}
private void handleCharArgument(@NotNull KeyStroke key, char chKey) {
// We are expecting a character argument - is this a regular character the user typed?
// Some special keys can be handled as character arguments - let's check for them here.
if (chKey == 0) {
switch (key.getKeyCode()) {
case KeyEvent.VK_TAB:
chKey = '\t';
break;
case KeyEvent.VK_ENTER:
chKey = '\n';
break;
}
}
if (chKey != 0) {
// Create the character argument, add it to the current command, and signal we are ready to process
// the command
Argument arg = new Argument(chKey);
Command cmd = currentCmd.peek();
cmd.setArgument(arg);
state = State.READY;
}
else {
// Oops - this isn't a valid character argument
state = State.BAD_COMMAND;
}
}
private boolean isCommandCount(char chKey, @NotNull CommandState editorState) {
return (editorState.getMode() == CommandState.Mode.COMMAND || editorState.getMode() == CommandState.Mode.VISUAL) &&
state == State.NEW_COMMAND &&
editorState.getCurrentArgumentType() != Argument.Type.CHARACTER &&
editorState.getCurrentArgumentType() != Argument.Type.DIGRAPH &&
Character.isDigit(chKey) &&
(editorState.getCount() != 0 || chKey != '0');
}
private boolean handleDigraph(@NotNull Editor editor,
@NotNull KeyStroke key,
@NotNull DataContext context,
@NotNull CommandState editorState) {
// Support starting a digraph/literal sequence if the operator accepts one as an argument, e.g. 'r' or 'f'.
// Normally, we start the sequence (in Insert or CmdLine mode) through a VimAction that can be mapped. Our
// VimActions don't work as arguments for operators, so we have to special case here. Helpfully, Vim appears to
// hardcode the shortcuts, and doesn't support mapping, so everything works nicely.
if (editorState.getCurrentArgumentType() == Argument.Type.DIGRAPH) {
if (DigraphSequence.isDigraphStart(key)) {
editorState.startDigraphSequence();
return true;
}
if (DigraphSequence.isLiteralStart(key)) {
editorState.startLiteralSequence();
return true;
}
}
DigraphResult res = editorState.processDigraphKey(key, editor);
switch (res.getResult()) {
case DigraphResult.RES_HANDLED:
case DigraphResult.RES_BAD:
return true;
case DigraphResult.RES_DONE:
if (editorState.getCurrentArgumentType() == Argument.Type.DIGRAPH) {
editorState.setCurrentArgumentType(Argument.Type.CHARACTER);
}
final KeyStroke stroke = res.getStroke();
if (stroke == null) {
return false;
}
handleKey(editor, stroke, context);
return true;
case DigraphResult.RES_UNHANDLED:
if (editorState.getCurrentArgumentType() == Argument.Type.DIGRAPH) {
editorState.setCurrentArgumentType(Argument.Type.CHARACTER);
handleKey(editor, key, context);
return true;
}
return false;
}
return false;
}
private void executeCommand(@NotNull Editor editor,
@NotNull KeyStroke key,
@NotNull DataContext context,
@NotNull CommandState editorState) {
// Let's go through the command stack and merge it all into one command. At this time there should never
// be more than two commands on the stack - one is the actual command and the other would be a motion
// command argument needed by the first command
Command cmd = currentCmd.pop();
while (currentCmd.size() > 0) {
Command top = currentCmd.pop();
top.setArgument(new Argument(cmd));
cmd = top;
}
// If we have a command and a motion command argument, both could possibly have their own counts. We
// need to adjust the counts so the motion gets the product of both counts and the count associated with
// the command gets reset. Example 3c2w (change 2 words, three times) becomes c6w (change 6 words)
final Argument arg = cmd.getArgument();
if (arg != null && arg.getType() == Argument.Type.MOTION) {
final Command mot = arg.getMotion();
// If no count was entered for either command then nothing changes. If either had a count then
// the motion gets the product of both.
int cnt = cmd.getRawCount() == 0 && mot.getRawCount() == 0 ? 0 : cmd.getCount() * mot.getCount();
mot.setCount(cnt);
cmd.setCount(0);
}
// If we were in "operator pending" mode, reset back to normal mode.
if (editorState.getMappingMode() == MappingMode.OP_PENDING) {
editorState.popState();
}
// Save off the command we are about to execute
editorState.setCommand(cmd);
Project project = editor.getProject();
final Command.Type type = cmd.getType();
if (type.isWrite() && !editor.getDocument().isWritable()) {
VimPlugin.indicateError();
reset(editor);
}
if (!cmd.getFlags().contains(CommandFlags.FLAG_TYPEAHEAD_SELF_MANAGE)) {
IdeEventQueue.getInstance().flushDelayedKeyEvents();
}
if (ApplicationManager.getApplication().isDispatchThread()) {
Runnable action = new ActionRunner(editor, context, cmd, key);
EditorActionHandlerBase cmdAction = cmd.getAction();
String name = cmdAction.getId();
if (type.isWrite()) {
RunnableHelper.runWriteCommand(project, action, name, action);
}
else if (type.isRead()) {
RunnableHelper.runReadCommand(project, action, name, action);
}
else {
CommandProcessor.getInstance().executeCommand(project, action, name, action);
}
}
}
private void handleCommandNode(Editor editor,
DataContext context,
KeyStroke key,
@NotNull CommandNode node,
CommandState editorState) {
// The user entered a valid command. Create the command and add it to the stack
final EditorActionHandlerBase myAction = node.getActionHolder().getAction();
Command cmd = new Command(editorState.getCount(), myAction, myAction.getType(), myAction.getFlags(), editorState.getKeys());
currentCmd.push(cmd);
if (editorState.getCurrentArgumentType() != null && !checkArgumentCompatibility(node, editorState)) return;
if (myAction.getArgumentType() == null || stopMacroRecord(node, editorState)) {
state = State.READY;
}
else {
editorState.setCurrentArgumentType(node.getActionHolder().getAction().getArgumentType());
startWaitingForArgument(editor, context, key.getKeyChar(), editorState.getCurrentArgumentType(), editorState);
partialReset(editor);
}
// TODO In the name of God, get rid of EX_STRING, FLAG_COMPLETE_EX and all the related staff
if (editorState.getCurrentArgumentType() == Argument.Type.EX_STRING && myAction.getFlags().contains(CommandFlags.FLAG_COMPLETE_EX)) {
EditorActionHandlerBase action;
if (VimPlugin.getProcess().isForwardSearch()) {
action = new SearchEntryFwdAction();
}
else {
action = new SearchEntryRevAction();
}
String text = VimPlugin.getProcess().endSearchCommand(editor);
currentCmd.pop();
Argument arg = new Argument(text);
cmd = new Command(editorState.getCount(), action, action.getType(), action.getFlags(), editorState.getKeys());
cmd.setArgument(arg);
currentCmd.push(cmd);
CommandState.getInstance(editor).popState();
}
}
private boolean stopMacroRecord(CommandNode node, @NotNull CommandState editorState) {
return editorState.isRecording() && node.getActionHolder().getAction() instanceof ToggleRecordingAction;
}
private void startWaitingForArgument(Editor editor,
DataContext context,
char key,
@NotNull Argument.Type argument,
CommandState editorState) {
switch (argument) {
case CHARACTER:
case DIGRAPH:
state = State.CHAR_OR_DIGRAPH;
break;
case MOTION:
if (CommandState.getInstance(editor).isDotRepeatInProgress() && VimRepeater.Extension.INSTANCE.getArgumentCaptured() != null) {
currentCmd.peek().setArgument(VimRepeater.Extension.INSTANCE.getArgumentCaptured());
state = State.READY;
}
editorState.pushState(editorState.getMode(), editorState.getSubMode(), MappingMode.OP_PENDING);
break;
case EX_STRING:
VimPlugin.getProcess().startSearchCommand(editor, context, editorState.getCount(), key);
state = State.NEW_COMMAND;
editorState.pushState(CommandState.Mode.CMD_LINE, CommandState.SubMode.NONE, MappingMode.CMD_LINE);
currentCmd.pop();
}
}
private boolean checkArgumentCompatibility(@NotNull CommandNode node, @NotNull CommandState editorState) {
if (editorState.getCurrentArgumentType() == Argument.Type.MOTION &&
node.getActionHolder().getAction().getType() != Command.Type.MOTION) {
state = State.BAD_COMMAND;
return false;
}
return true;
}
/**
* Execute an action by name
*
* @param name The name of the action to execute
* @param context The context to run it in
*/
public static boolean executeAction(@NotNull String name, @NotNull DataContext context) {
ActionManager aMgr = ActionManager.getInstance();
AnAction action = aMgr.getAction(name);
return action != null && executeAction(action, context);
}
/**
* Partially resets the state of this handler. Resets the command count, clears the key list, resets the key tree
* node to the root for the current mode we are in.
*
* @param editor The editor to reset.
*/
public void partialReset(@Nullable Editor editor) {
CommandState editorState = CommandState.getInstance(editor);
editorState.setCount(0);
editorState.stopMappingTimer();
editorState.getMappingKeys().clear();
editorState.getKeys().clear();
editorState.setCurrentNode(VimPlugin.getKey().getKeyRoot(editorState.getMappingMode()));
}
/**
* Resets the state of this handler. Does a partial reset then resets the mode, the command, and the argument
*
* @param editor The editor to reset.
*/
public void reset(@Nullable Editor editor) {
partialReset(editor);
state = State.NEW_COMMAND;
currentCmd.clear();
CommandState editorState = CommandState.getInstance(editor);
editorState.setCurrentArgumentType(null);
}
/**
* Completely resets the state of this handler. Resets the command mode to normal, resets, and clears the selected
* register.
*
* @param editor The editor to reset.
*/
public void fullReset(@Nullable Editor editor) {
VimPlugin.clearError();
CommandState.getInstance(editor).reset();
reset(editor);
VimPlugin.getRegister().resetRegister();
if (editor != null) {
VisualGroupKt.updateCaretState(editor);
editor.getSelectionModel().removeSelection();
}
}
// This method is copied from com.intellij.openapi.editor.actionSystem.EditorAction.getProjectAwareDataContext
@NotNull
private static DataContext getProjectAwareDataContext(@NotNull final Editor editor,
@NotNull final DataContext original) {
if (PROJECT.getData(original) == editor.getProject()) {
return new DialogAwareDataContext(original);
}
return dataId -> {
if (PROJECT.is(dataId)) {
final Project project = editor.getProject();
if (project != null) {
return project;
}
}
return original.getData(dataId);
};
}
// This class is copied from com.intellij.openapi.editor.actionSystem.DialogAwareDataContext.DialogAwareDataContext
private final static class DialogAwareDataContext implements DataContext {
private static final DataKey[] keys = {PROJECT, PROJECT_FILE_DIRECTORY, EDITOR, VIRTUAL_FILE, PSI_FILE};
private final Map<String, Object> values = new HashMap<>();
DialogAwareDataContext(DataContext context) {
for (DataKey key : keys) {
values.put(key.getName(), key.getData(context));
}
}
@Nullable
@Override
public Object getData(@NotNull @NonNls String dataId) {
if (values.containsKey(dataId)) {
return values.get(dataId);
}
final Editor editor = (Editor)values.get(EDITOR.getName());
if (editor != null) {
return DataManager.getInstance().getDataContext(editor.getContentComponent()).getData(dataId);
}
return null;
}
}
/**
* This was used as an experiment to execute actions as a runnable.
*/
static class ActionRunner implements Runnable {
@Contract(pure = true)
ActionRunner(Editor editor, DataContext context, Command cmd, KeyStroke key) {
this.editor = editor;
this.context = context;
this.cmd = cmd;
this.key = key;
}
@Override
public void run() {
CommandState editorState = CommandState.getInstance(editor);
boolean wasRecording = editorState.isRecording();
KeyHandler.getInstance().state = State.NEW_COMMAND;
executeVimAction(editor, cmd.getAction(), context);
if (editorState.getMode() == CommandState.Mode.INSERT || editorState.getMode() == CommandState.Mode.REPLACE) {
VimPlugin.getChange().processCommand(editor, cmd);
}
// Now the command has been executed let's clean up a few things.
// By default, the "empty" register is used by all commands, so we want to reset whatever the last register
// selected by the user was to the empty register - unless we just executed the "select register" command.
if (cmd.getType() != Command.Type.SELECT_REGISTER) {
VimPlugin.getRegister().resetRegister();
}
// If, at this point, we are not in insert, replace, or visual modes, we need to restore the previous
// mode we were in. This handles commands in those modes that temporarily allow us to execute normal
// mode commands. An exception is if this command should leave us in the temporary mode such as
// "select register"
if (editorState.getSubMode() == CommandState.SubMode.SINGLE_COMMAND &&
(!cmd.getFlags().contains(CommandFlags.FLAG_EXPECT_MORE))) {
editorState.popState();
}
KeyHandler.getInstance().reset(editor);
if (wasRecording && editorState.isRecording()) {
VimPlugin.getRegister().recordKeyStroke(key);
}
}
private final Editor editor;
private final DataContext context;
private final Command cmd;
private final KeyStroke key;
}
private enum State {
/** Awaiting a new command */
NEW_COMMAND,
// TODO: This should be probably processed in some better way
/** Awaiting char or digraph input. In this mode mappings doesn't work (even for <C-K>) */
CHAR_OR_DIGRAPH,
READY,
BAD_COMMAND
}
private TypedActionHandler origHandler;
private static KeyHandler instance;
// TODO: All of this state needs to be per-editor
private State state = State.NEW_COMMAND;
@NotNull private final Stack<Command> currentCmd = new Stack<>();
}
|
package org.springframework.ide.vscode.commons.languageserver.completion;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionList;
import org.eclipse.lsp4j.InsertTextFormat;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.TextDocumentPositionParams;
import org.eclipse.lsp4j.TextEdit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ide.vscode.commons.languageserver.completion.DocumentEdits.TextReplace;
import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer;
import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService;
import org.springframework.ide.vscode.commons.languageserver.util.SortKeys;
import org.springframework.ide.vscode.commons.util.Futures;
import org.springframework.ide.vscode.commons.util.Renderable;
import org.springframework.ide.vscode.commons.util.StringUtil;
import org.springframework.ide.vscode.commons.util.text.TextDocument;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
/**
* Adapts a {@link ICompletionEngine}, wrapping it, to implement {@link VscodeCompletionEngine}
*/
public class VscodeCompletionEngineAdapter implements VscodeCompletionEngine {
private final static int MAX_COMPLETIONS = 50;
private int maxCompletions = MAX_COMPLETIONS;
final static Logger logger = LoggerFactory.getLogger(VscodeCompletionEngineAdapter.class);
public static final String VS_CODE_CURSOR_MARKER = "{{}}";
private SimpleLanguageServer server;
private ICompletionEngine engine;
public VscodeCompletionEngineAdapter(SimpleLanguageServer server, ICompletionEngine engine) {
this.server = server;
this.engine = engine;
}
public void setMaxCompletionsNumber(int maxCompletions) {
this.maxCompletions = maxCompletions;
}
@Override
public CompletableFuture<CompletionList> getCompletions(TextDocumentPositionParams params) {
return getCompletionsMono(params).toFuture();
}
private Mono<CompletionList> getCompletionsMono(TextDocumentPositionParams params) {
SimpleTextDocumentService documents = server.getTextDocumentService();
TextDocument doc = documents.get(params).copy();
if (doc!=null) {
return Mono.fromCallable(() -> {
//TODO: This callable is a 'big lump of work' so can't be canceled in pieces.
// Should we push using of reactive streams down further and compose this all
// using reactive style? If not then this is overkill could just as well use
// only standard Java API such as Executor and CompletableFuture directly.
int offset = doc.toOffset(params.getPosition());
List<ICompletionProposal> completions = new ArrayList<>(engine.getCompletions(doc, offset));
Collections.sort(completions, ScoreableProposal.COMPARATOR);
CompletionList list = new CompletionList();
list.setIsIncomplete(false);
List<CompletionItem> items = new ArrayList<>(completions.size());
SortKeys sortkeys = new SortKeys();
int count = 0;
for (ICompletionProposal c : completions) {
count++;
if (maxCompletions > 0 && count>maxCompletions) {
list.setIsIncomplete(true);
break;
}
try {
items.add(adaptItem(doc, c, sortkeys));
} catch (Exception e) {
logger.error("error computing completion", e);
}
}
list.setItems(items);
return list;
})
.subscribeOn(Schedulers.elastic()); //!!! without this the mono will just be computed on the same thread that calls it.
}
return Mono.just(SimpleTextDocumentService.NO_COMPLETIONS);
}
private CompletionItem adaptItem(TextDocument doc, ICompletionProposal completion, SortKeys sortkeys) throws Exception {
CompletionItem item = new CompletionItem();
item.setLabel(completion.getLabel());
item.setKind(completion.getKind());
item.setSortText(sortkeys.next());
item.setFilterText(completion.getFilterText());
item.setDetail(completion.getDetail());
item.setDocumentation(toMarkdown(completion.getDocumentation()));
adaptEdits(item, doc, completion.getTextEdit());
return item;
}
private String toMarkdown(Renderable r) {
if (r!=null) {
return r.toMarkdown();
}
return null;
}
private void adaptEdits(CompletionItem item, TextDocument doc, DocumentEdits edits) throws Exception {
TextReplace replaceEdit = edits.asReplacement(doc);
if (replaceEdit==null) {
//The original edit does nothing.
item.setInsertText("");
} else {
TextDocument newDoc = doc.copy();
edits.apply(newDoc);
TextEdit vscodeEdit = new TextEdit();
vscodeEdit.setRange(doc.toRange(replaceEdit.start, replaceEdit.end-replaceEdit.start));
vscodeEdit.setNewText(vscodeIndentFix(doc, vscodeEdit.getRange().getStart(), replaceEdit.newText));
//TODO: cursor offset within newText? for now we assume its always at the end.
item.setTextEdit(vscodeEdit);
item.setInsertTextFormat(InsertTextFormat.Snippet);
}
}
private String vscodeIndentFix(TextDocument doc, Position start, String newText) {
//Vscode applies some magic indent to a multi-line edit text. We do everything ourself so we have adjust for the magic
// and do some kind of 'inverse magic' here.
int referenceLine = start.getLine();
int referenceLineIndent = doc.getLineIndentation(referenceLine);
int vscodeMagicIndent = Math.min(start.getCharacter(), referenceLineIndent);
return vscodeMagicIndent>0
? StringUtil.stripIndentation(vscodeMagicIndent, newText)
: newText;
}
@Override
public CompletableFuture<CompletionItem> resolveCompletion(CompletionItem unresolved) {
//TODO: item is pre-resoved so we don't do anything, but we really should somehow defer some work, such as
// for example computing docs and edits to resolve time.
//The tricky part is that we have to probably remember infos about the unresolved elements somehow so we can resolve later.
return Futures.of(unresolved);
}
}
|
package org.opentosca.iaengine.plugins.dockercompose.service.impl;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import org.opentosca.core.model.artifact.AbstractArtifact;
import org.opentosca.core.model.artifact.file.AbstractFile;
import org.opentosca.core.model.csar.id.CSARID;
import org.opentosca.iaengine.plugins.service.IIAEnginePluginService;
import org.opentosca.model.tosca.TImplementationArtifact;
import org.opentosca.model.tosca.TPropertyConstraint;
import org.opentosca.util.http.service.IHTTPService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.namespace.QName;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class IAEnginePluginDockerComposeServiceImpl implements IIAEnginePluginService {
private static final String TYPES = "{http://toscafy.github.io/artifacttypes}DockerComposeArtifact";
private static final String CAPABILITIES = "http:
private static final Logger LOG = LoggerFactory.getLogger(IAEnginePluginDockerComposeServiceImpl.class);
private static final Map<String, String> CONTEXT = new HashMap<String, String>();
private IHTTPService httpService;
@Override
public URI deployImplementationArtifact(CSARID csarId, QName artifactType, Document artifactContent,
Document properties, List<TPropertyConstraint> propertyConstraints, List<AbstractArtifact> artifacts,
List<String> requiredFeatures) {
/*
ArtifactProperties:
contextFile: 'context.tar.gz',
serviceName: 'mysql-mgmt-api',
containerPort: '3000',
endpointPath: '/',
endpointKind: 'soap'
AbstractFile:
String filePath = warFile.getPath();
String fileName = warFile.getName();
java.io.File file = warFile.getFile().toFile();
*/
String contextFile = getProperty(properties, "contextFile");
String serviceName = getProperty(properties, "serviceName");
String containerPort = getProperty(properties, "containerPort");
String endpointPath = getProperty(properties, "endpointPath");
String endpointKind = getProperty(properties, "endpointKind");
LOG.info("contextFile={} serviceName={} containerPort={} endpointPath={} endpointKind={}", contextFile, serviceName, containerPort, endpointPath, endpointKind);
String endpoint = null;
try {
String csarIdStr = normalizeCsarId(csarId);
AbstractFile context = getFile(artifacts, contextFile);
String contextFilePath = context.getPath();
//String contextFileName = context.getName();
//String contextPath = "/tmp/opentosca-docker-compose-" + csarIdStr + "-" + serviceName;
String contextPath = java.nio.file.Files.createTempDirectory("docker-compose-ia-").toString();
untar(contextFilePath, contextPath);
dcBuild(contextPath);
dcUp(contextPath);
String publicPort = dcPort(contextPath, serviceName, containerPort);
//String logs = dcLogs(contextPath);
endpoint = "http://localhost:" + publicPort + endpointPath;
CONTEXT.put(endpoint, contextPath);
append(ENDPOINTS_FILE, "{"
+ "\"contextPath\": \"" + contextPath + "\","
+ "\"endpoint\": \"" + endpoint + "\","
+ "\"publicPort\": \"" + publicPort + "\","
+ "\"containerPort\": \"" + containerPort + "\","
+ "\"serviceName\": \"" + serviceName + "\","
+ "\"endpointPath\": \"" + endpointPath + "\","
+ "\"endpointKind\": \"" + endpointKind + "\","
+ "\"csar\": \"" + csarIdStr + "\""
+ "}");
} catch (Exception e) {
LOG.error("Error deployImplementationArtifact", e);
}
return toUri(endpoint);
}
@Override
public boolean undeployImplementationArtifact(String iaName, QName nodeTypeImpl, CSARID csarId, URI endpointUri) {
try {
String endpoint = endpointUri.toString();
String contextPath = CONTEXT.get(endpoint);
dcDown(contextPath);
rmrf(contextPath);
CONTEXT.remove(endpoint);
} catch (Exception e) {
LOG.error("Error undeployImplementationArtifact", e);
return false;
}
return true;
}
private static AbstractFile getFile(List<AbstractArtifact> artifacts, String filename) {
if (artifacts != null && filename != null) {
for (AbstractArtifact artifact : artifacts) {
Set<AbstractFile> files = artifact.getFilesRecursively();
for (AbstractFile file : files) {
if (file.getName().toLowerCase().endsWith(filename.toLowerCase())) {
return file;
}
}
}
}
return null;
}
/*
private boolean isADeployableWar(AbstractFile file) {
if (file.getName().toLowerCase().endsWith(".war")) {
return true;
} else {
LOG.warn(
"Although the plugin-type and the IA-type are matching, the file {} can't be un-/deployed from this plugin.",
file.getName());
}
return false;
}
*/
private static String getProperty(Document properties, String propertyName) {
if (properties != null) {
NodeList list = properties.getFirstChild().getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node propertyNode = list.item(i);
if (hasProperty(propertyNode, propertyName)) {
String propertyValue = getNodeContent(propertyNode);
LOG.info("{} property found: {}", propertyName, propertyValue);
return propertyValue;
}
}
}
LOG.debug("{} property not found", propertyName);
return null;
}
private static boolean hasProperty(Node node, String propertyName) {
String localName = node.getLocalName();
if (localName != null) {
return localName.equals(propertyName);
}
return false;
}
private static String getNodeContent(Node node) {
return node.getTextContent().trim();
}
private static URI toUri(String endpoint) {
URI endpointURI = null;
if (endpoint != null) {
try {
endpointURI = new URI(endpoint);
} catch (Exception e) {
LOG.error("Exception occurred while creating endpoint URI: {}", endpoint, e);
}
}
return endpointURI;
}
private static String normalizeCsarId(CSARID id) {
if (id == null) return null;
else return id.toString().replaceAll("[^-a-zA-Z0-9]", "");
}
@Override
public List<String> getSupportedTypes() {
List<String> types = new ArrayList<String>();
for (String type : IAEnginePluginDockerComposeServiceImpl.TYPES.split("[,;]")) {
types.add(type.trim());
}
return types;
}
@Override
public List<String> getCapabilties() {
List<String> capabilities = new ArrayList<String>();
for (String capability : IAEnginePluginDockerComposeServiceImpl.CAPABILITIES.split("[,;]")) {
capabilities.add(capability.trim());
}
return capabilities;
}
// probably required for compatibility reasons
public void bindHTTPService(IHTTPService httpService) {
if (httpService != null) {
this.httpService = httpService;
LOG.debug("Register IHTTPService: {} registered", httpService.toString());
} else {
LOG.error("Register IHTTPService: supplied parameter is null");
}
}
// probably required for compatibility reasons
public void unbindHTTPService(IHTTPService httpService) {
this.httpService = null;
LOG.debug("Unregister IHTTPService: {} unregistered", httpService.toString());
}
/*
*
* Static helper functions
*
*/
private static final String DOCKER_COMPOSE_SCRIPT_URL = "https://github.com/docker/compose/releases/download/1.8.0/run.sh";
private static String DOCKER_COMPOSE = System.getenv("OPENTOSCA_DOCKER_COMPOSE_SCRIPT");
private static String LOG_FILE = System.getenv("OPENTOSCA_DOCKER_COMPOSE_LOG");
private static String ENDPOINTS_FILE = System.getenv("OPENTOSCA_ENDPOINTS_JSON");
static {
if (ENDPOINTS_FILE == null) ENDPOINTS_FILE = "/tmp/opentosca-docker-compose-endpoints.json";
if (DOCKER_COMPOSE == null) {
try {
DOCKER_COMPOSE = java.nio.file.Files.createTempDirectory("docker-compose-").toString() + "/run.sh";
fetchFile(DOCKER_COMPOSE_SCRIPT_URL, DOCKER_COMPOSE);
log("docker-compose is available: " + DOCKER_COMPOSE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void log(String message) {
try {
if (LOG_FILE != null) append(LOG_FILE, message);
//else System.out.println(message);
else LOG.info(message);
} catch (Exception e) {
//System.out.println(message);
LOG.info(message);
LOG.error("Error", e);
//e.printStackTrace();
}
}
private static void log(String[] cmd, String exitCode, String stdout, String stderr) {
String message = "Command " + cmd.toString() + " exit " + exitCode + ". stdout: " + stdout + ". stderr: " + stderr;
log(message);
}
private static void dcBuild(String contextPath) throws Exception {
String[] cmd = { "bash", DOCKER_COMPOSE, "build", "--force-rm" };
execCmd(cmd, contextPath);
}
private static void dcUp(String contextPath) throws Exception {
String[] cmd = { "bash", DOCKER_COMPOSE, "up", "-d", "--remove-orphans" };
execCmd(cmd, contextPath);
}
private static String dcLogs(String contextPath) throws Exception {
String[] cmd = { "bash", DOCKER_COMPOSE, "logs" };
String[] res = execCmd(cmd, contextPath);
String logs = res[1];
return logs;
}
private static String dcPort(String contextPath, String serviceName, String containerPort) throws Exception {
String[] cmd = { "bash", DOCKER_COMPOSE, "port", serviceName, containerPort };
String[] res = execCmd(cmd, contextPath);
try {
String port = res[1].split(":")[1];
return port;
} catch (Exception e) {
return null;
}
}
private static void dcDown(String contextPath) throws Exception {
String[] cmd = { "bash", DOCKER_COMPOSE, "down", "--rmi", "all", "-v", "--remove-orphans" };
execCmd(cmd, contextPath);
}
private static void untar(String filePath, String dirPath) throws Exception {
String[] cmd = { "tar", "-xvzf", filePath, "-C", dirPath };
execCmd(cmd);
}
private static void rmrf(String dirPath) throws Exception {
String[] cmd = { "rm", "-rf", dirPath };
execCmd(cmd);
}
private static void append(String filePath, String content) throws Exception {
String touchCmd[] = { "touch", filePath };
execCmd(touchCmd);
java.nio.file.Files.write(java.nio.file.Paths.get(filePath), (content + "\n").getBytes(), java.nio.file.StandardOpenOption.APPEND);
}
private static void fetchFile(String url, String filePath) throws Exception {
java.net.URL website = new java.net.URL(url);
java.nio.channels.ReadableByteChannel rbc = java.nio.channels.Channels.newChannel(website.openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(filePath);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
}
private static String[] execCmd(String[] cmd) throws Exception {
return execCmd(cmd, null, null);
}
private static String[] execCmd(String[] cmd, String cwd) throws Exception {
return execCmd(cmd, cwd, null);
}
private static String[] execCmd(String[] cmd, String cwd, String[] env) throws Exception {
java.io.File cwdObj = null;
if (cwd != null) cwdObj = new java.io.File(cwd);
Process proc = Runtime.getRuntime().exec(cmd, env, cwdObj);
java.io.InputStream stdoutStream = proc.getInputStream();
java.io.InputStream stderrStream = proc.getErrorStream();
java.util.Scanner stdoutScanner = new java.util.Scanner(stdoutStream).useDelimiter("\\A");
java.util.Scanner stderrScanner = new java.util.Scanner(stderrStream).useDelimiter("\\A");
String stdout = "";
if (stdoutScanner.hasNext()) stdout = stdoutScanner.next();
else stdout = "";
String stderr = "";
if (stderrScanner.hasNext()) stdout = stderrScanner.next();
else stderr = "";
int exitCode = proc.waitFor();
//String exitCode = Integer.toString(proc.waitFor());
//String exitCode = Integer.toString(proc.exitValue());
log(cmd, Integer.toString(exitCode), stdout.trim(), stderr.trim());
if (exitCode != 0) {
throw new Exception("Command " + cmd.toString() + " exit " + exitCode + ". stdout: " + stdout.trim() + ". stderr: " + stderr.trim());
}
String[] result = { Integer.toString(exitCode), stdout.trim(), stderr.trim() };
return result;
}
}
|
package de.uni_hildesheim.sse.easy_producer.instantiator.model.expressions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.common.VilException;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.Constants;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.IActualTypeProvider;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.IMetaOperation;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.IMetaType;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.ReflectionTypeDescriptor;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.TypeDescriptor;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.TypeHelper;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.TypeRegistry;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.configuration.EnumValue;
import de.uni_hildesheim.sse.easy_producer.instantiator.model.vilTypes.configuration.IvmlTypes;
import de.uni_hildesheim.sse.model.varModel.datatypes.IDatatype;
import de.uni_hildesheim.sse.utils.modelManagement.IModel;
/**
* Implements the type checking and automated type conversion mechanism in an abstracted form based on
* {@link IMetaType} and {@link IMetaOperation}. The search for matching operations is based on unnamed
* arguments. Named arguments are ignored here as they are handled differently.
* However, results may have to be casted.
*
* @author Holger Eichelberger
*/
public abstract class AbstractCallExpression extends Expression implements IArgumentProvider {
private static final ResolutionListener RESLIST = new ResolutionListener() {
@Override
public void resolved(VarModelIdentifierExpression ex) {
ex.markAsResolved();
}
};
private String name;
private String prefix;
protected AbstractCallExpression(String name, boolean unqualify) throws VilException {
this.name = name;
if (unqualify && null != name) {
int pos = name.lastIndexOf(Constants.QUALIFICATION_SEPARATOR);
if (pos > 0) {
this.prefix = name.substring(0, pos);
this.name = name.substring(pos + 2, name.length());
if (0 == this.name.length()) {
throw new VilException("illegal qualified name " + name, VilException.ID_INTERNAL);
}
}
}
}
/**
* Returns the name of the call.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Returns the name prefix.
*
* @return the prefix (or <b>null</b> if there is none)
*/
public String getPrefix() {
return prefix;
}
/**
* Returns the qualified name consisting of {@link #getPrefix()} (if present) and {@link #getName()}.
*
* @return the qualified name
*/
public String getQualifiedName() {
String result;
if (null == prefix) {
result = name;
} else {
result = prefix + Constants.QUALIFICATION_SEPARATOR + name;
}
return result;
}
/**
* Returns whether a given operation is an actual candidate for this
* call expression.
*
* @param op the operation to be compared
* @param name the name of the operation call to be resolved
* @param arguments the unnamed arguments
* @return <code>true</code> if <code>desc</code> is a candidate, <code>false</code> else
*/
protected static boolean isCandidate(IMetaOperation op, String name, CallArgument[] arguments) {
return null != op && null != arguments && op.getName().equals(name)
&& op.getParameterCount() == arguments.length;
}
/**
* Derives the assignable candidates from <code>operand</code>, i.e., operations which
* can be directly applied with identical parameters or (second step) with assignable
* parameters but without parameter conversion.
*
* @param operand the operand of the call to be resolved
* @param name the name of the operation call to be resolved
* @param arguments the (unnamed) arguments of the call
* @param allowAny allow AnyType as assignable parameter type (dynamic dispatch)
* @return the list of candidate operations
* @throws VilException in case of type resolution problems or in case of an ambiguous call specification
*/
private static List<IMetaOperation> assignableCandidates(IMetaType operand, String name, CallArgument[] arguments,
boolean allowAny) throws VilException {
List<IMetaOperation> result = new ArrayList<IMetaOperation>();
IMetaType[] argumentTypes = toTypeDescriptors(arguments);
for (int o = 0; o < operand.getOperationsCount(); o++) {
IMetaOperation desc = operand.getOperation(o);
if (isCandidate(desc, name, arguments)) {
boolean allEqual = true;
for (int p = 0; allEqual && p < arguments.length; p++) {
IMetaType pType = desc.getParameterType(p);
IMetaType aType = argumentTypes[p];
allEqual &= TypeRegistry.equals(pType, aType);
if (!allEqual) {
IMetaOperation funcOp = resolveResolvableOperation(operand, pType, aType,
arguments[p].getExpression(), RESLIST);
if (null != funcOp) {
arguments[p].resolveOperation((TypeDescriptor<?>) pType, funcOp);
allEqual = true;
}
}
}
if (allEqual) {
result.add(desc);
}
}
}
if (result.isEmpty()) {
int minAssignables = 0;
for (int o = 0; o < operand.getOperationsCount(); o++) {
IMetaOperation desc = operand.getOperation(o);
if (isCandidate(desc, name, arguments)) {
boolean allAssignable = true;
int aCount = 0;
final TypeDescriptor<?> any = TypeRegistry.anyType();
for (int p = 0; allAssignable && p < arguments.length; p++) {
IMetaType pType = desc.getParameterType(p);
IMetaType aType = argumentTypes[p];
if (pType.isAssignableFrom(aType) || (allowAny && any == pType)) {
if (pType != aType) {
aCount++;
}
} else {
allAssignable = false;
}
}
if (allAssignable) {
// consider only minimum number of implicit conversions -> dynamic dispatch
if (0 == minAssignables || aCount < minAssignables) {
result.clear();
minAssignables = aCount;
}
if (aCount == minAssignables) {
addAndPruneByType(result, desc, argumentTypes);
}
}
}
}
}
if (result.size() > 1) {
StringBuilder tmp = new StringBuilder();
for (IMetaOperation op : result) {
if (tmp.length() > 0) {
tmp.append(",");
}
tmp.append(op.getSignature());
}
throw new VilException(tmp + " are ambiguous" , VilException.ID_AMBIGUOUS);
}
return result;
}
/**
* Resolves a resolvable operation ("function pointer").
*
* @param operand the operand (must also be of type {@link IModel})
* @param pType the parameter type
* @param aType the argument type
* @param initExpression the initialization expression (shall be of <code>aType</code>)
* @param listener the listener to be informed about the variability model identifier resolution done
* @return the resolved operation if there is one, else <b>null</b>
* @throws VilException in case of type resolution problems
*/
public static IMetaOperation resolveResolvableOperation(IMetaType operand, IMetaType pType, IMetaType aType,
Expression initExpression, ResolutionListener listener) throws VilException {
IMetaOperation result = null;
if (TypeRegistry.resolvableOperationType().isAssignableFrom(pType)
&& IvmlTypes.ivmlElement().isAssignableFrom(aType) && operand instanceof IModel
&& initExpression instanceof VarModelIdentifierExpression) {
VarModelIdentifierExpression varModelIdEx = (VarModelIdentifierExpression) initExpression;
String opName = varModelIdEx.getIdentifier();
List<IMetaOperation> ops = assignableCandidates(operand, opName, toTypeDescriptors(pType, 1), false);
if (1 == ops.size()) { // return type may also select
IMetaOperation functionOp = ops.get(0);
TypeDescriptor<?> ret = pType.getGenericParameterType(pType.getGenericParameterCount() - 1);
if (ReflectionTypeDescriptor.VOID == ret
|| ret.isAssignableFrom(functionOp.getReturnType())) {
result = functionOp;
listener.resolved(varModelIdEx);
}
}
}
return result;
}
/**
* Turns the generic parameter types of <code>type</code> into an array.
*
* @param type the type to take the generic parameters from
* @param exclude the amount of parameters at the end of the generics to be excluded
* (operation return)
* @return the related type descriptors according sequence of generic types
*/
private static CallArgument[] toTypeDescriptors(IMetaType type, int exclude) {
CallArgument[] result = new CallArgument[Math.max(0, type.getGenericParameterCount() - exclude)];
for (int a = 0; a < result.length; a++) {
result[a] = new CallArgument(type.getGenericParameterType(a));
}
return result;
}
/**
* Turns the given call arguments to type descriptors.
*
* @param args the arguments to be turned into type descriptors
* @return the related type descriptors according to the input sequence
* @throws VilException in case that obtaining a type fails
*/
private static IMetaType[] toTypeDescriptors(CallArgument[] args) throws VilException {
IMetaType[] result = new IMetaType[args.length];
for (int a = 0; a < args.length; a++) {
result[a] = args[a].inferType();
}
return result;
}
/**
* Adds <code>toAdd</code> to <code>candidates</code> if it is considered as the best candidate with respect
* to the given <code>argTypes</code>. May prune existing candidates with lower ranking.
*
* @param candidates the candidates to modify
* @param toAdd the candidate to add if it is the best candidate
* @param argTypes the argument types
*/
private static void addAndPruneByType(List<IMetaOperation> candidates, IMetaOperation toAdd, IMetaType[] argTypes) {
if (!candidates.isEmpty()) {
int toAddDiff = calcTypeDiff(toAdd, argTypes);
// multiple conversion-equivalent candidates
for (int i = candidates.size() - 1; i >= 0; i
IMetaOperation op = candidates.get(i);
int opDiff = calcTypeDiff(op, argTypes);
if (toAddDiff < opDiff) {
candidates.remove(i);
}
}
}
if (candidates.isEmpty()) {
candidates.add(toAdd);
}
}
/**
* Calculates the differences in types between the given <code>operation</code> and the given argument types.
*
* @param operation the operation to compare
* @param argTypes the argument types to take into account
* @return the (pseudo) difference in number of types
*/
private static int calcTypeDiff(IMetaOperation operation, IMetaType[] argTypes) {
int diff = 0;
for (int p = 0; p < argTypes.length; p++) {
IMetaType pType = operation.getParameterType(p);
IMetaType aType = argTypes[p];
if (!TypeRegistry.equals(pType, aType)) {
diff += calcSuperDiffRec(aType, pType); // iterate over argType, consider generic parameter??
} // diff += 0
}
return diff;
}
/**
* Calculates the difference of super types from <code>reference</code> to <code>iter</code>
* over the types and their generic parameter.
*
* @param iter the node to follow the super type hierarchy
* @param reference the node to search for
* @return the difference if found, <code>0</code> if equal, a value of at least <code>100</code> if not found
* (shall not occur)
*/
private static int calcSuperDiffRec(IMetaType iter, IMetaType reference) {
int diff = calcSuperDiff(iter, reference); // iterate over argType, consider generic parameter??
for (int p = 0; p < iter.getGenericParameterCount(); p++) {
diff += calcSuperDiffRec(iter.getGenericParameterType(p), reference.getGenericParameterType(p));
}
return diff;
}
/**
* Calculates the difference of super types from <code>reference</code> to <code>iter</code>.
*
* @param iter the node to follow the super type hierarchy
* @param reference the node to search for
* @return the difference if found, <code>0</code> if equal, <code>100</code> if not found (shall not occur)
*/
private static int calcSuperDiff(IMetaType iter, IMetaType reference) {
int diff = 0;
while (null != iter && !TypeRegistry.equals(iter, reference)) {
diff++;
iter = iter.getSuperType();
}
if (null == iter) {
diff = 100; // not found, strange, higher than a typical hierarchy
}
return diff;
}
/**
* Stores an operation as well as the required type conversion operations.
*
* @author Holger Eichelberger
*/
private static class ConvertibleOperation {
private IMetaOperation operation;
private IMetaOperation[] conversions; // same length as parameter!
/**
* Creates a convertible operation instance describing the operation as well as
* the required conversions per parameter.
*
* @param operation the candidate operation resolving this call expression
* @param conversions the conversion operations (may contain <b>null</b> values
* if a conversion for a specific parameter is not required)
*/
ConvertibleOperation(IMetaOperation operation, IMetaOperation[] conversions) {
this.operation = operation;
this.conversions = conversions;
}
/**
* Returns the conversions core to compare similar canidates.
*
* @param arguments the actual arguments
* @return the number of conversions
* @throws VilException in case that types cannot be inferred
*/
public int getScore(CallArgument[] arguments) throws VilException {
int score = 0;
final int step = operation.getParameterCount();
for (int c = 0; c < conversions.length; c++) {
IMetaType pType = operation.getParameterType(c);
if (null == conversions[c]) {
IMetaType aType = arguments[c].inferType();
if (pType != aType) {
score += 1; // implicit conversion
}
} else { // score += 0
IMetaType cType = conversions[c].getReturnType();
if (pType == cType) {
score += step; // explicit conversion
} else {
score += step * step; // dynamic dispatch, defer - decide at runtime
}
}
}
return score;
}
}
/**
* Derives the convertible candidates from <code>operand</code>, i.e., operations which
* can be applied including parameter conversion.
*
* @param operand the operand of the call to be resolved
* @param name the name of the operation call to be resolved
* @param arguments the (unnamed) arguments of the call
* @return the list of candidate operations including their required conversions
* @throws VilException in case of type resolution problems or in case of an ambiguous call specification
*/
private static List<ConvertibleOperation> convertibleCandidates(IMetaType operand, String name,
CallArgument[] arguments) throws VilException {
List<ConvertibleOperation> result = new ArrayList<ConvertibleOperation>();
for (int o = 0; o < operand.getOperationsCount(); o++) {
IMetaOperation desc = operand.getOperation(o);
if (isCandidate(desc, name, arguments)) {
int conversionCount = 0;
IMetaOperation[] conversionOps = new IMetaOperation[arguments.length];
boolean allParamOk = true;
for (int p = 0; allParamOk && p < arguments.length; p++) {
IMetaType paramType = desc.getParameterType(p);
IMetaType argType = arguments[p].inferType();
if (!paramType.isAssignableFrom(argType)) {
conversionOps[p] = TypeHelper.findConversion(argType, paramType);
if (null != conversionOps[p]) {
conversionCount++;
}
allParamOk = (null != conversionOps[p]);
}
}
if (allParamOk && conversionCount > 0) {
assert null != conversionOps && conversionOps.length == arguments.length;
result.add(new ConvertibleOperation(desc, conversionOps));
conversionOps = new IMetaOperation[arguments.length];
} else {
Arrays.fill(conversionOps, null);
}
}
}
if (result.size() > 1) {
result = selectAmongMultipleCandidates(result, arguments);
if (result.size() > 1) {
StringBuilder tmp = new StringBuilder();
for (ConvertibleOperation op : result) {
if (tmp.length() > 0) {
tmp.append(",");
}
tmp.append(op.operation.getSignature());
}
throw new VilException(tmp + " are ambiguous", VilException.ID_AMBIGUOUS);
}
}
return result;
}
/**
* Selects among multiple convertible candidates.
*
* @param candidates the candidates
* @param arguments the actual arguments
* @return <code>candidates</code> or a list with exactly one candidate
* @throws VilException in case that types cannot be inferred
*/
private static List<ConvertibleOperation> selectAmongMultipleCandidates(List<ConvertibleOperation> candidates,
CallArgument[] arguments) throws VilException {
ConvertibleOperation op = null;
int opCount = 0;
int minScore = Integer.MAX_VALUE;
for (int c = 0; c < candidates.size(); c++) {
ConvertibleOperation tmp = candidates.get(c);
int score = tmp.getScore(arguments);
if (null == op || score < minScore) {
op = tmp;
minScore = score;
opCount = 1;
} else if (minScore == score) {
opCount++;
}
}
if (opCount == 1) {
candidates.clear();
candidates.add(op);
}
return candidates;
}
/**
* Resolves the given operation on <code>operand</code>.
*
* @param operand the operand, i.e., the type to be searched for operations
* @param name the name of the operation to be resolved
* @param arguments the (named) arguments of the call
* @return the resolved operation
* @throws VilException in case that no resolution can be found for various (typically type compliance)
* reasons
*/
public static IMetaOperation resolveOperation(IMetaType operand, String name, CallArgument[] arguments)
throws VilException {
IMetaOperation op = null;
try {
op = resolveOperation(operand, name, arguments, true, false);
} catch (VilException e) {
// operand is fixed... let's try for a conversion
try {
if (null != arguments && arguments.length > 0 && !(operand instanceof IModel)) {
// model is resolved before - consider only matching there as otherwise arbitrary operations on
// string may shadow artifact operations; this conversion is last resort on artifact level
IMetaType opType = arguments[0].inferType();
if (2 == arguments.length) { // it could be an operator and the first could be a decision variable
op = tryOpConversionToSecond(opType, name, arguments);
}
if (null == op) { // last resort... most types can be converted to string and it is ok
IMetaType stringType = TypeRegistry.stringType();
IMetaOperation convOp = TypeHelper.findConversion(opType, stringType); // includes Any->String
if (null != convOp) {
op = resolveOperation(stringType, name, arguments, true, false);
if (opType == TypeRegistry.anyType()) {
arguments[0].insertConversion(convOp);
// ANY is assignable by itself, other conversion
// will be added on the way but for ANY the conversion
// is still needed
}
} else {
throw e;
}
}
} else {
throw e;
}
} catch (VilException e1) {
throw e;
}
}
return op;
}
/**
* Resolves the given operation on <code>operand</code>, but allows checking the first field for a meta type
* (e.g., DecisionVariable instead of the actual field type).
*
* @param operand the operand, i.e., the type to be searched for operations
* @param checkMetaForFirstArgField whether the check for the meta type shall be enabled on the first field
* (replacing operand) or not. In case that this is enabled and there is a compliant operation for meta type,
* the found operation is returned.
* @param name the name of the operation to be resolved
* @param arguments the (named) arguments of the call
* @return the resolved operation
* @throws VilException in case that no resolution can be found for various (typically type compliance)
* reasons
*/
public static IMetaOperation resolveOperation(IMetaType operand, boolean checkMetaForFirstArgField, String name,
CallArgument[] arguments) throws VilException {
IMetaOperation op = null;
if (arguments.length > 0 && checkMetaForFirstArgField
&& arguments[0].getExpression() instanceof FieldAccessExpression) {
FieldAccessExpression fae = (FieldAccessExpression) arguments[0].getExpression();
TypeDescriptor<?> fOperand = fae.getField().getMetaType();
if (null != fOperand) {
CallArgument[] args = new CallArgument[arguments.length];
args[0] = new CallArgument(fOperand);
for (int a = 1; a < arguments.length; a++) {
args[a] = arguments[a];
}
try {
try {
op = resolveOperation(fOperand, name, args);
} catch (VilException e) {
if (operand instanceof IModel) {
op = resolveOperation(operand, name, args);
}
}
if (null != op && null == args[0].getExpression() /*&& op instanceof OperationDescriptor*/) {
fae.enableMetaAccess();
} else {
op = null; // args[0] indicates that a conversion was inserted; no conversions here!
}
} catch (VilException e) {
// ignore as this was just a trial
}
}
}
if (null == op) {
op = resolveOperation(operand, name, arguments);
}
return op;
}
/**
* Tries to convert the operand to the second argument type and resolves it.
*
* @param opType the operand type
* @param name the name of the operation
* @param arguments the actual call arguments
* @return the operation if resolved, <b>null</b> else
* @throws VilException in case of type resolution problems
*/
private static IMetaOperation tryOpConversionToSecond(IMetaType opType, String name, CallArgument[] arguments)
throws VilException {
IMetaOperation op = null;
IMetaType sndArgType = arguments[1].inferType();
IMetaOperation convOp = TypeHelper.findConversion(opType, sndArgType);
if (null != convOp) {
try {
// may already insert conversion
op = resolveOperation(sndArgType, name, arguments, true, false);
// don't accidentally insert conversion twice
if (!op.getReturnType().isAssignableFrom(sndArgType)) {
arguments[0].insertConversion(convOp);
}
} catch (VilException e1) {
// ok, let's try strings
}
}
return op;
}
/**
* Actually aims at resolving the operation.
*
* @param operand the operand, i.e., the type to be searched for operations
* @param name the name of the operation to be resolved
* @param arguments the (named) arguments of the call
* @param allowConversion whether conversion shall be allowed
* @param allowAny allow AnyType as assignable parameter type (dynamic dispatch)
* @return the resolved operation
* @throws VilException in case that no resolution can be found for various (typically type compliance)
* reasons
*/
private static IMetaOperation resolveOperation(IMetaType operand, String name, CallArgument[] arguments,
boolean allowConversion, boolean allowAny) throws VilException {
IMetaOperation resolved = null;
// check for direct applicable candidates
CallArgument[] unnamed = CallArgument.getUnnamedArguments(arguments);
List<IMetaOperation> candidates = assignableCandidates(operand, name, unnamed, allowAny);
if (1 == candidates.size()) {
resolved = candidates.get(0);
} else if (allowConversion) {
// check for candidates by conversion
List<ConvertibleOperation> convertible = convertibleCandidates(operand, name, unnamed);
if (0 == convertible.size() && null != operand.getBaseType()) {
// also operand operations must be considered
convertible = convertibleCandidates(operand.getBaseType(), name, unnamed);
}
if (1 == convertible.size()) {
ConvertibleOperation found = convertible.get(0);
// replace parameter expression by transparent call expression to conversion call
resolved = found.operation;
for (int i = 0; i < unnamed.length; i++) { // same length as conversions
IMetaOperation conversionOp = found.conversions[i];
if (null != conversionOp) {
unnamed[i].insertConversion(conversionOp);
}
}
}
}
if (null == resolved) {
// try to go for a placeholder, works only on placeholder types
resolved = operand.addPlaceholderOperation(name, unnamed.length, arguments.length - unnamed.length > 0);
}
if (null == resolved) {
throw new VilException("cannot call operation " + getSignature(name, arguments),
VilException.ID_CANNOT_RESOLVE);
} else {
if (unnamed.length != arguments.length && !resolved.acceptsNamedParameters()) {
// difference indicates named parameter
// use java signature as it is the matching signature!
throw new VilException(resolved.getJavaSignature()
+ " does not accept (optional) named parameters", VilException.ID_CANNOT_RESOLVE);
}
}
return resolved;
}
/**
* Returns a java-like signature for the specified operation.
*
* @param name the name of the operation
* @param arguments the (named) arguments of the call
* @return the signature
*/
public static final String getSignature(String name, CallArgument[] arguments) {
StringBuilder signature = new StringBuilder(name);
signature.append("(");
for (int a = 0; a < arguments.length; a++) {
CallArgument arg = arguments[a];
if (arg.hasName()) {
signature.append(arg.getName());
signature.append(" = ");
}
try {
signature.append(arguments[a].inferType().getName());
} catch (VilException e) {
signature.append("<unknown>");
}
if (a < arguments.length - 1) {
signature.append(",");
}
}
signature.append(")");
return signature.toString();
}
/**
* Determines the actual type of <code>object</code>. Considers {@link IMetaType#isActualTypeOf(IMetaType)}.
*
* @param type the type of <code>object</code>
* @param object the object to determine the type for
* @param registry the responsible type registry
* @return <code>type</code> or the actual type of <code>object</code>
*/
private static IMetaType determineActualType(IMetaType type, Object object, TypeRegistry registry) {
IMetaType result = type;
if (object instanceof IActualTypeProvider) {
IDatatype actualType = ((IActualTypeProvider) object).determineActualTypeName();
if (null != actualType) {
IMetaType tmpType = registry.getType(actualType);
if (null != tmpType && tmpType.isActualTypeOf(type)) {
result = tmpType;
}
}
}
return result;
}
/**
* Returns the VIL type for an enum value.
*
* @param registry the type registry
* @param val the enum value
* @return the enum type or <b>null</b>
*/
private static IMetaType getEnumType(TypeRegistry registry, EnumValue val) {
IMetaType tmp = registry.getType(val.getDatatype());
if (null == tmp) {
tmp = registry.getType(EnumValue.class);
}
return tmp;
}
/**
* Aims at re-resolving the given operation according to the dynamic types of <code>args</code>.
* Argument-less operations are not dispatched dynamically.
*
* @param <O> the actual type of operation
*
* @param operation the operation to be considered
* @param args the arguments
* @param cls the type of operation
* @param registry the (local) type registry
* @return <code>operation</code> or the one determined dynamically
*/
public static <O extends IMetaOperation> O dynamicDispatch(O operation, Object[] args, Class<O> cls,
TypeRegistry registry) {
O result = operation;
int offset = 0;
if (operation.isFirstParameterOperand()) {
offset = 1;
}
if (args.length >= offset) { // do only try to dispatch if there is at least one parameter
IMetaType operand = operation.getDeclaringType();
if (null != operand && operand.enableDynamicDispatch()) {
CallArgument[] types = new CallArgument[args.length - offset];
boolean allSame = true;
boolean failure = false;
int a = 0;
while (!failure && a < operation.getParameterCount()) {
// consider just parameter not named arguments
if (null == args[a]) {
if (a - offset < 0) {
failure = true;
} else {
types[a - offset] = new CallArgument((TypeDescriptor<?>) operation.getParameterType(a));
a++;
}
} else {
IMetaType tmp;
if (args[a] instanceof EnumValue) {
tmp = getEnumType(registry, (EnumValue) args[a]);
} else {
tmp = registry.obtainTypeDescriptor(args[a]);
}
tmp = determineActualType(tmp, args[a], registry);
if (null == tmp) {
tmp = operation.getParameterType(a);
} else {
allSame &= tmp == operation.getParameterType(a);
}
if (0 == a && offset > 0) {
operand = tmp;
} else {
if (tmp instanceof TypeDescriptor) {
types[a - offset] = new CallArgument((TypeDescriptor<?>) tmp); // ugly
} else {
failure = true;
}
}
a++;
}
}
// fill named/optional
while (!failure && a < types.length) {
types[a] = new CallArgument("name", null);
a++;
}
if (!allSame && !failure) {
try {
// no additional conversion while dynamic dispatch
IMetaOperation op = resolveOperation(operand, operation.getName(), types, false, true);
if (cls.isInstance(op)) {
result = cls.cast(op);
}
} catch (VilException e) {
// this may happen but then the passed in operation is ok and no other was found
}
}
}
}
return result;
}
/**
* Returns whether the specified operation is a placeholder and cannot be executed,
* i.e., the operation itself is a placeholder or a placeholder type is used in its
* signature.
*
* @param operation the operation to be tested
* @return <code>true</code> if <code>operation</code> is a placeholder, <code>false</code> else
*/
protected static boolean isPlaceholder(IMetaOperation operation) {
boolean isPlaceholder;
if (null == operation) {
isPlaceholder = true;
} else {
isPlaceholder = operation.isPlaceholder();
if (!isPlaceholder) {
isPlaceholder = operation.getReturnType().isPlaceholder();
for (int p = 0; !isPlaceholder && p < operation.getParameterCount(); p++) {
isPlaceholder = operation.getParameterType(p).isPlaceholder();
}
}
}
return isPlaceholder;
}
/**
* Returns the VIL signature of the specified <code>operation</code>.
*
* @param operation the operation to return the VIL signature for
* @return the VIL signature (for messages, warnings, errors, etc.)
*/
protected String getVilSignature(IMetaOperation operation) {
String result;
if (null == operation) {
result = name + "(?)";
} else {
result = operation.getSignature();
}
return result;
}
/**
* Returns whether this operation is a placeholder, i.e., either the resolved operation is
* a {@link IMetaOperation#isPlaceholder() placeholder}, its signature or its return
* type does contain a {@link IMetaType#isPlaceholder() placeholder type}.
*
* @return <code>true</code> if this operation is a placeholder and cannot be executed, <code>false</code> else
*/
public abstract boolean isPlaceholder();
/**
* Returns the VIL signature of the resolved operation.
*
* @return the VIL signature
*/
public abstract String getVilSignature();
/**
* Returns the number of arguments.
*
* @return the number of arguments
*/
public abstract int getArgumentsCount();
/**
* Returns the specified argument.
*
* @param index the 0-based index of the argument to return
* @return the argument
* @throws IndexOutOfBoundsException in case that
* <code>index < 0 || index >={@link #getArgumentsCount()}</code>
*/
public abstract CallArgument getArgument(int index);
}
|
package se.z_app.zmote.gui;
import java.util.ArrayList;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
/**
* This class extends the functionality of the HorizontalScrollView
* and create a new type of view which is able to snap the screen on
* the items you pass it in an ArrayList
* @author Francisco Valladares
*/
public class SnapHorizontalScrollView extends HorizontalScrollView {
private static final int SWIPE_MIN_DISTANCE = 5;
private static final int SWIPE_THRESHOLD_VELOCITY = 300;
private ArrayList mItems = null;
private GestureDetector mGestureDetector;
private int mActiveFeature = 0;
/**
* Same as default constructor for HorizontalScrollView with same parameters
* @param context
* @param attrs
* @param defStyle
*/
public SnapHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Same as default constructor for HorizontalScrollView with same parameters
* @param context
* @param attrs
*/
public SnapHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Same as default constructor for HorizontalScrollView with same parameters
* @param context
*/
public SnapHorizontalScrollView(Context context) {
super(context);
}
/**
* Inserts the items in the scroll view
* @param items list of items to insert
*/
public void setFeatureItems(ArrayList items){
LinearLayout internalWrapper = new LinearLayout(getContext()); // Main container for the items
internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
addView(internalWrapper);
this.mItems = items;
for(int i = 0; i< items.size();i++){
// Adding the items to the container
internalWrapper.addView((View) mItems.get(i));
}
// Now we set the listener to make it snap
setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//If the user swipes
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
int scrollX = getScrollX();
int featureWidth = v.getMeasuredWidth();
mActiveFeature = ((scrollX + (featureWidth/2))/featureWidth);
int scrollTo = mActiveFeature*featureWidth;
smoothScrollTo(scrollTo, 0);
return true;
}
else{
return false;
}
}
});
mGestureDetector = new GestureDetector(new MyGestureDetector());
}
/**
* Custom version of SimpleOnGestureListener
* @author Fransisco Valladares
*/
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
//right to left
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature < (mItems.size() - 1))? mActiveFeature + 1:mItems.size() -1;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
//left to right
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature > 0)? mActiveFeature - 1:0;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
} catch (Exception e) {
Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
}
return false;
}
}
}
|
package es.eurohelp.ldts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class LodTest {
LinkedDataRequestBean requestBean;
static List<LinkedDataRequestBean> tests = new ArrayList<LinkedDataRequestBean>();
@Test
public final void GETSPARQLHTML200 () {
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "sparql";
String name = "GETSPARQLHTML200";
String comment = "Ir directo a formulario SPARQL";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertEquals(requestBean.getStatus(), 200);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceHTMLPageNoRedirect303(){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GETNO303.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/asesor-de-la-secretaria-general-de-presidencia-aldekoa-de-la-torre-jon-andoni-lehendakaritza-lehendakaritza-2016-06-22";
String name = "GETResourceHTMLPageNoRedirect303";
String comment = "Recurso con pagina bonita, pero sin seguir el 303";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
System.out.println(requestBean.getLocation());
assertTrue(requestBean.getLocation().contains("/page/"));
assertEquals(requestBean.getStatus(), 303);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceHTMLPage(){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/asesor-de-la-secretaria-general-de-presidencia-aldekoa-de-la-torre-jon-andoni-lehendakaritza-lehendakaritza-2016-06-22";
String name = "GETResourceHTMLPage";
String comment = "Recurso con pagina bonita que no existe todavia";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
// System.out.println(requestBean.getLocation());
// System.out.println(requestBean.getResponseString());
assertTrue(requestBean.getResponseString().contains("<span>Lehendakaritza</span>"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceHTMLDocNoRedirect303(){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GETNO303.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "id/medio-ambiente/calidad-del-aire/elemento/ICAEstacion-2017-01-26";
// String pathUri = "id/medio-ambiente/calidad-del-aire/elemento/CO-2017-01-02";
// String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceHTMLDocNoRedirect303";
String comment = "Recurso con pagina fea, pero sin seguir 303";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getLocation().contains("/doc/es/"));
assertEquals(requestBean.getStatus(), 303);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceHTMLDoc(){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "id/medio-ambiente/calidad-del-aire/elemento/ICAEstacion-2017-01-26";
// String pathUri = "id/medio-ambiente/calidad-del-aire/elemento/CO-2017-01-02";
// String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceHTMLDoc";
String comment = "Recurso con pagina fea";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains("ICAEstacion</a>"));
// assertTrue(requestBean.getResponseString().contains("<h1>CO-2017-01-02</h1>"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceDirectlyDoc(){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "doc/es/medio-ambiente/calidad-del-aire/elemento/CO-2017-01-02";
// String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceDirectlyDoc";
String comment = "Recurso con pagina fea, ir directamente a pagina /doc sin pasar por /id";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertEquals(requestBean.getStatus(), 200);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceRDFXMLContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.RDFXML.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceRDFXMLContent";
String comment = "Obtener recurso en RDF/XML, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<ContractEconomicConditions xmlns=\"http://contsem.unizar.es/def/sector-publico/pproc
+ "rdf:datatype=\"http://www.w3.org/2001/XMLSchema#long\">3670496</ContractEconomicConditions>"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceDirectlyDataRDFXMLContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.RDFXML.mimetypevalue();
String pathUri = "data/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceDirectlyDataRDFXMLContent";
String comment = "Obtener recurso en RDF/XML directamente de /data, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<ContractEconomicConditions xmlns=\"http://contsem.unizar.es/def/sector-publico/pproc
+ "rdf:datatype=\"http://www.w3.org/2001/XMLSchema#long\">3670496</ContractEconomicConditions>"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceDirectlyDataTTLContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.Turtle.mimetypevalue();
String pathUri = "data/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceDirectlyDataTTLContent";
String comment = "Obtener recurso en TTL directamente de /data, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<http://contsem.unizar.es/def/sector-publico/pproc#formalizedDate> \"2000-03-31\"^^xsd:date ;"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceDirectlyDataJSONLDContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.JSONLD.mimetypevalue();
String pathUri = "data/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceDirectlyDataJSONLDContent";
String comment = "Obtener recurso en JSONLD directamente de /data, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"\"@value\" : \"10.0\""));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceDirectlyDataRDFXMLContentHTMLHeader (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "data/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09.rdf";
String name = "GETResourceDirectlyDataRDFXMLContentHTMLHeader";
String comment = "Obtener recurso en RDF/XML (por extension, no cabecera, cabecera HTML) directamente de /data, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<occupation xmlns=\"http://dbpedia.org/ontology/\" xml:lang=\"es\">jefe grupo inspector pesca</occupation>"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceDirectlyDataTTLContentHTMLHeader (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "data/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09.ttl";
String name = "GETResourceDirectlyDataTTLContentHTMLHeader";
String comment = "Obtener recurso en TTL (por extension, no cabecera, cabecera HTML) directamente de /data, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<http://contsem.unizar.es/def/sector-publico/pproc#formalizedDate> \"2000-03-31\"^^xsd:date ;"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceDirectlyDataJSONLDContentHTMLHeader (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "data/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09.jsonld";
String name = "GETResourceDirectlyDataJSONLDContentHTMLHeader";
String comment = "Obtener recurso en JSON-LD (por extension, no cabecera, cabecera HTML) directamente de /data, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"\"@value\" : \"2000-03-31\""));
} catch (IOException e) {
e.printStackTrace();
}
}
// Si la respuesta contiene lo que buscamos, ya implica una respuesta 200, luego este test es redundante
// @Test
// public final void GETResourceRDFXML200 (){
// try {
// String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
// String method = Methodtype.GET.methodtypevalue();
// String accept = MIMEtype.RDFXML.mimetypevalue();
// String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
// String name = "GETResourceRDFXML200";
// Map<String, String> parameters = new HashMap<String, String>();
// requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
// HttpManager.getInstance().doRequest(requestBean);
// assertEquals(requestBean.getStatus(), 200);
// } catch (IOException e) {
// e.printStackTrace();
@Test
public final void GETResourceJSONLDContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.JSONLD.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceJSONLDContent";
String comment = "Obtener recurso en JSON-LD, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains("\"@value\" : \"jefe grupo inspector pesca\""));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceN3Content (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.N3.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceN3Content";
String comment = "Obtener recurso en N3, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<http://contsem.unizar.es/def/sector-publico/pproc#managingDepartment> "
+ "<http://es.euskadi.eus/id/sector-publico/departamento/desarrollo-economico-e-infraestructuras> ;"));
} catch (IOException e) {
e.printStackTrace();
}
}
// @Test
// public final void GETResourceNQuadsContent (){
// try {
// String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
// String method = Methodtype.GET.methodtypevalue();
// String accept = MIMEtype.NQuads.mimetypevalue();
// String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
// String name = "GETResourceNQuadsContent";
// String comment = "Obtener recurso en NQuads, parsear contenido";
// Map<String, String> parameters = new HashMap<String, String>();
// requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
// HttpManager.getInstance().doRequest(requestBean);
// assertTrue(requestBean.getResponseString().contains(
// } catch (IOException e) {
// e.printStackTrace();
@Test
public final void GETResourceNTriplesContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.NTriples.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceNTriplesContent";
String comment = "Obtener recurso en NTriples, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<http://es.euskadi.eus/id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09> <http://www.w3.org/1999/02/22-rdf-syntax-ns
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceRDFJSON200 (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.RDFJSON.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceRDFJSON200";
String comment = "Obtener recurso en RDF/JSON, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"\"value\" : \"http://es.euskadi.eus/id/sector-publico/departamento/desarrollo-economico-e-infraestructuras\","));
} catch (IOException e) {
e.printStackTrace();
}
}
// @Test
// public final void GETResourceTriGContent (){
// try {
// String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
// String method = Methodtype.GET.methodtypevalue();
// String accept = MIMEtype.TriG.mimetypevalue();
// String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
// String name = "GETResourceTriGContent";
// String comment = "Obtener recurso en TriG, parsear contenido";
// Map<String, String> parameters = new HashMap<String, String>();
// requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
// HttpManager.getInstance().doRequest(requestBean);
// assertTrue(requestBean.getResponseString().contains(
// "GETResourceTriGContent Response no genera Trig, si no RDF/XML"));
// } catch (IOException e) {
// e.printStackTrace();
@Test
public final void GETResourceTriXContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.TriX.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceTriXContent";
String comment = "Obtener recurso en TriX, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<uri>http://dbpedia.org/ontology/occupation</uri>"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETResourceTurtleContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.Turtle.mimetypevalue();
String pathUri = "id/sector-publico/puestos-trabajo/contrato/1-gobierno-vasco-donostia-easo-10-3024.0-2016-05-09";
String name = "GETResourceTurtleContent";
String comment = "Obtener recurso en TTL, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<http://dbpedia.org/ontology/occupation> \"jefe grupo inspector pesca\"@es ;"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETClassRDFXMLContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.RDFXML.mimetypevalue();
String pathUri = "def/euskadipedia/Hotel";
String name = "GETClassRDFXMLContent";
String comment = "Obtener clase en RDF/XML, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"<owl:ObjectProperty rdf:about=\"http://euskadi.eus/def/euskadipedia#inHistoricTerritory\">"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETClassHTML200 (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "def/euskadipedia/Hotel";
String name = "GETClassHTML200";
String comment = "Obtener clase en HTML, sin parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertEquals(requestBean.getStatus(), 200);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETClassHTMLAnchorContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "def/euskadipedia.html#Hotel";
String name = "GETClassHTML200";
String comment = "Obtener clase en HTML con ancla, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertEquals(requestBean.getStatus(), 200);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETPropertyRDFXMLContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.RDFXML.mimetypevalue();
String pathUri = "def/euskadipedia/precio";
String name = "GETPropertyRDFXMLContent";
String comment = "Obtener propiedad en RDF/XML, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"</owl:Class>"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETPropertyHTML200 (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "def/euskadipedia/precio";
String name = "GETPropertyHTML200";
String comment = "Obtener propiedad en HTML, sin parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertEquals(requestBean.getStatus(), 200);
} catch (IOException e) {
e.printStackTrace();
}
}
// @Test
// public final void GETOntologyHTML200 (){
// try {
// String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
// String method = Methodtype.GET.methodtypevalue();
// String accept = MIMEtype.HTML.mimetypevalue();
// String pathUri = "def/turismo/alojamiento"; // Segun la NTI
// //String pathUri = "def/Euskadipedia"; // mas realista?
// String name = "GETOntologyHTML200";
// Map<String, String> parameters = new HashMap<String, String>();
// requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
// HttpManager.getInstance().doRequest(requestBean);
// assertEquals(requestBean.getStatus(), 200);
// } catch (IOException e) {
// e.printStackTrace();
@Test
public final void GETOntologyHTMLContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
// String pathUri = "def/turismo/alojamiento"; // Segun la NTI
String pathUri = "def/euskadipedia"; // mas realista?
String name = "GETOntologyHTMLContent";
String comment = "Obtener ontologia en HTML, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains("http://euskadi.eus/def/euskadipedia/0.0.1"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETOntologyHTMLContentFileExtensionHTML (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
// String pathUri = "def/turismo/alojamiento"; // Segun la NTI
String pathUri = "def/euskadipedia.html"; // mas realista?
String name = "GETOntologyHTMLContentFileExtensionHTML";
String comment = "Obtener ontologia en HTML con .html, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains("<a name=\"http://euskadi.eus/def/euskadipedia#Hotel\"></a>"));
} catch (IOException e) {
e.printStackTrace();
}
}
// @Test
// public final void GETOntologyRDFXML200 (){
// try {
// String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
// String method = Methodtype.GET.methodtypevalue();
// String accept = MIMEtype.RDFXML.mimetypevalue();
// String pathUri = "def/turismo/alojamiento"; // Segun la NTI
// //String pathUri = "def/Euskadipedia"; // mas realista?
// String name = "GETOntologyRDFXML200";
// Map<String, String> parameters = new HashMap<String, String>();
// requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
// HttpManager.getInstance().doRequest(requestBean);
// assertEquals(requestBean.getStatus(), 200);
// } catch (IOException e) {
// e.printStackTrace();
@Test
public final void GETOntologyRDFXMLContentHTMLHeader (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.HTML.mimetypevalue();
String pathUri = "def/euskadipedia.owl"; // Segun la NTI
//String pathUri = "def/Euskadipedia"; // mas realista?
String name = "GETOntologyRDFXMLContentHTMLHeader";
String comment = "Obtener ontologia en OWL (por extension, no cabecera, cabecera HTML), parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains("<owl:ObjectProperty rdf:about=\"http://euskadi.eus/def/euskadipedia#inHistoricTerritory\">"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETOntologyRDFXMLContentFileExtensionOWL (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.RDFXML.mimetypevalue();
// String pathUri = "def/turismo/alojamiento"; // Segun la NTI
String pathUri = "def/euskadipedia.owl"; // mas realista?
String name = "GETOntologyRDFXMLContentFileExtensionOWL ";
String comment = "Obtener ontologia en RDF/XML con .owl, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains("<owl:Ontology rdf:about=\"http://euskadi.eus/def/euskadipedia\">"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void GETOntologyRDFXMLContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.GET.methodtypevalue();
String accept = MIMEtype.RDFXML.mimetypevalue();
// String accept = MIMEtype.HTML.mimetypevalue();
// String pathUri = "def/turismo/alojamiento"; // Segun la NTI
String pathUri = "def/euskadipedia"; // mas realista?
String name = "GETOntologyRDFXMLContent";
String comment = "Obtener ontologia en RDF/XML, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains("<owl:Ontology rdf:about=\"http://euskadi.eus/def/euskadipedia\">"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void SPARQLPOSTNamedGraphsMetadataCSVContent (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.POST.methodtypevalue();
String accept = MIMEtype.CSV.mimetypevalue();
String pathUri = "sparql";
String name = "SPARQLPOSTNamedGraphsMetadataCSVContent";
String comment = "Consulta sobre datos y metadatos, parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("query",
"SELECT DISTINCT ?a ?b WHERE { ?a ?b ?g GRAPH ?g {?sub ?pred ?obj}}");
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertTrue(requestBean.getResponseString().contains(
"http://es.euskadi.eus/distribution/calidad-aire-en-euskadi-2017,http://www.w3.org/ns/sparql-service-description#namedGraph"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void SPARQLPOSTMassiveCSV200 (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.POST.methodtypevalue();
String accept = MIMEtype.CSV.mimetypevalue();
String pathUri = "sparql";
String name = "SPARQLPOSTMassiveCSV200";
String comment = "Consulta masiva, sin parsear contenido";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("query",
"SELECT ?g ?p ?o "
+ "WHERE { "
+ " ?g ?p ?o ."
+ "} LIMIT 145000");
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertEquals(requestBean.getStatus(), 200);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public final void SPARQLPOSTInsert400 (){
try {
String baseUri = PropertiesManager.getInstance().getProperty("lod.baseUri");
String method = Methodtype.POST.methodtypevalue();
String accept = MIMEtype.CSV.mimetypevalue();
String pathUri = "sparql";
String name = " SPARQLPOSTInsert400";
String comment = "Insertar datos, deberia fallar";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("query",
"INSERT DATA { "
+ "GRAPH <http://lod.eurohelp.es> "
+ "{ "
+ "<http:
+ "} }");
requestBean = new LinkedDataRequestBean(method,accept, baseUri, pathUri, name, comment, parameters);
HttpManager.getInstance().doRequest(requestBean);
assertEquals(requestBean.getStatus(),400);
} catch (IOException e) {
e.printStackTrace();
}
}
@Rule
public TestRule watchman = new TestWatcher() {
@Override
public Statement apply(Statement base, Description description) {
return super.apply(base, description);
}
@Override
protected void succeeded(Description description) {
try {
requestBean.setStatus(0);
tests.add(requestBean);
} catch (Exception e1) {
System.out.println(e1.getMessage());
}finally {
//System.out.println(tests.indexOf(requestBean));
requestBean.setTestIndex(tests.indexOf(requestBean));
}
}
@Override
protected void failed(Throwable e, Description description) {
try {
requestBean.setStatus(1);
tests.add(requestBean);
} catch (Exception e2) {
System.out.println(e2.getMessage());
}finally {
//System.out.println(tests.indexOf(requestBean));
requestBean.setTestIndex(tests.indexOf(requestBean));
}
}
};
@AfterClass
public static void createReport() {
try {
ReportManager.getInstance().createReport(tests);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package examples;
import co.unruly.control.result.Result;
import co.unruly.control.result.Types;
import co.unruly.control.validation.Validator;
import co.unruly.control.validation.Validators;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static co.unruly.control.result.Results.*;
import static co.unruly.control.validation.Validators.rejectIf;
public class FlatMapVariance {
private static Validator<Integer, String> fizzbuzz = Validators.compose(
rejectIf(n -> n % 3 == 0, "fizz"),
rejectIf(n -> n % 5 == 0, "buzz"));
private static Validator<String, String> under100 = Validators.compose(
rejectIf(s -> s.length() > 2, s -> s + " is too damn high")
);
public void canFlatmapErrorTypeOfStringIntoErrorTypeOfString() {
divideExactlyByTwo(3)
.then(flatMap(this::isPrime));
}
// // this should not compile
// public void cannotFlatmapErrorTypeOfListOfStringIntoErrorTypeOfString() {
// Result<Integer, Object> foo = divideExactlyByTwo(4)
// .then(flatMap(this::listFactors));
public String isThisAnInterview(final int m) {
final Validator<Integer, String> fizzbuzz = Validators.compose(
rejectIf(n -> n % 3 == 0, "fizz"),
rejectIf(n -> n % 5 == 0, "buzz"));
Validator<String, String> under100 = rejectIf(s -> s.length() > 2, s -> s + " is too damn high");
return with(m,
fizzbuzz
.then(map(x -> Integer.toString(x)))
.then(Types.<List<String>>forFailures().convert())
.then(flatMap(under100::lifting))
.then(map(s -> "Great success! " + s))
.then(mapFailure(f -> "Big fails :( " + String.join(", ", f)))
.andFinally(collapse()));
}
public void canFlatmapErrorTypeOfFailedValidationIntoErrorTypeOfListOfString() {
Result<Integer, List<String>> foo = fizzbuzz.lifting(4)
.then(Types.<List<String>>forFailures().convert())
.then(flatMap(this::listFactors));
}
public void canFlatmapErrorTypeOfListOfStringIntoErrorTypeOfFailedValidation() {
Result<Integer, List<String>> foo = listFactors(5)
.then(flatMap(fizzbuzz::lifting));
}
private Result<Integer, String> divideExactlyByTwo(int number) {
return number % 2 == 0
? Result.success(number / 2)
: Result.failure(number + " is odd: cannot divide exactly by two");
}
private Result<Integer, String> isPrime(int number) {
return IntStream.range(2, (int) Math.sqrt(number))
.anyMatch(possibleDivisor -> number % possibleDivisor == 0)
? Result.success(number)
: Result.failure(number + " is not prime");
}
private boolean checkPrime(int number) {
return IntStream
.range(2, (int) Math.sqrt(number))
.anyMatch(possibleDivisor -> number % possibleDivisor == 0);
}
private Result<Integer, List<String>> listFactors(int number) {
List<String> primeFactors = IntStream
.range(2, (int) Math.sqrt(number))
.filter(possibleDivisor -> number % possibleDivisor == 0)
.mapToObj(divisor -> number + " is divisible by " + divisor)
.collect(Collectors.toList());
return primeFactors.isEmpty()
? Result.success(number)
: Result.failure(primeFactors);
}
}
|
package guitests;
import static seedu.doit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.util.Arrays;
import java.util.Comparator;
import org.junit.Test;
import seedu.doit.commons.exceptions.IllegalValueException;
import seedu.doit.logic.commands.SortCommand;
import seedu.doit.model.comparators.EndTimeComparator;
import seedu.doit.model.comparators.PriorityComparator;
import seedu.doit.model.comparators.StartTimeComparator;
import seedu.doit.model.comparators.TaskNameComparator;
import seedu.doit.model.item.ReadOnlyTask;
import seedu.doit.testutil.TaskBuilder;
import seedu.doit.testutil.TestTask;
public class SortCommandTest extends TaskManagerGuiTest {
public static final int INDEX_TEST_MARK_VALID = 2;
@Test
public void sort() throws IllegalValueException {
// check default sorting by name
TestTask[] currentList = td.getTypicalTasks();
assertSortSuccess("name", currentList);
assertSortSuccess("priority", currentList);
assertSortSuccess("start time", currentList);
assertSortSuccess("end time", currentList);
// invalid sort command
this.commandBox.runCommand("sort invalid");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE));
// check sort with done tasks
commandBox.runCommand("mark " + INDEX_TEST_MARK_VALID);
TestTask[] expectedTasksList = currentList;
TestTask taskToMark = expectedTasksList[INDEX_TEST_MARK_VALID - 1];
TestTask markedTask = new TaskBuilder(taskToMark).withIsDone(true).build();
expectedTasksList[INDEX_TEST_MARK_VALID - 1] = markedTask;
assertSortSuccess("name", expectedTasksList);
assertSortSuccess("priority", expectedTasksList);
assertSortSuccess("start time", expectedTasksList);
assertSortSuccess("end time", expectedTasksList);
}
private void assertSortSuccess(String sortType, TestTask... currentList) {
commandBox.runCommand("sort " + sortType);
switch (sortType) {
case "name":
Comparator<ReadOnlyTask> nameComparator = new TaskNameComparator();
Arrays.sort(currentList, nameComparator);
assertAllPanelsMatch(currentList, nameComparator);
break;
case "priority":
Comparator<ReadOnlyTask> priorityComparator = new PriorityComparator();
Arrays.sort(currentList, priorityComparator);
assertAllPanelsMatch(currentList, priorityComparator);
break;
case "start time":
Comparator<ReadOnlyTask> startTimeComparator = new StartTimeComparator();
Arrays.sort(currentList, startTimeComparator);
assertAllPanelsMatch(currentList, startTimeComparator);
break;
case "end time":
Comparator<ReadOnlyTask> endTimeComparator = new EndTimeComparator();
Arrays.sort(currentList, endTimeComparator);
assertAllPanelsMatch(currentList, endTimeComparator);
break;
default:
break;
}
}
}
|
package imagej.patcher;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
public class TestUtils {
/**
* Makes a temporary directory for use with unit tests.
* <p>
* When the unit test runs in a Maven context, the temporary directory will be
* created in the <i>target/</i> directory corresponding to the calling class
* instead of <i>/tmp/</i>.
* </p>
*
* @param prefix the prefix for the directory's name
* @return the reference to the newly-created temporary directory
* @throws IOException
*/
public static File createTemporaryDirectory(final String prefix)
throws IOException
{
return createTemporaryDirectory(prefix, getCallingClass(null));
}
/**
* Makes a temporary directory for use with unit tests.
* <p>
* When the unit test runs in a Maven context, the temporary directory will be
* created in the corresponding <i>target/</i> directory instead of
* <i>/tmp/</i>.
* </p>
*
* @param prefix the prefix for the directory's name
* @param forClass the class for context (to determine whether there's a
* <i>target/<i> directory)
* @return the reference to the newly-created temporary directory
* @throws IOException
*/
public static File createTemporaryDirectory(final String prefix,
final Class<?> forClass) throws IOException
{
final URL directory = Utils.getLocation(forClass);
if (directory != null && "file".equals(directory.getProtocol())) {
final String path = directory.getPath();
if (path != null && path.endsWith("/target/test-classes/")) {
final File baseDirectory =
new File(path.substring(0, path.length() - 13));
final File file = File.createTempFile(prefix, "", baseDirectory);
if (file.delete() && file.mkdir()) return file;
}
}
return createTemporaryDirectory(prefix, "", null);
}
/**
* Returns the class of the caller (excluding the specified class).
* <p>
* Sometimes it is convenient to determine the caller's context, e.g. to
* determine whether running in a maven-surefire-plugin context (in which case
* the location of the caller's class would end in
* <i>target/test-classes/</i>).
* </p>
*
* @param excluding the class to exclude (or null)
* @return the class of the caller
*/
public static Class<?> getCallingClass(final Class<?> excluding) {
final String thisClassName = TestUtils.class.getName();
final String thisClassName2 =
excluding == null ? null : excluding.getName();
final Thread currentThread = Thread.currentThread();
for (final StackTraceElement element : currentThread.getStackTrace()) {
final String thatClassName = element.getClassName();
if (thatClassName == null || thatClassName.equals(thisClassName) ||
thatClassName.equals(thisClassName2) ||
thatClassName.startsWith("java.lang."))
{
continue;
}
final ClassLoader loader = currentThread.getContextClassLoader();
try {
return loader.loadClass(element.getClassName());
}
catch (ClassNotFoundException e) {
throw new UnsupportedOperationException("Could not load " +
element.getClassName() + " with the current context class loader (" +
loader + ")!");
}
}
throw new UnsupportedOperationException("No calling class outside " +
thisClassName + " found!");
}
/**
* Creates a temporary directory.
* <p>
* Since there is no atomic operation to do that, we create a temporary file,
* delete it and create a directory in its place. To avoid race conditions, we
* use the optimistic approach: if the directory cannot be created, we try to
* obtain a new temporary file rather than erroring out.
* </p>
* <p>
* It is the caller's responsibility to make sure that the directory is
* deleted.
* </p>
*
* @param prefix The prefix string to be used in generating the file's name;
* see {@link File#createTempFile(String, String, File)}
* @param suffix The suffix string to be used in generating the file's name;
* see {@link File#createTempFile(String, String, File)}
* @param directory The directory in which the file is to be created, or null
* if the default temporary-file directory is to be used
* @return: An abstract pathname denoting a newly-created empty directory
* @throws IOException
*/
public static File createTemporaryDirectory(final String prefix,
final String suffix, final File directory) throws IOException
{
for (int counter = 0; counter < 10; counter++) {
final File file = File.createTempFile(prefix, suffix, directory);
if (!file.delete()) {
throw new IOException("Could not delete file " + file);
}
// in case of a race condition, just try again
if (file.mkdir()) return file;
}
throw new IOException(
"Could not create temporary directory (too many race conditions?)");
}
/**
* Deletes a directory recursively.
*
* @param directory The directory to delete.
* @return whether it succeeded (see also {@link File#delete()})
*/
public static boolean deleteRecursively(final File directory) {
if (directory == null) return true;
final File[] list = directory.listFiles();
if (list == null) return true;
for (final File file : list) {
if (file.isFile()) {
if (!file.delete()) return false;
}
else if (file.isDirectory()) {
if (!deleteRecursively(file)) return false;
}
}
return directory.delete();
}
/**
* Bundles the given classes in a new .jar file.
*
* @param jarFile the output file
* @param classNames the classes to include
* @throws IOException
*/
public static void makeJar(final File jarFile, final String... classNames)
throws IOException
{
final JarOutputStream jar =
new JarOutputStream(new FileOutputStream(jarFile));
final byte[] buffer = new byte[16384];
final StringBuilder pluginsConfig = new StringBuilder();
for (final String className : classNames) {
final String path = className.replace('.', '/') + ".class";
final InputStream in = TestUtils.class.getResourceAsStream("/" + path);
final ZipEntry entry = new ZipEntry(path);
jar.putNextEntry(entry);
for (;;) {
int count = in.read(buffer);
if (count < 0) break;
jar.write(buffer, 0, count);
}
if (className.indexOf('_') >= 0) {
final String name =
className.substring(className.lastIndexOf('.') + 1).replace('_', ' ');
pluginsConfig.append("Plugins, \"").append(name).append("\", ").append(
className).append("\n");
}
in.close();
}
if (pluginsConfig.length() > 0) {
final ZipEntry entry = new ZipEntry("plugins.config");
jar.putNextEntry(entry);
jar.write(pluginsConfig.toString().getBytes());
}
jar.close();
}
}
|
package javax.time;
import static javax.time.DayOfWeek.*;
import static javax.time.Moments.*;
/**
* Test class.
*
* @author Stephen Colebourne
*/
public class TestFluentAPI {
public static void main(String[] args) {
TimeOfDay tod = currentTime();
tod.plusHours(6).plusMinutes(2);
tod.plus(hours(6), minutes(2));
CalendarDay date = null;
date = today().plusDays(3);
date = today().plus(days(3));
date = Now.today().plus(Days.days(3));
date = calendarDay(2007, 3, 20);
date = calendarDay(year(2007), march(), dayOfMonth(20));
date = moment().year(2007).december().dayOfMonth(20).resolveLenient();
date = moment().year(1972).december().dayOfMonth(3).resolve();
date = moment().currentYear().december().dayOfMonth(20).resolveLenient();
date = moment().zoneID("Europe/London").year(2007).august().dayOfMonth(2).resolve();
date = moment().zoneID("America/New_York").year(2007).march().dayOfMonth(20).resolveLenient();
date = moment().defaultZone().year(2007).march().dayOfMonth(20).resolveLenient();
date = CalendarDay.calendarDay(currentMonth(), dayOfMonth(6));
tod.with(hourOfDay(12), minuteOfHour(30));
tod.withHourOfDay(12).withMinuteOfHour(30);
//int q = date.get(QuarterOfYear.class);
//int hourOfDay = HourOfDay.of(tod).get();
DayOfWeek dow = MONDAY;
dow = dow.next();
dow = dow.plusDays(3);
// dow = dow.plusDaysSkipping(3, SATURDAY, SUNDAY);
// day = day.plusSkipping(days(3), WEDNESDAY_PM, SATURDAY, SUNDAY, FOURTH_JULY, XMAS_BREAK);
// int dayIndex = day.value();
// int dayIndex = day.value(Territory.US);
// int dayIndex = day.valueIndexedFrom(SUNDAY);
//// SundayBasedDayOfWeek.MONDAY != DayOfWeek.MONDAY;
// Territory.US.dayOfWeekComparator();
// date.dayOfMonth().value();
}
}
|
package oktesting;
import ext.junit.SparkApplicationTest;
import ext.junit.SparkRunner;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import oktesting.app.di.TestApplicationContainer;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static ext.assertj.MyAssertions.assertThat;
@RunWith(SparkRunner.class)
@SparkApplicationTest(value = TestApplicationContainer.class, port = 4444)
public class TwitterAppTest {
private final OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
@Test
public void test() throws IOException {
final Request request = new Request.Builder()
.get()
.url("http://localhost:4444/statuses/retweets/123")
.build();
final Response response = okHttpClient.newCall(request).execute();
assertThat(response.body().string()).startsWith("[{\"favorited\":false,\"id\":123");
}
@Test
public void testAgain() throws IOException {
final Request request = new Request.Builder()
.get()
.url("http://localhost:4444/statuses/retweets/200")
.build();
final Response response = okHttpClient.newCall(request).execute();
assertThat(response)
.isOk()
.hasContentType("application/json")
.jsonPath("$.length()", Integer.class, 100)
.jsonPath("$[0].id", Integer.class, 200)
.jsonPath("$[0].user.name", String.class, "Maria Moccachino");
}
}
|
package org.kitteh.irc;
import org.junit.Assert;
import org.junit.Test;
/**
* Confirm an event listener can be registered and an event fired.
*/
public class EventTest {
private class Event {
private boolean success = false;
}
@Test
public void testEventRegistration() {
EventManager manager = new EventManager();
manager.registerEventListener(this);
Event event = new Event();
manager.callEvent(event);
Assert.assertTrue("Failed to register and fire an event", event.success);
}
@EventHandler
public void eventHandler(Event e) {
e.success = true;
}
}
|
package org.takes.tk;
import com.jcabi.aspects.Tv;
import java.io.IOException;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.mockito.Mockito;
import org.takes.Request;
import org.takes.Take;
import org.takes.rq.RqFake;
import org.takes.rq.RqMethod;
import org.takes.rs.RsPrint;
import org.takes.rs.RsText;
/**
* TkRetry can retry till success or retry count is reached.
*
* @author Hamdi Douss (douss.hamdi@gmail.com)
* @version $Id$
* @since 0.28.3
*/
public final class TkRetryTest {
/**
* TkRetry can work when no IOException.
*
* @throws Exception if something is wrong
*/
@Test
public void worksWithNoException() throws Exception {
final String test = "test";
MatcherAssert.assertThat(
new RsPrint(
new TkRetry(2, 2, new TkText(test))
.act(new RqFake())
).print(),
Matchers.containsString(test)
);
}
/**
* TkRetry can retry when initial take fails once
* with IOException, till retry count is reached.
*
* @throws Exception if something is wrong
*/
@Test(expected = IOException.class)
public void retriesOnExceptionTillCount() throws Exception {
final int count = Tv.THREE;
final int delay = Tv.THOUSAND;
final Take take = Mockito.mock(Take.class);
Mockito
.when(take.act(Mockito.any(Request.class)))
.thenThrow(new IOException());
final long start = System.nanoTime();
try {
new TkRetry(count, delay, take).act(
new RqFake(RqMethod.GET)
);
} catch (final IOException exception) {
final long spent = System.nanoTime() - start;
MatcherAssert.assertThat(
new Long(count * delay - Tv.HUNDRED) * Tv.MILLION,
Matchers.lessThanOrEqualTo(spent)
);
throw exception;
}
}
/**
* TkRetry can retry when initial take fails with IOException,
* till get successful result.
*
* @throws Exception if something is wrong
*/
@Test
public void retriesOnExceptionTillSuccess() throws Exception {
final int count = Tv.THREE;
final int delay = Tv.THOUSAND;
final String data = "data";
final Take take = Mockito.mock(Take.class);
Mockito
.when(take.act(Mockito.any(Request.class)))
.thenThrow(new IOException())
.thenReturn(new RsText(data));
final long startTime = System.nanoTime();
final RsPrint response = new RsPrint(
new TkRetry(count, delay, take).act(new RqFake(RqMethod.GET))
);
final long spent = System.nanoTime() - startTime;
MatcherAssert.assertThat(
new Long(delay - Tv.HUNDRED) * Tv.MILLION,
Matchers.lessThanOrEqualTo(spent)
);
MatcherAssert.assertThat(
response.print(),
Matchers.containsString(data)
);
}
}
|
package BlueTurtle.TSE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import BlueTurtle.gui.GUIController.ASAT;
/**
* Test for the JavaController class.
*
* @author BlueTurtle.
*
*/
public class JavaControllerTest {
private String checkStyleOutputFilePath = System.getProperty("user.dir")
+ "/src/test/resources/exampleCheckStyle1.xml";
private String pmdOutputFilePath = System.getProperty("user.dir") + "/src/test/resources/examplePmd1.xml";
private String findBugsOutputFilePath = System.getProperty("user.dir") + "/src/test/resources/exampleFindbugs1.xml";
private String outputPath = System.getProperty("user.dir") + "/src/test/resources/testOutput.js";
/**
* Clear the attributes of JavaController.
*/
@Before
public void setUp() {
JavaController.setCheckStyleOutputFile(null);
JavaController.setPmdOutputFile(null);
JavaController.setFindBugsOutputFile(null);
}
// /**
// * Delete the created files.
// */
// @After
// public void cleanUp() {
// File f = new File(System.getProperty("user.dir") + "/src/main/resources/SummarizedOuput.js");
// if (f.exists()) {
// f.delete();
/**
* Test that the user direction path is the same.
*/
@Test
public void testUserDir() {
String expected = System.getProperty("user.dir");
String actual = JavaController.getUserDir();
assertEquals(expected, actual);
}
/**
* Test that all files are null at first.
*/
@Test
public void allFilesStringsAreNull() {
assertTrue(JavaController.getCheckStyleOutputFile() == null && JavaController.getPmdOutputFile() == null
&& JavaController.getFindBugsOutputFile() == null);
}
/**
* Test changing CheckStyle output file.
*/
@Test
public void testChangingCheckStyleOutputFile() {
String emptyFile = JavaController.getCheckStyleOutputFile();
File newFile = new File("newFile");
JavaController.setASATOutput(ASAT.CheckStyle, newFile);
String checkStyleFile = JavaController.getCheckStyleOutputFile();
assertNotEquals(emptyFile, checkStyleFile);
}
/**
* Test changing PMD output file.
*/
@Test
public void testChangingPMDOutputFile() {
String emptyFile = JavaController.getPmdOutputFile();
File newFile = new File("newFile");
JavaController.setASATOutput(ASAT.PMD, newFile);
String pmdFile = JavaController.getPmdOutputFile();
assertNotEquals(emptyFile, pmdFile);
}
/**
* Test changing FindBugs output file.
*/
@Test
public void testChangingFindBugsOutputFile() {
String emptyFile = JavaController.getFindBugsOutputFile();
File newFile = new File("newFile");
JavaController.setASATOutput(ASAT.FindBugs, newFile);
String findBugsFile = JavaController.getFindBugsOutputFile();
assertNotEquals(emptyFile, findBugsFile);
}
/**
* Test SetASATOutput with a null.
*/
@Test
public void testSetOutputWithNull() {
String currentFile = JavaController.getCheckStyleOutputFile();
JavaController.setASATOutput(ASAT.CheckStyle, null);
String newFile = JavaController.getCheckStyleOutputFile();
assertEquals(currentFile, newFile);
}
// /**
// * Test execute should output file.
// *
// * @throws IOException
// * throws an exception if a problem is encountered while reading
// * the file.
// */
// @Test
// public void testExecute() throws IOException {
// JavaController.setASATOutput(ASAT.CheckStyle, new File(checkStyleOutputFilePath));
// JavaController.setASATOutput(ASAT.PMD, new File(pmdOutputFilePath));
// JavaController.setASATOutput(ASAT.FindBugs, new File(findBugsOutputFilePath));
// JavaController jc = new JavaController();
// jc.execute();
// assertTrue(new File(System.getProperty("user.dir") + "/src/main/resources/SummarizedOuput.js").exists());
}
|
package com.alibaba.json.bvt.bug;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import junit.framework.TestCase;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Issue978 extends TestCase {
protected void setUp() throws Exception {
JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
JSON.defaultLocale = Locale.CHINA;
}
public void test_for_issue() throws Exception {
Model model = new Model();
model.date = new Date(1483413683714L);
JSONObject obj = (JSONObject) JSON.toJSON(model);
assertEquals("{\"date\":\"2017-01-03 11:21:23\"}", obj.toJSONString());
}
public static class Model {
@JSONField(format="yyyy-MM-dd HH:mm:ss")
public Date date;
}
}
|
package org.javacint.settings;
//#if sdkns == "siemens"
import com.siemens.icm.io.file.FileConnection;
//#elif sdkns == "cinterion"
//# import com.cinterion.io.file.FileConnection;
//#endif
import java.io.*;
import java.util.*;
import javax.microedition.io.Connector;
import org.javacint.logging.Logger;
/**
* Settings management class.
*
* This class should take advantage of the PropertiesFile class.
*/
public class Settings {
private static final boolean LOG = false;
/**
* Settings container. It has both the default and specific settings.
*/
private static PropertiesFileWithDefaultValues settings;
/**
* Settings filename
*/
private static String fileName = "settings.txt";
/**
* Settings providers. They provide some settings with some default values
* and they receive events when some settings are changed.
*/
private static final Vector providers = new Vector();
/**
* APN setting. In the AT^SJNET=... format
*/
public static final String SETTING_APN = "apn";
/**
* Protection code
*/
public static final String SETTING_CODE = "code";
public static final String SETTING_MANAGERSPHONE = "phoneManager";
/**
* ICCID sim card setting. This is very useful to detect iccid card change
* (SIM card change detection not handled by the settings class itself).
*/
public static final String SETTING_ICCID = "iccid";
/**
* pincode setting name. Using pincode is NOT recommended.
*/
public static final String SETTING_PINCODE = "pincode";
/**
* jadurl setting
*/
public static final String SETTING_JADURL = "jadurl";
private static boolean madeSomeChanges = false;
private static boolean firstStartup = false;
/**
* loading state
*/
private static boolean loading;
public static synchronized void setFilename(String filename) {
fileName = filename;
settings = null;
}
/**
* Define if we are loading the program. If we are loading, we can't
* get/set/load/save settings. We can only add and remove settings
* consumers.
*
* @param l Loading state
*/
public static void loading(boolean l) {
loading = l;
if (loading) {
// It's the first startup if the settings file doesn't exists
try {
FileConnection fc = (FileConnection) Connector.open("file:///a:/" + fileName, Connector.READ);
firstStartup = !fc.exists();
} catch (Exception ex) {
}
}
}
/**
* Get the settings filename.
*
* @return Filename without the "file:///a:/" path prefix
*/
public static String getFilename() {
return fileName;
}
/**
* If this is the first startup.
*
* The first statup flag is activated if we don't have any settings file.
*
* @return If this is the first startup
*/
public static boolean firstStartup() {
return firstStartup;
}
/**
* Load settings. We should replace the line by line loading code by using
* the PropertiesFile class.
*/
public static synchronized void load() {
if (Logger.BUILD_DEBUG) {
Logger.log(THIS + ".load();");
}
try {
settings = new PropertiesFileWithDefaultValues(fileName, getDefaultSettings());
} catch (IOException ex) {
// The exception we shoud have is at first launch :
// There shouldn't be any file to read from
if (Logger.BUILD_CRITICAL) {
Logger.log(THIS + ".load", ex);
}
}
}
public static void onSettingsChanged(String[] names) {
onSettingsChanged(names, null);
}
/**
* Launch an event when some settings
*
* @param names Names of the settings
*/
public static void onSettingsChanged(String[] names, SettingsProvider caller) {
try {
synchronized (providers) {
for (Enumeration en = providers.elements(); en.hasMoreElements();) {
SettingsProvider cons = (SettingsProvider) en.nextElement();
if (cons == caller) {
continue;
}
cons.settingsChanged(names);
}
}
} catch (Exception ex) {
if (Logger.BUILD_CRITICAL) {
Logger.log(THIS + ".onSettingsChanged", ex);
}
}
}
/**
* Get default settings
*
* @return Default settings Hashtable
*/
public static Hashtable getDefaultSettings() {
Hashtable defaultSettings = new Hashtable();
// The following settings are mandatory but they
// are NOT handled by the Settings class.
// Code is mandatory (SMS control protection)
defaultSettings.put(SETTING_CODE, "1234");
// APN is mandatory (GPRS setup)
defaultSettings.put(SETTING_APN, "");
// ICCID is mandatory (SIM card detection)
defaultSettings.put(SETTING_ICCID, "");
synchronized (providers) {
for (Enumeration en = providers.elements(); en.hasMoreElements();) {
SettingsProvider prov = (SettingsProvider) en.nextElement();
prov.getDefaultSettings(defaultSettings);
}
}
return defaultSettings;
}
/**
* Add a settings provier class
*
* @param provider Provider of settings and consumer of settings change
*/
public static void addProvider(SettingsProvider provider) {
// if (Logger.BUILD_DEBUG) {
// Logger.log("Settings.addSettingsConsumer( " + consumer + " );");
if (!loading) {
// We should never add or removed a settings provider when we have finished loading
throw new RuntimeException(THIS + ".addProvider: We're not loading anymore !");
}
synchronized (providers) {
providers.addElement(provider);
// Adding a provider voids the current state of the settings
settings = null;
}
}
/**
* Remove a settings consumer class
*
* @param consumer Consumer of settings
*/
public static void removeProvider(SettingsProvider consumer) {
synchronized (providers) {
if (providers.contains(consumer)) {
providers.removeElement(consumer);
}
settings = null;
}
}
/**
* Reset all settings
*/
public synchronized static void reset() {
try {
checkLoad();
if (settings != null) {
settings.delete();
load();
}
} catch (Exception ex) {
if (Logger.BUILD_CRITICAL) {
Logger.log(THIS + ".reset", ex);
}
}
}
/**
* Save setttings
*/
public static synchronized void save() {
synchronized (Settings.class) {
// If there's no settings, we shouldn't have to save anything
if (settings == null) {
return;
}
// If no changes were made, we shouldn't have to save anything
if (!madeSomeChanges) {
return;
}
try {
settings.save(getDefaultSettings());
// We don't have anything to be written anymore
madeSomeChanges = false;
} catch (Exception ex) {
if (Logger.BUILD_CRITICAL) {
Logger.log(THIS + ".save", ex, true);
}
}
}
}
/**
* Init (and ReInit) method
*/
private static void checkLoad() {
if (settings == null) {
load();
}
}
/**
* Get a setting's value as a String
*
* @param key Key Name of the setting
* @return String value of the setting
*/
public static synchronized String get(String key) {
return (String) getSettings().get(key);
}
/**
* Get all the settings
*
* @return All the settings
*/
public static synchronized Hashtable getSettings() {
checkLoad();
return settings.getData();
}
/**
* Set a setting
*
* @param key Name of the setting
* @param value Value of the setting
*/
public static void set(String key, String value) {
if (Logger.BUILD_DEBUG) {
Logger.log(THIS + ".set( \"" + key + "\", \"" + value + "\" );");
}
if (setWithoutEvent(key, value)) {
onSettingsChanged(new String[]{key});
}
}
/**
* Set a setting
*
* @param key Name of the setting
* @param value Value of the setting
*/
public static void set(String key, int value) {
set(key, Integer.toString(value));
}
/**
* Set a setting
*
* @param key Name of the setting
* @param value Value of the setting
*/
public static void set(String key, boolean value) {
set(key, value ? "1" : "0");
}
/**
* Set a setting without launching the onSettingsChange method
*
* @param key Setting to set
* @param value Value of the setting
* @return If setting was actually changed
*/
public static synchronized boolean setWithoutEvent(String key, String value) {
checkLoad();
String previousValue = settings.get(key, null);
if (previousValue != null && previousValue.compareTo(value) == 0) {
return false;
}
if (loading) {
throw new RuntimeException(THIS + ".setWithoutEvent: You can't change a setting while loading !");
}
settings.set(key, value);
madeSomeChanges = true;
return true;
}
/**
* Get a setting's value as an int
*
* @param key Key Name of the setting
* @return Integer value of the setting
* @throws java.lang.NumberFormatException When the int cannot be parsed
*/
public static int getInt(String key) throws NumberFormatException {
checkLoad();
if (Logger.BUILD_DEBUG && LOG) {
Logger.log(THIS + ".getInt( \"" + key + "\" );");
}
return settings.get(key, -1);
}
/**
* Get a setting's value as a boolean
*
* @param key Key name of the setting
* @return The value of the setting (any value not understood will be
* treated as false)
*/
public static boolean getBool(String key) {
checkLoad();
if (Logger.BUILD_DEBUG && LOG) {
Logger.log(THIS + ".getBool( \"" + key + "\" );");
}
return settings.get(key, false);
}
public static Enumeration names() {
return getSettings().keys();
}
private static final String THIS = "Settings";
}
|
package ie.omk.smpp.message;
import ie.omk.smpp.Address;
import ie.omk.smpp.BadCommandIDException;
import ie.omk.smpp.ErrorAddress;
import ie.omk.smpp.SMPPException;
import ie.omk.smpp.util.GSMConstants;
import ie.omk.smpp.util.PacketFactory;
import ie.omk.smpp.util.SMPPDate;
import ie.omk.smpp.util.SMPPIO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import junit.framework.TestCase;
/**
* Test that the value reported by <code>getLength</code> matches the actual
* length a packet serializes to and deserializes from.
*
* @author Oran Kelly <orank@users.sf.net>
*/
public class SizeTest extends TestCase {
// List of all the message types.
private static final Class[] classList = {
AlertNotification.class,
BindReceiver.class,
BindReceiverResp.class,
BindTransceiver.class,
BindTransceiverResp.class,
BindTransmitter.class,
BindTransmitterResp.class,
CancelSM.class,
CancelSMResp.class,
DataSM.class,
DataSMResp.class,
DeliverSM.class,
DeliverSMResp.class,
EnquireLink.class,
EnquireLinkResp.class,
GenericNack.class,
ParamRetrieve.class,
ParamRetrieveResp.class,
QueryLastMsgs.class,
QueryLastMsgsResp.class,
QueryMsgDetails.class,
QueryMsgDetailsResp.class,
QuerySM.class,
QuerySMResp.class,
ReplaceSM.class,
ReplaceSMResp.class,
SubmitMulti.class,
SubmitMultiResp.class,
SubmitSM.class,
SubmitSMResp.class,
Unbind.class,
UnbindResp.class,
};
public void testPacketsWithDefaultConstructor() {
testPacketSizes(false);
}
public void testPacketsWithFieldsSet() {
testPacketSizes(true);
}
/**
* Test that packets report their sizes correctly. The <code>filled</code>
* parameter determines if the test run uses all the default values for the
* fields as determined by a message's constructor or if the test will fill
* in test values for all relevant fields in the message.
*/
private void testPacketSizes(boolean filled) {
for (int i = 0; i < classList.length; i++) {
String className = classList[i].getName();
className = className.substring(className.lastIndexOf('.'));
try {
SMPPPacket p = (SMPPPacket) classList[i].newInstance();
if (filled) {
initialiseFields(p);
}
testPacket(className, p);
} catch (SMPPException x) {
fail(className + " field initialisation caused an SMPP exception:\n"
+ x.toString());
} catch (InstantiationException x) {
fail(className + " is implemented incorrectly. Exception thrown:\n"
+ x.toString());
} catch (IllegalAccessException x) {
fail(className + " constructor is not public.\n" + x.toString());
} catch (ExceptionInInitializerError x) {
fail(className + " constructor threw an exception.\n" + x.toString());
} catch (SecurityException x) {
fail("SecurityException instantiating " + className + "\n"
+ x.toString());
}
}
}
/**
* Test an individual packet. This method serializes the packet to a byte
* array and then deserializes a second packet from that byte array. It then
* asserts that <code>getLength</code> on the original packet matches the
* length of the byte array and that the length of the byte array matches
* the value returned from <code>getLength</code> on the deserialized
* packet.
*/
private void testPacket(String n, SMPPPacket original) {
try {
SMPPPacket deserialized;
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.writeTo(out);
byte[] array = out.toByteArray();
int id = SMPPIO.bytesToInt(array, 4, 4);
deserialized = PacketFactory.newInstance(id);
if (deserialized == null) {
fail(n + " - PacketFactory returned null for Id 0x"
+ Integer.toHexString(id));
return;
}
deserialized.readFrom(array, 0);
assertEquals(n + " serialized length does not match.",
original.getLength(), array.length);
assertEquals(n + " deserialized length does not match.",
array.length, deserialized.getLength());
} catch (BadCommandIDException x) {
fail(n + " serialization caused BadCommandIDException:\n"
+ x.toString());
} catch (SMPPProtocolException x) {
fail(n + " serialization caused SMPPProtocolException:\n"
+ x.toString());
} catch (IOException x) {
fail(n + " serialization caused I/O Exception:\n" + x.toString());
return;
}
}
/**
* Initialise field contents for the filled field test.
*/
private void initialiseFields(SMPPPacket p)
throws ie.omk.smpp.SMPPException {
int id = p.getCommandId();
switch (id) {
case SMPPPacket.ALERT_NOTIFICATION:
p.setSequenceNum(34);
p.setSource(new Address(0, 0, "445445445"));
p.setDestination(new Address(0, 0, "67676767676767"));
break;
case SMPPPacket.BIND_TRANSMITTER:
case SMPPPacket.BIND_RECEIVER:
case SMPPPacket.BIND_TRANSCEIVER:
Bind b = (Bind) p;
b.setSequenceNum(1);
b.setSystemId("sysId");
b.setSystemType("sysType");
b.setPassword("passwd");
b.setSource(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534[1-3]"));
break;
case SMPPPacket.BIND_TRANSMITTER_RESP:
case SMPPPacket.BIND_RECEIVER_RESP:
case SMPPPacket.BIND_TRANSCEIVER_RESP:
p.setSequenceNum(2);
BindResp br = (BindResp) p;
br.setSystemId("SMSC-ID");
break;
case SMPPPacket.CANCEL_SM:
p.setSequenceNum(3);
p.setMessageId("deadbeef");
p.setSource(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534111"));
p.setDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534222"));
break;
case SMPPPacket.DELIVER_SM:
case SMPPPacket.SUBMIT_SM:
case SMPPPacket.SUBMIT_MULTI:
p.setSequenceNum(5);
p.setServiceType("svcTp");
p.setSource(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534111"));
if (id == SMPPPacket.SUBMIT_MULTI) {
SubmitMulti sml = (SubmitMulti) p;
sml.addDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "991293211"));
sml.addDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "991293212"));
sml.addDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "991293213"));
} else {
p.setDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534222"));
}
//p.setProtocolId();
p.setPriority(1);
p.setDeliveryTime(new SMPPDate(new Date()));
p.setExpiryTime(new SMPPDate(new Date()));
p.setRegistered(1);
p.setReplaceIfPresent(1);
//p.setDataCoding();
p.setMessageText("This is a short message");
break;
case SMPPPacket.DATA_SM:
p.setSequenceNum(45);
p.setServiceType("svcTp");
p.setSource(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534111"));
p.setDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534222"));
p.setRegistered(1);
break;
case SMPPPacket.DATA_SM_RESP:
p.setSequenceNum(46);
p.setMessageId("deadbeef");
break;
case SMPPPacket.SUBMIT_SM_RESP:
case SMPPPacket.SUBMIT_MULTI_RESP:
p.setSequenceNum(6);
p.setMessageId("deadbeef");
if (id == SMPPPacket.SUBMIT_MULTI_RESP) {
SubmitMultiResp smr = (SubmitMultiResp) p;
smr.add(new ErrorAddress(0, 0, "12345", 65));
smr.add(new ErrorAddress(0, 0, "12346", 66));
smr.add(new ErrorAddress(0, 0, "12347", 90));
smr.add(new ErrorAddress(0, 0, "99999", 999));
}
break;
case SMPPPacket.PARAM_RETRIEVE:
p.setSequenceNum(7);
((ParamRetrieve) p).setParamName("getParam");
break;
case SMPPPacket.PARAM_RETRIEVE_RESP:
p.setSequenceNum(8);
((ParamRetrieveResp) p).setParamValue("paramValue - can be long.");
break;
case SMPPPacket.QUERY_LAST_MSGS:
p.setSequenceNum(9);
p.setSource(new Address(0, 0, "65534111"));
((QueryLastMsgs) p).setMsgCount(45);
break;
case SMPPPacket.QUERY_LAST_MSGS_RESP:
p.setSequenceNum(10);
QueryLastMsgsResp q = (QueryLastMsgsResp) p;
q.addMessageId("deadbeef");
q.addMessageId("cafecafe");
q.addMessageId("12345678");
q.addMessageId("77777777");
q.addMessageId("beefdead");
break;
case SMPPPacket.QUERY_MSG_DETAILS:
p.setSequenceNum(11);
p.setSource(new Address(0, 0, "65534111"));
p.setMessageId("deadbeef");
((QueryMsgDetails) p).setSmLength(160);
break;
case SMPPPacket.QUERY_MSG_DETAILS_RESP:
p.setSequenceNum(15);
QueryMsgDetailsResp q1 = (QueryMsgDetailsResp) p;
q1.setServiceType("svcTp");
q1.setSource(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534111"));
q1.addDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "991293211"));
q1.addDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "991293212"));
q1.addDestination(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "991293213"));
q1.setPriority(1);
q1.setDeliveryTime(new SMPPDate());
q1.setExpiryTime(new SMPPDate());
q1.setRegistered(1);
q1.setReplaceIfPresent(1);
q1.setMessageText("This is a short message");
q1.setMessageId("deadbeef");
q1.setFinalDate(new SMPPDate());
q1.setMessageStatus(1);
q1.setErrorCode(2);
break;
case SMPPPacket.QUERY_SM:
p.setSequenceNum(17);
p.setMessageId("deadbeef");
p.setSource(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534111"));
break;
case SMPPPacket.QUERY_SM_RESP:
p.setSequenceNum(20);
p.setMessageId("deadbeef");
p.setFinalDate(new SMPPDate());
p.setMessageStatus(1);
p.setErrorCode(4);
break;
case SMPPPacket.REPLACE_SM:
p.setSequenceNum(22);
p.setMessageId("deadbeef");
p.setServiceType("svcTp");
p.setSource(new Address(GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN, "65534111"));
p.setDeliveryTime(new SMPPDate());
p.setExpiryTime(new SMPPDate());
p.setRegistered(1);
p.setMessageText("This is a short message");
break;
default:
p.setSequenceNum(4);
break;
}
}
}
|
package e2e;
import scaffolding.TestProject;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static scaffolding.CountMatcher.noneOf;
import static scaffolding.CountMatcher.oneOf;
import static scaffolding.MvnRunner.assertArtifactInLocalRepo;
import static scaffolding.MvnRunner.assertArtifactNotInLocalRepo;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import de.hilling.maven.release.TestUtils;
public class IndependentVersionsBugfixTest {
private static final String GROUP_ID = TestUtils.TEST_GROUP_ID + ".independentversions";
public static final String INDEPENDENT_VERSIONS_ARTIFACT = "independent-versions";
public static final String CORE_UTILS_ARTIFACT = "core-utils";
public static final String CONSOLE_APP_ARTIFACT = "console-app";
private final String expectedParentVersion = "1.0";
private final String expectedCoreVersion = "2.0";
private final String expectedAppVersion = "3.0";
private String branchName = "bugfix-test";
@Rule
public TestProject testProject = new TestProject(ProjectType.INDEPENDENT_VERSIONS_BUGFIX);
@Before
public void releaseProject() throws Exception {
assertArtifactNotInLocalRepo(GROUP_ID, INDEPENDENT_VERSIONS_ARTIFACT, expectedParentVersion);
assertArtifactNotInLocalRepo(GROUP_ID, CORE_UTILS_ARTIFACT, expectedCoreVersion);
assertArtifactNotInLocalRepo(GROUP_ID, CONSOLE_APP_ARTIFACT, expectedAppVersion);
testProject.checkClean = false;
testProject.mvnRelease();
testProject.local.branchCreate().setName(branchName).call();
}
@Test
public void checkReleasesBeforeBugfix() throws Exception {
assertArtifactInLocalRepo(GROUP_ID, INDEPENDENT_VERSIONS_ARTIFACT, expectedParentVersion);
assertArtifactInLocalRepo(GROUP_ID, CORE_UTILS_ARTIFACT, expectedCoreVersion);
assertArtifactInLocalRepo(GROUP_ID, CONSOLE_APP_ARTIFACT, expectedAppVersion);
}
@Test
public void createBugfixReleaseAll() throws Exception {
testProject.local.checkout().setName(branchName).call();
testProject.mvnReleaseBugfix();
assertArtifactInLocalRepo(GROUP_ID, INDEPENDENT_VERSIONS_ARTIFACT, expectedParentVersion + ".1");
assertArtifactInLocalRepo(GROUP_ID, CORE_UTILS_ARTIFACT, expectedCoreVersion + ".1");
assertArtifactInLocalRepo(GROUP_ID, CONSOLE_APP_ARTIFACT, expectedAppVersion + ".1");
}
@Test
public void createBugfixReleaseAllAndIgnoreNextMasterRelease() throws Exception {
testProject.mvnRelease();
testProject.local.pull();
testProject.local.checkout().setName(branchName).call();
testProject.mvnReleaseBugfix();
assertArtifactInLocalRepo(GROUP_ID, INDEPENDENT_VERSIONS_ARTIFACT, expectedParentVersion + ".1");
assertArtifactInLocalRepo(GROUP_ID, CORE_UTILS_ARTIFACT, expectedCoreVersion + ".1");
assertArtifactInLocalRepo(GROUP_ID, CONSOLE_APP_ARTIFACT, expectedAppVersion + ".1");
}
@Test
public void releaseOnlyModulesThatHaveChanged() throws Exception {
testProject.local.checkout().setName(branchName).call();
testProject.commitRandomFile(CONSOLE_APP_ARTIFACT);
testProject.mvnReleaseBugfix();
assertArtifactNotInLocalRepo(GROUP_ID, INDEPENDENT_VERSIONS_ARTIFACT, expectedParentVersion + ".1");
assertArtifactNotInLocalRepo(GROUP_ID, CORE_UTILS_ARTIFACT, expectedCoreVersion + ".1");
assertArtifactInLocalRepo(GROUP_ID, CONSOLE_APP_ARTIFACT, expectedAppVersion + ".1");
}
@Test
public void buildOnlyModulesThatHaveChanged() throws Exception {
testProject.local.checkout().setName(branchName).call();
testProject.commitRandomFile(CONSOLE_APP_ARTIFACT);
final List<String> outputLines = testProject.mvnReleaseBugfix();
assertThat(outputLines, oneOf(containsString("Building console-app 3.0.1")));
assertThat(outputLines, noneOf(containsString("Building core-utils")));
assertThat(outputLines, noneOf(containsString("Building independent-versions 1.0")));
}
@Test
public void createBugfixCoreChanged() throws Exception {
testProject.local.checkout().setName(branchName).call();
testProject.commitRandomFile(CORE_UTILS_ARTIFACT);
testProject.mvnReleaseBugfix();
assertArtifactInLocalRepo(GROUP_ID, INDEPENDENT_VERSIONS_ARTIFACT, expectedParentVersion);
assertArtifactInLocalRepo(GROUP_ID, CORE_UTILS_ARTIFACT, expectedCoreVersion + ".1");
assertArtifactInLocalRepo(GROUP_ID, CONSOLE_APP_ARTIFACT, expectedAppVersion + ".1");
}
@Test
public void createSecondBugfixReleaseAll() throws Exception {
testProject.local.checkout().setName(branchName).call();
testProject.mvnReleaseBugfix();
testProject.mvnReleaseBugfix();
assertArtifactInLocalRepo(GROUP_ID, INDEPENDENT_VERSIONS_ARTIFACT, expectedParentVersion + ".2");
assertArtifactInLocalRepo(GROUP_ID, CORE_UTILS_ARTIFACT, expectedCoreVersion + ".2");
assertArtifactInLocalRepo(GROUP_ID, CONSOLE_APP_ARTIFACT, expectedAppVersion + ".2");
}
}
|
package hudson.plugins.git;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.SECONDS;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.plugins.git.extensions.impl.EnforceGitClient;
import hudson.scm.PollingResult;
import hudson.triggers.SCMTrigger;
import hudson.util.RunList;
import hudson.model.TaskListener;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.jvnet.hudson.test.Issue;
public abstract class SCMTriggerTest extends AbstractGitProject
{
private ZipFile namespaceRepoZip;
private Properties namespaceRepoCommits;
private ExecutorService singleThreadExecutor;
protected boolean expectChanges = false;
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Before
public void setUp() throws Exception {
expectChanges = false;
namespaceRepoZip = new ZipFile("src/test/resources/namespaceBranchRepo.zip");
namespaceRepoCommits = parseLsRemote(new File("src/test/resources/namespaceBranchRepo.ls-remote"));
singleThreadExecutor = Executors.newSingleThreadExecutor();
}
protected abstract EnforceGitClient getGitClient();
protected abstract boolean isDisableRemotePoll();
@Test
public void testNamespaces_with_refsHeadsMaster() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"refs/heads/master",
namespaceRepoCommits.getProperty("refs/heads/master"),
"origin/master");
}
// @Test
public void testNamespaces_with_remotesOriginMaster() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"remotes/origin/master",
namespaceRepoCommits.getProperty("refs/heads/master"),
"origin/master");
}
// @Test
public void testNamespaces_with_refsRemotesOriginMaster() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"refs/remotes/origin/master",
namespaceRepoCommits.getProperty("refs/heads/master"),
"origin/master");
}
// @Test
public void testNamespaces_with_master() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"master",
namespaceRepoCommits.getProperty("refs/heads/master"),
"origin/master");
}
// @Test
public void testNamespaces_with_namespace1Master() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"a_tests/b_namespace1/master",
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace1/master"),
"origin/a_tests/b_namespace1/master");
}
// @Test
public void testNamespaces_with_refsHeadsNamespace1Master() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"refs/heads/a_tests/b_namespace1/master",
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace1/master"),
"origin/a_tests/b_namespace1/master");
}
// @Test
public void testNamespaces_with_namespace2Master() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"a_tests/b_namespace2/master",
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace2/master"),
"origin/a_tests/b_namespace2/master");
}
// @Test
public void testNamespaces_with_refsHeadsNamespace2Master() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"refs/heads/a_tests/b_namespace2/master",
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace2/master"),
"origin/a_tests/b_namespace2/master");
}
// @Test
public void testNamespaces_with_namespace3_feature3_sha1() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"),
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"),
"detached");
}
// @Test
public void testNamespaces_with_namespace3_feature3_branchName() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"a_tests/b_namespace3/feature3",
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"),
"origin/a_tests/b_namespace3/feature3");
}
// @Test
public void testNamespaces_with_refsHeadsNamespace3_feature3_sha1() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"),
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"),
"detached");
}
// @Test
public void testNamespaces_with_refsHeadsNamespace3_feature3_branchName() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"refs/heads/a_tests/b_namespace3/feature3",
namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"),
"origin/a_tests/b_namespace3/feature3");
}
// @Test
public void testTags_with_TagA() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"TagA",
namespaceRepoCommits.getProperty("refs/tags/TagA"),
"TagA"); //TODO: What do we expect!?
}
// @Test
public void testTags_with_TagBAnnotated() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"TagBAnnotated",
namespaceRepoCommits.getProperty("refs/tags/TagBAnnotated^{}"),
"TagBAnnotated"); //TODO: What do we expect!?
}
// @Test
public void testTags_with_refsTagsTagA() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"refs/tags/TagA",
namespaceRepoCommits.getProperty("refs/tags/TagA"),
"refs/tags/TagA"); //TODO: What do we expect!?
}
// @Test
public void testTags_with_refsTagsTagBAnnotated() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"refs/tags/TagBAnnotated",
namespaceRepoCommits.getProperty("refs/tags/TagBAnnotated^{}"),
"refs/tags/TagBAnnotated");
}
// @Test
public void testCommitAsBranchSpec_feature4_sha1() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
namespaceRepoCommits.getProperty("refs/heads/b_namespace3/feature4"),
namespaceRepoCommits.getProperty("refs/heads/b_namespace3/feature4"),
"detached");
}
// @Test
public void testCommitAsBranchSpec_feature4_branchName() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
"refs/heads/b_namespace3/feature4",
namespaceRepoCommits.getProperty("refs/heads/b_namespace3/feature4"),
"origin/b_namespace3/feature4");
}
// @Test
public void testCommitAsBranchSpec() throws Exception {
check(namespaceRepoZip, namespaceRepoCommits,
namespaceRepoCommits.getProperty("refs/heads/b_namespace3/master"),
namespaceRepoCommits.getProperty("refs/heads/b_namespace3/master"),
"detached");
}
@Issue("JENKINS-29796")
// @Test
public void testMultipleRefspecs() throws Exception {
final String remote = prepareRepo(namespaceRepoZip);
final UserRemoteConfig remoteConfig = new UserRemoteConfig(remote, "origin",
/** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */
|
package info.javaspecproto;
import info.javaspec.dsl.Because;
import info.javaspec.dsl.Cleanup;
import info.javaspec.dsl.Establish;
import info.javaspec.dsl.It;
import org.hamcrest.MatcherAssert;
import java.io.ByteArrayOutputStream;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/** Inner classes are declared static to avoid the gaze of HierarchicalContextRunner when testing JavaSpec. */
//@SuppressWarnings("unused")
public class ContextClasses {
public static Class<?> hiddenClass() {
Class<?> outer;
try {
outer = Class.forName("info.javaspecproto.HiddenContext");
return outer.getDeclaredClasses()[0];
} catch(ClassNotFoundException e) {
throw new AssertionError("Failed to set up test", e);
}
}
public static class ConstructorWithArguments {
public ConstructorWithArguments(int _id) { }
It is_otherwise_valid = () -> assertEquals(1, 1);
}
public static final class ConstructorWithSideEffects {
private static int _numTimesInitialized = 0;
public ConstructorWithSideEffects() { _numTimesInitialized++; }
It expects_to_be_run_once = () -> MatcherAssert.assertThat(_numTimesInitialized, equalTo(1));
}
public static class DuplicateContextNames {
public class Left {
public class Duplicate {
It runs_one = () -> assertEquals(1, 1);
}
}
public class Right {
public class Duplicate {
It runs_another = () -> assertEquals(2, 2);
}
}
}
public static class DuplicateSpecNames {
public class OneSetOfConditions {
public class DuplicateContext {
It duplicate_behavior = () -> assertEquals(1, 1);
}
}
public class AnotherSetOfConditions {
public class DuplicateContext {
It duplicate_behavior = () -> assertEquals(2, 2);
}
}
}
public static class Empty { }
public static class FailingCleanup {
Cleanup flawed_cleanup = () -> assertEquals(42, -1);
It may_run = () -> assertEquals(42, 42);
}
public static class FailingConstructor {
public FailingConstructor() throws HardToFindThrowable {
throw new HardToFindThrowable();
}
It will_fail = () -> assertEquals(1, 1);
public static class HardToFindThrowable extends Throwable {
private static final long serialVersionUID = 1L;
}
}
public static class FailingEstablish {
Establish flawed_setup = () -> assertEquals(42, -1);
It will_never_run = () -> assertEquals(42, 42);
}
public static class FailingEstablishWithCleanup extends ExecutionSpy {
Establish establish = () -> {
notifyEvent.accept("ContextClasses.FailingEstablishWithCleanup::establish");
throw new UnsupportedOperationException("flawed_setup");
};
It it = () -> notifyEvent.accept("ContextClasses.FailingEstablishWithCleanup::it");
Cleanup cleanup = () -> notifyEvent.accept("ContextClasses.FailingEstablishWithCleanup::cleanup");
}
public static class FailingIt {
It fails = () -> assertEquals(42, -1);
}
public static class FullFixture extends ExecutionSpy {
public FullFixture() { notifyEvent.accept("ContextClasses.FullFixture::new"); }
Establish arranges = () -> notifyEvent.accept("ContextClasses.FullFixture::arrange");
Because acts = () -> notifyEvent.accept("ContextClasses.FullFixture::act");
It asserts = () -> notifyEvent.accept("ContextClasses.FullFixture::assert");
Cleanup cleans = () -> notifyEvent.accept("ContextClasses.FullFixture::cleans");
}
public static class NestedCleanup extends ExecutionSpy {
public NestedCleanup() { notifyEvent.accept("ContextClasses.NestedCleanup::new"); }
Cleanup cleans = () -> notifyEvent.accept("ContextClasses.NestedCleanup::cleans");
public class innerContext {
public innerContext() { notifyEvent.accept("ContextClasses.NestedCleanup.innerContext::new"); }
Cleanup cleans = () -> notifyEvent.accept("ContextClasses.NestedCleanup::innerContext::cleans");
It asserts = () -> notifyEvent.accept("ContextClasses.NestedCleanup.innerContext::asserts");
}
}
public static class NestedContexts {
public class one {
It asserts_one = () -> assertEquals(1, 1);
}
public class two {
It asserts_two = () -> assertEquals(2, 2);
}
}
public static class NestedEstablish extends ExecutionSpy {
public NestedEstablish() { notifyEvent.accept("ContextClasses.NestedEstablish::new"); }
Establish arranges = () -> notifyEvent.accept("ContextClasses.NestedEstablish::arranges");
public class innerContext {
public innerContext() { notifyEvent.accept("ContextClasses.NestedEstablish.innerContext::new"); }
Establish arranges = () -> notifyEvent.accept("ContextClasses.NestedEstablish::innerContext::arranges");
It asserts = () -> notifyEvent.accept("ContextClasses.NestedEstablish.innerContext::asserts");
}
}
public static class NestedIt {
public class nestedContext {
It tests_something_more_specific = () -> assertThat(1, equalTo(1));
}
}
public static class NestedStaticClassIt {
public static class Helper {
It is_not_a_test = () -> assertEquals(1, 1);
}
}
public static class OneIt extends ExecutionSpy {
public OneIt() { notifyEvent.accept("ContextClasses.OneIt::new"); }
It only_test = () -> notifyEvent.accept("ContextClasses.OneIt::only_test");
}
public static class PendingBecause {
private Object subject;
private int hashcode;
Establish arranges = () -> subject = new Object();
Because acts;
It asserts = () -> assertThat(hashcode, equalTo(42));
}
public static class PendingCleanup {
private ByteArrayOutputStream subject;
Establish arranges = () -> subject = new ByteArrayOutputStream(4);
Because acts = () -> subject.write(42);
It asserts = () -> assertThat(subject.size(), equalTo(4));
Cleanup cleans;
}
public static class PendingEstablish {
private Object subject;
private int hashcode;
Establish arranges;
Because acts = () -> hashcode = subject.hashCode();
It asserts = () -> assertThat(hashcode, equalTo(42));
}
public static class PendingIt {
private Object subject;
private int hashcode;
Establish arranges = () -> subject = new Object();
Because acts = () -> hashcode = subject.hashCode();
It asserts;
}
public static class TwoEstablish {
private final List<String> orderMatters = new LinkedList<>();
Establish arrange_part_one = () -> orderMatters.add("do this first");
Establish arrange_part_two_or_is_this_part_one = () -> orderMatters.add("do this second");
It runs = () -> assertThat(orderMatters, contains("do this first", "do this second"));
}
public static class TwoBecause {
private final List<String> orderMatters = new LinkedList<>();
Because act_part_one = () -> orderMatters.add("do this first");
Because act_part_two_or_is_this_part_one = () -> orderMatters.add("do this second");
It runs = () -> assertThat(orderMatters, contains("do this first", "do this second"));
}
public static class TwoCleanup {
private final List<String> orderMatters = new LinkedList<>();
Cleanup cleanup_part_one = () -> orderMatters.add("do this first");
Cleanup cleanup_part_two_or_is_this_part_one = () -> orderMatters.add("do this second");
It runs = () -> assertThat(orderMatters, contains("do this first", "do this second"));
}
public static class TwoContexts {
public class subcontext1 {
It asserts = () -> assertEquals(1, 1);
}
public class subcontext2 {
It asserts = () -> assertEquals(2, 2);
}
}
public static class TwoIt extends ExecutionSpy {
It first_test = () -> notifyEvent.accept("TwoIt::first_test");
It second_test = () -> notifyEvent.accept("TwoIt::second_test");
}
public static class TwoIts {
It one = () -> assertEquals(1, 1);
It two = () -> assertEquals(2, 2);
}
public static class StaticIt {
static It looks_like_an_isolated_test_but_beware = () -> assertThat("this test", not("independent"));
}
public static class UnderscoreIt {
It read_me = () -> assertEquals(1, 1);
}
public static class UnderscoreSubContext {
public class read_me {
It asserts = () -> assertEquals(1, 1);
}
}
public static class WrongTypeField {
public Object inaccessibleAsIt = new Object();
}
}
|
//@@author A0121621Y
package jfdi.test.storage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import jfdi.storage.Constants;
import jfdi.storage.FileManager;
import jfdi.storage.apis.MainStorage;
import jfdi.storage.exceptions.FilesReplacedException;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class FileManagerTest {
private static Path testDirectoryRoot = null;
private static MainStorage mainStorageInstance = null;
private static String originalPreference = null;
private Path testDirectoryPath = null;
private File testDirectoryFile = null;
private String testDirectoryString = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
testDirectoryRoot = Files.createTempDirectory(Constants.TEST_DIRECTORY_PREFIX);
mainStorageInstance = MainStorage.getInstance();
originalPreference = mainStorageInstance.getPreferredDirectory();
mainStorageInstance.setPreferredDirectory(testDirectoryRoot.toString());
mainStorageInstance.initialize();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
FileUtils.deleteDirectory(testDirectoryRoot.toFile());
TestHelper.revertOriginalPreference(mainStorageInstance, originalPreference);
}
@Before
public void setUp() throws Exception {
testDirectoryPath = Paths.get(testDirectoryRoot.toString(), Constants.TEST_DIRECTORY_NAME);
testDirectoryFile = testDirectoryPath.toFile();
testDirectoryString = testDirectoryFile.getAbsolutePath();
assertFalse(testDirectoryFile.exists());
}
@After
public void tearDown() throws Exception {
if (testDirectoryFile.exists()) {
FileUtils.deleteDirectory(testDirectoryFile);
}
}
@Test
public void testPrepareDirectory() throws Exception {
// The folder should not exist at the start
assertFalse(testDirectoryFile.exists());
// Command under test (we prepare the directory for storage)
FileManager.prepareDirectory(testDirectoryString);
// Now the folder should exist
assertTrue(testDirectoryFile.exists());
}
@Test
public void testMoveFilesToNewDirectory() throws Exception {
// Create some valid data files and get their checksums
mainStorageInstance.use(testDirectoryString);
TestHelper.createValidDataFiles(testDirectoryString);
HashMap<String, Long> checksums = TestHelper.getDataFileChecksums(testDirectoryString);
String subdirectory = Paths.get(testDirectoryString, Constants.TEST_SUBDIRECTORY_NAME).toString();
// Command under test (move the data files to the new directory)
String dataPath = TestHelper.getDataDirectory(subdirectory);
FileManager.moveFilesToDirectory(dataPath);
// Assert that their checksums remain the same
assertTrue(TestHelper.hasDataFileChecksums(subdirectory, checksums));
}
@Test(expected = FilesReplacedException.class)
public void testMoveFilesToDirectoryWithExistingData() throws Exception {
// Create some valid data files and get their checksums
mainStorageInstance.use(testDirectoryString);
TestHelper.createValidDataFiles(testDirectoryString);
HashMap<String, Long> checksums = TestHelper.getDataFileChecksums(testDirectoryString);
String subdirectory = Paths.get(testDirectoryString, Constants.TEST_SUBDIRECTORY_NAME).toString();
// Create some invalid data files in the destination directory for collision
TestHelper.createInvalidDataFiles(subdirectory);
try {
// Command under test (move the data files to the new directory)
String dataPath = TestHelper.getDataDirectory(subdirectory);
FileManager.moveFilesToDirectory(dataPath);
} catch (FilesReplacedException e) {
// Ensure that files are replaced and assert that the data files in
// the destination remains the same
assertTrue(TestHelper.hasDataFileChecksums(subdirectory, checksums));
throw e;
}
}
@Test
public void testBackupAndRemove() {
// Create the test file
Path testFilePath = Paths.get(testDirectoryString, Constants.TEST_FILE_NAME);
File testFile = testFilePath.toFile();
testFile.getParentFile().mkdirs();
FileManager.writeToFile(Constants.TEST_FILE_DATA, testFilePath);
// Command under test (backup and remove the file)
String backupPath = FileManager.backupAndRemove(testFilePath);
// Assert that the test file has now been moved to the backup location
File backupFile = new File(backupPath);
assertFalse(testFile.exists());
assertTrue(backupFile.exists());
// Create the test file again
FileManager.writeToFile(Constants.TEST_FILE_DATA, testFilePath);
// The backup method should work even if a backup already exists
String backupPath2 = FileManager.backupAndRemove(testFilePath);
File backupFile2 = new File(backupPath2);
assertFalse(testFile.exists());
assertTrue(backupFile2.exists());
}
@Test
public void testWriteAndRead() {
// Create the necessary directories
Path filePath = Paths.get(testDirectoryString, Constants.TEST_FILE_NAME);
File parentFile = filePath.getParent().toFile();
parentFile.mkdirs();
// Test writing to the file
FileManager.writeToFile(Constants.TEST_FILE_DATA, filePath);
// Test reading from the file
String readString = FileManager.readFileToString(filePath);
// Ensure that both are the same
assertEquals(Constants.TEST_FILE_DATA, readString);
}
}
|
package org.exist.storage.btree;
import org.exist.EXistException;
import org.exist.storage.BrokerPool;
import org.exist.test.ExistEmbeddedServer;
import org.exist.util.*;
import org.exist.xquery.TerminatedException;
import org.exist.xquery.value.AtomicValue;
import org.exist.xquery.value.DoubleValue;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
/**
* Low-level tests on the B+tree.
*/
public class BTreeTest {
private final static byte BTREE_TEST_FILE_ID = 0x7F;
private final static short BTREE_TEST_FILE_VERSION = Short.MIN_VALUE;
private Path file = null;
private int count = 0;
private static final int COUNT = 5000;
@Test
public void simpleUpdates() throws DBException, IOException, TerminatedException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try(final BTree btree = new BTree(pool, BTREE_TEST_FILE_ID, BTREE_TEST_FILE_VERSION, false, pool.getCacheManager(), file)) {
btree.create((short) -1);
String prefixStr = "K";
for (int i = 1; i <= COUNT; i++) {
Value value = new Value(prefixStr + Integer.toString(i));
btree.addValue(value, i);
}
//Testing IndexQuery.TRUNC_RIGHT
IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, new Value(prefixStr));
btree.query(query, new StringIndexCallback());
assertEquals(COUNT, count);
btree.flush();
//Removing index entries
btree.remove(query, new StringIndexCallback());
assertEquals(COUNT, count);
btree.flush();
//Reading data
for (int i = 1; i <= COUNT; i++) {
Value value = new Value(prefixStr + Integer.toString(i));
btree.addValue(value, i);
}
//Testing IndexQuery.TRUNC_RIGHT
btree.query(query, new StringIndexCallback());
assertEquals(COUNT, count);
btree.flush();
}
}
@Test
public void strings() throws DBException, IOException, TerminatedException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try(final BTree btree = new BTree(pool, BTREE_TEST_FILE_ID, BTREE_TEST_FILE_VERSION, false, pool.getCacheManager(), file)) {
btree.create((short) -1);
String prefixStr = "C";
for (int i = 1; i <= COUNT; i++) {
Value value = new Value(prefixStr + Integer.toString(i));
btree.addValue(value, i);
}
btree.flush();
try(final StringWriter writer = new StringWriter()) {
btree.dump(writer);
}
for (int i = 1; i <= COUNT; i++) {
long p = btree.findValue(new Value(prefixStr + Integer.toString(i)));
assertEquals(p, i);
}
//Testing IndexQuery.TRUNC_RIGHT
IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, new Value(prefixStr));
btree.query(query, new StringIndexCallback());
assertEquals(COUNT, count);
//Testing IndexQuery.TRUNC_RIGHT
query = new IndexQuery(IndexQuery.TRUNC_RIGHT, new Value(prefixStr + "1"));
btree.query(query, new StringIndexCallback());
assertEquals(1111, count);
//Testing IndexQuery.NEQ
query = new IndexQuery(IndexQuery.NEQ, new Value(prefixStr + "10"));
btree.query(query, new StringIndexCallback());
assertEquals(COUNT - 1, count);
//Testing IndexQuery.GT
query = new IndexQuery(IndexQuery.GT, new Value(prefixStr));
btree.query(query, new StringIndexCallback());
assertEquals(COUNT, count);
//Testing IndexQuery.GT
query = new IndexQuery(IndexQuery.GT, new Value(prefixStr + "1"));
btree.query(query, new StringIndexCallback());
assertEquals(COUNT - 1, count);
//Testing IndexQuery.LT
query = new IndexQuery(IndexQuery.LT, new Value(prefixStr));
btree.query(query, new StringIndexCallback());
assertEquals(count, 0);
}
}
@Test
public void longStrings() throws DBException, IOException {
// Test storage of long keys up to half of the page size (4k)
final Random rand = new Random(System.currentTimeMillis());
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try(final BTree btree = new BTree(pool, BTREE_TEST_FILE_ID, BTREE_TEST_FILE_VERSION, false, pool.getCacheManager(), file)) {
btree.setSplitFactor(0.7);
btree.create((short) -1);
Map<String, Integer> keys = new TreeMap<>();
String prefixStr = "C";
for (int i = 1; i <= COUNT; i++) {
StringBuilder buf = new StringBuilder();
buf.append(prefixStr).append(Integer.toString(i));
int nextLen = rand.nextInt(2000);
while (nextLen < 512) {
nextLen = rand.nextInt(2000);
}
for (int j = 0; j < nextLen; j++) {
buf.append('x');
}
final String key = buf.toString();
Value value = new Value(key);
btree.addValue(value, i);
keys.put(key, i);
}
btree.flush();
for (Map.Entry<String, Integer> entry: keys.entrySet()) {
long p = btree.findValue(new Value(entry.getKey().toString()));
assertEquals(p, entry.getValue().intValue());
}
}
}
@Test
public void stringsTruncated() throws DBException, IOException, TerminatedException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try(BTree btree = new BTree(pool, BTREE_TEST_FILE_ID, BTREE_TEST_FILE_VERSION, false, pool.getCacheManager(), file)) {
btree.create((short) -1);
char prefix = 'A';
for (int i = 0; i < 24; i++) {
for (int j = 1; j <= COUNT; j++) {
Value value = new Value(prefix + Integer.toString(j));
btree.addValue(value, j);
}
prefix++;
}
btree.flush();
//Testing IndexQuery.TRUNC_RIGHT
prefix = 'A';
for (int i = 0; i < 24; i++) {
IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, new Value(Character.toString(prefix)));
btree.query(query, new StringIndexCallback());
assertEquals(COUNT, count);
prefix++;
}
}
}
@Test
public void removeStrings() throws DBException, IOException, TerminatedException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try(final BTree btree = new BTree(pool, BTREE_TEST_FILE_ID, BTREE_TEST_FILE_VERSION, false, pool.getCacheManager(), file)) {
btree.create((short) -1);
char prefix = 'A';
for (int i = 0; i < 24; i++) {
for (int j = 1; j <= COUNT; j++) {
Value value = new Value(prefix + Integer.toString(j));
btree.addValue(value, j);
}
prefix++;
}
btree.flush();
prefix = 'A';
for (int i = 0; i < 24; i++) {
IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, new Value(Character.toString(prefix)));
btree.remove(query, new StringIndexCallback());
assertEquals(COUNT, count);
assertEquals(-1, btree.findValue(new Value(prefix + Integer.toString(100))));
query = new IndexQuery(IndexQuery.TRUNC_RIGHT, new Value(prefix + Integer.toString(100)));
btree.query(query, new StringIndexCallback());
assertEquals(0, count);
prefix++;
}
//Testing IndexQuery.TRUNC_RIGHT
IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, new Value(Character.toString('D')));
btree.query(query, new StringIndexCallback());
assertEquals(0, count);
}
}
@Test
public void numbers() throws TerminatedException, DBException, EXistException, IOException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try(final BTree btree = new BTree(pool, BTREE_TEST_FILE_ID, BTREE_TEST_FILE_VERSION, false, pool.getCacheManager(), file)) {
btree.create((short) -1);
for (int i = 1; i <= COUNT; i++) {
Value value = new SimpleValue(new DoubleValue(i));
btree.addValue(value, i);
}
btree.flush();
for (int i = 1; i <= COUNT; i++) {
long p = btree.findValue(new SimpleValue(new DoubleValue(i)));
assertEquals(p, i);
}
//Testing IndexQuery.GT
IndexQuery query;
for (int i = 0; i < COUNT; i += 10) {
query = new IndexQuery(IndexQuery.GT, new SimpleValue(new DoubleValue(i)));
btree.query(query, new SimpleCallback());
assertEquals(COUNT - i, count);
}
//Testing IndexQuery.GEQ
query = new IndexQuery(IndexQuery.GEQ, new SimpleValue(new DoubleValue(COUNT / 2)));
btree.query(query, new SimpleCallback());
assertEquals(COUNT / 2 + 1, count);
//Testing IndexQuery.NEQ
for (int i = 1; i <= COUNT / 8; i++) {
query = new IndexQuery(IndexQuery.NEQ, new SimpleValue(new DoubleValue(i)));
btree.query(query, new SimpleCallback());
assertEquals(COUNT - 1, count);
}
}
}
@Test
public void numbersWithPrefix() throws DBException, EXistException, IOException, TerminatedException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try(final BTree btree = new BTree(pool, BTREE_TEST_FILE_ID, BTREE_TEST_FILE_VERSION, false, pool.getCacheManager(), file)) {
btree.create((short) -1);
for (int i = 1; i <= COUNT; i++) {
Value value = new PrefixValue(99, new DoubleValue(i));
btree.addValue(value, i);
}
for (int i = 1; i <= COUNT; i++) {
Value value = new PrefixValue(100, new DoubleValue(i));
btree.addValue(value, i);
}
btree.flush();
for (int i = 1; i <= COUNT; i++) {
long p = btree.findValue(new PrefixValue(99, new DoubleValue(i)));
assertEquals(p, i);
}
Value prefix = new PrefixValue(99);
//Testing IndexQuery.TRUNC_RIGHT
IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, new PrefixValue(99));
btree.query(query, new PrefixIndexCallback());
assertEquals(COUNT, count);
//Testing IndexQuery.GT
for (int i = 0; i < COUNT; i += 10) {
query = new IndexQuery(IndexQuery.GT, new PrefixValue(99, new DoubleValue(i)));
btree.query(query, prefix, new PrefixIndexCallback());
assertEquals(COUNT - i, count);
}
//Testing IndexQuery.GEQ
query = new IndexQuery(IndexQuery.GEQ, new PrefixValue(99, new DoubleValue(COUNT / 2)));
btree.query(query, prefix, new PrefixIndexCallback());
assertEquals(COUNT / 2 + 1, count);
//Testing IndexQuery.LT
query = new IndexQuery(IndexQuery.LT, new PrefixValue(99, new DoubleValue(COUNT / 2)));
btree.query(query, prefix, new PrefixIndexCallback());
assertEquals(COUNT / 2 - 1, count);
//Testing IndexQuery.LEQ
query = new IndexQuery(IndexQuery.LEQ, new PrefixValue(99, new DoubleValue(COUNT / 2)));
btree.query(query, prefix, new PrefixIndexCallback());
assertEquals(COUNT / 2, count);
//Testing IndexQuery.NEQ
for (int i = 1; i <= COUNT / 8; i++) {
count = 0;
query = new IndexQuery(IndexQuery.NEQ, new PrefixValue(99, new DoubleValue(i)));
btree.query(query, prefix, new PrefixIndexCallback());
assertEquals(COUNT - 1, count);
}
}
}
@ClassRule
public static final ExistEmbeddedServer existEmbeddedServer = new ExistEmbeddedServer(true, false);
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
public void initialize() throws IOException {
file = temporaryFolder.newFile("test.dbx").toPath();
assertTrue(Files.exists(file));
}
@After
public void cleanUp() {
FileUtils.deleteQuietly(file);
}
private final class SimpleCallback implements BTreeCallback {
public SimpleCallback() {
count = 0;
}
@Override
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
count++;
return false;
}
}
private final class PrefixIndexCallback implements BTreeCallback {
public PrefixIndexCallback() {
count = 0;
}
@Override
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
int prefix = ByteConversion.byteToInt(value.data(), value.start());
assertEquals(99, prefix);
// XMLString key = UTF8.decode(value.data(), value.start() + 4, value.getLength() - 4);
count++;
return false;
}
}
private final class StringIndexCallback implements BTreeCallback {
public StringIndexCallback() {
count = 0;
}
@Override
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
@SuppressWarnings("unused")
XMLString key = UTF8.decode(value.data(), value.start(), value.getLength());
count++;
return false;
}
}
private class SimpleValue extends Value {
public SimpleValue(AtomicValue value) throws EXistException {
data = value.serializeValue(0);
len = data.length;
pos = 0;
}
}
private class PrefixValue extends Value {
public PrefixValue(int prefix) {
len = 4;
data = new byte[len];
ByteConversion.intToByte(prefix, data, 0);
pos = 0;
}
public PrefixValue(int prefix, AtomicValue value) throws EXistException {
data = value.serializeValue(4);
len = data.length;
ByteConversion.intToByte(prefix, data, 0);
pos = 0;
}
}
}
|
package org.opencompare;
import org.junit.Assert;
import org.junit.Test;
import org.opencompare.api.java.PCMElement;
import org.opencompare.api.java.PCMFactory;
import org.opencompare.api.java.Value;
import org.opencompare.api.java.util.PCMVisitor;
import org.opencompare.api.java.value.BooleanValue;
import org.opencompare.model.impl.BooleanValueImpl;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Moussa Lydia
*/
public class TraitementPcmTest {
@Test
public void testWhenFileExistsGetPcmIsNotNull() throws IOException {
// si le fichier pcm exist
final File file = new File("pcms/Comparison_between_Argentine_provinces_and_countries_by_GDP_(PPP)_per_capita_0.pcm");
final TraitementPcm traitementPcm = new TraitementPcm(file);
Assert.assertNotNull(traitementPcm.getPcm());
Assert.assertEquals("Comparison_between_Argentine_provinces_and_countries_by_GDP_(PPP)_per_capita", traitementPcm.getPcm().getName());
}
@Test
public void testWhenFileExistsGetPcmNameIsNotNull() throws IOException {
// si le fichier pcm exist
final File file = new File("pcms/Comparison_between_Argentine_provinces_and_countries_by_GDP_(PPP)_per_capita_0.pcm");
final TraitementPcm traitementPcm = new TraitementPcm(file);
Assert.assertNotNull(traitementPcm.getNamePcm());
// et verifie que le nom du pcm est correct
Assert.assertEquals("Comparison between Argentine provinces and countries by GDP (PPP) per capita", traitementPcm.getNamePcm());
}
@Test
public void testAllValueToTypes() {
this.assertValueToType(
new org.opencompare.api.java.impl.value.BooleanValueImpl(null),
"boolean"
);
this.assertValueToType(
new org.opencompare.api.java.impl.value.IntegerValueImpl(null),
"integer"
);
this.assertValueToType(
new org.opencompare.api.java.impl.value.NotApplicableImpl(null),
"string"
);
this.assertValueToType(
new org.opencompare.api.java.impl.value.NotAvailableImpl(null),
"string"
);
this.assertValueToType(
new org.opencompare.api.java.impl.value.RealValueImpl(null),
"real"
);
this.assertValueToType(
null,
"string"
);
// Be careful, maybe dimension should return "dimension" !
this.assertValueToType(
new org.opencompare.api.java.impl.value.DimensionImpl(null),
"dimension"
);
}
@Test(expected = UnsupportedOperationException.class)
public void testUnknownValueType() {
TraitementPcm.valueToType(new Value() {
@Override
public PCMElement clone(PCMFactory factory) {
return null;
}
@Override
public void accept(PCMVisitor visitor) {
}
});
}
private void assertValueToType(Value value, String expectedResult) {
final String result =
TraitementPcm.valueToType(value);
Assert.assertEquals(expectedResult, result);
}
@Test
public void setConditionalTypeHtml() {
final String result = TraitementPcm.setTypeHtml("conditional");
Assert.assertEquals("text", result);
}
@Test (expected = NullPointerException.class)
public void setTypeHtmlnull(){
TraitementPcm.setTypeHtml(null);
}
@Test
public void testGetBestTypes() {
final Map<String, String> result = TraitementPcm.getBestTypes(new HashMap<>());
Assert.assertEquals(new HashMap<>(), result);
}
@Test
public void testGetBestTypesWithOneFeatureOneType() {
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("conditional");
map.put("feature1", list);
final Map<String, String> result = TraitementPcm.getBestTypes(map);
Map<String, String> expected = new HashMap<>();
expected.put("feature1", "text");
Assert.assertEquals(expected, result);
}
@Test
public void testGetBestTypesWithOneFeatureMultipleTypes() {
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("conditional");
list.add("boolean");
list.add("conditional");
map.put("feature1", list);
final Map<String, String> result = TraitementPcm.getBestTypes(map);
Map<String, String> expected = new HashMap<>();
expected.put("feature1", "text");
Assert.assertEquals(expected, result);
}
}
|
package org.redmine.ta;
import org.junit.*;
import org.redmine.ta.RedmineManager.INCLUDE;
import org.redmine.ta.beans.*;
import org.redmine.ta.internal.logging.Logger;
import org.redmine.ta.internal.logging.LoggerFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
import static org.junit.Assert.*;
/**
* This class and its dependencies are located in org.redmine.ta.api project.
*/
public class RedmineManagerTest {
// TODO We don't know activities IDs!
private static final Integer ACTIVITY_ID = 8;
private static Logger logger = LoggerFactory.getLogger(RedmineManagerTest.class);
private static RedmineManager mgr;
private static String projectKey;
private static TestConfig testConfig;
@BeforeClass
public static void oneTimeSetUp() {
testConfig = new TestConfig();
logger.info("Running redmine tests using: " + testConfig.getURI());
// mgr = new RedmineManager(TestConfig.getURI(), TestConfig.getApiKey());
mgr = new RedmineManager(testConfig.getURI());
mgr.setLogin(testConfig.getLogin());
mgr.setPassword(testConfig.getPassword());
Project junitTestProject = new Project();
junitTestProject.setName("test project");
junitTestProject.setIdentifier("test"
+ Calendar.getInstance().getTimeInMillis());
try {
Project createdProject = mgr.createProject(junitTestProject);
projectKey = createdProject.getIdentifier();
} catch (Exception e) {
logger.error(e, "Exception while creating test project");
Assert.fail("can't create a test project. " + e.getMessage());
}
}
@AfterClass
public static void oneTimeTearDown() {
try {
if (mgr != null && projectKey != null) {
mgr.deleteProject(projectKey);
}
} catch (Exception e) {
logger.error(e, "Exception while deleting test project");
Assert.fail("can't delete the test project '" + projectKey + ". reason: "
+ e.getMessage());
}
}
@Before
// Is executed before each test method
public void setup() throws Exception {
}
@Test
public void testCreateIssue() {
try {
Issue issueToCreate = new Issue();
issueToCreate.setSubject("test zzx");
Calendar startCal = Calendar.getInstance();
// have to clear them because they are ignored by Redmine and prevent from comparison later
startCal.clear(Calendar.HOUR_OF_DAY);
startCal.clear(Calendar.MINUTE);
startCal.clear(Calendar.SECOND);
startCal.clear(Calendar.MILLISECOND);
startCal.add(Calendar.DATE, 5);
issueToCreate.setStartDate(startCal.getTime());
Calendar due = Calendar.getInstance();
due.add(Calendar.MONTH, 1);
issueToCreate.setDueDate(due.getTime());
User assignee = getOurUser();
issueToCreate.setAssignee(assignee);
String description = "This is the description for the new task." +
"\nIt has several lines." +
"\nThis is the last line.";
issueToCreate.setDescription(description);
float estimatedHours = 44;
issueToCreate.setEstimatedHours(estimatedHours);
Issue newIssue = mgr.createIssue(projectKey, issueToCreate);
// System.out.println("created: " + newIssue);
Assert.assertNotNull("Checking returned result", newIssue);
Assert.assertNotNull("New issue must have some ID", newIssue.getId());
// check startDate
Calendar returnedStartCal = Calendar.getInstance();
returnedStartCal.setTime(newIssue.getStartDate());
Assert.assertEquals(startCal.get(Calendar.YEAR), returnedStartCal.get(Calendar.YEAR));
Assert.assertEquals(startCal.get(Calendar.MONTH), returnedStartCal.get(Calendar.MONTH));
Assert.assertEquals(startCal.get(Calendar.DAY_OF_MONTH), returnedStartCal.get(Calendar.DAY_OF_MONTH));
// check dueDate
Calendar returnedDueCal = Calendar.getInstance();
returnedDueCal.setTime(newIssue.getDueDate());
Assert.assertEquals(due.get(Calendar.YEAR), returnedDueCal.get(Calendar.YEAR));
Assert.assertEquals(due.get(Calendar.MONTH), returnedDueCal.get(Calendar.MONTH));
Assert.assertEquals(due.get(Calendar.DAY_OF_MONTH), returnedDueCal.get(Calendar.DAY_OF_MONTH));
// check ASSIGNEE
User actualAssignee = newIssue.getAssignee();
Assert.assertNotNull("Checking assignee not null", actualAssignee);
Assert.assertEquals("Checking assignee id", assignee.getId(),
actualAssignee.getId());
// check AUTHOR
Integer EXPECTED_AUTHOR_ID = getOurUser().getId();
Assert.assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthor().getId());
// check ESTIMATED TIME
Assert.assertEquals((Float) estimatedHours, newIssue.getEstimatedHours());
// check multi-line DESCRIPTION
String regexpStripExtra = "\\r|\\n|\\s";
description = description.replaceAll(regexpStripExtra, "");
String actualDescription = newIssue.getDescription();
actualDescription = actualDescription.replaceAll(regexpStripExtra, "");
Assert.assertEquals(description, actualDescription);
// PRIORITY
Assert.assertNotNull(newIssue.getPriorityId());
Assert.assertTrue(newIssue.getPriorityId() > 0);
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void testCreateIssueWithParent() {
try {
Issue parentIssue = new Issue();
parentIssue.setSubject("parent 1");
Issue newParentIssue = mgr.createIssue(projectKey, parentIssue);
logger.debug("created parent: " + newParentIssue);
Assert.assertNotNull("Checking parent was created", newParentIssue);
Assert.assertNotNull("Checking ID of parent issue is not null",
newParentIssue.getId());
// Integer parentId = 46;
Integer parentId = newParentIssue.getId();
Issue childIssue = new Issue();
childIssue.setSubject("child 1");
childIssue.setParentId(parentId);
Issue newChildIssue = mgr.createIssue(projectKey, childIssue);
logger.debug("created child: " + newChildIssue);
Assert.assertEquals("Checking parent ID of the child issue", parentId,
newChildIssue.getParentId());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void testStartDateNull() {
try {
Issue issue = new Issue();
issue.setSubject("test start date");
issue.setStartDate(null);
Issue newIssue = mgr.createIssue(projectKey, issue);
Issue loadedIssue = mgr.getIssueById(newIssue.getId());
Assert.assertNull(loadedIssue.getStartDate());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void testGetIssuesBySummary() {
String summary = "issue with subject ABC";
try {
Issue issue = new Issue();
issue.setSubject(summary);
User assignee = getOurUser();
issue.setAssignee(assignee);
Issue newIssue = mgr.createIssue(projectKey, issue);
logger.debug("created: " + newIssue);
Assert.assertNotNull("Checking returned result", newIssue);
Assert.assertNotNull("New issue must have some ID", newIssue.getId());
// try to find the issue
List<Issue> foundIssues = mgr.getIssuesBySummary(projectKey,
summary);
Assert.assertNotNull("Checking if search results is not NULL", foundIssues);
Assert.assertTrue("Search results must be not empty",
!(foundIssues.isEmpty()));
Issue loadedIssue1 = RedmineTestUtils.findIssueInList(foundIssues, newIssue.getId());
Assert.assertNotNull(loadedIssue1);
Assert.assertEquals(summary, loadedIssue1.getSubject());
// User actualAssignee = newIssue.getAssignee();
// assertNotNull("Checking assignee not null", actualAssignee);
// assertEquals("Checking assignee Name", assignee.getName(),
// actualAssignee.getName());
// assertEquals("Checking assignee Id", assignee.getId(),
// actualAssignee.getId());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void testTryFindNonExistingIssue() {
String summary = "some summary here for issue which does not exist";
try {
// try to find the issue
List<Issue> foundIssues = mgr.getIssuesBySummary(projectKey,
summary);
Assert.assertNotNull("Search result must be not null", foundIssues);
Assert.assertTrue("Search result list must be empty",
foundIssues.isEmpty());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
private static User getOurUser() {
Integer userId = Integer
.parseInt(testConfig.getParam("createissue.userid"));
String login = testConfig.getLogin();
String fName = testConfig.getParam("userFName");
String lName = testConfig.getParam("userLName");
User user = new User();
user.setId(userId);
user.setLogin(login);
user.setFirstName(fName);
user.setLastName(lName);
return user;
}
@Test(expected = IllegalArgumentException.class)
public void testNULLHostParameter() {
new RedmineManager(null);
}
@Test(expected = IllegalArgumentException.class)
public void testEmptyHostParameter() throws RuntimeException {
new RedmineManager("");
}
@Test(expected = AuthenticationException.class)
public void noAPIKeyOnCreateIssueThrowsAE() throws Exception {
RedmineManager redmineMgrEmpty = new RedmineManager(testConfig.getURI());
Issue issue = new Issue();
issue.setSubject("test zzx");
redmineMgrEmpty.createIssue(projectKey, issue);
}
@Test(expected = AuthenticationException.class)
public void wrongAPIKeyOnCreateIssueThrowsAE() throws Exception {
RedmineManager redmineMgrInvalidKey = new RedmineManager(testConfig.getURI(), "wrong_key");
Issue issue = new Issue();
issue.setSubject("test zzx");
redmineMgrInvalidKey.createIssue(projectKey, issue);
}
@Test
public void testUpdateIssue() {
try {
Issue issue = new Issue();
String originalSubject = "Issue " + new Date();
issue.setSubject(originalSubject);
Issue newIssue = mgr.createIssue(projectKey, issue);
String changedSubject = "changed subject";
newIssue.setSubject(changedSubject);
mgr.updateIssue(newIssue);
Issue reloadedFromRedmineIssue = mgr.getIssueById(newIssue.getId());
Assert.assertEquals(
"Checking if 'update issue' operation changed the 'subject' field",
changedSubject, reloadedFromRedmineIssue.getSubject());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
/**
* Tests the retrieval of an {@link Issue} by its ID.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetIssueById() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Issue issue = new Issue();
String originalSubject = "Issue " + new Date();
issue.setSubject(originalSubject);
Issue newIssue = mgr.createIssue(projectKey, issue);
Issue reloadedFromRedmineIssue = mgr.getIssueById(newIssue.getId());
Assert.assertEquals(
"Checking if 'get issue by ID' operation returned issue with same 'subject' field",
originalSubject, reloadedFromRedmineIssue.getSubject());
Tracker tracker = reloadedFromRedmineIssue.getTracker();
Assert.assertNotNull("Tracker of issue should not be null", tracker);
Assert.assertNotNull("ID of tracker of issue should not be null", tracker.getId());
Assert.assertNotNull("Name of tracker of issue should not be null", tracker.getName());
}
@Test
public void testGetProjects() {
try {
List<Project> projects = mgr.getProjects();
Assert.assertTrue(projects.size() > 0);
boolean found = false;
for (Project project : projects) {
if (project.getIdentifier().equals(projectKey)) {
found = true;
break;
}
}
if (!found) {
Assert.fail("Our project with key '" + projectKey + "' is not found on the server");
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test
public void testGetIssues() {
try {
// create at least 1 issue
Issue issueToCreate = new Issue();
issueToCreate.setSubject("testGetIssues: " + new Date());
Issue newIssue = mgr.createIssue(projectKey, issueToCreate);
List<Issue> issues = mgr.getIssues(projectKey, null);
logger.debug("getIssues() loaded " + issues.size() + " issues");//using query #" + queryIdIssuesCreatedLast2Days);
Assert.assertTrue(issues.size() > 0);
boolean found = false;
for (Issue issue : issues) {
if (issue.getId().equals(newIssue.getId())) {
found = true;
break;
}
}
if (!found) {
Assert.fail("getIssues() didn't return the issue we just created. The query "
+ " must have returned all issues created during the last 2 days");
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test(expected = NotFoundException.class)
public void testGetIssuesInvalidQueryId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
Integer invalidQueryId = 9999999;
mgr.getIssues(projectKey, invalidQueryId);
}
@Test
public void testCreateProject() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Project projectToCreate = generateRandomProject();
String key = null;
try {
Project createdProject = mgr.createProject(projectToCreate);
key = createdProject.getIdentifier();
Assert.assertNotNull("checking that a non-null project is returned", createdProject);
Assert.assertEquals(projectToCreate.getIdentifier(), createdProject.getIdentifier());
Assert.assertEquals(projectToCreate.getName(), createdProject.getName());
Assert.assertEquals(projectToCreate.getDescription(), createdProject.getDescription());
Assert.assertEquals(projectToCreate.getHomepage(), createdProject.getHomepage());
List<Tracker> trackers = createdProject.getTrackers();
Assert.assertNotNull("checking that project has some trackers", trackers);
Assert.assertTrue("checking that project has some trackers", !(trackers.isEmpty()));
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
if (key != null) {
mgr.deleteProject(key);
}
}
}
@Test
public void testCreateGetUpdateDeleteProject() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Project projectToCreate = generateRandomProject();
String key = null;
try {
projectToCreate.setIdentifier("id" + new Date().getTime());
logger.debug("trying to create a project with id " + projectToCreate.getIdentifier());
Project createdProject = mgr.createProject(projectToCreate);
key = createdProject.getIdentifier();
String newDescr = "NEW123";
String newName = "new name here";
createdProject.setName(newName);
createdProject.setDescription(newDescr);
mgr.updateProject(createdProject);
Project updatedProject = mgr.getProjectByKey(key);
Assert.assertNotNull(updatedProject);
Assert.assertEquals(createdProject.getIdentifier(), updatedProject.getIdentifier());
Assert.assertEquals(newName, updatedProject.getName());
Assert.assertEquals(newDescr, updatedProject.getDescription());
List<Tracker> trackers = updatedProject.getTrackers();
Assert.assertNotNull("checking that project has some trackers", trackers);
Assert.assertTrue("checking that project has some trackers", !(trackers.isEmpty()));
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
} finally {
if (key != null) {
mgr.deleteProject(key);
}
}
}
@Test
public void testCreateProjectFailsWithReservedIdentifier() throws Exception {
Project projectToCreate = new Project();
projectToCreate.setName("new");
projectToCreate.setIdentifier("new");
String key = null;
try {
Project createdProject = mgr.createProject(projectToCreate);
// in case if the creation haven't failed (although it should have had!),
// need to cleanup - delete this project
key = createdProject.getIdentifier();
} catch (RedmineException e) {
Assert.assertNotNull(e.getErrors());
Assert.assertEquals(1, e.getErrors().size());
Assert.assertEquals("Identifier is reserved", e.getErrors().get(0));
} finally {
if (key != null) {
mgr.deleteProject(key);
}
}
}
private static Project generateRandomProject() {
Project project = new Project();
Long timeStamp = Calendar.getInstance().getTimeInMillis();
String key = "projkey" + timeStamp;
String name = "project number " + timeStamp;
String description = "some description for the project";
project.setIdentifier(key);
project.setName(name);
project.setDescription(description);
project.setHomepage("www.randompage" + timeStamp + ".com");
return project;
}
@Test
public void testCreateIssueNonUnicodeSymbols() {
try {
String nonLatinSymbols = "Example with accents Ao";
Issue toCreate = new Issue();
toCreate.setSubject(nonLatinSymbols);
Issue created = mgr.createIssue(projectKey, toCreate);
Assert.assertEquals(nonLatinSymbols, created.getSubject());
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void testCreateIssueSummaryOnly() {
try {
Issue issueToCreate = new Issue();
issueToCreate.setSubject("This is the summary line 123");
Issue newIssue = mgr.createIssue(projectKey, issueToCreate);
Assert.assertNotNull("Checking returned result", newIssue);
Assert.assertNotNull("New issue must have some ID", newIssue.getId());
// check AUTHOR
Integer EXPECTED_AUTHOR_ID = getOurUser().getId();
Assert.assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthor().getId());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test(expected = NotFoundException.class)
public void testCreateIssueInvalidProjectKey() throws IOException, AuthenticationException, RedmineException, NotFoundException {
Issue issueToCreate = new Issue();
issueToCreate.setSubject("Summary line 100");
mgr.createIssue("someNotExistingProjectKey", issueToCreate);
}
@Test(expected = NotFoundException.class)
public void testGetProjectNonExistingId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.getProjectByKey("some-non-existing-key");
}
@Test(expected = NotFoundException.class)
public void testDeleteNonExistingProject() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.deleteProject("some-non-existing-key");
}
@Test(expected = NotFoundException.class)
public void testGetIssueNonExistingId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
int someNonExistingID = 999999;
mgr.getIssueById(someNonExistingID);
}
@Test(expected = NotFoundException.class)
public void testUpdateIssueNonExistingId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
int nonExistingId = 999999;
Issue issue = new Issue();
issue.setId(nonExistingId);
mgr.updateIssue(issue);
}
@Test
public void testGetUsers() {
try {
List<User> users = mgr.getUsers();
Assert.assertTrue(users.size() > 0);
// boolean found = false;
// for (Project project : projects) {
// if (project.getIdentifier().equals(projectKey)) {
// found = true;
// break;
// if (!found) {
// fail("Our project with key '" + projectKey+"' is not found on the server");
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test
public void testGetCurrentUser() throws IOException, AuthenticationException, RedmineException, NotFoundException {
User currentUser = mgr.getCurrentUser();
Assert.assertEquals(getOurUser().getId(), currentUser.getId());
Assert.assertEquals(getOurUser().getLogin(), currentUser.getLogin());
}
@Test
public void testGetUserById() throws IOException, AuthenticationException, NotFoundException, RedmineException {
User loadedUser = mgr.getUserById(getOurUser().getId());
Assert.assertEquals(getOurUser().getId(), loadedUser.getId());
Assert.assertEquals(getOurUser().getLogin(), loadedUser.getLogin());
}
@Test(expected = NotFoundException.class)
public void testGetUserNonExistingId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.getUserById(999999);
}
@Test(expected = NotFoundException.class)
public void testInvalidGetCurrentUser() throws IOException, AuthenticationException, RedmineException, NotFoundException {
RedmineManager invalidManager = new RedmineManager(testConfig.getURI() + "/INVALID");
invalidManager.setLogin("Invalid");
invalidManager.setPassword("Invalid");
invalidManager.getCurrentUser();
}
@Test
public void testCreateUser() throws IOException, AuthenticationException, NotFoundException {
try {
User userToCreate = generateRandomUser();
User createdUser = mgr.createUser(userToCreate);
Assert.assertNotNull("checking that a non-null project is returned", createdUser);
Assert.assertEquals(userToCreate.getLogin(), createdUser.getLogin());
Assert.assertEquals(userToCreate.getFirstName(), createdUser.getFirstName());
Assert.assertEquals(userToCreate.getLastName(), createdUser.getLastName());
Integer id = createdUser.getId();
Assert.assertNotNull(id);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
private static User generateRandomUser() {
User user = new User();
user.setFirstName("fname");
user.setLastName("lname");
long randomNumber = new Date().getTime();
user.setLogin("login" + randomNumber);
user.setMail("somemail" + randomNumber + "@somedomain.com");
user.setPassword("zzzz");
return user;
}
@Test
public void testUpdateUser() throws IOException, AuthenticationException, NotFoundException {
User userToCreate = new User();
userToCreate.setFirstName("fname2");
userToCreate.setLastName("lname2");
long randomNumber = new Date().getTime();
userToCreate.setLogin("login33" + randomNumber);
userToCreate.setMail("email" + randomNumber + "@somedomain.com");
userToCreate.setPassword("1234");
try {
User createdUser = mgr.createUser(userToCreate);
Integer userId = createdUser.getId();
Assert.assertNotNull("checking that a non-null project is returned", createdUser);
String newFirstName = "fnameNEW";
String newLastName = "lnameNEW";
String newMail = "newmail" + randomNumber + "@asd.com";
createdUser.setFirstName(newFirstName);
createdUser.setLastName(newLastName);
createdUser.setMail(newMail);
mgr.updateUser(createdUser);
User updatedUser = mgr.getUserById(userId);
Assert.assertEquals(newFirstName, updatedUser.getFirstName());
Assert.assertEquals(newLastName, updatedUser.getLastName());
Assert.assertEquals(newMail, updatedUser.getMail());
Assert.assertEquals(userId, updatedUser.getId());
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void userCanBeDeleted() throws IOException, AuthenticationException, RedmineException, NotFoundException {
User user = generateRandomUser();
User createdUser = mgr.createUser(user);
Integer newUserId = createdUser.getId();
try {
mgr.deleteUser(newUserId);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
try {
mgr.getUserById(newUserId);
fail("Must have failed with NotFoundException because we tried to delete the user");
} catch (NotFoundException e) {
// ignore: the user should not be found
}
}
@Test(expected = NotFoundException.class)
public void deletingNonExistingUserThrowsNFE() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.deleteUser(999999);
}
@Test
public void testGetIssuesPaging() {
try {
// create 27 issues. default page size is 25.
createIssues(27);
// mgr.setObjectsPerPage(5); <-- does not work now
List<Issue> issues = mgr.getIssues(projectKey, null);
logger.debug("testGetIssuesPaging() loaded " + issues.size() + " issues");//using query #" + queryIdIssuesCreatedLast2Days);
Assert.assertTrue(issues.size() > 26);
Set<Issue> issueSet = new HashSet<Issue>(issues);
Assert.assertEquals(issues.size(), issueSet.size());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
private List<Issue> createIssues(int issuesNumber) throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<Issue> issues = new ArrayList<Issue>(issuesNumber);
for (int i = 0; i < issuesNumber; i++) {
Issue issueToCreate = new Issue();
issueToCreate.setSubject("some issue " + i + " " + new Date());
Issue issue = mgr.createIssue(projectKey, issueToCreate);
issues.add(issue);
}
return issues;
}
private Issue createIssue() throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<Issue> createIssues = createIssues(1);
return createIssues.get(0);
}
private Issue generateRandomIssue() {
Random r = new Random();
Issue issue = new Issue();
issue.setSubject("some issue " + r.nextInt() + " " + new Date());
return issue;
}
@Test
public void testProjectsAllPagesLoaded() throws IOException, AuthenticationException, NotFoundException, URISyntaxException, RedmineException {
int NUM = 27; // must be larger than 25, which is a default page size in Redmine
List<Project> projects = createProjects(NUM);
List<Project> loadedProjects = mgr.getProjects();
Assert.assertTrue(
"Number of projects loaded from the server must be bigger than "
+ NUM + ", but it's " + loadedProjects.size(),
loadedProjects.size() > NUM);
deleteProjects(projects);
}
private List<Project> createProjects(int num) throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<Project> projects = new ArrayList<Project>(num);
for (int i = 0; i < num; i++) {
Project projectToCreate = generateRandomProject();
Project p = mgr.createProject(projectToCreate);
projects.add(p);
}
return projects;
}
private void deleteProjects(List<Project> projects) throws IOException, AuthenticationException, NotFoundException, RedmineException {
for (Project p : projects) {
mgr.deleteProject(p.getIdentifier());
}
}
@Test
public void testGetTimeEntries() throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<TimeEntry> list = mgr.getTimeEntries();
Assert.assertNotNull(list);
// boolean found = false;
// for (Project project : projects) {
// if (project.getIdentifier().equals(projectKey)) {
// found = true;
// break;
// if (!found) {
// fail("Our project with key '" + projectKey+"' is not found on the server");
}
@Test
public void testCreateGetTimeEntry() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Issue issue = createIssues(1).get(0);
Integer issueId = issue.getId();
TimeEntry entry = new TimeEntry();
Float hours = 11f;
entry.setHours(hours);
entry.setIssueId(issueId);
// TODO We don't know activities IDs!
entry.setActivityId(ACTIVITY_ID);
TimeEntry createdEntry = mgr.createTimeEntry(entry);
Assert.assertNotNull(createdEntry);
logger.debug("Created time entry " + createdEntry);
Assert.assertEquals(hours, createdEntry.getHours());
Float newHours = 22f;
createdEntry.setHours(newHours);
mgr.updateTimeEntry(createdEntry);
TimeEntry updatedEntry = mgr.getTimeEntry(createdEntry.getId());
Assert.assertEquals(newHours, updatedEntry.getHours());
}
@Test(expected = NotFoundException.class)
public void testCreateDeleteTimeEntry() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Issue issue = createIssues(1).get(0);
Integer issueId = issue.getId();
TimeEntry entry = new TimeEntry();
Float hours = 4f;
entry.setHours(hours);
entry.setIssueId(issueId);
entry.setActivityId(ACTIVITY_ID);
TimeEntry createdEntry = mgr.createTimeEntry(entry);
Assert.assertNotNull(createdEntry);
mgr.deleteTimeEntry(createdEntry.getId());
mgr.getTimeEntry(createdEntry.getId());
}
@Test
public void testGetTimeEntriesForIssue() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Issue issue = createIssues(1).get(0);
Integer issueId = issue.getId();
Float hours1 = 2f;
Float hours2 = 7f;
Float totalHoursExpected = hours1 + hours2;
TimeEntry createdEntry1 = createTimeEntry(issueId, hours1);
TimeEntry createdEntry2 = createTimeEntry(issueId, hours2);
Assert.assertNotNull(createdEntry1);
Assert.assertNotNull(createdEntry2);
List<TimeEntry> entries = mgr.getTimeEntriesForIssue(issueId);
Assert.assertEquals(2, entries.size());
Float totalTime = 0f;
for (TimeEntry timeEntry : entries) {
totalTime += timeEntry.getHours();
}
Assert.assertEquals(totalHoursExpected, totalTime);
}
private TimeEntry createTimeEntry(Integer issueId, float hours) throws IOException,
AuthenticationException, NotFoundException, RedmineException {
TimeEntry entry = new TimeEntry();
entry.setHours(hours);
entry.setIssueId(issueId);
entry.setActivityId(ACTIVITY_ID);
TimeEntry createdEntry = mgr.createTimeEntry(entry);
return createdEntry;
}
@Test(expected = NotFoundException.class)
public void testDeleteIssue() throws IOException, AuthenticationException,
NotFoundException, RedmineException {
Issue issue = createIssues(1).get(0);
Issue retrievedIssue = mgr.getIssueById(issue.getId());
Assert.assertEquals(issue, retrievedIssue);
mgr.deleteIssue(issue.getId());
mgr.getIssueById(issue.getId());
}
@Test
public void testUpdateIssueSpecialXMLtags() throws Exception {
Issue issue = createIssues(1).get(0);
String newSubject = "\"text in quotes\" and <xml> tags";
String newDescription = "<teghere>\"abc\"</here>";
issue.setSubject(newSubject);
issue.setDescription(newDescription);
mgr.updateIssue(issue);
Issue updatedIssue = mgr.getIssueById(issue.getId());
Assert.assertEquals(newSubject, updatedIssue.getSubject());
Assert.assertEquals(newDescription, updatedIssue.getDescription());
}
@Test
public void testCustomFields() throws Exception {
Issue issue = createIssues(1).get(0);
// default empty values
Assert.assertEquals(2, issue.getCustomFields().size());
// TODO update this!
int id1 = 1; // TODO this is pretty much a hack, we don't generally know these ids!
String custom1FieldName = "my_custom_1";
String custom1Value = "some value 123";
int id2 = 2;
String custom2FieldName = "custom_boolean_1";
String custom2Value = "true";
issue.setCustomFields(new ArrayList<CustomField>());
issue.getCustomFields().add(new CustomField(id1, custom1FieldName, custom1Value));
issue.getCustomFields().add(new CustomField(id2, custom2FieldName, custom2Value));
mgr.updateIssue(issue);
Issue updatedIssue = mgr.getIssueById(issue.getId());
Assert.assertEquals(2, updatedIssue.getCustomFields().size());
Assert.assertEquals(custom1Value, updatedIssue.getCustomField(custom1FieldName));
Assert.assertEquals(custom2Value, updatedIssue.getCustomField(custom2FieldName));
}
@Test
public void testUpdateIssueDoesNotChangeEstimatedTime() {
try {
Issue issue = new Issue();
String originalSubject = "Issue " + new Date();
issue.setSubject(originalSubject);
Issue newIssue = mgr.createIssue(projectKey, issue);
Assert.assertEquals("Estimated hours must be NULL", null, newIssue.getEstimatedHours());
mgr.updateIssue(newIssue);
Issue reloadedFromRedmineIssue = mgr.getIssueById(newIssue.getId());
Assert.assertEquals("Estimated hours must be NULL", null, reloadedFromRedmineIssue.getEstimatedHours());
} catch (Exception e) {
Assert.fail();
}
}
@Test
public void testCreateSubProject() {
Project createdMainProject = null;
try {
createdMainProject = createProject();
Project subProject = createSubProject(createdMainProject);
Assert.assertEquals("Must have correct parent ID",
createdMainProject.getId(), subProject.getParentId());
} catch (Exception e) {
Assert.fail();
} finally {
if (createdMainProject != null) {
try {
mgr.deleteProject(createdMainProject.getIdentifier());
} catch (Exception e) {
Assert.fail();
}
}
}
}
private Project createProject() throws IOException, AuthenticationException, RedmineException {
Project mainProject = new Project();
long id = new Date().getTime();
mainProject.setName("project" + id);
mainProject.setIdentifier("project" + id);
return mgr.createProject(mainProject);
}
private Project createSubProject(Project parent) throws IOException, AuthenticationException, RedmineException {
Project project = new Project();
long id = new Date().getTime();
project.setName("sub_pr" + id);
project.setIdentifier("subpr" + id);
project.setParentId(parent.getId());
return mgr.createProject(project);
}
@Test
public void testIssueDoneRatio() {
try {
Issue issue = new Issue();
String subject = "Issue " + new Date();
issue.setSubject(subject);
Issue createdIssue = mgr.createIssue(projectKey, issue);
Assert.assertEquals("Initial 'done ratio' must be 0", (Integer) 0, createdIssue.getDoneRatio());
Integer doneRatio = 50;
createdIssue.setDoneRatio(doneRatio);
mgr.updateIssue(createdIssue);
Integer issueId = createdIssue.getId();
Issue reloadedFromRedmineIssue = mgr.getIssueById(issueId);
Assert.assertEquals(
"Checking if 'update issue' operation changed 'done ratio' field",
doneRatio, reloadedFromRedmineIssue.getDoneRatio());
Integer invalidDoneRatio = 130;
reloadedFromRedmineIssue.setDoneRatio(invalidDoneRatio);
try {
mgr.updateIssue(reloadedFromRedmineIssue);
} catch (RedmineException e) {
Assert.assertEquals("Must be 1 error", 1, e.getErrors().size());
Assert.assertEquals("Checking error text", "% Done is not included in the list", e.getErrors().get(0).toString());
}
Issue reloadedFromRedmineIssueUnchanged = mgr.getIssueById(issueId);
Assert.assertEquals(
"'done ratio' must have remained unchanged after invalid value",
doneRatio, reloadedFromRedmineIssueUnchanged.getDoneRatio());
} catch (Exception e) {
Assert.fail();
}
}
@Test
public void testIssueNullDescriptionDoesNotEraseIt() {
try {
Issue issue = new Issue();
String subject = "Issue " + new Date();
String descr = "Some description";
issue.setSubject(subject);
issue.setDescription(descr);
Issue createdIssue = mgr.createIssue(projectKey, issue);
Assert.assertEquals("Checking description", descr, createdIssue.getDescription());
createdIssue.setDescription(null);
mgr.updateIssue(createdIssue);
Integer issueId = createdIssue.getId();
Issue reloadedFromRedmineIssue = mgr.getIssueById(issueId);
Assert.assertEquals(
"Description must not be erased",
descr, reloadedFromRedmineIssue.getDescription());
reloadedFromRedmineIssue.setDescription("");
mgr.updateIssue(reloadedFromRedmineIssue);
Issue reloadedFromRedmineIssueUnchanged = mgr.getIssueById(issueId);
Assert.assertEquals(
"Description must be erased",
"", reloadedFromRedmineIssueUnchanged.getDescription());
} catch (Exception e) {
Assert.fail();
}
}
@Test
public void testIssueJournals() {
try {
// create at least 1 issue
Issue issueToCreate = new Issue();
issueToCreate.setSubject("testGetIssues: " + new Date());
Issue newIssue = mgr.createIssue(projectKey, issueToCreate);
Issue loadedIssueWithJournals = mgr.getIssueById(newIssue.getId(), INCLUDE.journals);
Assert.assertTrue(loadedIssueWithJournals.getJournals().isEmpty());
String commentDescribingTheUpdate = "some comment describing the issue update";
loadedIssueWithJournals.setSubject("new subject");
loadedIssueWithJournals.setNotes(commentDescribingTheUpdate);
mgr.updateIssue(loadedIssueWithJournals);
Issue loadedIssueWithJournals2 = mgr.getIssueById(newIssue.getId(), INCLUDE.journals);
Assert.assertEquals(1, loadedIssueWithJournals2.getJournals().size());
Journal journalItem = loadedIssueWithJournals2.getJournals().get(0);
Assert.assertEquals(commentDescribingTheUpdate, journalItem.getNotes());
User ourUser = getOurUser();
// can't compare User objects because either of them is not completely filled
Assert.assertEquals(ourUser.getId(), journalItem.getUser().getId());
Assert.assertEquals(ourUser.getFirstName(), journalItem.getUser().getFirstName());
Assert.assertEquals(ourUser.getLastName(), journalItem.getUser().getLastName());
Issue loadedIssueWithoutJournals = mgr.getIssueById(newIssue.getId());
Assert.assertTrue(loadedIssueWithoutJournals.getJournals().isEmpty());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test
public void testCreateRelation() {
try {
List<Issue> issues = createIssues(2);
Issue src = issues.get(0);
Issue target = issues.get(1);
String relationText = IssueRelation.TYPE.precedes.toString();
IssueRelation r = mgr.createRelation(src.getId(), target.getId(), relationText);
assertEquals(src.getId(), r.getIssueId());
Assert.assertEquals(target.getId(), r.getIssueToId());
Assert.assertEquals(relationText, r.getType());
} catch (Exception e) {
Assert.fail(e.toString());
}
}
private IssueRelation createTwoRelatedIssues() throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<Issue> issues = createIssues(2);
Issue src = issues.get(0);
Issue target = issues.get(1);
String relationText = IssueRelation.TYPE.precedes.toString();
return mgr.createRelation(src.getId(), target.getId(), relationText);
}
@Test
public void issueRelationsAreCreatedAndLoadedOK() {
try {
IssueRelation relation = createTwoRelatedIssues();
Issue issue = mgr.getIssueById(relation.getIssueId(), INCLUDE.relations);
Issue issueTarget = mgr.getIssueById(relation.getIssueToId(), INCLUDE.relations);
Assert.assertEquals(1, issue.getRelations().size());
Assert.assertEquals(1, issueTarget.getRelations().size());
IssueRelation relation1 = issue.getRelations().get(0);
assertEquals(issue.getId(), relation1.getIssueId());
assertEquals(issueTarget.getId(), relation1.getIssueToId());
assertEquals("precedes", relation1.getType());
assertEquals((Integer) 0, relation1.getDelay());
IssueRelation reverseRelation = issueTarget.getRelations().get(0);
// both forward and reverse relations are the same!
Assert.assertEquals(relation1, reverseRelation);
} catch (Exception e) {
Assert.fail(e.toString());
}
}
@Ignore
@Test
public void issueFixVersionIsSet() throws Exception {
String existingProjectKey = "test";
Issue toCreate = generateRandomIssue();
Version v = new Version();
String versionName = "1.0";
v.setName("1.0");
v.setId(1);
toCreate.setTargetVersion(v);
Issue createdIssue = mgr.createIssue(existingProjectKey, toCreate);
Assert.assertNotNull(createdIssue.getTargetVersion());
Assert.assertEquals(createdIssue.getTargetVersion().getName(), versionName);
}
@Ignore
@Test
public void testGetProjectsIncludesTrackers() {
try {
List<Project> projects = mgr.getProjects();
Assert.assertTrue(projects.size() > 0);
Project p1 = projects.get(0);
Assert.assertNotNull(p1.getTrackers());
// XXX there could be a case when a project does not have any trackers
// need to create a project with some trackers to make this test deterministic
Assert.assertTrue(!p1.getTrackers().isEmpty());
logger.debug("Created trackers " + p1.getTrackers());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Ignore
@Test
public void testSpentTime() {
// TODO need to use "Time Entries"
// float spentHours = 12.5f;
// issueToCreate.setSpentHours(spentHours);
// check SPENT TIME
// assertEquals((Float) spentHours, newIssue.getSpentHours());
}
@Test
public void testViolateTimeEntryConstraint_ProjectOrIssueID_issue66() throws IOException, AuthenticationException, RedmineException {
TimeEntry timeEntry = new TimeEntry();
timeEntry.setActivityId(ACTIVITY_ID);
timeEntry.setSpentOn(new Date());
timeEntry.setHours(1.5f);
try {
mgr.createTimeEntry(timeEntry);
} catch (IllegalArgumentException e) {
logger.debug("create: Got expected IllegalArgumentException for invalid Time Entry (issue
} catch (Exception e) {
e.printStackTrace();
fail("Got unexpected " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
try {
mgr.updateTimeEntry(timeEntry);
} catch (IllegalArgumentException e) {
logger.debug("update: Got expected IllegalArgumentException for invalid Time Entry (issue
} catch (Exception e) {
e.printStackTrace();
fail("Got unexpected " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
// Now can try to verify with project ID (only test with issue ID seems to be already covered)
int projectId = mgr.getProjects().get(0).getId();
timeEntry.setProjectId(projectId);
try {
TimeEntry created = mgr.createTimeEntry(timeEntry);
logger.debug("Created time entry " + created);
} catch (Exception e) {
e.printStackTrace();
fail("Unexpected " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
/**
* tests the retrieval of statuses.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetStatuses() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// TODO we should create some statuses first, but the Redmine Java API does not support this presently
List<IssueStatus> statuses = mgr.getStatuses();
Assert.assertFalse("Expected list of statuses not to be empty", statuses.isEmpty());
for (IssueStatus issueStatus : statuses) {
// asserts on status
assertNotNull("ID of status must not be null", issueStatus.getId());
assertNotNull("Name of status must not be null", issueStatus.getName());
}
}
/**
* tests the creation of an invalid {@link Version}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test(expected = IllegalArgumentException.class)
public void testCreateInvalidVersion() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Version version = new Version(null, "Invalid test version " + UUID.randomUUID().toString());
mgr.createVersion(version);
}
/**
* tests the deletion of an invalid {@link Version}. Expects a
* {@link NotFoundException} to be thrown.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test(expected = NotFoundException.class)
public void testDeleteInvalidVersion() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// create new test version
Version version = new Version(null, "Invalid test version " + UUID.randomUUID().toString());
version.setDescription("An invalid test version created by " + this.getClass());
// set invalid id
version.setId(-1);
// now try to delete version
mgr.deleteVersion(version);
}
/**
* tests the deletion of a {@link Version}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testDeleteVersion() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
// create new test version
Version version = new Version(project, "Test version " + UUID.randomUUID().toString());
version.setDescription("A test version created by " + this.getClass());
version.setStatus("open");
Version newVersion = mgr.createVersion(version);
// assert new test version
Assert.assertNotNull("Expected new version not to be null", newVersion);
// now delete version
mgr.deleteVersion(newVersion);
// assert that the version is gone
List<Version> versions = mgr.getVersions(project.getId());
Assert.assertTrue("List of versions of test project must be empty now but is " + versions, versions.isEmpty());
}
/**
* tests the retrieval of {@link Version}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetVersions() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
// create some versions
Version testVersion1 = mgr.createVersion(new Version(project, "Version" + UUID.randomUUID()));
Version testVersion2 = mgr.createVersion(new Version(project, "Version" + UUID.randomUUID()));
try {
List<Version> versions = mgr.getVersions(project.getId());
Assert.assertEquals("Wrong number of versions for project " + project.getName() + " delivered by Redmine Java API", 2, versions.size());
for (Version version : versions) {
// assert version
Assert.assertNotNull("ID of version must not be null", version.getId());
Assert.assertNotNull("Name of version must not be null", version.getName());
Assert.assertNotNull("Project of version must not be null", version.getProject());
}
} finally {
// scrub test versions
if (testVersion1 != null) {
mgr.deleteVersion(testVersion1);
}
if (testVersion2 != null) {
mgr.deleteVersion(testVersion2);
}
}
}
/**
* tests the creation and deletion of a {@link IssueCategory}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testCreateAndDeleteIssueCategory() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
// create new test category
IssueCategory category = new IssueCategory(project, "Category" + new Date().getTime());
category.setAssignee(getOurUser());
IssueCategory newIssueCategory = mgr.createCategory(category);
// assert new test category
Assert.assertNotNull("Expected new category not to be null", newIssueCategory);
Assert.assertNotNull("Expected project of new category not to be null", newIssueCategory.getProject());
Assert.assertNotNull("Expected assignee of new category not to be null", newIssueCategory.getAssignee());
// now delete category
mgr.deleteCategory(newIssueCategory);
// assert that the category is gone
List<IssueCategory> categories = mgr.getCategories(project.getId());
Assert.assertTrue("List of categories of test project must be empty now but is " + categories, categories.isEmpty());
}
/**
* tests the retrieval of {@link IssueCategory}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetIssueCategories() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
// create some categories
IssueCategory testIssueCategory1 = new IssueCategory(project, "Category" + new Date().getTime());
testIssueCategory1.setAssignee(getOurUser());
IssueCategory newIssueCategory1 = mgr.createCategory(testIssueCategory1);
IssueCategory testIssueCategory2 = new IssueCategory(project, "Category" + new Date().getTime());
testIssueCategory2.setAssignee(getOurUser());
IssueCategory newIssueCategory2 = mgr.createCategory(testIssueCategory2);
try {
List<IssueCategory> categories = mgr.getCategories(project.getId());
Assert.assertEquals("Wrong number of categories for project " + project.getName() + " delivered by Redmine Java API", 2, categories.size());
for (IssueCategory category : categories) {
// assert category
Assert.assertNotNull("ID of category must not be null", category.getId());
Assert.assertNotNull("Name of category must not be null", category.getName());
Assert.assertNotNull("Project of category must not be null", category.getProject());
Assert.assertNotNull("Assignee of category must not be null", category.getAssignee());
}
} finally {
// scrub test categories
if (newIssueCategory1 != null) {
mgr.deleteCategory(newIssueCategory1);
}
if (newIssueCategory2 != null) {
mgr.deleteCategory(newIssueCategory2);
}
}
}
/**
* tests the creation of an invalid {@link IssueCategory}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test(expected = IllegalArgumentException.class)
public void testCreateInvalidIssueCategory() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// create new invalid test category
IssueCategory category = new IssueCategory(null, "InvalidCategory" + new Date().getTime());
mgr.createCategory(category);
}
/**
* tests the deletion of an invalid {@link IssueCategory}. Expects a
* {@link NotFoundException} to be thrown.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test(expected = NotFoundException.class)
public void testDeleteInvalidIssueCategory() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// create new test category
IssueCategory category = new IssueCategory(null, "InvalidCategory" + new Date().getTime());
// set invalid id
category.setId(-1);
// now try to delete category
mgr.deleteCategory(category);
}
/**
* Tests the retrieval of {@link Tracker}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetTrackers() throws RedmineException, IOException, AuthenticationException, NotFoundException {
List<Tracker> trackers = mgr.getTrackers();
assertNotNull("List of trackers returned should not be null", trackers);
assertFalse("List of trackers returned should not be empty", trackers.isEmpty());
for (Tracker tracker : trackers) {
assertNotNull("Tracker returned should not be null", tracker);
assertNotNull("ID of tracker returned should not be null", tracker.getId());
assertNotNull("Name of tracker returned should not be null", tracker.getName());
}
}
/**
* Tests the retrieval of an {@link Issue}, inlcuding the {@link org.redmine.ta.beans.Attachment}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetIssueWithAttachments() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Issue newIssue = null;
try {
// create at least 1 issue
Issue issueToCreate = new Issue();
issueToCreate.setSubject("testGetIssueAttachment_" + UUID.randomUUID());
newIssue = mgr.createIssue(projectKey, issueToCreate);
// TODO create test attachments for the issue once the Redmine REST API allows for it
// retrieve issue attachments
Issue retrievedIssue = mgr.getIssueById(newIssue.getId(), INCLUDE.attachments);
Assert.assertNotNull("List of attachments retrieved for issue " + newIssue.getId() + " delivered by Redmine Java API should not be null", retrievedIssue.getAttachments());
// TODO assert attachments once we actually receive ones for our test issue
} finally {
// scrub test issue
if (newIssue != null) {
mgr.deleteIssue(newIssue.getId());
}
}
}
/**
* Tests the retrieval of an {@link org.redmine.ta.beans.Attachment} by its ID.
* TODO reactivate once the Redmine REST API allows for creating attachments
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
// @Test
public void testGetAttachmentById() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// TODO where do we get a valid attachment number from? We can't create an attachment by our own for the test as the Redmine REST API does not support that.
int attachmentID = 1;
// retrieve issue attachment
Attachment attachment = mgr.getAttachmentById(attachmentID);
Assert.assertNotNull("Attachment retrieved by ID " + attachmentID + " should not be null", attachment);
Assert.assertNotNull("Content URL of attachment retrieved by ID " + attachmentID + " should not be null", attachment.getContentURL());
// TODO more asserts on the attachment once this delivers an attachment
}
/**
* Tests the download of the content of an {@link org.redmine.ta.beans.Attachment}.
* TODO reactivate once the Redmine REST API allows for creating attachments
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
// @Test
public void testDownloadAttachmentContent() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// TODO where do we get a valid attachment number from? We can't create an attachment by our own for the test as the Redmine REST API does not support that.
int attachmentID = 1;
// retrieve issue attachment
Attachment attachment = mgr.getAttachmentById(attachmentID);
// download attachment content
byte[] attachmentContent = mgr.downloadAttachmentContent(attachment);
Assert.assertNotNull("Download of content of attachment with content URL " + attachment.getContentURL() + " should not be null", attachmentContent);
}
/**
* Tests the creation and retrieval of an {@link org.redmine.ta.beans.Issue} with a {@link IssueCategory}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testCreateAndGetIssueWithCategory() throws RedmineException, IOException, AuthenticationException, NotFoundException {
IssueCategory newIssueCategory = null;
Issue newIssue = null;
try {
Project project = mgr.getProjectByKey(projectKey);
// create an issue category
IssueCategory category = new IssueCategory(project, "Category_" + new Date().getTime());
category.setAssignee(getOurUser());
newIssueCategory = mgr.createCategory(category);
// create an issue
Issue issueToCreate = new Issue();
issueToCreate.setSubject("testGetIssueWithCategory_" + UUID.randomUUID());
issueToCreate.setCategory(newIssueCategory);
newIssue = mgr.createIssue(projectKey, issueToCreate);
// retrieve issue
Issue retrievedIssue = mgr.getIssueById(newIssue.getId());
// assert retrieved category of issue
IssueCategory retrievedCategory = retrievedIssue.getCategory();
Assert.assertNotNull("Category retrieved for issue " + newIssue.getId() + " should not be null", retrievedCategory);
Assert.assertEquals("ID of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getId(), retrievedCategory.getId());
Assert.assertEquals("Name of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getName(), retrievedCategory.getName());
} finally {
// scrub test issue and category
if (newIssue != null) {
mgr.deleteIssue(newIssue.getId());
}
if (newIssueCategory != null) {
mgr.deleteCategory(newIssueCategory);
}
}
}
}
|
package cgeo.geocaching;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cgeo.geocaching.activity.ShowcaseViewBuilder;
import cgeo.geocaching.connector.ILoggingManager;
import cgeo.geocaching.connector.ImageResult;
import cgeo.geocaching.connector.LogResult;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.LogTypeTrackable;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.gcvote.GCVote;
import cgeo.geocaching.gcvote.GCVoteRatingBarUtil;
import cgeo.geocaching.gcvote.GCVoteRatingBarUtil.OnRatingChangeListener;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.twitter.Twitter;
import cgeo.geocaching.ui.dialog.DateDialog;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.AsyncTaskWithProgress;
import cgeo.geocaching.utils.DateUtils;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.LogTemplateProvider;
import cgeo.geocaching.utils.LogTemplateProvider.LogContext;
import com.github.amlcurran.showcaseview.targets.ActionItemTarget;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class LogCacheActivity extends AbstractLoggingActivity implements DateDialog.DateDialogParent {
private static final String SAVED_STATE_RATING = "cgeo.geocaching.saved_state_rating";
private static final String SAVED_STATE_TYPE = "cgeo.geocaching.saved_state_type";
private static final String SAVED_STATE_DATE = "cgeo.geocaching.saved_state_date";
private static final String SAVED_STATE_IMAGE_CAPTION = "cgeo.geocaching.saved_state_image_caption";
private static final String SAVED_STATE_IMAGE_DESCRIPTION = "cgeo.geocaching.saved_state_image_description";
private static final String SAVED_STATE_IMAGE_URI = "cgeo.geocaching.saved_state_image_uri";
private static final int SELECT_IMAGE = 101;
private LayoutInflater inflater = null;
private Geocache cache = null;
private String geocode = null;
private String text = null;
private List<LogType> possibleLogTypes = new ArrayList<>();
private List<TrackableLog> trackables = null;
protected @InjectView(R.id.tweet) CheckBox tweetCheck;
protected @InjectView(R.id.tweet_box) LinearLayout tweetBox;
protected @InjectView(R.id.log_password_box) LinearLayout logPasswordBox;
private SparseArray<TrackableLog> actionButtons;
private ILoggingManager loggingManager;
// Data to be saved while reconfiguring
private float rating;
private LogType typeSelected;
private Calendar date;
private String imageCaption;
private String imageDescription;
private Uri imageUri;
private boolean sendButtonEnabled;
public void onLoadFinished() {
if (loggingManager.hasLoaderError()) {
showErrorLoadingData();
return;
}
trackables = loggingManager.getTrackables();
possibleLogTypes = loggingManager.getPossibleLogTypes();
if (possibleLogTypes.isEmpty()) {
showErrorLoadingData();
return;
}
if (!possibleLogTypes.contains(typeSelected)) {
typeSelected = possibleLogTypes.get(0);
setType(typeSelected);
showToast(res.getString(R.string.info_log_type_changed));
}
initializeRatingBar();
enablePostButton(true);
initializeTrackablesAction();
updateTrackablesList();
showProgress(false);
}
private void showErrorLoadingData() {
showToast(res.getString(R.string.err_log_load_data));
showProgress(false);
}
private void initializeTrackablesAction() {
if (Settings.isTrackableAutoVisit()) {
for (final TrackableLog trackable : trackables) {
trackable.action = LogTypeTrackable.VISITED;
}
}
}
private void updateTrackablesList() {
if (CollectionUtils.isEmpty(trackables)) {
return;
}
if (inflater == null) {
inflater = getLayoutInflater();
}
actionButtons = new SparseArray<>();
final LinearLayout inventoryView = ButterKnife.findById(this, R.id.inventory);
inventoryView.removeAllViews();
for (final TrackableLog tb : trackables) {
final LinearLayout inventoryItem = (LinearLayout) inflater.inflate(R.layout.logcache_trackable_item, inventoryView, false);
final TextView codeView = ButterKnife.findById(inventoryItem, R.id.trackcode);
codeView.setText(tb.trackCode);
final TextView nameView = ButterKnife.findById(inventoryItem, R.id.name);
nameView.setText(tb.name);
final TextView actionButton = ButterKnife.findById(inventoryItem, R.id.action);
actionButton.setId(tb.id);
actionButtons.put(actionButton.getId(), tb);
actionButton.setText(tb.action.getLabel() + " ");
actionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
selectTrackableAction(view);
}
});
final String tbCode = tb.trackCode;
inventoryItem.setClickable(true);
ButterKnife.findById(inventoryItem, R.id.info).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
final Intent trackablesIntent = new Intent(LogCacheActivity.this, TrackableActivity.class);
trackablesIntent.putExtra(Intents.EXTRA_GEOCODE, tbCode);
startActivity(trackablesIntent);
}
});
inventoryView.addView(inventoryItem);
}
if (inventoryView.getChildCount() > 0) {
ButterKnife.findById(this, R.id.inventory_box).setVisibility(View.VISIBLE);
}
if (inventoryView.getChildCount() > 1) {
final LinearLayout inventoryChangeAllView = ButterKnife.findById(this, R.id.inventory_changeall);
final Button changeButton = ButterKnife.findById(inventoryChangeAllView, R.id.changebutton);
changeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
selectAllTrackablesAction();
}
});
inventoryChangeAllView.setVisibility(View.VISIBLE);
}
}
private void enablePostButton(final boolean enabled) {
sendButtonEnabled = enabled;
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.logcache_activity);
// Get parameters from intent and basic cache information from database
final Bundle extras = getIntent().getExtras();
if (extras != null) {
geocode = extras.getString(Intents.EXTRA_GEOCODE);
if (StringUtils.isBlank(geocode)) {
final String cacheid = extras.getString(Intents.EXTRA_ID);
if (StringUtils.isNotBlank(cacheid)) {
geocode = DataStore.getGeocodeForGuid(cacheid);
}
}
}
cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB);
invalidateOptionsMenuCompatible();
possibleLogTypes = cache.getPossibleLogTypes();
if (StringUtils.isNotBlank(cache.getName())) {
setTitle(res.getString(R.string.log_new_log) + ": " + cache.getName());
} else {
setTitle(res.getString(R.string.log_new_log) + ": " + cache.getGeocode());
}
initializeRatingBar();
// initialize with default values
setDefaultValues();
// Restore previous state
if (savedInstanceState != null) {
rating = savedInstanceState.getFloat(SAVED_STATE_RATING);
typeSelected = LogType.getById(savedInstanceState.getInt(SAVED_STATE_TYPE));
date.setTimeInMillis(savedInstanceState.getLong(SAVED_STATE_DATE));
imageCaption = savedInstanceState.getString(SAVED_STATE_IMAGE_CAPTION);
imageDescription = savedInstanceState.getString(SAVED_STATE_IMAGE_DESCRIPTION);
imageUri = Uri.parse(savedInstanceState.getString(SAVED_STATE_IMAGE_URI));
} else {
// If log had been previously saved, load it now, otherwise initialize signature as needed
final LogEntry log = DataStore.loadLogOffline(geocode);
if (log != null) {
typeSelected = log.type;
date.setTime(new Date(log.date));
text = log.log;
} else if (StringUtils.isNotBlank(Settings.getSignature())
&& Settings.isAutoInsertSignature()
&& StringUtils.isBlank(currentLogText())) {
insertIntoLog(LogTemplateProvider.applyTemplates(Settings.getSignature(), new LogContext(cache, null)), false);
}
}
enablePostButton(false);
final Button typeButton = ButterKnife.findById(this, R.id.type);
typeButton.setText(typeSelected.getL10n());
typeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
selectLogType();
}
});
final Button dateButton = ButterKnife.findById(this, R.id.date);
setDate(date);
dateButton.setOnClickListener(new DateListener());
final EditText logView = ButterKnife.findById(this, R.id.log);
if (StringUtils.isBlank(currentLogText()) && StringUtils.isNotBlank(text)) {
logView.setText(text);
Dialogs.moveCursorToEnd(logView);
}
tweetCheck.setChecked(true);
updateTweetBox(typeSelected);
updateLogPasswordBox(typeSelected);
loggingManager = cache.getLoggingManager(this);
loggingManager.init();
requestKeyboardForLogging();
}
private void initializeRatingBar() {
if (GCVote.isVotingPossible(cache)) {
GCVoteRatingBarUtil.initializeRatingBar(cache, getWindow().getDecorView().getRootView(), new OnRatingChangeListener() {
@Override
public void onRatingChanged(final float stars) {
rating = stars;
}
});
}
}
private void setDefaultValues() {
date = Calendar.getInstance();
rating = GCVote.NO_RATING;
typeSelected = cache.getDefaultLogType();
// it this is an attended event log, use the event date by default instead of the current date
if (cache.isEventCache() && DateUtils.isPastEvent(cache) && typeSelected == LogType.ATTENDED) {
date.setTime(cache.getHiddenDate());
}
text = null;
imageCaption = StringUtils.EMPTY;
imageDescription = StringUtils.EMPTY;
imageUri = Uri.EMPTY;
}
private void clearLog() {
cache.clearOfflineLog();
setDefaultValues();
setType(typeSelected);
setDate(date);
final EditText logView = ButterKnife.findById(this, R.id.log);
logView.setText(StringUtils.EMPTY);
final EditText logPasswordView = ButterKnife.findById(this, R.id.log_password);
logPasswordView.setText(StringUtils.EMPTY);
showToast(res.getString(R.string.info_log_cleared));
}
@Override
public void finish() {
saveLog(false);
super.finish();
}
@Override
public void onStop() {
saveLog(false);
super.onStop();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putDouble(SAVED_STATE_RATING, rating);
outState.putInt(SAVED_STATE_TYPE, typeSelected.id);
outState.putLong(SAVED_STATE_DATE, date.getTimeInMillis());
outState.putString(SAVED_STATE_IMAGE_URI, imageUri.getPath());
outState.putString(SAVED_STATE_IMAGE_CAPTION, imageCaption);
outState.putString(SAVED_STATE_IMAGE_DESCRIPTION, imageDescription);
}
@Override
public void setDate(final Calendar dateIn) {
date = dateIn;
final Button dateButton = ButterKnife.findById(this, R.id.date);
dateButton.setText(Formatter.formatShortDateVerbally(date.getTime().getTime()));
}
public void setType(final LogType type) {
final Button typeButton = ButterKnife.findById(this, R.id.type);
typeSelected = type;
typeButton.setText(typeSelected.getL10n());
updateTweetBox(type);
updateLogPasswordBox(type);
}
private void updateTweetBox(final LogType type) {
if (type == LogType.FOUND_IT && Settings.isUseTwitter() && Settings.isTwitterLoginValid()) {
tweetBox.setVisibility(View.VISIBLE);
} else {
tweetBox.setVisibility(View.GONE);
}
}
private void updateLogPasswordBox(final LogType type) {
if (type == LogType.FOUND_IT && cache.isLogPasswordRequired()) {
logPasswordBox.setVisibility(View.VISIBLE);
} else {
logPasswordBox.setVisibility(View.GONE);
}
}
private class DateListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
final DateDialog dateDialog = DateDialog.getInstance(date);
dateDialog.setCancelable(true);
dateDialog.show(getSupportFragmentManager(), "date_dialog");
}
}
private class Poster extends AsyncTaskWithProgress<String, StatusCode> {
public Poster(final Activity activity, final String progressMessage) {
super(activity, null, progressMessage, true);
}
@Override
protected StatusCode doInBackgroundInternal(final String[] logTexts) {
final String log = logTexts[0];
final String logPwd = logTexts.length > 1 ? logTexts[1] : null;
try {
final LogResult logResult = loggingManager.postLog(typeSelected, date, log, logPwd, trackables);
if (logResult.getPostLogResult() == StatusCode.NO_ERROR) {
// update geocache in DB
if (typeSelected.isFoundLog()) {
cache.setFound(true);
cache.setVisitedDate(date.getTimeInMillis());
}
DataStore.saveChangedCache(cache);
// update logs in DB
final ArrayList<LogEntry> newLogs = new ArrayList<>(cache.getLogs());
final LogEntry logNow = new LogEntry(date.getTimeInMillis(), typeSelected, log);
logNow.friend = true;
newLogs.add(0, logNow);
DataStore.saveLogsWithoutTransaction(cache.getGeocode(), newLogs);
// update offline log in DB
cache.clearOfflineLog();
if (typeSelected == LogType.FOUND_IT) {
if (tweetCheck.isChecked() && tweetBox.getVisibility() == View.VISIBLE) {
Twitter.postTweetCache(geocode, logNow);
}
}
if (GCVote.isValidRating(rating) && GCVote.isVotingPossible(cache)) {
if (GCVote.setRating(cache, rating)) {
cache.setMyVote(rating);
DataStore.saveChangedCache(cache);
} else {
showToast(res.getString(R.string.err_gcvote_send_rating));
}
}
if (StringUtils.isNotBlank(imageUri.getPath())) {
final ImageResult imageResult = loggingManager.postLogImage(logResult.getLogId(), imageCaption, imageDescription, imageUri);
final String uploadedImageUrl = imageResult.getImageUri();
if (StringUtils.isNotEmpty(uploadedImageUrl)) {
logNow.addLogImage(new Image(uploadedImageUrl, imageCaption, imageDescription));
DataStore.saveLogsWithoutTransaction(cache.getGeocode(), newLogs);
}
return imageResult.getPostResult();
}
}
return logResult.getPostLogResult();
} catch (final RuntimeException e) {
Log.e("VisitCacheActivity.Poster.doInBackgroundInternal", e);
}
return StatusCode.LOG_POST_ERROR;
}
@Override
protected void onPostExecuteInternal(final StatusCode status) {
if (status == StatusCode.NO_ERROR) {
showToast(res.getString(R.string.info_log_posted));
// No need to save the log when quitting if it has been posted.
text = currentLogText();
finish();
} else if (status == StatusCode.LOG_SAVED) {
showToast(res.getString(R.string.info_log_saved));
finish();
} else {
showToast(status.getErrorString(res));
}
}
}
private void saveLog(final boolean force) {
final String log = currentLogText();
// Do not erase the saved log if the user has removed all the characters
// without using "Clear". This may be a manipulation mistake, and erasing
// again will be easy using "Clear" while retyping the text may not be.
if (force || (StringUtils.isNotEmpty(log) && !StringUtils.equals(log, text))) {
cache.logOffline(this, log, date, typeSelected);
Settings.setLastCacheLog(log);
}
text = log;
}
private String currentLogText() {
return ButterKnife.<EditText>findById(this, R.id.log).getText().toString();
}
private String currentLogPassword() {
return ButterKnife.<EditText>findById(this, R.id.log_password).getText().toString();
}
@Override
protected LogContext getLogContext() {
return new LogContext(cache, null);
}
private void selectAllTrackablesAction() {
final Builder alert = new AlertDialog.Builder(this);
alert.setTitle(res.getString(R.string.log_tb_changeall));
final String[] tbLogTypes = getTBLogTypes();
alert.setItems(tbLogTypes, new OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int position) {
final LogTypeTrackable logType = LogTypeTrackable.values()[position];
for (final TrackableLog tb : trackables) {
tb.action = logType;
}
updateTrackablesList();
dialog.dismiss();
}
});
alert.create().show();
}
private static String[] getTBLogTypes() {
final LogTypeTrackable[] logTypeValues = LogTypeTrackable.values();
final String[] logTypes = new String[logTypeValues.length];
for (int i = 0; i < logTypes.length; i++) {
logTypes[i] = logTypeValues[i].getLabel();
}
return logTypes;
}
private void selectLogType() {
// use a local copy of the possible types, as that one might be modified in the background by the loader
final ArrayList<LogType> possible = new ArrayList<>(possibleLogTypes);
final Builder alert = new AlertDialog.Builder(this);
final String[] choices = new String[possible.size()];
for (int i = 0; i < choices.length; i++) {
choices[i] = possible.get(i).getL10n();
}
alert.setSingleChoiceItems(choices, possible.indexOf(typeSelected), new OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int position) {
setType(possible.get(position));
dialog.dismiss();
}
});
alert.create().show();
}
private void selectTrackableAction(final View view) {
final int realViewId = view.getId();
final Builder alert = new AlertDialog.Builder(this);
final TrackableLog trackableLog = actionButtons.get(realViewId);
alert.setTitle(trackableLog.name);
final String[] tbLogTypes = getTBLogTypes();
alert.setItems(tbLogTypes, new OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int position) {
final LogTypeTrackable logType = LogTypeTrackable.values()[position];
trackableLog.action = logType;
Log.i("Trackable " + trackableLog.trackCode + " (" + trackableLog.name + ") has new action: #" + logType);
updateTrackablesList();
dialog.dismiss();
}
});
alert.create().show();
}
private void selectImage() {
final Intent selectImageIntent = new Intent(this, ImageSelectActivity.class);
selectImageIntent.putExtra(Intents.EXTRA_CAPTION, imageCaption);
selectImageIntent.putExtra(Intents.EXTRA_DESCRIPTION, imageDescription);
selectImageIntent.putExtra(Intents.EXTRA_URI_AS_STRING, imageUri.toString());
startActivityForResult(selectImageIntent, SELECT_IMAGE);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (requestCode == SELECT_IMAGE) {
if (resultCode == RESULT_OK) {
imageCaption = data.getStringExtra(Intents.EXTRA_CAPTION);
imageDescription = data.getStringExtra(Intents.EXTRA_DESCRIPTION);
imageUri = Uri.parse(data.getStringExtra(Intents.EXTRA_URI_AS_STRING));
} else if (resultCode != RESULT_CANCELED) {
// Image capture failed, advise user
showToast(getResources().getString(R.string.err_select_logimage_failed));
}
}
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_send:
sendLogAndConfirm();
return true;
case R.id.menu_image:
selectImage();
return true;
case R.id.save:
saveLog(true);
finish();
return true;
case R.id.clear:
clearLog();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void sendLogAndConfirm() {
if (!sendButtonEnabled) {
Dialogs.message(this, R.string.log_post_not_possible);
return;
}
if (typeSelected.mustConfirmLog()) {
Dialogs.confirm(this, R.string.confirm_log_title, res.getString(R.string.confirm_log_message, typeSelected.getL10n()), new OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
sendLogInternal();
}
});
}
else {
sendLogInternal();
}
}
private void sendLogInternal() {
final String message = res.getString(StringUtils.isBlank(imageUri.getPath()) ?
R.string.log_saving :
R.string.log_saving_and_uploading);
new Poster(this, message).execute(currentLogText(), currentLogPassword());
Settings.setLastCacheLog(currentLogText());
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
super.onCreateOptionsMenu(menu);
menu.findItem(R.id.menu_image).setVisible(cache.supportsLogImages());
menu.findItem(R.id.save).setVisible(true);
menu.findItem(R.id.clear).setVisible(true);
presentShowcase();
return true;
}
@Override
public ShowcaseViewBuilder getShowcase() {
return new ShowcaseViewBuilder(this)
.setTarget(new ActionItemTarget(this, R.id.menu_send))
.setContent(R.string.showcase_logcache_title, R.string.showcase_logcache_text);
}
public static Intent getLogCacheIntent(final Activity context, final String cacheId, final String geocode) {
final Intent logVisitIntent = new Intent(context, LogCacheActivity.class);
logVisitIntent.putExtra(Intents.EXTRA_ID, cacheId);
logVisitIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
return logVisitIntent;
}
@Override
protected String getLastLog() {
return Settings.getLastCacheLog();
}
}
|
package org.redmine.ta;
import org.junit.*;
import org.redmine.ta.RedmineManager.INCLUDE;
import org.redmine.ta.beans.*;
import org.redmine.ta.internal.logging.Logger;
import org.redmine.ta.internal.logging.LoggerFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
import static org.junit.Assert.*;
/**
* This class and its dependencies are located in org.redmine.ta.api project.
*/
public class RedmineManagerTest {
// TODO We don't know activities IDs!
private static final Integer ACTIVITY_ID = 8;
private static Logger logger = LoggerFactory.getLogger(RedmineManagerTest.class);
private static RedmineManager mgr;
private static String projectKey;
private static TestConfig testConfig;
@BeforeClass
public static void oneTimeSetUp() {
testConfig = new TestConfig();
logger.info("Running redmine tests using: " + testConfig.getURI());
// mgr = new RedmineManager(TestConfig.getURI(), TestConfig.getApiKey());
mgr = new RedmineManager(testConfig.getURI());
mgr.setLogin(testConfig.getLogin());
mgr.setPassword(testConfig.getPassword());
Project junitTestProject = new Project();
junitTestProject.setName("test project");
junitTestProject.setIdentifier("test"
+ Calendar.getInstance().getTimeInMillis());
try {
Project createdProject = mgr.createProject(junitTestProject);
projectKey = createdProject.getIdentifier();
} catch (Exception e) {
logger.error(e, "Exception while creating test project");
Assert.fail("can't create a test project. " + e.getMessage());
}
}
@AfterClass
public static void oneTimeTearDown() {
try {
if (mgr != null && projectKey != null) {
mgr.deleteProject(projectKey);
}
} catch (Exception e) {
logger.error(e, "Exception while deleting test project");
Assert.fail("can't delete the test project '" + projectKey + ". reason: "
+ e.getMessage());
}
}
@Test
public void testCreateIssue() {
try {
Issue issueToCreate = new Issue();
issueToCreate.setSubject("test zzx");
Calendar startCal = Calendar.getInstance();
// have to clear them because they are ignored by Redmine and prevent from comparison later
startCal.clear(Calendar.HOUR_OF_DAY);
startCal.clear(Calendar.MINUTE);
startCal.clear(Calendar.SECOND);
startCal.clear(Calendar.MILLISECOND);
startCal.add(Calendar.DATE, 5);
issueToCreate.setStartDate(startCal.getTime());
Calendar due = Calendar.getInstance();
due.add(Calendar.MONTH, 1);
issueToCreate.setDueDate(due.getTime());
User assignee = getOurUser();
issueToCreate.setAssignee(assignee);
String description = "This is the description for the new task." +
"\nIt has several lines." +
"\nThis is the last line.";
issueToCreate.setDescription(description);
float estimatedHours = 44;
issueToCreate.setEstimatedHours(estimatedHours);
Issue newIssue = mgr.createIssue(projectKey, issueToCreate);
// System.out.println("created: " + newIssue);
Assert.assertNotNull("Checking returned result", newIssue);
Assert.assertNotNull("New issue must have some ID", newIssue.getId());
// check startDate
Calendar returnedStartCal = Calendar.getInstance();
returnedStartCal.setTime(newIssue.getStartDate());
Assert.assertEquals(startCal.get(Calendar.YEAR), returnedStartCal.get(Calendar.YEAR));
Assert.assertEquals(startCal.get(Calendar.MONTH), returnedStartCal.get(Calendar.MONTH));
Assert.assertEquals(startCal.get(Calendar.DAY_OF_MONTH), returnedStartCal.get(Calendar.DAY_OF_MONTH));
// check dueDate
Calendar returnedDueCal = Calendar.getInstance();
returnedDueCal.setTime(newIssue.getDueDate());
Assert.assertEquals(due.get(Calendar.YEAR), returnedDueCal.get(Calendar.YEAR));
Assert.assertEquals(due.get(Calendar.MONTH), returnedDueCal.get(Calendar.MONTH));
Assert.assertEquals(due.get(Calendar.DAY_OF_MONTH), returnedDueCal.get(Calendar.DAY_OF_MONTH));
// check ASSIGNEE
User actualAssignee = newIssue.getAssignee();
Assert.assertNotNull("Checking assignee not null", actualAssignee);
Assert.assertEquals("Checking assignee id", assignee.getId(),
actualAssignee.getId());
// check AUTHOR
Integer EXPECTED_AUTHOR_ID = getOurUser().getId();
Assert.assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthor().getId());
// check ESTIMATED TIME
Assert.assertEquals((Float) estimatedHours, newIssue.getEstimatedHours());
// check multi-line DESCRIPTION
String regexpStripExtra = "\\r|\\n|\\s";
description = description.replaceAll(regexpStripExtra, "");
String actualDescription = newIssue.getDescription();
actualDescription = actualDescription.replaceAll(regexpStripExtra, "");
Assert.assertEquals(description, actualDescription);
// PRIORITY
Assert.assertNotNull(newIssue.getPriorityId());
Assert.assertTrue(newIssue.getPriorityId() > 0);
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void testCreateIssueWithParent() {
try {
Issue parentIssue = new Issue();
parentIssue.setSubject("parent 1");
Issue newParentIssue = mgr.createIssue(projectKey, parentIssue);
logger.debug("created parent: " + newParentIssue);
Assert.assertNotNull("Checking parent was created", newParentIssue);
Assert.assertNotNull("Checking ID of parent issue is not null",
newParentIssue.getId());
// Integer parentId = 46;
Integer parentId = newParentIssue.getId();
Issue childIssue = new Issue();
childIssue.setSubject("child 1");
childIssue.setParentId(parentId);
Issue newChildIssue = mgr.createIssue(projectKey, childIssue);
logger.debug("created child: " + newChildIssue);
Assert.assertEquals("Checking parent ID of the child issue", parentId,
newChildIssue.getParentId());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void testStartDateNull() {
try {
Issue issue = new Issue();
issue.setSubject("test start date");
issue.setStartDate(null);
Issue newIssue = mgr.createIssue(projectKey, issue);
Issue loadedIssue = mgr.getIssueById(newIssue.getId());
Assert.assertNull(loadedIssue.getStartDate());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void testGetIssuesBySummary() {
String summary = "issue with subject ABC";
try {
Issue issue = new Issue();
issue.setSubject(summary);
User assignee = getOurUser();
issue.setAssignee(assignee);
Issue newIssue = mgr.createIssue(projectKey, issue);
logger.debug("created: " + newIssue);
Assert.assertNotNull("Checking returned result", newIssue);
Assert.assertNotNull("New issue must have some ID", newIssue.getId());
// try to find the issue
List<Issue> foundIssues = mgr.getIssuesBySummary(projectKey,
summary);
Assert.assertNotNull("Checking if search results is not NULL", foundIssues);
Assert.assertTrue("Search results must be not empty",
!(foundIssues.isEmpty()));
Issue loadedIssue1 = RedmineTestUtils.findIssueInList(foundIssues, newIssue.getId());
Assert.assertNotNull(loadedIssue1);
Assert.assertEquals(summary, loadedIssue1.getSubject());
// User actualAssignee = newIssue.getAssignee();
// assertNotNull("Checking assignee not null", actualAssignee);
// assertEquals("Checking assignee Name", assignee.getName(),
// actualAssignee.getName());
// assertEquals("Checking assignee Id", assignee.getId(),
// actualAssignee.getId());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void testTryFindNonExistingIssue() {
String summary = "some summary here for issue which does not exist";
try {
// try to find the issue
List<Issue> foundIssues = mgr.getIssuesBySummary(projectKey,
summary);
Assert.assertNotNull("Search result must be not null", foundIssues);
Assert.assertTrue("Search result list must be empty",
foundIssues.isEmpty());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
private static User getOurUser() {
Integer userId = Integer
.parseInt(testConfig.getParam("createissue.userid"));
String login = testConfig.getLogin();
String fName = testConfig.getParam("userFName");
String lName = testConfig.getParam("userLName");
User user = new User();
user.setId(userId);
user.setLogin(login);
user.setFirstName(fName);
user.setLastName(lName);
return user;
}
@Test(expected = IllegalArgumentException.class)
public void testNULLHostParameter() {
new RedmineManager(null);
}
@Test(expected = IllegalArgumentException.class)
public void testEmptyHostParameter() throws RuntimeException {
new RedmineManager("");
}
@Test(expected = AuthenticationException.class)
public void noAPIKeyOnCreateIssueThrowsAE() throws Exception {
RedmineManager redmineMgrEmpty = new RedmineManager(testConfig.getURI());
Issue issue = new Issue();
issue.setSubject("test zzx");
redmineMgrEmpty.createIssue(projectKey, issue);
}
@Test(expected = AuthenticationException.class)
public void wrongAPIKeyOnCreateIssueThrowsAE() throws Exception {
RedmineManager redmineMgrInvalidKey = new RedmineManager(testConfig.getURI(), "wrong_key");
Issue issue = new Issue();
issue.setSubject("test zzx");
redmineMgrInvalidKey.createIssue(projectKey, issue);
}
@Test
public void testUpdateIssue() {
try {
Issue issue = new Issue();
String originalSubject = "Issue " + new Date();
issue.setSubject(originalSubject);
Issue newIssue = mgr.createIssue(projectKey, issue);
String changedSubject = "changed subject";
newIssue.setSubject(changedSubject);
mgr.update(newIssue);
Issue reloadedFromRedmineIssue = mgr.getIssueById(newIssue.getId());
Assert.assertEquals(
"Checking if 'update issue' operation changed the 'subject' field",
changedSubject, reloadedFromRedmineIssue.getSubject());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
/**
* Tests the retrieval of an {@link Issue} by its ID.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetIssueById() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Issue issue = new Issue();
String originalSubject = "Issue " + new Date();
issue.setSubject(originalSubject);
Issue newIssue = mgr.createIssue(projectKey, issue);
Issue reloadedFromRedmineIssue = mgr.getIssueById(newIssue.getId());
Assert.assertEquals(
"Checking if 'get issue by ID' operation returned issue with same 'subject' field",
originalSubject, reloadedFromRedmineIssue.getSubject());
Tracker tracker = reloadedFromRedmineIssue.getTracker();
Assert.assertNotNull("Tracker of issue should not be null", tracker);
Assert.assertNotNull("ID of tracker of issue should not be null", tracker.getId());
Assert.assertNotNull("Name of tracker of issue should not be null", tracker.getName());
}
/**
* Tests the retrieval of {@link Project}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetProjects() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// retrieve projects
List<Project> projects = mgr.getProjects();
// asserts
Assert.assertTrue(projects.size() > 0);
boolean found = false;
for (Project project : projects) {
if (project.getIdentifier().equals(projectKey)) {
found = true;
break;
}
}
if (!found) {
Assert.fail("Our project with key '" + projectKey + "' is not found on the server");
}
}
@Test
public void testGetIssues() {
try {
// create at least 1 issue
Issue issueToCreate = new Issue();
issueToCreate.setSubject("testGetIssues: " + new Date());
Issue newIssue = mgr.createIssue(projectKey, issueToCreate);
List<Issue> issues = mgr.getIssues(projectKey, null);
logger.debug("getIssues() loaded " + issues.size() + " issues");//using query #" + queryIdIssuesCreatedLast2Days);
Assert.assertTrue(issues.size() > 0);
boolean found = false;
for (Issue issue : issues) {
if (issue.getId().equals(newIssue.getId())) {
found = true;
break;
}
}
if (!found) {
Assert.fail("getIssues() didn't return the issue we just created. The query "
+ " must have returned all issues created during the last 2 days");
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test(expected = NotFoundException.class)
public void testGetIssuesInvalidQueryId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
Integer invalidQueryId = 9999999;
mgr.getIssues(projectKey, invalidQueryId);
}
@Test
public void testCreateProject() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Project projectToCreate = generateRandomProject();
String key = null;
try {
Project createdProject = mgr.createProject(projectToCreate);
key = createdProject.getIdentifier();
Assert.assertNotNull("checking that a non-null project is returned", createdProject);
Assert.assertEquals(projectToCreate.getIdentifier(), createdProject.getIdentifier());
Assert.assertEquals(projectToCreate.getName(), createdProject.getName());
Assert.assertEquals(projectToCreate.getDescription(), createdProject.getDescription());
Assert.assertEquals(projectToCreate.getHomepage(), createdProject.getHomepage());
List<Tracker> trackers = createdProject.getTrackers();
Assert.assertNotNull("checking that project has some trackers", trackers);
Assert.assertTrue("checking that project has some trackers", !(trackers.isEmpty()));
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
if (key != null) {
mgr.deleteProject(key);
}
}
}
@Test
public void testCreateGetUpdateDeleteProject() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Project projectToCreate = generateRandomProject();
String key = null;
try {
projectToCreate.setIdentifier("id" + new Date().getTime());
logger.debug("trying to create a project with id " + projectToCreate.getIdentifier());
Project createdProject = mgr.createProject(projectToCreate);
key = createdProject.getIdentifier();
String newDescr = "NEW123";
String newName = "new name here";
createdProject.setName(newName);
createdProject.setDescription(newDescr);
mgr.update(createdProject);
Project updatedProject = mgr.getProjectByKey(key);
Assert.assertNotNull(updatedProject);
Assert.assertEquals(createdProject.getIdentifier(), updatedProject.getIdentifier());
Assert.assertEquals(newName, updatedProject.getName());
Assert.assertEquals(newDescr, updatedProject.getDescription());
List<Tracker> trackers = updatedProject.getTrackers();
Assert.assertNotNull("checking that project has some trackers", trackers);
Assert.assertTrue("checking that project has some trackers", !(trackers.isEmpty()));
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
} finally {
if (key != null) {
mgr.deleteProject(key);
}
}
}
@Test
public void testCreateProjectFailsWithReservedIdentifier() throws Exception {
Project projectToCreate = new Project();
projectToCreate.setName("new");
projectToCreate.setIdentifier("new");
String key = null;
try {
Project createdProject = mgr.createProject(projectToCreate);
// in case if the creation haven't failed (although it should have had!),
// need to cleanup - delete this project
key = createdProject.getIdentifier();
} catch (RedmineException e) {
Assert.assertNotNull(e.getErrors());
Assert.assertEquals(1, e.getErrors().size());
Assert.assertEquals("Identifier is reserved", e.getErrors().get(0));
} finally {
if (key != null) {
mgr.deleteProject(key);
}
}
}
private static Project generateRandomProject() {
Project project = new Project();
Long timeStamp = Calendar.getInstance().getTimeInMillis();
String key = "projkey" + timeStamp;
String name = "project number " + timeStamp;
String description = "some description for the project";
project.setIdentifier(key);
project.setName(name);
project.setDescription(description);
project.setHomepage("www.randompage" + timeStamp + ".com");
return project;
}
@Test
public void testCreateIssueNonUnicodeSymbols() {
try {
String nonLatinSymbols = "Example with accents Ao";
Issue toCreate = new Issue();
toCreate.setSubject(nonLatinSymbols);
Issue created = mgr.createIssue(projectKey, toCreate);
Assert.assertEquals(nonLatinSymbols, created.getSubject());
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void testCreateIssueSummaryOnly() {
try {
Issue issueToCreate = new Issue();
issueToCreate.setSubject("This is the summary line 123");
Issue newIssue = mgr.createIssue(projectKey, issueToCreate);
Assert.assertNotNull("Checking returned result", newIssue);
Assert.assertNotNull("New issue must have some ID", newIssue.getId());
// check AUTHOR
Integer EXPECTED_AUTHOR_ID = getOurUser().getId();
Assert.assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthor().getId());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test(expected = NotFoundException.class)
public void testCreateIssueInvalidProjectKey() throws IOException, AuthenticationException, RedmineException, NotFoundException {
Issue issueToCreate = new Issue();
issueToCreate.setSubject("Summary line 100");
mgr.createIssue("someNotExistingProjectKey", issueToCreate);
}
@Test(expected = NotFoundException.class)
public void testGetProjectNonExistingId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.getProjectByKey("some-non-existing-key");
}
@Test(expected = NotFoundException.class)
public void testDeleteNonExistingProject() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.deleteProject("some-non-existing-key");
}
@Test(expected = NotFoundException.class)
public void testGetIssueNonExistingId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
int someNonExistingID = 999999;
mgr.getIssueById(someNonExistingID);
}
@Test(expected = NotFoundException.class)
public void testUpdateIssueNonExistingId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
int nonExistingId = 999999;
Issue issue = new Issue();
issue.setId(nonExistingId);
mgr.update(issue);
}
@Test
public void testGetUsers() {
try {
List<User> users = mgr.getUsers();
Assert.assertTrue(users.size() > 0);
// boolean found = false;
// for (Project project : projects) {
// if (project.getIdentifier().equals(projectKey)) {
// found = true;
// break;
// if (!found) {
// fail("Our project with key '" + projectKey+"' is not found on the server");
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test
public void testGetCurrentUser() throws IOException, AuthenticationException, RedmineException, NotFoundException {
User currentUser = mgr.getCurrentUser();
Assert.assertEquals(getOurUser().getId(), currentUser.getId());
Assert.assertEquals(getOurUser().getLogin(), currentUser.getLogin());
}
@Test
public void testGetUserById() throws IOException, AuthenticationException, NotFoundException, RedmineException {
User loadedUser = mgr.getUserById(getOurUser().getId());
Assert.assertEquals(getOurUser().getId(), loadedUser.getId());
Assert.assertEquals(getOurUser().getLogin(), loadedUser.getLogin());
}
@Test(expected = NotFoundException.class)
public void testGetUserNonExistingId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.getUserById(999999);
}
@Test(expected = NotFoundException.class)
public void testInvalidGetCurrentUser() throws IOException, AuthenticationException, RedmineException, NotFoundException {
RedmineManager invalidManager = new RedmineManager(testConfig.getURI() + "/INVALID");
invalidManager.setLogin("Invalid");
invalidManager.setPassword("Invalid");
invalidManager.getCurrentUser();
}
@Test
public void testCreateUser() throws IOException, AuthenticationException, NotFoundException, RedmineException {
User createdUser = null;
try {
User userToCreate = generateRandomUser();
createdUser = mgr.createUser(userToCreate);
Assert.assertNotNull("checking that a non-null project is returned", createdUser);
Assert.assertEquals(userToCreate.getLogin(), createdUser.getLogin());
Assert.assertEquals(userToCreate.getFirstName(), createdUser.getFirstName());
Assert.assertEquals(userToCreate.getLastName(), createdUser.getLastName());
Integer id = createdUser.getId();
Assert.assertNotNull(id);
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
if (createdUser != null) {
mgr.deleteUser(createdUser.getId());
}
}
}
private static User generateRandomUser() {
User user = new User();
user.setFirstName("fname");
user.setLastName("lname");
long randomNumber = new Date().getTime();
user.setLogin("login" + randomNumber);
user.setMail("somemail" + randomNumber + "@somedomain.com");
user.setPassword("zzzz");
return user;
}
@Test
public void testUpdateUser() throws IOException, AuthenticationException, NotFoundException {
User userToCreate = new User();
userToCreate.setFirstName("fname2");
userToCreate.setLastName("lname2");
long randomNumber = new Date().getTime();
userToCreate.setLogin("login33" + randomNumber);
userToCreate.setMail("email" + randomNumber + "@somedomain.com");
userToCreate.setPassword("1234");
try {
User createdUser = mgr.createUser(userToCreate);
Integer userId = createdUser.getId();
Assert.assertNotNull("checking that a non-null project is returned", createdUser);
String newFirstName = "fnameNEW";
String newLastName = "lnameNEW";
String newMail = "newmail" + randomNumber + "@asd.com";
createdUser.setFirstName(newFirstName);
createdUser.setLastName(newLastName);
createdUser.setMail(newMail);
mgr.update(createdUser);
User updatedUser = mgr.getUserById(userId);
Assert.assertEquals(newFirstName, updatedUser.getFirstName());
Assert.assertEquals(newLastName, updatedUser.getLastName());
Assert.assertEquals(newMail, updatedUser.getMail());
Assert.assertEquals(userId, updatedUser.getId());
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void userCanBeDeleted() throws IOException, AuthenticationException, RedmineException, NotFoundException {
User user = generateRandomUser();
User createdUser = mgr.createUser(user);
Integer newUserId = createdUser.getId();
try {
mgr.deleteUser(newUserId);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
try {
mgr.getUserById(newUserId);
fail("Must have failed with NotFoundException because we tried to delete the user");
} catch (NotFoundException e) {
// ignore: the user should not be found
}
}
@Test(expected = NotFoundException.class)
public void deletingNonExistingUserThrowsNFE() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.deleteUser(999999);
}
@Test
public void testGetIssuesPaging() {
try {
// create 27 issues. default page size is 25.
createIssues(27);
// mgr.setObjectsPerPage(5); <-- does not work now
List<Issue> issues = mgr.getIssues(projectKey, null);
logger.debug("testGetIssuesPaging() loaded " + issues.size() + " issues");//using query #" + queryIdIssuesCreatedLast2Days);
Assert.assertTrue(issues.size() > 26);
Set<Issue> issueSet = new HashSet<Issue>(issues);
Assert.assertEquals(issues.size(), issueSet.size());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
private List<Issue> createIssues(int issuesNumber) throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<Issue> issues = new ArrayList<Issue>(issuesNumber);
for (int i = 0; i < issuesNumber; i++) {
Issue issueToCreate = new Issue();
issueToCreate.setSubject("some issue " + i + " " + new Date());
Issue issue = mgr.createIssue(projectKey, issueToCreate);
issues.add(issue);
}
return issues;
}
private Issue generateRandomIssue() {
Random r = new Random();
Issue issue = new Issue();
issue.setSubject("some issue " + r.nextInt() + " " + new Date());
return issue;
}
@Test
public void testProjectsAllPagesLoaded() throws IOException, AuthenticationException, NotFoundException, URISyntaxException, RedmineException {
int NUM = 27; // must be larger than 25, which is a default page size in Redmine
List<Project> projects = createProjects(NUM);
List<Project> loadedProjects = mgr.getProjects();
Assert.assertTrue(
"Number of projects loaded from the server must be bigger than "
+ NUM + ", but it's " + loadedProjects.size(),
loadedProjects.size() > NUM);
deleteProjects(projects);
}
private List<Project> createProjects(int num) throws IOException, AuthenticationException, RedmineException, NotFoundException {
List<Project> projects = new ArrayList<Project>(num);
for (int i = 0; i < num; i++) {
Project projectToCreate = generateRandomProject();
Project p = mgr.createProject(projectToCreate);
projects.add(p);
}
return projects;
}
private void deleteProjects(List<Project> projects) throws IOException, AuthenticationException, NotFoundException, RedmineException {
for (Project p : projects) {
mgr.deleteProject(p.getIdentifier());
}
}
@Test
public void testGetTimeEntries() throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<TimeEntry> list = mgr.getTimeEntries();
Assert.assertNotNull(list);
}
@Test
public void testCreateGetTimeEntry() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Issue issue = createIssues(1).get(0);
Integer issueId = issue.getId();
TimeEntry entry = new TimeEntry();
Float hours = 11f;
entry.setHours(hours);
entry.setIssueId(issueId);
// TODO We don't know activities IDs!
entry.setActivityId(ACTIVITY_ID);
TimeEntry createdEntry = mgr.createTimeEntry(entry);
Assert.assertNotNull(createdEntry);
logger.debug("Created time entry " + createdEntry);
Assert.assertEquals(hours, createdEntry.getHours());
Float newHours = 22f;
createdEntry.setHours(newHours);
mgr.update(createdEntry);
TimeEntry updatedEntry = mgr.getTimeEntry(createdEntry.getId());
Assert.assertEquals(newHours, updatedEntry.getHours());
}
@Test(expected = NotFoundException.class)
public void testCreateDeleteTimeEntry() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Issue issue = createIssues(1).get(0);
Integer issueId = issue.getId();
TimeEntry entry = new TimeEntry();
Float hours = 4f;
entry.setHours(hours);
entry.setIssueId(issueId);
entry.setActivityId(ACTIVITY_ID);
TimeEntry createdEntry = mgr.createTimeEntry(entry);
Assert.assertNotNull(createdEntry);
mgr.deleteTimeEntry(createdEntry.getId());
mgr.getTimeEntry(createdEntry.getId());
}
@Test
public void testGetTimeEntriesForIssue() throws IOException, AuthenticationException, NotFoundException, RedmineException {
Issue issue = createIssues(1).get(0);
Integer issueId = issue.getId();
Float hours1 = 2f;
Float hours2 = 7f;
Float totalHoursExpected = hours1 + hours2;
TimeEntry createdEntry1 = createTimeEntry(issueId, hours1);
TimeEntry createdEntry2 = createTimeEntry(issueId, hours2);
Assert.assertNotNull(createdEntry1);
Assert.assertNotNull(createdEntry2);
List<TimeEntry> entries = mgr.getTimeEntriesForIssue(issueId);
Assert.assertEquals(2, entries.size());
Float totalTime = 0f;
for (TimeEntry timeEntry : entries) {
totalTime += timeEntry.getHours();
}
Assert.assertEquals(totalHoursExpected, totalTime);
}
private TimeEntry createTimeEntry(Integer issueId, float hours) throws IOException,
AuthenticationException, NotFoundException, RedmineException {
TimeEntry entry = new TimeEntry();
entry.setHours(hours);
entry.setIssueId(issueId);
entry.setActivityId(ACTIVITY_ID);
return mgr.createTimeEntry(entry);
}
@Test(expected = NotFoundException.class)
public void testDeleteIssue() throws IOException, AuthenticationException,
NotFoundException, RedmineException {
Issue issue = createIssues(1).get(0);
Issue retrievedIssue = mgr.getIssueById(issue.getId());
Assert.assertEquals(issue, retrievedIssue);
mgr.deleteIssue(issue.getId());
mgr.getIssueById(issue.getId());
}
@Test
public void testUpdateIssueSpecialXMLtags() throws Exception {
Issue issue = createIssues(1).get(0);
String newSubject = "\"text in quotes\" and <xml> tags";
String newDescription = "<taghere>\"abc\"</here>";
issue.setSubject(newSubject);
issue.setDescription(newDescription);
mgr.update(issue);
Issue updatedIssue = mgr.getIssueById(issue.getId());
Assert.assertEquals(newSubject, updatedIssue.getSubject());
Assert.assertEquals(newDescription, updatedIssue.getDescription());
}
@Test
public void testCustomFields() throws Exception {
Issue issue = createIssues(1).get(0);
// default empty values
Assert.assertEquals(2, issue.getCustomFields().size());
// TODO update this!
int id1 = 1; // TODO this is pretty much a hack, we don't generally know these ids!
String custom1FieldName = "my_custom_1";
String custom1Value = "some value 123";
int id2 = 2;
String custom2FieldName = "custom_boolean_1";
String custom2Value = "true";
issue.setCustomFields(new ArrayList<CustomField>());
issue.getCustomFields().add(new CustomField(id1, custom1FieldName, custom1Value));
issue.getCustomFields().add(new CustomField(id2, custom2FieldName, custom2Value));
mgr.update(issue);
Issue updatedIssue = mgr.getIssueById(issue.getId());
Assert.assertEquals(2, updatedIssue.getCustomFields().size());
Assert.assertEquals(custom1Value, updatedIssue.getCustomField(custom1FieldName));
Assert.assertEquals(custom2Value, updatedIssue.getCustomField(custom2FieldName));
}
@Test
public void testUpdateIssueDoesNotChangeEstimatedTime() {
try {
Issue issue = new Issue();
String originalSubject = "Issue " + new Date();
issue.setSubject(originalSubject);
Issue newIssue = mgr.createIssue(projectKey, issue);
Assert.assertEquals("Estimated hours must be NULL", null, newIssue.getEstimatedHours());
mgr.update(newIssue);
Issue reloadedFromRedmineIssue = mgr.getIssueById(newIssue.getId());
Assert.assertEquals("Estimated hours must be NULL", null, reloadedFromRedmineIssue.getEstimatedHours());
} catch (Exception e) {
Assert.fail();
}
}
/**
* Tests the correct retrieval of the parent id of sub {@link Project}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testSubProjectIsCreatedWithCorrectParentId() throws IOException, AuthenticationException, RedmineException, NotFoundException {
Project createdMainProject = null;
try {
createdMainProject = createProject();
Project subProject = createSubProject(createdMainProject);
Assert.assertEquals("Must have correct parent ID",
createdMainProject.getId(), subProject.getParentId());
} finally {
if (createdMainProject != null) {
mgr.deleteProject(createdMainProject.getIdentifier());
}
}
}
private Project createProject() throws IOException, AuthenticationException, RedmineException, NotFoundException {
Project mainProject = new Project();
long id = new Date().getTime();
mainProject.setName("project" + id);
mainProject.setIdentifier("project" + id);
return mgr.createProject(mainProject);
}
private Project createSubProject(Project parent) throws IOException, AuthenticationException, RedmineException, NotFoundException {
Project project = new Project();
long id = new Date().getTime();
project.setName("sub_pr" + id);
project.setIdentifier("subpr" + id);
project.setParentId(parent.getId());
return mgr.createProject(project);
}
@Test
public void testIssueDoneRatio() {
try {
Issue issue = new Issue();
String subject = "Issue " + new Date();
issue.setSubject(subject);
Issue createdIssue = mgr.createIssue(projectKey, issue);
Assert.assertEquals("Initial 'done ratio' must be 0", (Integer) 0, createdIssue.getDoneRatio());
Integer doneRatio = 50;
createdIssue.setDoneRatio(doneRatio);
mgr.update(createdIssue);
Integer issueId = createdIssue.getId();
Issue reloadedFromRedmineIssue = mgr.getIssueById(issueId);
Assert.assertEquals(
"Checking if 'update issue' operation changed 'done ratio' field",
doneRatio, reloadedFromRedmineIssue.getDoneRatio());
Integer invalidDoneRatio = 130;
reloadedFromRedmineIssue.setDoneRatio(invalidDoneRatio);
try {
mgr.update(reloadedFromRedmineIssue);
} catch (RedmineException e) {
Assert.assertEquals("Must be 1 error", 1, e.getErrors().size());
Assert.assertEquals("Checking error text", "% Done is not included in the list", e.getErrors().get(0));
}
Issue reloadedFromRedmineIssueUnchanged = mgr.getIssueById(issueId);
Assert.assertEquals(
"'done ratio' must have remained unchanged after invalid value",
doneRatio, reloadedFromRedmineIssueUnchanged.getDoneRatio());
} catch (Exception e) {
fail(e.toString());
}
}
@Test
public void testIssueNullDescriptionDoesNotEraseIt() {
try {
Issue issue = new Issue();
String subject = "Issue " + new Date();
String descr = "Some description";
issue.setSubject(subject);
issue.setDescription(descr);
Issue createdIssue = mgr.createIssue(projectKey, issue);
Assert.assertEquals("Checking description", descr, createdIssue.getDescription());
createdIssue.setDescription(null);
mgr.update(createdIssue);
Integer issueId = createdIssue.getId();
Issue reloadedFromRedmineIssue = mgr.getIssueById(issueId);
Assert.assertEquals(
"Description must not be erased",
descr, reloadedFromRedmineIssue.getDescription());
reloadedFromRedmineIssue.setDescription("");
mgr.update(reloadedFromRedmineIssue);
Issue reloadedFromRedmineIssueUnchanged = mgr.getIssueById(issueId);
Assert.assertEquals(
"Description must be erased",
"", reloadedFromRedmineIssueUnchanged.getDescription());
} catch (Exception e) {
Assert.fail();
}
}
@Test
public void testIssueJournals() {
try {
// create at least 1 issue
Issue issueToCreate = new Issue();
issueToCreate.setSubject("testGetIssues: " + new Date());
Issue newIssue = mgr.createIssue(projectKey, issueToCreate);
Issue loadedIssueWithJournals = mgr.getIssueById(newIssue.getId(), INCLUDE.journals);
Assert.assertTrue(loadedIssueWithJournals.getJournals().isEmpty());
String commentDescribingTheUpdate = "some comment describing the issue update";
loadedIssueWithJournals.setSubject("new subject");
loadedIssueWithJournals.setNotes(commentDescribingTheUpdate);
mgr.update(loadedIssueWithJournals);
Issue loadedIssueWithJournals2 = mgr.getIssueById(newIssue.getId(), INCLUDE.journals);
Assert.assertEquals(1, loadedIssueWithJournals2.getJournals().size());
Journal journalItem = loadedIssueWithJournals2.getJournals().get(0);
Assert.assertEquals(commentDescribingTheUpdate, journalItem.getNotes());
User ourUser = getOurUser();
// can't compare User objects because either of them is not completely filled
Assert.assertEquals(ourUser.getId(), journalItem.getUser().getId());
Assert.assertEquals(ourUser.getFirstName(), journalItem.getUser().getFirstName());
Assert.assertEquals(ourUser.getLastName(), journalItem.getUser().getLastName());
Issue loadedIssueWithoutJournals = mgr.getIssueById(newIssue.getId());
Assert.assertTrue(loadedIssueWithoutJournals.getJournals().isEmpty());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test
public void testCreateRelation() {
try {
List<Issue> issues = createIssues(2);
Issue src = issues.get(0);
Issue target = issues.get(1);
String relationText = IssueRelation.TYPE.precedes.toString();
IssueRelation r = mgr.createRelation(src.getId(), target.getId(), relationText);
assertEquals(src.getId(), r.getIssueId());
Assert.assertEquals(target.getId(), r.getIssueToId());
Assert.assertEquals(relationText, r.getType());
} catch (Exception e) {
Assert.fail(e.toString());
}
}
private IssueRelation createTwoRelatedIssues() throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<Issue> issues = createIssues(2);
Issue src = issues.get(0);
Issue target = issues.get(1);
String relationText = IssueRelation.TYPE.precedes.toString();
return mgr.createRelation(src.getId(), target.getId(), relationText);
}
@Test
public void issueRelationsAreCreatedAndLoadedOK() {
try {
IssueRelation relation = createTwoRelatedIssues();
Issue issue = mgr.getIssueById(relation.getIssueId(), INCLUDE.relations);
Issue issueTarget = mgr.getIssueById(relation.getIssueToId(), INCLUDE.relations);
Assert.assertEquals(1, issue.getRelations().size());
Assert.assertEquals(1, issueTarget.getRelations().size());
IssueRelation relation1 = issue.getRelations().get(0);
assertEquals(issue.getId(), relation1.getIssueId());
assertEquals(issueTarget.getId(), relation1.getIssueToId());
assertEquals("precedes", relation1.getType());
assertEquals((Integer) 0, relation1.getDelay());
IssueRelation reverseRelation = issueTarget.getRelations().get(0);
// both forward and reverse relations are the same!
Assert.assertEquals(relation1, reverseRelation);
} catch (Exception e) {
Assert.fail(e.toString());
}
}
@Test
public void testIssureRelationDelete() throws IOException, AuthenticationException, RedmineException, NotFoundException {
IssueRelation relation = createTwoRelatedIssues();
mgr.deleteRelation(relation.getId());
Issue issue = mgr.getIssueById(relation.getIssueId(), INCLUDE.relations);
Assert.assertEquals(0, issue.getRelations().size());
}
@Test
public void testIssueRelationsDelete() throws IOException, AuthenticationException, RedmineException, NotFoundException {
List<Issue> issues = createIssues(3);
Issue src = issues.get(0);
Issue target = issues.get(1);
String relationText = IssueRelation.TYPE.precedes.toString();
mgr.createRelation(src.getId(), target.getId(), relationText);
target = issues.get(2);
mgr.createRelation(src.getId(), target.getId(), relationText);
src = mgr.getIssueById(src.getId(), INCLUDE.relations);
mgr.deleteIssueRelations(src);
Issue issue = mgr.getIssueById(src.getId(), INCLUDE.relations);
Assert.assertEquals(0, issue.getRelations().size());
}
@Ignore
@Test
public void issueFixVersionIsSet() throws Exception {
String existingProjectKey = "test";
Issue toCreate = generateRandomIssue();
Version v = new Version();
String versionName = "1.0";
v.setName("1.0");
v.setId(1);
toCreate.setTargetVersion(v);
Issue createdIssue = mgr.createIssue(existingProjectKey, toCreate);
Assert.assertNotNull(createdIssue.getTargetVersion());
Assert.assertEquals(createdIssue.getTargetVersion().getName(), versionName);
}
@Ignore
@Test
public void testGetProjectsIncludesTrackers() {
try {
List<Project> projects = mgr.getProjects();
Assert.assertTrue(projects.size() > 0);
Project p1 = projects.get(0);
Assert.assertNotNull(p1.getTrackers());
// XXX there could be a case when a project does not have any trackers
// need to create a project with some trackers to make this test deterministic
Assert.assertTrue(!p1.getTrackers().isEmpty());
logger.debug("Created trackers " + p1.getTrackers());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Ignore
@Test
public void testSpentTimeFieldLoaded() {
try {
Issue issue = new Issue();
String subject = "Issue " + new Date();
issue.setSubject(subject);
float spentHours = 2;
issue.setSpentHours(spentHours);
Issue createdIssue = mgr.createIssue(projectKey, issue);
Issue newIssue = mgr.getIssueById(createdIssue.getId());
Assert.assertEquals((Float)spentHours, newIssue.getSpentHours());
} catch (Exception e) {
Assert.fail();
}
}
@Ignore
@Test
public void testSpentTime() {
// TODO need to use "Time Entries"
// float spentHours = 12.5f;
// issueToCreate.setSpentHours(spentHours);
// check SPENT TIME
// assertEquals((Float) spentHours, newIssue.getSpentHours());
}
@Test(expected = IllegalArgumentException.class)
public void invalidTimeEntryFailsWithIAEOnCreate() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.createTimeEntry(createIncompleteTimeEntry());
}
@Test(expected = IllegalArgumentException.class)
public void invalidTimeEntryFailsWithIAEOnUpdate() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.update(createIncompleteTimeEntry());
}
private TimeEntry createIncompleteTimeEntry() {
TimeEntry timeEntry = new TimeEntry();
timeEntry.setActivityId(ACTIVITY_ID);
timeEntry.setSpentOn(new Date());
timeEntry.setHours(1.5f);
return timeEntry;
}
@Test
public void testViolateTimeEntryConstraint_ProjectOrIssueID_issue66() throws IOException, AuthenticationException, RedmineException {
TimeEntry timeEntry = createIncompleteTimeEntry();
// Now can try to verify with project ID (only test with issue ID seems to be already covered)
int projectId = mgr.getProjects().get(0).getId();
timeEntry.setProjectId(projectId);
try {
TimeEntry created = mgr.createTimeEntry(timeEntry);
logger.debug("Created time entry " + created);
} catch (Exception e) {
e.printStackTrace();
fail("Unexpected " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
/**
* tests the retrieval of statuses.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetStatuses() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// TODO we should create some statuses first, but the Redmine Java API does not support this presently
List<IssueStatus> statuses = mgr.getStatuses();
Assert.assertFalse("Expected list of statuses not to be empty", statuses.isEmpty());
for (IssueStatus issueStatus : statuses) {
// asserts on status
assertNotNull("ID of status must not be null", issueStatus.getId());
assertNotNull("Name of status must not be null", issueStatus.getName());
}
}
/**
* tests the creation of an invalid {@link Version}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test(expected = IllegalArgumentException.class)
public void testCreateInvalidVersion() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Version version = new Version(null, "Invalid test version " + UUID.randomUUID().toString());
mgr.createVersion(version);
}
/**
* tests the deletion of an invalid {@link Version}. Expects a
* {@link NotFoundException} to be thrown.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test(expected = NotFoundException.class)
public void testDeleteInvalidVersion() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// create new test version
Version version = new Version(null, "Invalid test version " + UUID.randomUUID().toString());
version.setDescription("An invalid test version created by " + this.getClass());
// set invalid id
version.setId(-1);
// now try to delete version
mgr.deleteVersion(version);
}
/**
* tests the deletion of a {@link Version}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testDeleteVersion() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
// create new test version
Version version = new Version(project, "Test version " + UUID.randomUUID().toString());
version.setDescription("A test version created by " + this.getClass());
version.setStatus("open");
Version newVersion = mgr.createVersion(version);
// assert new test version
Assert.assertNotNull("Expected new version not to be null", newVersion);
// now delete version
mgr.deleteVersion(newVersion);
// assert that the version is gone
List<Version> versions = mgr.getVersions(project.getId());
Assert.assertTrue("List of versions of test project must be empty now but is " + versions, versions.isEmpty());
}
/**
* tests the retrieval of {@link Version}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetVersions() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
// create some versions
Version testVersion1 = mgr.createVersion(new Version(project, "Version" + UUID.randomUUID()));
Version testVersion2 = mgr.createVersion(new Version(project, "Version" + UUID.randomUUID()));
try {
List<Version> versions = mgr.getVersions(project.getId());
Assert.assertEquals("Wrong number of versions for project " + project.getName() + " delivered by Redmine Java API", 2, versions.size());
for (Version version : versions) {
// assert version
Assert.assertNotNull("ID of version must not be null", version.getId());
Assert.assertNotNull("Name of version must not be null", version.getName());
Assert.assertNotNull("Project of version must not be null", version.getProject());
}
} finally {
if (testVersion1 != null) {
mgr.deleteVersion(testVersion1);
}
if (testVersion2 != null) {
mgr.deleteVersion(testVersion2);
}
}
}
@Ignore
@Test
public void versionIsRetrievedById() throws IOException, AuthenticationException, RedmineException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
Version createdVersion = mgr.createVersion(new Version(project, "Version_1_" + UUID.randomUUID()));
Version versionById = mgr.getVersionById(createdVersion.getId());
assertEquals(createdVersion, versionById);
}
@Ignore
@Test
public void versionIsUpdated() throws IOException, AuthenticationException, RedmineException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
Version createdVersion = mgr.createVersion(new Version(project, "Version_1_" + UUID.randomUUID()));
String description = "new description";
createdVersion.setDescription(description);
mgr.update(createdVersion);
Version versionById = mgr.getVersionById(createdVersion.getId());
assertEquals(description, versionById.getDescription());
}
/**
* tests the creation and deletion of a {@link IssueCategory}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testCreateAndDeleteIssueCategory() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
// create new test category
IssueCategory category = new IssueCategory(project, "Category" + new Date().getTime());
category.setAssignee(getOurUser());
IssueCategory newIssueCategory = mgr.createCategory(category);
// assert new test category
Assert.assertNotNull("Expected new category not to be null", newIssueCategory);
Assert.assertNotNull("Expected project of new category not to be null", newIssueCategory.getProject());
Assert.assertNotNull("Expected assignee of new category not to be null", newIssueCategory.getAssignee());
// now delete category
mgr.deleteCategory(newIssueCategory);
// assert that the category is gone
List<IssueCategory> categories = mgr.getCategories(project.getId());
Assert.assertTrue("List of categories of test project must be empty now but is " + categories, categories.isEmpty());
}
/**
* tests the retrieval of {@link IssueCategory}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetIssueCategories() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Project project = mgr.getProjectByKey(projectKey);
// create some categories
IssueCategory testIssueCategory1 = new IssueCategory(project, "Category" + new Date().getTime());
testIssueCategory1.setAssignee(getOurUser());
IssueCategory newIssueCategory1 = mgr.createCategory(testIssueCategory1);
IssueCategory testIssueCategory2 = new IssueCategory(project, "Category" + new Date().getTime());
testIssueCategory2.setAssignee(getOurUser());
IssueCategory newIssueCategory2 = mgr.createCategory(testIssueCategory2);
try {
List<IssueCategory> categories = mgr.getCategories(project.getId());
Assert.assertEquals("Wrong number of categories for project " + project.getName() + " delivered by Redmine Java API", 2, categories.size());
for (IssueCategory category : categories) {
// assert category
Assert.assertNotNull("ID of category must not be null", category.getId());
Assert.assertNotNull("Name of category must not be null", category.getName());
Assert.assertNotNull("Project of category must not be null", category.getProject());
Assert.assertNotNull("Assignee of category must not be null", category.getAssignee());
}
} finally {
// scrub test categories
if (newIssueCategory1 != null) {
mgr.deleteCategory(newIssueCategory1);
}
if (newIssueCategory2 != null) {
mgr.deleteCategory(newIssueCategory2);
}
}
}
/**
* tests the creation of an invalid {@link IssueCategory}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test(expected = IllegalArgumentException.class)
public void testCreateInvalidIssueCategory() throws RedmineException, IOException, AuthenticationException, NotFoundException {
IssueCategory category = new IssueCategory(null, "InvalidCategory" + new Date().getTime());
mgr.createCategory(category);
}
/**
* tests the deletion of an invalid {@link IssueCategory}. Expects a
* {@link NotFoundException} to be thrown.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test(expected = NotFoundException.class)
public void testDeleteInvalidIssueCategory() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// create new test category
IssueCategory category = new IssueCategory(null, "InvalidCategory" + new Date().getTime());
// set invalid id
category.setId(-1);
// now try to delete category
mgr.deleteCategory(category);
}
/**
* Tests the retrieval of {@link Tracker}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetTrackers() throws RedmineException, IOException, AuthenticationException, NotFoundException {
List<Tracker> trackers = mgr.getTrackers();
assertNotNull("List of trackers returned should not be null", trackers);
assertFalse("List of trackers returned should not be empty", trackers.isEmpty());
for (Tracker tracker : trackers) {
assertNotNull("Tracker returned should not be null", tracker);
assertNotNull("ID of tracker returned should not be null", tracker.getId());
assertNotNull("Name of tracker returned should not be null", tracker.getName());
}
}
/**
* Tests the retrieval of an {@link Issue}, inlcuding the {@link org.redmine.ta.beans.Attachment}s.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testGetIssueWithAttachments() throws RedmineException, IOException, AuthenticationException, NotFoundException {
Issue newIssue = null;
try {
// create at least 1 issue
Issue issueToCreate = new Issue();
issueToCreate.setSubject("testGetIssueAttachment_" + UUID.randomUUID());
newIssue = mgr.createIssue(projectKey, issueToCreate);
// TODO create test attachments for the issue once the Redmine REST API allows for it
// retrieve issue attachments
Issue retrievedIssue = mgr.getIssueById(newIssue.getId(), INCLUDE.attachments);
Assert.assertNotNull("List of attachments retrieved for issue " + newIssue.getId() + " delivered by Redmine Java API should not be null", retrievedIssue.getAttachments());
// TODO assert attachments once we actually receive ones for our test issue
} finally {
// scrub test issue
if (newIssue != null) {
mgr.deleteIssue(newIssue.getId());
}
}
}
/**
* Tests the retrieval of an {@link org.redmine.ta.beans.Attachment} by its ID.
* TODO reactivate once the Redmine REST API allows for creating attachments
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
// @Test
public void testGetAttachmentById() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// TODO where do we get a valid attachment number from? We can't create an attachment by our own for the test as the Redmine REST API does not support that.
int attachmentID = 1;
Attachment attachment = mgr.getAttachmentById(attachmentID);
Assert.assertNotNull("Attachment retrieved by ID " + attachmentID + " should not be null", attachment);
Assert.assertNotNull("Content URL of attachment retrieved by ID " + attachmentID + " should not be null", attachment.getContentURL());
// TODO more asserts on the attachment once this delivers an attachment
}
/**
* Tests the download of the content of an {@link org.redmine.ta.beans.Attachment}.
* TODO reactivate once the Redmine REST API allows for creating attachments
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
// @Test
public void testDownloadAttachmentContent() throws RedmineException, IOException, AuthenticationException, NotFoundException {
// TODO where do we get a valid attachment number from? We can't create an attachment by our own for the test as the Redmine REST API does not support that.
int attachmentID = 1;
// retrieve issue attachment
Attachment attachment = mgr.getAttachmentById(attachmentID);
// download attachment content
byte[] attachmentContent = mgr.downloadAttachmentContent(attachment);
Assert.assertNotNull("Download of content of attachment with content URL " + attachment.getContentURL() + " should not be null", attachmentContent);
}
/**
* Tests the creation and retrieval of an {@link org.redmine.ta.beans.Issue} with a {@link IssueCategory}.
*
* @throws RedmineException thrown in case something went wrong in Redmine
* @throws IOException thrown in case something went wrong while performing I/O
* operations
* @throws AuthenticationException thrown in case something went wrong while trying to login
* @throws NotFoundException thrown in case the objects requested for could not be found
*/
@Test
public void testCreateAndGetIssueWithCategory() throws RedmineException, IOException, AuthenticationException, NotFoundException {
IssueCategory newIssueCategory = null;
Issue newIssue = null;
try {
Project project = mgr.getProjectByKey(projectKey);
// create an issue category
IssueCategory category = new IssueCategory(project, "Category_" + new Date().getTime());
category.setAssignee(getOurUser());
newIssueCategory = mgr.createCategory(category);
// create an issue
Issue issueToCreate = new Issue();
issueToCreate.setSubject("testGetIssueWithCategory_" + UUID.randomUUID());
issueToCreate.setCategory(newIssueCategory);
newIssue = mgr.createIssue(projectKey, issueToCreate);
// retrieve issue
Issue retrievedIssue = mgr.getIssueById(newIssue.getId());
// assert retrieved category of issue
IssueCategory retrievedCategory = retrievedIssue.getCategory();
Assert.assertNotNull("Category retrieved for issue " + newIssue.getId() + " should not be null", retrievedCategory);
Assert.assertEquals("ID of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getId(), retrievedCategory.getId());
Assert.assertEquals("Name of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getName(), retrievedCategory.getName());
} finally {
if (newIssue != null) {
mgr.deleteIssue(newIssue.getId());
}
if (newIssueCategory != null) {
mgr.deleteCategory(newIssueCategory);
}
}
}
@Test
public void getNewsDoesNotFailForNULLProject() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.getNews(null);
}
@Test
public void getNewsDoesNotFailForTempProject() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.getNews(projectKey);
}
@Test
public void getSavedQueriesDoesNotFailForTempProject() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.getSavedQueries(projectKey);
}
@Test
public void getSavedQueriesDoesNotFailForNULLProject() throws IOException, AuthenticationException, RedmineException, NotFoundException {
mgr.getSavedQueries(null);
}
}
|
package org.deviceconnect.android.deviceplugin.smartmeter.setting.fragment;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.deviceconnect.android.deviceplugin.smartmeter.BuildConfig;
import org.deviceconnect.android.deviceplugin.smartmeter.R;
import org.deviceconnect.android.deviceplugin.smartmeter.SmartMeterMessageService;
import org.deviceconnect.android.deviceplugin.smartmeter.param.DongleConst;
import org.deviceconnect.android.deviceplugin.smartmeter.setting.SmartMeterConnectActivity;
import org.deviceconnect.android.deviceplugin.smartmeter.util.PrefUtil;
import java.util.HashMap;
/**
* Fragment.
*
* @author NTT DOCOMO, INC.
*/
public class SmartMeterConnectFragment extends Fragment {
private static final boolean DEBUG = BuildConfig.DEBUG;
/** Context. */
private static Context mContext;
/** Activity. */
private static Activity mActivity;
/** TAG. */
private static final String TAG = "SMT_MTR_PLUGIN_SETTING";
/** TextView. */
private static TextView mTextViewCommment;
/** Service Status. */
private static int mDongleStatus;
/** Activity Status. */
private static int mActivityStatus;
/** DongleActivity. */
public static final String EXTRA_FINISH_FLAG = "flag";
/** PrefUtil Instance. */
private PrefUtil mPrefUtil;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// Root view.
View root = inflater.inflate(R.layout.connect, container, false);
// Context.
mContext = getActivity().getBaseContext();
mActivity = getActivity();
// PrefUtil Instance.
mPrefUtil = ((SmartMeterConnectActivity) getContext()).getPrefUtil();
// Set status.
mActivityStatus = DongleConst.STATUS_ACTIVITY_DISPLAY;
mDongleStatus = DongleConst.STATUS_DONGLE_NOCONNECT;
// Textview.
mTextViewCommment = (TextView) root.findViewById(R.id.textViewComment);
return root;
}
/**
* Close software Keyboard
*/
private void closeSoftwareKeyboard(final View v) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
@Override
public void onResume() {
super.onResume();
// USBBroadcast Receiver.
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(DongleConst.DEVICE_TO_DONGLE_OPEN_USB_RESULT);
mIntentFilter.addAction(DongleConst.DEVICE_TO_DONGLE_CHECK_USB_RESULT);
mIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
mContext.registerReceiver(mUSBResultEvent, mIntentFilter);
Intent intent = new Intent(DongleConst.DEVICE_TO_DONGLE_CHECK_USB);
mContext.sendBroadcast(intent);
// USB.
UsbManager manager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
for (UsbDevice device : deviceList.values()) {
if (device.getVendorId() == 1027) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// Service.
Intent mIntent = new Intent(mContext, SmartMeterMessageService.class);
mContext.startService(mIntent);
// USB OpenServiceBroadcast.
Intent intent = new Intent(DongleConst.DEVICE_TO_DONGLE_OPEN_USB);
mContext.sendBroadcast(intent);
}
});
break;
}
}
}
@Override
public void onStop() {
super.onStop();
if (mUSBResultEvent != null) {
try {
mContext.unregisterReceiver(mUSBResultEvent);
} catch (Exception e) {
if (DEBUG) {
e.printStackTrace();
}
}
}
mActivityStatus = DongleConst.STATUS_ACTIVITY_PAUSE;
}
/**
* Broadcast receiver for usb event.
*/
private BroadcastReceiver mUSBResultEvent = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
String action = intent.getAction();
boolean bCloseFlag = intent.getBooleanExtra(EXTRA_FINISH_FLAG, false);
switch (action) {
case DongleConst.DEVICE_TO_DONGLE_OPEN_USB_RESULT:
int resultId = intent.getIntExtra("resultId", 0);
if (resultId == DongleConst.CAN_NOT_FIND_USB) {
mTextViewCommment.setText(R.string.not_found_arduino);
} else if (resultId == DongleConst.FAILED_OPEN_USB) {
mTextViewCommment.setText(R.string.failed_open_usb);
} else if (resultId == DongleConst.FAILED_CONNECT_DONGLE) {
mTextViewCommment.setText(R.string.failed_connect_dongle);
} else if (resultId == DongleConst.SUCCESS_CONNECT_DONGLE) {
mTextViewCommment.setText(R.string.success_connect_dongle);
String bRouteId = mPrefUtil.getBRouteId();
String bRoutePassword = mPrefUtil.getBRoutePass();
if (bRouteId == null || bRouteId.length() == 0) {
Toast.makeText(getContext(), R.string.setting_error_b_route_id, Toast.LENGTH_LONG).show();
} else if (bRoutePassword == null || bRoutePassword.length() == 0) {
Toast.makeText(getContext(), R.string.setting_error_b_route_password, Toast.LENGTH_LONG).show();
} else {
checkAndFinish(bCloseFlag);
}
}
break;
case DongleConst.DEVICE_TO_DONGLE_CHECK_USB_RESULT:
int statusId = intent.getIntExtra("statusId", 0);
if (statusId == DongleConst.STATUS_DONGLE_NOCONNECT) {
mDongleStatus = DongleConst.STATUS_DONGLE_NOCONNECT;
} else if (statusId == DongleConst.STATUS_DONGLE_INIT) {
mDongleStatus = DongleConst.STATUS_DONGLE_INIT;
} else if (statusId == DongleConst.STATUS_DONGLE_RUNNING) {
mTextViewCommment.setText(R.string.success_connect);
mDongleStatus = DongleConst.STATUS_DONGLE_RUNNING;
checkAndFinish(bCloseFlag);
}
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED:
mTextViewCommment.setText(R.string.disconnect_usb);
mDongleStatus = DongleConst.STATUS_DONGLE_NOCONNECT;
Intent closeIntent = new Intent(DongleConst.DEVICE_TO_DONGLE_CLOSE_USB);
mContext.sendBroadcast(closeIntent);
checkAndFinish(bCloseFlag);
break;
}
}
};
/**
* Activity.
*/
private void checkAndFinish(final boolean closeFlag) {
Activity activity = getActivity();
if (activity == null) {
return;
}
if (closeFlag) {
activity.finish();
}
}
}
|
package tutorialspoint.basicoperators;
public class Test {
void printArithmeticOperatorsExample() {
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + a * b);
System.out.println("b / a = " + b / a);
System.out.println("b % a = " + b % a);
System.out.println("c % a = " + c % a);
System.out.println("a++ = " + a++);
System.out.println("b
// Check the difference in d++ and ++d
System.out.println("d++ = " + d++);
System.out.println("++d = " + (++d));
}
void printRelationalOperatorsExample() {
int a = 10;
int b = 20;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("a == b = " + (a == b));
System.out.println("a != b = " + (a != b));
System.out.println("a > b = " + (a > b));
System.out.println("a < b = " + (a < b));
System.out.println("b >= a = " + (b >= a));
System.out.println("b <= a = " + (b <= a));
}
void printBitwiseOperatorsExample() {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
int d = -64;
System.out.printf("a = %4d = %s", a, makeZeroPaddedBinary(a, 8));
System.out.printf("\nb = %4d = %s", b, makeZeroPaddedBinary(b, 8));
System.out.printf("\nd = %4d = %s\n", d, makeZeroPaddedBinary(d, 8));
c = a & b; /* 12 = 0000 1100 */
System.out.printf("\n%-8s = %s = %3d", "a & b", makeZeroPaddedBinary(c, 8), c);
c = a | b; /* 61 = 0011 1101 */
System.out.printf("\n%-8s = %s = %3d", "a | b", makeZeroPaddedBinary(c, 8), c);
c = a ^ b; /* 49 = 0011 0001 */
System.out.printf("\n%-8s = %s = %3d", "a ^ b", makeZeroPaddedBinary(c, 8), c);
c = ~a; /*-61 = 1100 0011 */
System.out.printf("\n%-8s = %s = %3d", "~a", makeZeroPaddedBinary(c, 8), c);
c = a << 2; /* 240 = 1111 0000 */
System.out.printf("\n%-8s = %s = %3d", "a << 2", makeZeroPaddedBinary(c, 8), c);
c = a >> 2; /* 215 = 1111 */
System.out.printf("\n%-8s = %s = %3d", "a >> 2", makeZeroPaddedBinary(c, 8), c);
c = d >> 2; /* -16 = 1111 0000 */
System.out.printf("\n%-8s = %s = %3d", "d >> 2", makeZeroPaddedBinary(c, 8), c);
c = d >> 6; /* -1 = 1111 1111 */
System.out.printf("\n%-8s = %s = %3d", "d >> 6", makeZeroPaddedBinary(c, 8), c);
c = a >>> 2; /* 215 = 0000 1111 */
System.out.printf("\n%-8s = %s = %3d\n", "a >>> 2", makeZeroPaddedBinary(c, 8), c);
}
void printLogicalOperatorsExample() {
boolean a = true;
boolean b = false;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("a && b = " + (a && b));
System.out.println("a || b = " + (a || b));
System.out.println("!(a && b) = " + !(a && b));
}
void printAssignmentOperatorsExample() {
int a = 10;
int b = 20;
int c = 0;
System.out.println("a = " + a);
System.out.println("b = " + b);
c = a + b;
System.out.println("c = a + b = " + c);
c += a;
System.out.println("c += a = " + c);
c -= a;
System.out.println("c -= a = " + c);
c *= a;
System.out.println("c *= a = " + c);
a = 10;
c = 15;
System.out.println("a = " + a);
System.out.println("c = " + c);
c /= a;
System.out.println("c /= a = " + c);
a = 10;
c = 15;
System.out.printf("a = %3d = %8s", a, makeZeroPaddedBinary(a, 8));
System.out.printf("\nc = %3d = %8s", c, makeZeroPaddedBinary(c, 8));
c %= a;
System.out.print("\nc %= a = " + c);
System.out.printf(" = %8s", makeZeroPaddedBinary(c, 8));
c <<= 2;
System.out.printf("\nc <<= 2 = %3d = %8s", c, makeZeroPaddedBinary(c, 8));
c >>= 2;
System.out.printf("\nc >>= 2 = %3d = %8s", c, makeZeroPaddedBinary(c, 8));
c &= a;
System.out.printf("\nc &= 2 = %3d = %8s", c, makeZeroPaddedBinary(c, 8));
c ^= a;
System.out.printf("\nc ^= a = %3d = %8s", c, makeZeroPaddedBinary(c, 8));
c |= a;
System.out.printf("\nc |= a = %3d = %8s\n", c, makeZeroPaddedBinary(c, 8));
}
void printConditionalOperatorExample() {
int a, b;
a = 10;
System.out.println("a = " + a);
b = a == 1 ? 20 : 30;
System.out.println("b = a == 1 ? 20 : 30");
System.out.println("Value of b is : " + b);
b = a == 10 ? 20 : 30;
System.out.println("b = a == 10 ? 20 : 30");
System.out.println("Value of b is : " + b);
}
String makeZeroPaddedBinary(int number, int bit) {
String padding = "00000000000000000000000000000000";
String bin = padding + Integer.toBinaryString(number);
return bin.substring(bin.length() - bit, bin.length());
}
public static void main(String args[]) {
Test t = new Test();
t.printArithmeticOperatorsExample();
System.out.println();
t.printRelationalOperatorsExample();
System.out.println();
t.printBitwiseOperatorsExample();
System.out.println();
t.printLogicalOperatorsExample();
System.out.println();
t.printAssignmentOperatorsExample();
System.out.println();
t.printConditionalOperatorExample();;
}
}
|
package seedu.ezdo.logic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
import static seedu.ezdo.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import static seedu.ezdo.model.tag.Tag.MESSAGE_TAG_CONSTRAINTS;
import static seedu.ezdo.model.todo.DueDate.MESSAGE_DUEDATE_CONSTRAINTS;
import static seedu.ezdo.model.todo.Name.MESSAGE_NAME_CONSTRAINTS;
import static seedu.ezdo.model.todo.Priority.MESSAGE_PRIORITY_CONSTRAINTS;
import static seedu.ezdo.model.todo.StartDate.MESSAGE_STARTDATE_CONSTRAINTS;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.google.common.eventbus.Subscribe;
import seedu.ezdo.commons.core.Config;
import seedu.ezdo.commons.core.EventsCenter;
import seedu.ezdo.commons.events.model.EzDoChangedEvent;
import seedu.ezdo.commons.events.ui.JumpToListRequestEvent;
import seedu.ezdo.commons.events.ui.ShowHelpRequestEvent;
import seedu.ezdo.logic.commands.AddCommand;
import seedu.ezdo.logic.commands.ClearCommand;
import seedu.ezdo.logic.commands.Command;
import seedu.ezdo.logic.commands.CommandResult;
import seedu.ezdo.logic.commands.FindCommand;
import seedu.ezdo.logic.commands.HelpCommand;
import seedu.ezdo.logic.commands.KillCommand;
import seedu.ezdo.logic.commands.ListCommand;
import seedu.ezdo.logic.commands.QuitCommand;
import seedu.ezdo.logic.commands.SaveCommand;
import seedu.ezdo.logic.commands.SelectCommand;
import seedu.ezdo.logic.commands.exceptions.CommandException;
import seedu.ezdo.model.EzDo;
import seedu.ezdo.model.Model;
import seedu.ezdo.model.ModelManager;
import seedu.ezdo.model.ReadOnlyEzDo;
import seedu.ezdo.model.tag.Tag;
import seedu.ezdo.model.tag.UniqueTagList;
import seedu.ezdo.model.todo.DueDate;
import seedu.ezdo.model.todo.Name;
import seedu.ezdo.model.todo.Priority;
import seedu.ezdo.model.todo.ReadOnlyTask;
import seedu.ezdo.model.todo.StartDate;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.TaskDate;
import seedu.ezdo.model.todo.UniqueTaskList;
import seedu.ezdo.storage.StorageManager;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
//These are for checking the correctness of the events raised
private ReadOnlyEzDo latestSavedEzDo;
private boolean helpShown;
private int targetedJumpIndex;
@Subscribe
private void handleLocalModelChangedEvent(EzDoChangedEvent ezce) {
latestSavedEzDo = new EzDo(ezce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedJumpIndex = je.targetIndex;
}
@Before
public void setUp() {
model = new ModelManager();
Config config = new Config();
String tempEzDoFile = saveFolder.getRoot().getPath() + "TempEzDo.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempEzDoFile, tempPreferencesFile, config));
EventsCenter.getInstance().registerHandler(this);
latestSavedEzDo = new EzDo(model.getEzDo()); // last saved assumed to be up to date
helpShown = false;
targetedJumpIndex = -1; // non yet
// sort by a field other than name so that it does not affect the tests
model.sortTasks(UniqueTaskList.SortCriteria.PRIORITY);
}
@After
public void tearDown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() {
String invalidCommand = " ";
assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command, confirms that a CommandException is not thrown and that the result message is correct.
* Also confirms that both the 'ezDo' and the 'last shown list' are as specified.
* @see #assertCommandBehavior(boolean, String, String, ReadOnlyEzDo, List)
*/
private void assertCommandSuccess(String inputCommand, String expectedMessage,
ReadOnlyEzDo expectedEzDo,
List<? extends ReadOnlyTask> expectedShownList) {
assertCommandBehavior(false, inputCommand, expectedMessage, expectedEzDo, expectedShownList);
}
/**
* Executes the command, confirms that a CommandException is thrown and that the result message is correct.
* Both the 'ezDo' and the 'last shown list' are verified to be unchanged.
* @see #assertCommandBehavior(boolean, String, String, ReadOnlyEzDo, List)
*/
private void assertCommandFailure(String inputCommand, String expectedMessage) {
EzDo expectedEzDo = new EzDo(model.getEzDo());
List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList());
assertCommandBehavior(true, inputCommand, expectedMessage, expectedEzDo, expectedShownList);
}
/**
* Executes the command, confirms that the result message is correct
* and that a CommandException is thrown if expected
* and also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal ezDo data are same as those in the {@code expectedEzDo} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedEzDo} was saved to the storage file. <br>
*/
private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage,
ReadOnlyEzDo expectedEzDo,
List<? extends ReadOnlyTask> expectedShownList) {
try {
CommandResult result = logic.execute(inputCommand);
assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected);
assertEquals(expectedMessage, result.feedbackToUser);
} catch (CommandException e) {
assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected);
assertEquals(expectedMessage, e.getMessage());
}
//Confirm the ui display elements should contain the right data
assertEquals(expectedShownList, model.getFilteredTaskList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedEzDo, model.getEzDo());
assertEquals(expectedEzDo, latestSavedEzDo);
}
@Test
public void execute_unknownCommandWord() {
String unknownCommand = "uicfhmowqewca";
assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() {
assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new EzDo(), Collections.emptyList());
assertTrue(helpShown);
}
@Test
public void execute_quit() {
assertCommandSuccess("quit", QuitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT,
new EzDo(), Collections.emptyList());
}
@Test
public void execute_quitShortCommand() {
assertCommandSuccess("q", QuitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT,
new EzDo(), Collections.emptyList());
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateTask(1));
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new EzDo(), Collections.emptyList());
}
@Test
public void execute_add_invalidArgsFormat() {
assertCommandFailure("add Valid Name p/1"
+ ", todo d/s23/03/2017 12:23", MESSAGE_PRIORITY_CONSTRAINTS);
assertCommandFailure("add Valid Name p/1 "
+ "s/abcd d/24/04/2017 21:11", MESSAGE_STARTDATE_CONSTRAINTS);
assertCommandFailure("add Valid Name p/1 "
+ "s/abcd d/24/04/2017 10:14", MESSAGE_STARTDATE_CONSTRAINTS);
assertCommandFailure("add Valid Name p/1 "
+ "s/12/12/2013 23:00 d/dueDA1E", MESSAGE_DUEDATE_CONSTRAINTS);
}
@Test
public void execute_add_invalidPersonData() {
assertCommandFailure("add []\\[;] p/3 s/30/03/1999 12:00 d/31/05/1999 13:00 t/invalidName",
MESSAGE_NAME_CONSTRAINTS);
assertCommandFailure("add Valid Name p/not_numbers s/01/08/1998 14:22 d/11/08/1998 15:21 t/invalidPriority",
MESSAGE_PRIORITY_CONSTRAINTS);
assertCommandFailure("add Valid Name p/2 s/Invalid_Start.Date d/11/08/1998 12:22 t/invalidStartDate",
MESSAGE_STARTDATE_CONSTRAINTS);
assertCommandFailure("add Valid Name p/1 s/01/08/1998 14:55 d/invalid_DueDate. t/invalidDueDate",
MESSAGE_DUEDATE_CONSTRAINTS);
assertCommandFailure("add Valid Name p/1 s/01/01/1990 02:33 d/01/03/1990 23:35 t/invalid_-[.tag",
MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.test();
EzDo expectedEZ = new EzDo();
expectedEZ.addTask(toBeAdded);
// execute command and verify result
assertCommandSuccess(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedEZ,
expectedEZ.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.test();
// setup starting state
model.addTask(toBeAdded); // task already in internal ezDo
// execute command and verify result
assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK);
}
@Test
public void execute_list_showsAllTasks() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
EzDo expectedEZ = helper.generateEzDo(2);
List<? extends ReadOnlyTask> expectedList = expectedEZ.getTaskList();
// prepare ezDo state
helper.addToModel(model, 2);
assertCommandSuccess("list",
ListCommand.MESSAGE_SUCCESS,
expectedEZ,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list
* based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage)
throws Exception {
assertCommandFailure(commandWord , expectedMessage); //index missing
assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandFailure(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list
* based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> taskList = helper.generateTaskList(2);
// set AB state to 2 tasks
model.resetData(new EzDo());
for (Task p : taskList) {
model.addTask(p);
}
assertCommandFailure(commandWord + " 3", expectedMessage);
}
@Test
public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
}
@Test
public void execute_selectIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
}
@Test
public void execute_select_jumpsToCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
EzDo expectedEZ = helper.generateEzDo(threeTasks);
helper.addToModel(model, threeTasks);
assertCommandSuccess("select 2",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2),
expectedEZ,
expectedEZ.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1));
}
@Test
public void execute_killInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, KillCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("kill", expectedMessage);
}
@Test
public void execute_killIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("kill");
}
@Test
public void execute_kill_removesCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
EzDo expectedEZ = helper.generateEzDo(threeTasks);
expectedEZ.removeTask(threeTasks.get(1));
helper.addToModel(model, threeTasks);
assertCommandSuccess("kill 2",
String.format(KillCommand.MESSAGE_KILL_TASK_SUCCESS, threeTasks.get(1)),
expectedEZ,
expectedEZ.getTaskList());
}
@Test
public void execute_find_invalidArgsFormat() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandFailure("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task p1 = helper.generateTaskWithName("KE Y");
Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo");
List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2);
EzDo expectedEZ = helper.generateEzDo(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2);
helper.addToModel(model, fourTasks);
assertCommandSuccess("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedEZ,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithName("bla bla KEY bla");
Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task p3 = helper.generateTaskWithName("key key");
Task p4 = helper.generateTaskWithName("KEy sduauo");
List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2);
EzDo expectedEZ = helper.generateEzDo(fourTasks);
List<Task> expectedList = fourTasks;
helper.addToModel(model, fourTasks);
assertCommandSuccess("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedEZ,
expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia");
Task pTarget3 = helper.generateTaskWithName("key key");
Task p1 = helper.generateTaskWithName("sduauo");
List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3);
EzDo expectedEZ = helper.generateEzDo(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3);
helper.addToModel(model, fourTasks);
assertCommandSuccess("find key rAnDoM",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedEZ,
expectedList);
}
@Test
public void execute_save_successful() {
String directory = "./";
assertCommandSuccess("save " + directory, String.format(SaveCommand.MESSAGE_SAVE_TASK_SUCCESS,
directory + SaveCommand.DATA_FILE_NAME), new EzDo(), Collections.emptyList());
}
/**
* A utility class to generate test data.
*/
class TestDataHelper {
private Task test() throws Exception {
Name name = new Name("LogicManager Test Case");
Priority privatePriority = new Priority("1");
TaskDate privateStartDate = new StartDate("3/3/2015 21:12");
TaskDate privateDueDate = new DueDate("tomorrow");
Tag tag1 = new Tag("tag1");
Tag tag2 = new Tag("longertag2");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
return new Task(name, privatePriority, privateStartDate, privateDueDate, tags);
}
/**
* Generates a valid task using the given seed.
* Running this function with the same parameter values guarantees the returned task will have the same state.
* Each unique seed will generate a unique Task object.
*
* @param seed used to generate the task data field values
*/
private Task generateTask(int seed) throws Exception {
return new Task(
new Name("LogicManager Generated Task " + seed),
new Priority("1"),
new StartDate("01/01/2000 09:09"),
new DueDate("07/07/2017 12:12"),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))
);
}
/** Generates the correct add command based on the task given */
private String generateAddCommand(Task p) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ");
cmd.append(p.getName().toString());
cmd.append(" p/").append(p.getPriority());
cmd.append(" s/").append(p.getStartDate());
cmd.append(" d/").append(p.getDueDate());
UniqueTagList tags = p.getTags();
for (Tag t: tags) {
cmd.append(" t/").append(t.tagName);
}
return cmd.toString();
}
/**
* Generates an EzDo with auto-generated tasks.
*/
private EzDo generateEzDo(int numGenerated) throws Exception {
EzDo ezDo = new EzDo();
addToEzDo(ezDo, numGenerated);
return ezDo;
}
/**
* Generates an EzDo based on the list of Tasks given.
*/
private EzDo generateEzDo(List<Task> tasks) throws Exception {
EzDo ezDo = new EzDo();
addToEzDo(ezDo, tasks);
return ezDo;
}
/**
* Adds auto-generated Task objects to the given EzDo
* @param ezDo The EzDo to which the Tasks will be added
*/
private void addToEzDo(EzDo ezDo, int numGenerated) throws Exception {
addToEzDo(ezDo, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given EzDo
*/
private void addToEzDo(EzDo ezDo, List<Task> tasksToAdd) throws Exception {
for (Task p: tasksToAdd) {
ezDo.addTask(p);
}
}
/**
* Adds auto-generated Task objects to the given model
* @param model The model to which the Tasks will be added
*/
private void addToModel(Model model, int numGenerated) throws Exception {
addToModel(model, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given model
*/
private void addToModel(Model model, List<Task> tasksToAdd) throws Exception {
for (Task p: tasksToAdd) {
model.addTask(p);
}
}
/**
* Generates a list of Tasks based on the flags.
*/
private List<Task> generateTaskList(int numGenerated) throws Exception {
List<Task> tasks = new ArrayList<>();
for (int i = 1; i <= numGenerated; i++) {
tasks.add(generateTask(i));
}
return tasks;
}
private List<Task> generateTaskList(Task... tasks) {
return Arrays.asList(tasks);
}
/**
* Generates a Task object with given name. Other fields will have some dummy values.
*/
private Task generateTaskWithName(String name) throws Exception {
return new Task(
new Name(name),
new Priority("1"),
new StartDate("01/01/2009 09:14"),
new DueDate("09/09/2017 10:10"),
new UniqueTagList(new Tag("tag"))
);
}
}
}
|
package org.deeplearning4j.models.sequencevectors.transformers.impl.iterables;
import lombok.extern.slf4j.Slf4j;
import org.datavec.api.util.ClassPathResource;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.sequencevectors.transformers.impl.SentenceTransformer;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.deeplearning4j.text.sentenceiterator.BasicLineIterator;
import org.deeplearning4j.text.sentenceiterator.MutipleEpochsSentenceIterator;
import org.deeplearning4j.text.sentenceiterator.PrefetchingSentenceIterator;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;
import org.junit.Before;
import org.junit.Test;
import java.util.Iterator;
import static org.junit.Assert.*;
/**
* @author raver119@gmail.com
*/
@Slf4j
public class ParallelTransformerIteratorTest {
private TokenizerFactory factory = new DefaultTokenizerFactory();
@Before
public void setUp() throws Exception {
}
@Test
public void hasNext() throws Exception {
SentenceIterator iterator = new PrefetchingSentenceIterator.Builder(new BasicLineIterator(new ClassPathResource("/big/raw_sentences.txt").getFile()))
.setFetchSize(1000)
.build();
SentenceTransformer transformer = new SentenceTransformer.Builder()
.iterator(iterator)
.allowMultithreading(true)
.tokenizerFactory(factory)
.build();
Iterator<Sequence<VocabWord>> iter = transformer.iterator();
int cnt = 0;
while (iter.hasNext()) {
Sequence<VocabWord> sequence = iter.next();
assertNotEquals("Failed on [" + cnt + "] iteration", null, sequence);
assertNotEquals("Failed on [" + cnt + "] iteration", 0, sequence.size());
cnt++;
}
assertEquals(97162, cnt);
}
@Test
public void testSpeedComparison1() throws Exception {
SentenceIterator iterator = new MutipleEpochsSentenceIterator(new BasicLineIterator(new ClassPathResource("/big/raw_sentences.txt").getFile()), 25);
SentenceTransformer transformer = new SentenceTransformer.Builder()
.iterator(iterator)
.allowMultithreading(false)
.tokenizerFactory(factory)
.build();
Iterator<Sequence<VocabWord>> iter = transformer.iterator();
int cnt = 0;
long time1 = System.currentTimeMillis();
while (iter.hasNext()) {
Sequence<VocabWord> sequence = iter.next();
assertNotEquals("Failed on [" + cnt + "] iteration", null, sequence);
assertNotEquals("Failed on [" + cnt + "] iteration", 0, sequence.size());
cnt++;
}
long time2 = System.currentTimeMillis();
log.info("Single-threaded time: {} ms", time2 - time1);
iterator.reset();
transformer = new SentenceTransformer.Builder()
.iterator(iterator)
.allowMultithreading(true)
.tokenizerFactory(factory)
.build();
iter = transformer.iterator();
time1 = System.currentTimeMillis();
while (iter.hasNext()) {
Sequence<VocabWord> sequence = iter.next();
assertNotEquals("Failed on [" + cnt + "] iteration", null, sequence);
assertNotEquals("Failed on [" + cnt + "] iteration", 0, sequence.size());
cnt++;
}
time2 = System.currentTimeMillis();
log.info("Multi-threaded time: {} ms", time2 - time1);
SentenceIterator baseIterator = iterator;
baseIterator.reset();
iterator = new PrefetchingSentenceIterator.Builder(baseIterator)
.setFetchSize(1024)
.build();
iter = transformer.iterator();
time1 = System.currentTimeMillis();
while (iter.hasNext()) {
Sequence<VocabWord> sequence = iter.next();
assertNotEquals("Failed on [" + cnt + "] iteration", null, sequence);
assertNotEquals("Failed on [" + cnt + "] iteration", 0, sequence.size());
cnt++;
}
time2 = System.currentTimeMillis();
log.info("Prefetched Single-threaded time: {} ms", time2 - time1);
iterator.reset();
transformer = new SentenceTransformer.Builder()
.iterator(iterator)
.allowMultithreading(true)
.tokenizerFactory(factory)
.build();
iter = transformer.iterator();
time1 = System.currentTimeMillis();
while (iter.hasNext()) {
Sequence<VocabWord> sequence = iter.next();
assertNotEquals("Failed on [" + cnt + "] iteration", null, sequence);
assertNotEquals("Failed on [" + cnt + "] iteration", 0, sequence.size());
cnt++;
}
time2 = System.currentTimeMillis();
log.info("Prefetched Multi-threaded time: {} ms", time2 - time1);
}
}
|
package seedu.jimi.logic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
import static seedu.jimi.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.google.common.eventbus.Subscribe;
import seedu.jimi.TestApp;
import seedu.jimi.commons.core.Config;
import seedu.jimi.commons.core.EventsCenter;
import seedu.jimi.commons.events.model.TaskBookChangedEvent;
import seedu.jimi.commons.events.ui.JumpToListRequestEvent;
import seedu.jimi.commons.events.ui.ShowHelpRequestEvent;
import seedu.jimi.commons.util.CommandUtil;
import seedu.jimi.commons.util.ConfigUtil;
import seedu.jimi.logic.commands.AddCommand;
import seedu.jimi.logic.commands.ClearCommand;
import seedu.jimi.logic.commands.Command;
import seedu.jimi.logic.commands.CommandResult;
import seedu.jimi.logic.commands.DeleteCommand;
import seedu.jimi.logic.commands.ExitCommand;
import seedu.jimi.logic.commands.FindCommand;
import seedu.jimi.logic.commands.HelpCommand;
import seedu.jimi.logic.commands.ListCommand;
import seedu.jimi.logic.commands.SaveAsCommand;
import seedu.jimi.logic.commands.ShowCommand;
import seedu.jimi.model.Model;
import seedu.jimi.model.ModelManager;
import seedu.jimi.model.ReadOnlyTaskBook;
import seedu.jimi.model.TaskBook;
import seedu.jimi.model.tag.Priority;
import seedu.jimi.model.tag.Tag;
import seedu.jimi.model.tag.UniqueTagList;
import seedu.jimi.model.task.FloatingTask;
import seedu.jimi.model.task.Name;
import seedu.jimi.model.task.ReadOnlyTask;
import seedu.jimi.storage.StorageManager;
import seedu.jimi.testutil.TestUtil;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
//These are for checking the correctness of the events raised
private ReadOnlyTaskBook latestSavedTaskBook;
private boolean helpShown;
private ReadOnlyTask targetedTask;
private List<Command> cmdStubList = CommandUtil.getInstance().getCommandStubList();
@Subscribe
private void handleLocalModelChangedEvent(TaskBookChangedEvent tbce) {
latestSavedTaskBook = new TaskBook(tbce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedTask = je.targetTask;
}
@Before
public void setup() {
model = new ModelManager();
String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedTaskBook = new TaskBook(model.getTaskBook()); // last saved assumed to be up to date before.
helpShown = false;
}
@After
public void teardown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() throws Exception {
String invalidCommand = " ";
assertCommandBehavior(invalidCommand,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command and confirms that the result message is correct.
* Both the 'address book' and the 'last shown list' are expected to be empty.
* @see #assertCommandBehavior(String, String, ReadOnlyTaskBook, List)
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception {
assertCommandBehavior(inputCommand, expectedMessage, new TaskBook(), Collections.emptyList());
}
/**
* Executes the command and confirms that the result message is correct and
* also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal address book data are same as those in the {@code expectedAddressBook} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedAddressBook} was saved to the storage file. <br>
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage,
ReadOnlyTaskBook expectedTaskBook,
List<? extends ReadOnlyTask> expectedShownList) throws Exception {
//Execute the command
CommandResult result = logic.execute(inputCommand);
//Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownList, model.getFilteredAgendaTaskList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTaskBook, model.getTaskBook());
assertEquals(expectedTaskBook, latestSavedTaskBook);
}
// @@author A0140133B
@Test
public void execute_unknownCommandWord() throws Exception {
String unknownCommand = "uicfhmowqewca";
assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand));
/* exit and clear should have the user type the full command word for it to be valid */
unknownCommand = "ex";
assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand));
unknownCommand = "exi";
assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand));
unknownCommand = "cl";
assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand));
unknownCommand = "cle";
assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand));
unknownCommand = "clea";
assertCommandBehavior(unknownCommand, String.format(MESSAGE_UNKNOWN_COMMAND, unknownCommand));
}
@Test
public void execute_help() throws Exception {
// testing pop up page
assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
helpShown = false;
assertCommandBehavior("h", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
helpShown = false;
assertCommandBehavior("he", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
helpShown = false;
assertCommandBehavior("hel", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
helpShown = false;
for (Command c : cmdStubList) {
// to account for some commands having no command words e.g. IncorrectCommand
if (c.getCommandWord().isEmpty()) {
continue;
}
assertCommandBehavior("help " + c.getCommandWord(), c.getMessageUsage());
assertFalse(helpShown);
assertCommandBehavior("h " + c.getCommandWord(), c.getMessageUsage());
assertFalse(helpShown);
assertCommandBehavior("he " + c.getCommandWord(), c.getMessageUsage());
assertFalse(helpShown);
assertCommandBehavior("hel " + c.getCommandWord(), c.getMessageUsage());
assertFalse(helpShown);
}
}
@Test
public void execute_help_unknown_cmd() throws Exception {
String invalidCmd = "asdasdasdasd";
String expectedMessage = String.format(MESSAGE_UNKNOWN_COMMAND, invalidCmd);
helpShown = false;
assertCommandBehavior("help " + invalidCmd, expectedMessage);
assertFalse(helpShown);
}
@Test
public void execute_exit() throws Exception {
assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT);
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateFloatingTask(1));
model.addTask(helper.generateFloatingTask(2));
model.addTask(helper.generateFloatingTask(3));
assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new TaskBook(), Collections.emptyList());
}
@Test
public void execute_add_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
assertCommandBehavior(
"add \"do dishes\" t/impt t/asd", expectedMessage);
assertCommandBehavior(
"add \"wash //plates\"", expectedMessage);
assertCommandBehavior(
"a \"do dishes\" t/impt t/asd", expectedMessage);
assertCommandBehavior(
"a \"wash //plates\"", expectedMessage);
assertCommandBehavior(
"ad \"do dishes\" t/impt t/asd", expectedMessage);
assertCommandBehavior(
"ad \"wash //plates\"", expectedMessage);
}
@Test
public void execute_add_invalidPersonData() throws Exception {
assertCommandBehavior(
"add \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS);
assertCommandBehavior(
"a \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS);
assertCommandBehavior(
"ad \"Valid task\" t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS);
assertCommandBehavior(
"add \"Valid task\" t/valid p/invalid", Priority.MESSAGE_PRIORITY_CONSTRAINTS);
}
// @@author
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
TaskBook expectedAB = new TaskBook();
// execute command and verify result
FloatingTask toBeAdded = helper.adam();
expectedAB.addTask(toBeAdded);
assertCommandBehavior(
helper.generateAddCommand_Ad(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getTaskList());
toBeAdded = helper.homework();
expectedAB.addTask(toBeAdded);
assertCommandBehavior(
helper.generateAddCommand_A(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getTaskList());
toBeAdded = helper.laundry();
expectedAB.addTask(toBeAdded);
assertCommandBehavior(
helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
FloatingTask toBeAdded = helper.adam();
TaskBook expectedAB = new TaskBook();
expectedAB.addTask(toBeAdded);
// setup starting state
model.addTask(toBeAdded); // person already in internal address book
// execute command and verify result
assertCommandBehavior(
helper.generateAddCommand(toBeAdded),
AddCommand.MESSAGE_DUPLICATE_TASK,
expectedAB,
expectedAB.getTaskList());
assertCommandBehavior(
helper.generateAddCommand_A(toBeAdded),
AddCommand.MESSAGE_DUPLICATE_TASK,
expectedAB,
expectedAB.getTaskList());
assertCommandBehavior(
helper.generateAddCommand_Ad(toBeAdded),
AddCommand.MESSAGE_DUPLICATE_TASK,
expectedAB,
expectedAB.getTaskList());
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single person in the shown list, using visible index.
* @param commandWord to test assuming it targets a single person in the last shown list based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception {
assertCommandBehavior(commandWord , expectedMessage); //index missing
assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandBehavior(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single person in the shown list, using visible index.
* @param commandWord to test assuming it targets a single person in the last shown list based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<FloatingTask> floatingTaskList = helper.generateFloatingTaskList(2);
// set AB state to 2 persons
model.resetData(new TaskBook());
for (FloatingTask p : floatingTaskList) {
model.addTask(p);
}
assertCommandBehavior(commandWord + " t3", expectedMessage, model.getTaskBook(), floatingTaskList);
}
//@@author A0138915X
@Test
public void execute_show_showsAllTasksAndEvents() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
TaskBook expectedAB = helper.generateTaskBook(2);
List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList();
// prepare address book state
helper.addToModel(model, 2);
assertCommandBehavior("s all",
ShowCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
assertCommandBehavior("sh all",
ShowCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
assertCommandBehavior("sho all",
ShowCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
assertCommandBehavior("show all",
ShowCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
}
public void execute_show_showsFloatingTasks() throws Exception {
}
//@@author
/*
@Test
public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("s", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("se", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("sel", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("sele", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("selec", expectedMessage);
}
@Test
public void execute_selectIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
assertIndexNotFoundBehaviorForCommand("s");
assertIndexNotFoundBehaviorForCommand("se");
assertIndexNotFoundBehaviorForCommand("sel");
assertIndexNotFoundBehaviorForCommand("sele");
assertIndexNotFoundBehaviorForCommand("selec");
}
@Test
public void execute_select_jumpsToCorrectPerson() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<FloatingTask> threeFloatingTasks = helper.generateFloatingTaskList(3);
TaskBook expectedAB = helper.generateFloatingTaskBook(threeFloatingTasks);
helper.addToModel(model, threeFloatingTasks);
assertCommandBehavior("select t2",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2),
expectedAB,
expectedAB.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredAgendaTaskList().get(1), threeFloatingTasks.get(1));
assertCommandBehavior("s t1",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1),
expectedAB,
expectedAB.getTaskList());
assertEquals(0, targetedJumpIndex);
assertEquals(model.getFilteredAgendaTaskList().get(0), threeFloatingTasks.get(0));
assertCommandBehavior("se t2",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2),
expectedAB,
expectedAB.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredAgendaTaskList().get(1), threeFloatingTasks.get(1));
assertCommandBehavior("sel t1",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1),
expectedAB,
expectedAB.getTaskList());
assertEquals(0, targetedJumpIndex);
assertEquals(model.getFilteredAgendaTaskList().get(0), threeFloatingTasks.get(0));
assertCommandBehavior("sele t2",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2),
expectedAB,
expectedAB.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredAgendaTaskList().get(1), threeFloatingTasks.get(1));
assertCommandBehavior("selec t1",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 1),
expectedAB,
expectedAB.getTaskList());
assertEquals(0, targetedJumpIndex);
assertEquals(model.getFilteredAgendaTaskList().get(0), threeFloatingTasks.get(0));
}
*/
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("d", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("de", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("del", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("dele", expectedMessage);
assertIncorrectIndexFormatBehaviorForCommand("delet", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
assertIndexNotFoundBehaviorForCommand("d");
assertIndexNotFoundBehaviorForCommand("de");
assertIndexNotFoundBehaviorForCommand("del");
assertIndexNotFoundBehaviorForCommand("dele");
assertIndexNotFoundBehaviorForCommand("delet");
}
@Test
public void execute_delete_removesCorrectPerson() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
FloatingTask index0 = helper.generateFloatingTaskWithName("first");
FloatingTask index1 = helper.generateFloatingTaskWithName("second");
FloatingTask index2 = helper.generateFloatingTaskWithName("third");
List<FloatingTask> threeFloatingTasks = helper.generateFloatingTaskList(index0, index1, index2);
TaskBook expectedAB = helper.generateFloatingTaskBook(threeFloatingTasks);
helper.addToModel(model, threeFloatingTasks);
// execute command and verify result
expectedAB.removeTask(threeFloatingTasks.get(1));
assertCommandBehavior("delete t2",
String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeFloatingTasks.get(1)),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_find_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandBehavior("find ", expectedMessage);
assertCommandBehavior("f ", expectedMessage);
assertCommandBehavior("fi ", expectedMessage);
assertCommandBehavior("fin ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
FloatingTask pTarget1 = helper.generateFloatingTaskWithName("bla bla KEY bla");
FloatingTask pTarget2 = helper.generateFloatingTaskWithName("bla KEY bla bceofeia");
FloatingTask p1 = helper.generateFloatingTaskWithName("KE Y");
FloatingTask p2 = helper.generateFloatingTaskWithName("KEYKEYKEY sduauo");
List<FloatingTask> fourFloatingTasks = helper.generateFloatingTaskList(p1, pTarget1, p2, pTarget2);
TaskBook expectedAB = helper.generateFloatingTaskBook(fourFloatingTasks);
List<FloatingTask> expectedList = helper.generateFloatingTaskList(pTarget1, pTarget2, p1, p2);
helper.addToModel(model, fourFloatingTasks);
assertCommandBehavior("find \"KEY\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("fi \"KEY\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("fin \"KEY\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("f \"KEY\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
FloatingTask p1 = helper.generateFloatingTaskWithName("bla bla KEY bla");
FloatingTask p2 = helper.generateFloatingTaskWithName("bla KEY bla bceofeia");
FloatingTask p3 = helper.generateFloatingTaskWithName("key key");
FloatingTask p4 = helper.generateFloatingTaskWithName("KEy sduauo");
List<FloatingTask> fourFloatingTasks = helper.generateFloatingTaskList(p1, p2, p3, p4);
TaskBook expectedAB = helper.generateFloatingTaskBook(fourFloatingTasks);
List<FloatingTask> expectedList = fourFloatingTasks;
helper.addToModel(model, fourFloatingTasks);
assertCommandBehavior("find \"KEY\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("fi \"KEY\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("fin \"KEY\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("f \"KEY\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
FloatingTask pTarget1 = helper.generateFloatingTaskWithName("bla bla KEY bla");
FloatingTask pTarget2 = helper.generateFloatingTaskWithName("bla rAnDoM bla bceofeia");
FloatingTask pTarget3 = helper.generateFloatingTaskWithName("key key");
FloatingTask p1 = helper.generateFloatingTaskWithName("sduauo");
List<FloatingTask> fourFloatingTasks = helper.generateFloatingTaskList(pTarget1, p1, pTarget2, pTarget3);
TaskBook expectedAB = helper.generateFloatingTaskBook(fourFloatingTasks);
List<FloatingTask> expectedList = helper.generateFloatingTaskList(pTarget1, pTarget2, pTarget3);
helper.addToModel(model, fourFloatingTasks);
assertCommandBehavior("find \"key rAnDoM\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("f \"key rAnDoM\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("fi \"key rAnDoM\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
assertCommandBehavior("fin \"key rAnDoM\"",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_saveAs_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveAsCommand.MESSAGE_USAGE);
assertCommandBehavior("saveas ", expectedMessage);
assertCommandBehavior("saveas data/taskbook", expectedMessage);
assertCommandBehavior("saveas data/taskbook.txt", expectedMessage);
}
@Test
public void execute_saveAs_successful() throws Exception {
SaveAsCommand.setConfigFilePath(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING); //Access config file used for testing only
TestDataHelper helper = new TestDataHelper();
String originalTaskBookFilePathName = TestUtil.getFilePathInSandboxFolder("sampleData.xml");
String newTaskBookFilePathName = TestUtil.getFilePathInSandboxFolder("newSampleData.xml");
Config originalConfig = helper.generateConfigFile(originalTaskBookFilePathName);
Config expectedConfig = helper.generateConfigFile(newTaskBookFilePathName);
Config currentConfig = ConfigUtil.readConfig(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING).orElse(new Config());
assertCommandBehavior(helper.generateSaveAsCommand(newTaskBookFilePathName),
String.format(SaveAsCommand.MESSAGE_SUCCESS, expectedConfig.getTaskBookFilePath()));
currentConfig = ConfigUtil.readConfig(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING).orElse(new Config());
assertEquals(expectedConfig, currentConfig);
assertCommandBehavior(helper.generateSaveAsCommand(originalTaskBookFilePathName),
String.format(SaveAsCommand.MESSAGE_SUCCESS, originalConfig.getTaskBookFilePath()));
currentConfig = ConfigUtil.readConfig(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING).orElse(new Config());
assertEquals(originalConfig, currentConfig);
}
@Test
public void execute_saveAs_duplicateNotAllowed() throws Exception {
SaveAsCommand.setConfigFilePath(TestApp.DEFAULT_CONFIG_FILE_FOR_TESTING); //Access config file used for testing only
TestDataHelper helper = new TestDataHelper();
String originalTaskBookFilePathName = TestUtil.getFilePathInSandboxFolder("sampleData.xml");
String expectedMessage = String.format(SaveAsCommand.MESSAGE_DUPLICATE_SAVE_DIRECTORY);
assertCommandBehavior(helper.generateSaveAsCommand(originalTaskBookFilePathName), expectedMessage);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper {
FloatingTask adam() throws Exception {
Name name = new Name("Adam Brown");
Tag tag1 = new Tag("tag1");
UniqueTagList tags = new UniqueTagList(tag1);
Priority priority = new Priority("HIGH");
return new FloatingTask(name, tags, priority);
}
FloatingTask laundry() throws Exception {
Name name = new Name("laundry");
Tag tag1 = new Tag("dothem");
UniqueTagList tags = new UniqueTagList(tag1);
Priority priority = new Priority("MED");
return new FloatingTask(name, tags, priority);
}
FloatingTask homework() throws Exception {
Name name = new Name("homework");
Tag tag1 = new Tag("impt");
UniqueTagList tags = new UniqueTagList(tag1);
Priority priority = new Priority("LOW");
return new FloatingTask(name, tags, priority);
}
/**
* Generates a valid person using the given seed.
* Running this function with the same parameter values guarantees the returned person will have the same state.
* Each unique seed will generate a unique FloatingTask object.
*
* @param seed used to generate the person data field values
*/
FloatingTask generateFloatingTask(int seed) throws Exception {
return new FloatingTask(
new Name("FloatingTask " + seed),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))),
new Priority("MED")
);
}
// @@author A0140133B
/** Generates the correct add command based on the person given */
String generateAddCommand(FloatingTask p) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ");
cmd.append("\"");
cmd.append(p.getName().toString());
cmd.append("\"");
UniqueTagList tags = p.getTags();
for (Tag t : tags) {
cmd.append(" t/").append(t.tagName);
cmd.append(" p/");
cmd.append(p.getPriority().tagName);
}
return cmd.toString();
}
String generateAddCommand_A(FloatingTask p) {
StringBuffer cmd = new StringBuffer();
cmd.append("a ");
cmd.append("\"");
cmd.append(p.getName().toString());
cmd.append("\"");
UniqueTagList tags = p.getTags();
for (Tag t : tags) {
cmd.append(" t/").append(t.tagName);
cmd.append(" p/").append(p.getPriority().tagName);
}
return cmd.toString();
}
String generateAddCommand_Ad(FloatingTask p) {
StringBuffer cmd = new StringBuffer();
cmd.append("ad ");
cmd.append("\"");
cmd.append(p.getName().toString());
cmd.append("\"");
UniqueTagList tags = p.getTags();
for (Tag t : tags) {
cmd.append(" t/").append(t.tagName);
cmd.append(" p/").append(p.getPriority().tagName);
}
return cmd.toString();
}
// @@author
/**
* Generates an TaskBook with auto-generated persons.
*/
TaskBook generateTaskBook(int numGenerated) throws Exception{
TaskBook taskBook = new TaskBook();
addToTaskBook(taskBook, numGenerated);
return taskBook;
}
/**
* Generates an TaskBook based on the list of Persons given.
*/
TaskBook generateFloatingTaskBook(List<FloatingTask> floatingTasks) throws Exception{
TaskBook taskBook = new TaskBook();
addToFloatingTaskBook(taskBook, floatingTasks);
return taskBook;
}
/**
* Adds auto-generated FloatingTask objects to the given TaskBook
* @param taskBook The TaskBook to which the Persons will be added
*/
void addToTaskBook(TaskBook taskBook, int numGenerated) throws Exception{
addToFloatingTaskBook(taskBook, generateFloatingTaskList(numGenerated));
}
/**
* Adds the given list of Persons to the given TaskBook
*/
void addToFloatingTaskBook(TaskBook taskBook, List<FloatingTask> floatingTasksToAdd) throws Exception{
for(FloatingTask p: floatingTasksToAdd){
taskBook.addTask(p);
}
}
/**
* Adds auto-generated FloatingTask objects to the given model
* @param model The model to which the Persons will be added
*/
void addToModel(Model model, int numGenerated) throws Exception{
addToModel(model, generateFloatingTaskList(numGenerated));
}
/**
* Adds the given list of Persons to the given model
*/
void addToModel(Model model, List<FloatingTask> floatingTasksToAdd) throws Exception{
for (FloatingTask p : floatingTasksToAdd) {
model.addTask(p);
}
}
/**
* Generates a list of FloatingTasks based on the flags.
*/
List<FloatingTask> generateFloatingTaskList(int numGenerated) throws Exception{
List<FloatingTask> floatingTasks = new ArrayList<>();
for (int i = 1; i <= numGenerated; i++) {
floatingTasks.add(generateFloatingTask(i));
}
return floatingTasks;
}
List<FloatingTask> generateFloatingTaskList(FloatingTask... persons) {
return Arrays.asList(persons);
}
/**
* Generates a FloatingTask object with given name. Other fields will have some dummy values.
*/
FloatingTask generateFloatingTaskWithName(String name) throws Exception {
return new FloatingTask(
new Name(name),
new UniqueTagList(new Tag("tag")),
new Priority("MED")
);
}
/**
* Generates the correct saveAs command based on the filepath given
**/
String generateSaveAsCommand(String taskBookFilePathName) {
StringBuffer cmd = new StringBuffer();
cmd.append("saveas ");
cmd.append(taskBookFilePathName);
return cmd.toString();
}
/**
* Generates a config file with the given task book file path name. Other fields will have some dummy values.
*/
Config generateConfigFile(String taskBookFilePathName) throws Exception {
Config config = new Config();
config.setTaskBookFilePath(taskBookFilePathName);
return config;
}
}
}
|
package io.quarkus.resteasy.reactive.server.deployment;
import static io.quarkus.resteasy.reactive.common.deployment.QuarkusResteasyReactiveDotNames.HTTP_SERVER_REQUEST;
import static io.quarkus.resteasy.reactive.common.deployment.QuarkusResteasyReactiveDotNames.HTTP_SERVER_RESPONSE;
import static io.quarkus.resteasy.reactive.common.deployment.QuarkusResteasyReactiveDotNames.ROUTING_CONTEXT;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import javax.transaction.RollbackException;
import javax.ws.rs.Priorities;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.CompositeIndex;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.Indexer;
import org.jboss.jandex.MethodInfo;
import org.jboss.resteasy.reactive.common.core.BlockingNotAllowedException;
import org.jboss.resteasy.reactive.common.model.ResourceContextResolver;
import org.jboss.resteasy.reactive.common.model.ResourceExceptionMapper;
import org.jboss.resteasy.reactive.common.model.ResourceInterceptors;
import org.jboss.resteasy.reactive.common.model.ResourceParamConverterProvider;
import org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames;
import org.jboss.resteasy.reactive.common.processor.scanning.ApplicationScanningResult;
import org.jboss.resteasy.reactive.common.processor.scanning.ResteasyReactiveInterceptorScanner;
import org.jboss.resteasy.reactive.server.core.ExceptionMapping;
import org.jboss.resteasy.reactive.server.model.ContextResolvers;
import org.jboss.resteasy.reactive.server.model.ParamConverterProviders;
import org.jboss.resteasy.reactive.server.processor.generation.exceptionmappers.ServerExceptionMapperGenerator;
import org.jboss.resteasy.reactive.server.processor.generation.filters.FilterGeneration;
import org.jboss.resteasy.reactive.server.processor.scanning.AsyncReturnTypeScanner;
import org.jboss.resteasy.reactive.server.processor.scanning.CacheControlScanner;
import org.jboss.resteasy.reactive.server.processor.scanning.ResteasyReactiveContextResolverScanner;
import org.jboss.resteasy.reactive.server.processor.scanning.ResteasyReactiveExceptionMappingScanner;
import org.jboss.resteasy.reactive.server.processor.scanning.ResteasyReactiveFeatureScanner;
import io.quarkus.arc.ArcUndeclaredThrowableException;
import io.quarkus.arc.Unremovable;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor;
import io.quarkus.arc.processor.DotNames;
import io.quarkus.deployment.Capabilities;
import io.quarkus.deployment.Capability;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.index.IndexingUtil;
import io.quarkus.resteasy.reactive.common.deployment.ApplicationResultBuildItem;
import io.quarkus.resteasy.reactive.common.deployment.ResourceInterceptorsContributorBuildItem;
import io.quarkus.resteasy.reactive.common.deployment.ResourceScanningResultBuildItem;
import io.quarkus.resteasy.reactive.server.spi.MethodScannerBuildItem;
import io.quarkus.resteasy.reactive.server.spi.UnwrappedExceptionBuildItem;
import io.quarkus.resteasy.reactive.spi.ContainerRequestFilterBuildItem;
import io.quarkus.resteasy.reactive.spi.ContainerResponseFilterBuildItem;
import io.quarkus.resteasy.reactive.spi.ContextResolverBuildItem;
import io.quarkus.resteasy.reactive.spi.CustomContainerRequestFilterBuildItem;
import io.quarkus.resteasy.reactive.spi.CustomContainerResponseFilterBuildItem;
import io.quarkus.resteasy.reactive.spi.CustomExceptionMapperBuildItem;
import io.quarkus.resteasy.reactive.spi.DynamicFeatureBuildItem;
import io.quarkus.resteasy.reactive.spi.ExceptionMapperBuildItem;
import io.quarkus.resteasy.reactive.spi.JaxrsFeatureBuildItem;
import io.quarkus.resteasy.reactive.spi.ParamConverterBuildItem;
import io.quarkus.runtime.BlockingOperationNotAllowedException;
/**
* Processor that handles scanning for types and turning them into build items
*/
public class ResteasyReactiveScanningProcessor {
@BuildStep
public MethodScannerBuildItem asyncSupport() {
return new MethodScannerBuildItem(new AsyncReturnTypeScanner());
}
@BuildStep
public MethodScannerBuildItem cacheControlSupport() {
return new MethodScannerBuildItem(new CacheControlScanner());
}
@BuildStep
public ResourceInterceptorsContributorBuildItem scanForInterceptors(CombinedIndexBuildItem combinedIndexBuildItem,
ApplicationResultBuildItem applicationResultBuildItem) {
return new ResourceInterceptorsContributorBuildItem(new Consumer<ResourceInterceptors>() {
@Override
public void accept(ResourceInterceptors interceptors) {
ResteasyReactiveInterceptorScanner.scanForInterceptors(interceptors, combinedIndexBuildItem.getIndex(),
applicationResultBuildItem.getResult());
}
});
}
@BuildStep
public List<UnwrappedExceptionBuildItem> defaultUnwrappedException() {
return List.of(new UnwrappedExceptionBuildItem(ArcUndeclaredThrowableException.class),
new UnwrappedExceptionBuildItem(RollbackException.class));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@BuildStep
public ExceptionMappersBuildItem scanForExceptionMappers(CombinedIndexBuildItem combinedIndexBuildItem,
ApplicationResultBuildItem applicationResultBuildItem,
BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer,
BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer,
List<ExceptionMapperBuildItem> mappers, List<UnwrappedExceptionBuildItem> unwrappedExceptions,
Capabilities capabilities) {
AdditionalBeanBuildItem.Builder beanBuilder = AdditionalBeanBuildItem.builder().setUnremovable();
ExceptionMapping exceptions = ResteasyReactiveExceptionMappingScanner
.scanForExceptionMappers(combinedIndexBuildItem.getComputingIndex(), applicationResultBuildItem.getResult());
exceptions.addBlockingProblem(BlockingOperationNotAllowedException.class);
exceptions.addBlockingProblem(BlockingNotAllowedException.class);
for (UnwrappedExceptionBuildItem bi : unwrappedExceptions) {
exceptions.addUnwrappedException(bi.getThrowableClass().getName());
}
if (capabilities.isPresent(Capability.HIBERNATE_REACTIVE)) {
exceptions.addNonBlockingProblem(
new ExceptionMapping.ExceptionTypeAndMessageContainsPredicate(IllegalStateException.class, "HR000068"));
}
for (Map.Entry<String, ResourceExceptionMapper<? extends Throwable>> i : exceptions.getMappers()
.entrySet()) {
beanBuilder.addBeanClass(i.getValue().getClassName());
}
for (ExceptionMapperBuildItem additionalExceptionMapper : mappers) {
if (additionalExceptionMapper.isRegisterAsBean()) {
beanBuilder.addBeanClass(additionalExceptionMapper.getClassName());
} else {
reflectiveClassBuildItemBuildProducer
.produce(new ReflectiveClassBuildItem(true, false, false, additionalExceptionMapper.getClassName()));
}
int priority = Priorities.USER;
if (additionalExceptionMapper.getPriority() != null) {
priority = additionalExceptionMapper.getPriority();
}
ResourceExceptionMapper<Throwable> mapper = new ResourceExceptionMapper<>();
mapper.setPriority(priority);
mapper.setClassName(additionalExceptionMapper.getClassName());
exceptions.addExceptionMapper(additionalExceptionMapper.getHandledExceptionName(), mapper);
}
additionalBeanBuildItemBuildProducer.produce(beanBuilder.build());
return new ExceptionMappersBuildItem(exceptions);
}
@BuildStep
public ParamConverterProvidersBuildItem scanForParamConverters(
BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer,
BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer,
List<ParamConverterBuildItem> paramConverterBuildItems) {
AdditionalBeanBuildItem.Builder beanBuilder = AdditionalBeanBuildItem.builder().setUnremovable();
ParamConverterProviders paramConverterProviders = new ParamConverterProviders();
for (ParamConverterBuildItem additionalParamConverter : paramConverterBuildItems) {
if (additionalParamConverter.isRegisterAsBean()) {
beanBuilder.addBeanClass(additionalParamConverter.getClassName());
} else {
reflectiveClassBuildItemBuildProducer
.produce(new ReflectiveClassBuildItem(true, false, false, additionalParamConverter.getClassName()));
}
int priority = Priorities.USER;
if (additionalParamConverter.getPriority() != null) {
priority = additionalParamConverter.getPriority();
}
ResourceParamConverterProvider provider = new ResourceParamConverterProvider();
provider.setPriority(priority);
provider.setClassName(additionalParamConverter.getClassName());
paramConverterProviders.addParamConverterProviders(provider);
}
additionalBeanBuildItemBuildProducer.produce(beanBuilder.build());
return new ParamConverterProvidersBuildItem(paramConverterProviders);
}
@BuildStep
public void scanForDynamicFeatures(CombinedIndexBuildItem combinedIndexBuildItem,
ApplicationResultBuildItem applicationResultBuildItem,
BuildProducer<DynamicFeatureBuildItem> dynamicFeatureBuildItemBuildProducer) {
IndexView index = combinedIndexBuildItem.getComputingIndex();
Set<String> features = ResteasyReactiveFeatureScanner.scanForDynamicFeatures(index,
applicationResultBuildItem.getResult());
for (String dynamicFeatureClass : features) {
dynamicFeatureBuildItemBuildProducer
.produce(new DynamicFeatureBuildItem(dynamicFeatureClass, true));
}
}
@BuildStep
public void scanForFeatures(CombinedIndexBuildItem combinedIndexBuildItem,
ApplicationResultBuildItem applicationResultBuildItem,
BuildProducer<JaxrsFeatureBuildItem> featureBuildItemBuildProducer) {
IndexView index = combinedIndexBuildItem.getComputingIndex();
Set<String> features = ResteasyReactiveFeatureScanner.scanForFeatures(index, applicationResultBuildItem.getResult());
for (String feature : features) {
featureBuildItemBuildProducer
.produce(new JaxrsFeatureBuildItem(feature, true));
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@BuildStep
public ContextResolversBuildItem scanForContextResolvers(CombinedIndexBuildItem combinedIndexBuildItem,
ApplicationResultBuildItem applicationResultBuildItem,
BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer,
BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer,
List<ContextResolverBuildItem> additionalResolvers) {
IndexView index = combinedIndexBuildItem.getComputingIndex();
AdditionalBeanBuildItem.Builder beanBuilder = AdditionalBeanBuildItem.builder().setUnremovable();
ContextResolvers resolvers = ResteasyReactiveContextResolverScanner.scanForContextResolvers(index,
applicationResultBuildItem.getResult());
for (Map.Entry<Class<?>, List<ResourceContextResolver>> entry : resolvers.getResolvers().entrySet()) {
for (ResourceContextResolver i : entry.getValue()) {
beanBuilder.addBeanClass(i.getClassName());
}
}
for (ContextResolverBuildItem i : additionalResolvers) {
if (i.isRegisterAsBean()) {
beanBuilder.addBeanClass(i.getClassName());
} else {
reflectiveClassBuildItemBuildProducer
.produce(new ReflectiveClassBuildItem(true, false, false, i.getClassName()));
}
ResourceContextResolver resolver = new ResourceContextResolver();
resolver.setClassName(i.getClassName());
resolver.setMediaTypeStrings(i.getMediaTypes());
try {
resolvers.addContextResolver((Class) Class.forName(i.getProvidedType(), false,
Thread.currentThread().getContextClassLoader()), resolver);
} catch (ClassNotFoundException e) {
throw new RuntimeException(
"Unable to load handled exception type " + i.getProvidedType(), e);
}
}
additionalBeanBuildItemBuildProducer.produce(beanBuilder.build());
return new ContextResolversBuildItem(resolvers);
}
@BuildStep
public void scanForParamConverters(CombinedIndexBuildItem combinedIndexBuildItem,
ApplicationResultBuildItem applicationResultBuildItem,
BuildProducer<ParamConverterBuildItem> paramConverterBuildItemBuildProducer) {
IndexView index = combinedIndexBuildItem.getComputingIndex();
Collection<ClassInfo> paramConverterProviders = index
.getAllKnownImplementors(ResteasyReactiveDotNames.PARAM_CONVERTER_PROVIDER);
for (ClassInfo converterClass : paramConverterProviders) {
ApplicationScanningResult.KeepProviderResult keepProviderResult = applicationResultBuildItem.getResult()
.keepProvider(converterClass);
if (keepProviderResult != ApplicationScanningResult.KeepProviderResult.DISCARD) {
AnnotationInstance priorityInstance = converterClass.classAnnotation(ResteasyReactiveDotNames.PRIORITY);
paramConverterBuildItemBuildProducer.produce(new ParamConverterBuildItem(converterClass.name().toString(),
priorityInstance != null ? priorityInstance.value().asInt() : Priorities.USER, true));
}
}
}
@BuildStep
public void handleCustomAnnotatedMethods(
Optional<ResourceScanningResultBuildItem> resourceScanningResultBuildItem,
CombinedIndexBuildItem combinedIndexBuildItem,
BuildProducer<GeneratedBeanBuildItem> generatedBean,
List<CustomContainerRequestFilterBuildItem> customContainerRequestFilters,
List<CustomContainerResponseFilterBuildItem> customContainerResponseFilters,
List<CustomExceptionMapperBuildItem> customExceptionMappers,
BuildProducer<ContainerRequestFilterBuildItem> additionalContainerRequestFilters,
BuildProducer<ContainerResponseFilterBuildItem> additionalContainerResponseFilters,
BuildProducer<ExceptionMapperBuildItem> additionalExceptionMappers,
BuildProducer<AdditionalBeanBuildItem> additionalBean) {
IndexView index = combinedIndexBuildItem.getComputingIndex();
AdditionalBeanBuildItem.Builder additionalBeans = AdditionalBeanBuildItem.builder();
// if we have custom filters, we need to index these classes
if (!customContainerRequestFilters.isEmpty() || !customContainerResponseFilters.isEmpty()
|| !customExceptionMappers.isEmpty()) {
Indexer indexer = new Indexer();
Set<DotName> additionalIndex = new HashSet<>();
//we have to use the non-computing index here
//the logic checks if the bean is already indexed, so the computing one breaks this
for (CustomContainerRequestFilterBuildItem filter : customContainerRequestFilters) {
IndexingUtil.indexClass(filter.getClassName(), indexer, combinedIndexBuildItem.getIndex(), additionalIndex,
Thread.currentThread().getContextClassLoader());
}
for (CustomContainerResponseFilterBuildItem filter : customContainerResponseFilters) {
IndexingUtil.indexClass(filter.getClassName(), indexer, combinedIndexBuildItem.getIndex(), additionalIndex,
Thread.currentThread().getContextClassLoader());
}
for (CustomExceptionMapperBuildItem mapper : customExceptionMappers) {
IndexingUtil.indexClass(mapper.getClassName(), indexer, combinedIndexBuildItem.getIndex(), additionalIndex,
Thread.currentThread().getContextClassLoader());
}
index = CompositeIndex.create(index, indexer.complete());
}
List<FilterGeneration.GeneratedFilter> generatedFilters = FilterGeneration.generate(index,
Set.of(HTTP_SERVER_REQUEST, HTTP_SERVER_RESPONSE, ROUTING_CONTEXT), Set.of(Unremovable.class.getName()));
for (var generated : generatedFilters) {
for (var i : generated.getGeneratedClasses()) {
generatedBean.produce(new GeneratedBeanBuildItem(i.getName(), i.getData()));
}
if (generated.isRequestFilter()) {
// the user class itself is made to be a bean as we want the user to be able to declare dependencies
additionalBeans.addBeanClass(generated.getDeclaringClassName());
ContainerRequestFilterBuildItem.Builder builder = new ContainerRequestFilterBuildItem.Builder(
generated.getGeneratedClassName())
.setRegisterAsBean(false) // it has already been made a bean
.setPriority(generated.getPriority())
.setPreMatching(generated.isPreMatching())
.setNonBlockingRequired(generated.isNonBlocking())
.setReadBody(generated.isReadBody());
if (!generated.getNameBindingNames().isEmpty()) {
builder.setNameBindingNames(generated.getNameBindingNames());
}
additionalContainerRequestFilters.produce(builder.build());
} else {
// the user class itself is made to be a bean as we want the user to be able to declare dependencies
additionalBeans.addBeanClass(generated.getDeclaringClassName());
ContainerResponseFilterBuildItem.Builder builder = new ContainerResponseFilterBuildItem.Builder(
generated.getGeneratedClassName())
.setRegisterAsBean(false)// it has already been made a bean
.setPriority(generated.getPriority());
additionalContainerResponseFilters.produce(builder.build());
}
}
Set<MethodInfo> classLevelExceptionMappers = new HashSet<>(resourceScanningResultBuildItem
.map(s -> s.getResult().getClassLevelExceptionMappers()).orElse(Collections.emptyList()));
for (AnnotationInstance instance : index
.getAnnotations(ResteasyReactiveDotNames.SERVER_EXCEPTION_MAPPER)) {
if (instance.target().kind() != AnnotationTarget.Kind.METHOD) {
continue;
}
MethodInfo methodInfo = instance.target().asMethod();
if (classLevelExceptionMappers.contains(methodInfo)) { // methods annotated with @ServerExceptionMapper that exist inside a Resource Class are handled differently
continue;
}
// the user class itself is made to be a bean as we want the user to be able to declare dependencies
additionalBeans.addBeanClass(methodInfo.declaringClass().name().toString());
Map<String, String> generatedClassNames = ServerExceptionMapperGenerator.generateGlobalMapper(methodInfo,
new GeneratedBeanGizmoAdaptor(generatedBean),
Set.of(HTTP_SERVER_REQUEST, HTTP_SERVER_RESPONSE, ROUTING_CONTEXT), Set.of(Unremovable.class.getName()));
for (Map.Entry<String, String> entry : generatedClassNames.entrySet()) {
ExceptionMapperBuildItem.Builder builder = new ExceptionMapperBuildItem.Builder(entry.getValue(),
entry.getKey()).setRegisterAsBean(false);// it has already been made a bean
AnnotationValue priorityValue = instance.value("priority");
if (priorityValue != null) {
builder.setPriority(priorityValue.asInt());
}
additionalExceptionMappers.produce(builder.build());
}
}
additionalBean.produce(additionalBeans.setUnremovable().setDefaultScope(DotNames.SINGLETON).build());
}
}
|
package org.innovateuk.ifs.application.forms.questions.generic.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.applicant.resource.ApplicantQuestionResource;
import org.innovateuk.ifs.applicant.service.ApplicantRestService;
import org.innovateuk.ifs.application.forms.questions.generic.populator.GenericQuestionApplicationFormPopulator;
import org.innovateuk.ifs.application.forms.questions.generic.populator.GenericQuestionApplicationModelPopulator;
import org.innovateuk.ifs.application.forms.questions.generic.viewmodel.GenericQuestionApplicationViewModel;
import org.innovateuk.ifs.application.resource.FormInputResponseResource;
import org.innovateuk.ifs.application.service.QuestionStatusRestService;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.innovateuk.ifs.filter.CookieFlashMessageFilter;
import org.innovateuk.ifs.form.resource.FormInputResource;
import org.innovateuk.ifs.form.service.FormInputResponseRestService;
import org.innovateuk.ifs.form.service.FormInputRestService;
import org.innovateuk.ifs.user.resource.ProcessRoleResource;
import org.innovateuk.ifs.user.resource.Role;
import org.innovateuk.ifs.user.service.UserRestService;
import org.junit.Test;
import org.mockito.Mock;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.validation.Validator;
import javax.servlet.http.HttpServletResponse;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.innovateuk.ifs.application.builder.FormInputResponseResourceBuilder.newFormInputResponseResource;
import static org.innovateuk.ifs.commons.error.ValidationMessages.noErrors;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.form.builder.FormInputResourceBuilder.newFormInputResource;
import static org.innovateuk.ifs.form.resource.FormInputScope.APPLICATION;
import static org.innovateuk.ifs.form.resource.FormInputType.*;
import static org.innovateuk.ifs.user.builder.ProcessRoleResourceBuilder.newProcessRoleResource;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class GenericQuestionApplicationControllerTest extends BaseControllerMockMVCTest<GenericQuestionApplicationController> {
@Mock
private ApplicantRestService applicantRestService;
@Mock
private GenericQuestionApplicationModelPopulator modelPopulator;
@Mock
private GenericQuestionApplicationFormPopulator formPopulator;
@Mock
private FormInputRestService formInputRestService;
@Mock
private FormInputResponseRestService formInputResponseRestService;
@Mock
private UserRestService userRestService;
@Mock
private QuestionStatusRestService questionStatusRestService;
@Mock
private CookieFlashMessageFilter cookieFlashMessageFilter;
@Mock
private Validator validator;
private long applicationId = 1L;
private long questionId = 2L;
@Override
protected GenericQuestionApplicationController supplyControllerUnderTest() {
return new GenericQuestionApplicationController();
}
@Test
public void viewPage() throws Exception {
GenericQuestionApplicationViewModel viewModel = mock(GenericQuestionApplicationViewModel.class);
ApplicantQuestionResource applicantQuestion = mock(ApplicantQuestionResource.class);
when(applicantRestService.getQuestion(loggedInUser.getId(), applicationId, questionId)).thenReturn(applicantQuestion);
when(modelPopulator.populate(applicantQuestion)).thenReturn(viewModel);
mockMvc.perform(get("/application/{applicationId}/form/question/{questionId}/generic", applicationId, questionId))
.andExpect(view().name("application/questions/generic"))
.andExpect(model().attribute("model", viewModel));
verify(formPopulator).populate(any(), eq(applicantQuestion));
}
@Test
public void showErrors() throws Exception {
FormInputResource formInput = newFormInputResource()
.withType(TEMPLATE_DOCUMENT)
.withScope(APPLICATION)
.build();
FormInputResponseResource response = newFormInputResponseResource()
.withFileName(null)
.build();
when(formInputRestService.getByQuestionId(questionId)).thenReturn(restSuccess(singletonList(formInput)));
when(formInputResponseRestService.getByFormInputIdAndApplication(formInput.getId(), applicationId)).thenReturn(restSuccess(singletonList(response)));
GenericQuestionApplicationViewModel viewModel = mock(GenericQuestionApplicationViewModel.class);
ApplicantQuestionResource applicantQuestion = mock(ApplicantQuestionResource.class);
when(applicantRestService.getQuestion(loggedInUser.getId(), applicationId, questionId)).thenReturn(applicantQuestion);
when(modelPopulator.populate(applicantQuestion)).thenReturn(viewModel);
mockMvc.perform(get("/application/{applicationId}/form/question/{questionId}/generic?show-errors=true", applicationId, questionId))
.andExpect(view().name("application/questions/generic"))
.andExpect(model().attribute("model", viewModel))
.andExpect(model().attributeHasFieldErrorCode("form", "templateDocument", "validation.file.required"));
verify(formPopulator).populate(any(), eq(applicantQuestion));
verify(validator).validate(any(), any());
}
@Test
public void assignToLeadForReview() throws Exception {
ProcessRoleResource userProcessRole = newProcessRoleResource()
.withRole(Role.COLLABORATOR)
.withUser(loggedInUser)
.build();
ProcessRoleResource leadProcessRole = newProcessRoleResource()
.withRole(Role.LEADAPPLICANT)
.build();
when(userRestService.findProcessRole(applicationId)).thenReturn(restSuccess(asList(leadProcessRole, userProcessRole)));
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(userProcessRole));
when(questionStatusRestService.assign(questionId, applicationId, leadProcessRole.getId(), userProcessRole.getId())).thenReturn(restSuccess());
mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/generic", applicationId, questionId)
.param("assign", "true"))
.andExpect(redirectedUrl(String.format("/application/%d/form/question/%d/generic", applicationId, questionId)));
verify(questionStatusRestService).assign(questionId, applicationId, leadProcessRole.getId(), userProcessRole.getId());
verify(cookieFlashMessageFilter).setFlashMessage(any(HttpServletResponse.class), eq("assignedQuestion"));
verifyNoMoreInteractions(questionStatusRestService);
}
@Test
public void complete() throws Exception {
ProcessRoleResource userProcessRole = newProcessRoleResource()
.withRole(Role.COLLABORATOR)
.withUser(loggedInUser)
.build();
FormInputResource formInput = newFormInputResource()
.withType(TEXTAREA)
.withScope(APPLICATION)
.build();
when(formInputRestService.getByQuestionId(questionId)).thenReturn(restSuccess(singletonList(formInput)));
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(userProcessRole));
when(formInputResponseRestService.saveQuestionResponse(loggedInUser.getId(), applicationId, formInput.getId(), "answer", false)).thenReturn(restSuccess(noErrors()));
when(questionStatusRestService.markAsComplete(questionId, applicationId, userProcessRole.getId())).thenReturn(restSuccess(emptyList()));
mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/generic", applicationId, questionId)
.param("complete", "true")
.param("answer", "answer"))
.andExpect(redirectedUrl(String.format("/application/%d/form/question/%d/generic", applicationId, questionId)));
verify(formInputResponseRestService).saveQuestionResponse(loggedInUser.getId(), applicationId, formInput.getId(), "answer", false);
verify(questionStatusRestService).markAsComplete(questionId, applicationId, userProcessRole.getId());
verifyNoMoreInteractions(questionStatusRestService);
}
@Test
public void edit() throws Exception {
ProcessRoleResource userProcessRole = newProcessRoleResource()
.withRole(Role.COLLABORATOR)
.withUser(loggedInUser)
.build();
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(userProcessRole));
when(questionStatusRestService.markAsInComplete(questionId, applicationId, userProcessRole.getId())).thenReturn(restSuccess());
mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/generic", applicationId, questionId)
.param("edit", "true"))
.andExpect(redirectedUrl(String.format("/application/%d/form/question/%d/generic", applicationId, questionId)));
verify(questionStatusRestService).markAsInComplete(questionId, applicationId, userProcessRole.getId());
verifyNoMoreInteractions(questionStatusRestService);
}
@Test
public void uploadTemplateDocument() throws Exception {
GenericQuestionApplicationViewModel viewModel = mock(GenericQuestionApplicationViewModel.class);
ApplicantQuestionResource applicantQuestion = mock(ApplicantQuestionResource.class);
when(applicantRestService.getQuestion(loggedInUser.getId(), applicationId, questionId)).thenReturn(applicantQuestion);
when(modelPopulator.populate(applicantQuestion)).thenReturn(viewModel);
ProcessRoleResource userProcessRole = newProcessRoleResource()
.withRole(Role.COLLABORATOR)
.withUser(loggedInUser)
.build();
FormInputResource formInput = newFormInputResource()
.withType(TEMPLATE_DOCUMENT)
.withScope(APPLICATION)
.build();
when(formInputRestService.getByQuestionId(questionId)).thenReturn(restSuccess(singletonList(formInput)));
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(userProcessRole));
MockMultipartFile file = new MockMultipartFile("templateDocument", "testFile.pdf", "application/pdf", "My content!".getBytes());
when(formInputResponseRestService.createFileEntry(formInput.getId(),
applicationId,
userProcessRole.getId(),
"application/pdf",11, "testFile.pdf", "My content!".getBytes()))
.thenReturn(restSuccess(mock(FileEntryResource.class)));
mockMvc.perform(multipart("/application/{applicationId}/form/question/{questionId}/generic", applicationId, questionId)
.file(file)
.param("uploadTemplateDocument", "true"))
.andExpect(view().name("application/questions/generic"));
verify(formInputResponseRestService).createFileEntry(formInput.getId(),
applicationId,
userProcessRole.getId(),
"application/pdf",11, "testFile.pdf", "My content!".getBytes());
verifyNoMoreInteractions(formInputResponseRestService);
}
@Test
public void removeTemplateDocument() throws Exception {
GenericQuestionApplicationViewModel viewModel = mock(GenericQuestionApplicationViewModel.class);
ApplicantQuestionResource applicantQuestion = mock(ApplicantQuestionResource.class);
when(applicantRestService.getQuestion(loggedInUser.getId(), applicationId, questionId)).thenReturn(applicantQuestion);
when(modelPopulator.populate(applicantQuestion)).thenReturn(viewModel);
ProcessRoleResource userProcessRole = newProcessRoleResource()
.withRole(Role.COLLABORATOR)
.withUser(loggedInUser)
.build();
FormInputResource formInput = newFormInputResource()
.withType(TEMPLATE_DOCUMENT)
.withScope(APPLICATION)
.build();
when(formInputRestService.getByQuestionId(questionId)).thenReturn(restSuccess(singletonList(formInput)));
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(userProcessRole));
when(formInputResponseRestService.removeFileEntry(formInput.getId(),
applicationId,
userProcessRole.getId())).thenReturn(restSuccess());
mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/generic", applicationId, questionId)
.param("removeTemplateDocument", "true"))
.andExpect(view().name("application/questions/generic"));
verify(formInputResponseRestService).removeFileEntry(formInput.getId(),
applicationId,
userProcessRole.getId());
verifyNoMoreInteractions(formInputResponseRestService);
}
@Test
public void uploadAppendix() throws Exception {
GenericQuestionApplicationViewModel viewModel = mock(GenericQuestionApplicationViewModel.class);
ApplicantQuestionResource applicantQuestion = mock(ApplicantQuestionResource.class);
when(applicantRestService.getQuestion(loggedInUser.getId(), applicationId, questionId)).thenReturn(applicantQuestion);
when(modelPopulator.populate(applicantQuestion)).thenReturn(viewModel);
ProcessRoleResource userProcessRole = newProcessRoleResource()
.withRole(Role.COLLABORATOR)
.withUser(loggedInUser)
.build();
FormInputResource formInput = newFormInputResource()
.withType(FILEUPLOAD)
.withScope(APPLICATION)
.build();
when(formInputRestService.getByQuestionId(questionId)).thenReturn(restSuccess(singletonList(formInput)));
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(userProcessRole));
MockMultipartFile file = new MockMultipartFile("appendix", "testFile.pdf", "application/pdf", "My content!".getBytes());
when(formInputResponseRestService.createFileEntry(formInput.getId(),
applicationId,
userProcessRole.getId(),
"application/pdf",11, "testFile.pdf", "My content!".getBytes()))
.thenReturn(restSuccess(mock(FileEntryResource.class)));
mockMvc.perform(multipart("/application/{applicationId}/form/question/{questionId}/generic", applicationId, questionId)
.file(file)
.param("uploadAppendix", "true"))
.andExpect(view().name("application/questions/generic"));
verify(formInputResponseRestService).createFileEntry(formInput.getId(),
applicationId,
userProcessRole.getId(),
"application/pdf",11, "testFile.pdf", "My content!".getBytes());
verifyNoMoreInteractions(formInputResponseRestService);
}
@Test
public void removeAppendix() throws Exception {
GenericQuestionApplicationViewModel viewModel = mock(GenericQuestionApplicationViewModel.class);
ApplicantQuestionResource applicantQuestion = mock(ApplicantQuestionResource.class);
when(applicantRestService.getQuestion(loggedInUser.getId(), applicationId, questionId)).thenReturn(applicantQuestion);
when(modelPopulator.populate(applicantQuestion)).thenReturn(viewModel);
ProcessRoleResource userProcessRole = newProcessRoleResource()
.withRole(Role.COLLABORATOR)
.withUser(loggedInUser)
.build();
FormInputResource formInput = newFormInputResource()
.withType(FILEUPLOAD)
.withScope(APPLICATION)
.build();
when(formInputRestService.getByQuestionId(questionId)).thenReturn(restSuccess(singletonList(formInput)));
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(userProcessRole));
when(formInputResponseRestService.removeFileEntry(formInput.getId(),
applicationId,
userProcessRole.getId())).thenReturn(restSuccess());
mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/generic", applicationId, questionId)
.param("removeAppendix", "true"))
.andExpect(view().name("application/questions/generic"));
verify(formInputResponseRestService).removeFileEntry(formInput.getId(),
applicationId,
userProcessRole.getId());
verifyNoMoreInteractions(formInputResponseRestService);
}
}
|
package fr.openwide.core.showcase.web.application.portfolio.component;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import org.odlabs.wiquery.core.events.MouseEvent;
import fr.openwide.core.showcase.core.business.user.model.User;
import fr.openwide.core.showcase.core.business.user.model.UserBinding;
import fr.openwide.core.showcase.web.application.portfolio.form.EditUserPopupPanel;
import fr.openwide.core.wicket.markup.html.panel.GenericPanel;
import fr.openwide.core.wicket.more.markup.html.basic.DateLabel;
import fr.openwide.core.wicket.more.markup.html.image.BooleanGlyphicon;
import fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.bootstrap.modal.behavior.AjaxModalOpenBehavior;
import fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.emailobfuscator.ObfuscatedEmailLink;
import fr.openwide.core.wicket.more.model.BindingModel;
import fr.openwide.core.wicket.more.util.DatePattern;
public class UserProfilePanel extends GenericPanel<User> {
private static final long serialVersionUID = 646894189220818498L;
private static final UserBinding USER_BINDING = new UserBinding();
public UserProfilePanel(String id, IModel<User> userModel) {
super(id, userModel);
add(new Label("userName", BindingModel.of(userModel, USER_BINDING.userName())));
add(new ObfuscatedEmailLink("emailLink", BindingModel.of(userModel, USER_BINDING.email()), true));
add(new Label("phoneNumber", BindingModel.of(userModel, USER_BINDING.phoneNumber())));
add(new Label("gsmNumber", BindingModel.of(userModel, USER_BINDING.gsmNumber())));
add(new Label("faxNumber", BindingModel.of(userModel, USER_BINDING.faxNumber())));
add(new DateLabel("creationDate", BindingModel.of(userModel, USER_BINDING.creationDate()),
DatePattern.SHORT_DATETIME));
add(new DateLabel("lastLoginDate", BindingModel.of(userModel, USER_BINDING.lastLoginDate()),
DatePattern.SHORT_DATETIME));
add(new BooleanGlyphicon("active", BindingModel.of(userModel, USER_BINDING.active())));
// Edit user popup panel
EditUserPopupPanel userEditPopupPanel = new EditUserPopupPanel("userEditPopupPanel", userModel);
add(userEditPopupPanel);
WebMarkupContainer editUserPopupLink = new WebMarkupContainer("editUserPopupLink");
editUserPopupLink.add(new AjaxModalOpenBehavior(userEditPopupPanel, MouseEvent.CLICK));
add(editUserPopupLink);
}
}
|
package org.xins.tests.server;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.server.AccessRule;
import org.xins.server.IPFilter;
import org.xins.util.text.FastStringBuffer;
import org.xins.util.text.ParseException;
/**
* Tests for class <code>AccessRule</code>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public class AccessRuleTests extends TestCase {
// Class functions
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(AccessRuleTests.class);
}
// Class fields
// Constructor
/**
* Constructs a new <code>AccessRuleTests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public AccessRuleTests(String name) {
super(name);
}
// Fields
// Methods
/**
* Performs setup for the tests.
*/
protected void setUp() {
// empty
}
public void testParseAccessRule() throws Throwable {
try {
AccessRule.parseAccessRule(null);
fail("AccessRule.parseAccessRule(null) should throw an IllegalArgumentException.");
} catch (IllegalArgumentException exception) {
// as expected
}
doTestParseAccessRule("1.2.3.4");
doTestParseAccessRule("1.101.3.4");
doTestParseAccessRule("194.134.168.213");
doTestParseAccessRule("104.1.2.254");
}
private void doTestParseAccessRule(String ip)
throws Throwable {
for (int mask = 0; mask <= 32; mask++) {
doTestParseAccessRule(false, ip, mask);
doTestParseAccessRule(true, ip, mask);
}
}
private void doTestParseAccessRule(boolean allow, String ip, int mask)
throws Throwable {
try {
String expression = "";
AccessRule.parseAccessRule(expression);
fail("AccessRule(\"" + expression + "\") should throw a ParseException.");
} catch (ParseException exception) {
// as expected
}
try {
String expression = " \t\r\n ";
AccessRule.parseAccessRule(expression);
fail("AccessRule(\"" + expression + "\") should throw a ParseException.");
} catch (ParseException exception) {
// as expected
}
try {
String expression = "something 1.2.3.4/32 *";
AccessRule.parseAccessRule(expression);
fail("AccessRule(\"" + expression + "\") should throw a ParseException.");
} catch (ParseException exception) {
// as expected
}
doTestParseAccessRule(allow, ip, mask, " ", " ");
doTestParseAccessRule(allow, ip, mask, "\t", "\t");
doTestParseAccessRule(allow, ip, mask, " ", "\t");
doTestParseAccessRule(allow, ip, mask, " \t\n\r ", "\t\n\r");
doTestParseAccessRule(allow, ip, mask, "\n ", "\r");
}
private void doTestParseAccessRule(boolean allow, String ip, int mask, String whitespace1, String whitespace2)
throws Throwable {
final String pattern = "_*";
FastStringBuffer buffer = new FastStringBuffer(250);
if (allow) {
buffer.append("allow");
} else {
buffer.append("deny");
}
buffer.append(whitespace1);
buffer.append(ip);
buffer.append('/');
buffer.append(mask);
buffer.append(whitespace2);
buffer.append(pattern);
AccessRule rule = AccessRule.parseAccessRule(buffer.toString());
assertNotNull(rule);
assertEquals(allow, rule.isAllowRule());
String function = "_GetVersion";
if (! rule.match(ip, function)) {
fail("AccessRule(" + rule + ") should match(\"" + ip + "\", \"" + function + "\").");
}
function = "GetVersion";
if (rule.match(ip, function)) {
fail("AccessRule(" + rule + ") should not match(\"" + ip + "\", \"" + function + "\").");
}
String asString = (allow ? "allow" : "deny") + ' ' + ip + '/' + mask + ' ' + pattern;
assertEquals(asString, rule.toString());
IPFilter ipFilter = rule.getIPFilter();
assertNotNull(ipFilter);
assertEquals(ip, ipFilter.getBaseIP());
assertEquals(mask, ipFilter.getMask());
}
}
|
package rapanui.dsl;
public interface Visitor {
default void visit(RuleSystem ruleSystem) {}
default void visit(Rule rule) {}
default void visit(Definition definition) {}
default void visit(Formula formula) {};
default void visit(Equation equation) { visit((Formula)equation); }
default void visit(Inclusion inclusion) { visit((Formula)inclusion); }
default void visit(DefinitionReference reference) { visit((Formula)reference); }
default void visit(Term term) {};
default void visit(VariableReference variable) { visit((Term)variable); }
default void visit(ConstantReference constant) { visit((Term)constant); }
default void visit(BinaryOperation operation) { visit((Term)operation); }
default void visit(UnaryOperation operation) { visit((Term)operation); }
}
|
package org.apereo.cas.support.oauth.web.response.accesstoken.response;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.OAuth20ResponseTypes;
import org.apereo.cas.ticket.accesstoken.AccessToken;
import org.apereo.cas.token.JWTBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apereo.inspektr.audit.annotation.Audit;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;
import static java.util.stream.Collectors.joining;
/**
* This is {@link OAuth20DefaultAccessTokenResponseGenerator}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Slf4j
@RequiredArgsConstructor
public class OAuth20DefaultAccessTokenResponseGenerator implements OAuth20AccessTokenResponseGenerator {
private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();
/**
* JWT builder.
*/
protected final JWTBuilder jwtBuilder;
@Audit(action = "OAUTH2_ACCESS_TOKEN_RESPONSE",
actionResolverName = "OAUTH2_ACCESS_TOKEN_RESPONSE_ACTION_RESOLVER",
resourceResolverName = "OAUTH2_ACCESS_TOKEN_RESPONSE_RESOURCE_RESOLVER")
@Override
@SneakyThrows
public ModelAndView generate(final HttpServletRequest request, final HttpServletResponse response,
final OAuth20AccessTokenResponseResult result) {
if (shouldGenerateDeviceFlowResponse(result)) {
return generateResponseForDeviceToken(request, response, result);
}
return generateResponseForAccessToken(request, response, result);
}
private static boolean shouldGenerateDeviceFlowResponse(final OAuth20AccessTokenResponseResult result) {
val generatedToken = result.getGeneratedToken();
return OAuth20ResponseTypes.DEVICE_CODE == result.getResponseType()
&& generatedToken.getDeviceCode().isPresent()
&& generatedToken.getUserCode().isPresent()
&& generatedToken.getAccessToken().isEmpty();
}
/**
* Generate response for device token model and view.
*
* @param request the request
* @param response the response
* @param result the result
* @return the model and view
*/
@SneakyThrows
protected ModelAndView generateResponseForDeviceToken(final HttpServletRequest request,
final HttpServletResponse response,
final OAuth20AccessTokenResponseResult result) {
val model = getDeviceTokenResponseModel(result);
return new ModelAndView(new MappingJackson2JsonView(MAPPER), model);
}
/**
* Gets device token response model.
*
* @param result the result
* @return the device token response model
*/
protected Map getDeviceTokenResponseModel(final OAuth20AccessTokenResponseResult result) {
val model = new LinkedHashMap<String, Object>();
val uri = result.getCasProperties().getServer().getPrefix()
.concat(OAuth20Constants.BASE_OAUTH20_URL)
.concat("/")
.concat(OAuth20Constants.DEVICE_AUTHZ_URL);
model.put(OAuth20Constants.DEVICE_VERIFICATION_URI, uri);
model.put(OAuth20Constants.EXPIRES_IN, result.getDeviceTokenTimeout());
val generatedToken = result.getGeneratedToken();
generatedToken.getUserCode().ifPresent(c -> model.put(OAuth20Constants.DEVICE_USER_CODE, c));
generatedToken.getDeviceCode().ifPresent(c -> model.put(OAuth20Constants.DEVICE_CODE, c));
model.put(OAuth20Constants.DEVICE_INTERVAL, result.getDeviceRefreshInterval());
return model;
}
/**
* Generate response for access token model and view.
*
* @param request the request
* @param response the response
* @param result the result
* @return the model and view
*/
protected ModelAndView generateResponseForAccessToken(final HttpServletRequest request,
final HttpServletResponse response,
final OAuth20AccessTokenResponseResult result) {
val model = getAccessTokenResponseModel(request, response, result);
return new ModelAndView(new MappingJackson2JsonView(MAPPER), model);
}
/**
* Generate internal.
*
* @param request the request
* @param response the response
* @param result the result
* @return the access token response model
*/
protected Map<String, Object> getAccessTokenResponseModel(final HttpServletRequest request,
final HttpServletResponse response,
final OAuth20AccessTokenResponseResult result) {
val model = new LinkedHashMap<String, Object>();
val generatedToken = result.getGeneratedToken();
generatedToken.getAccessToken().ifPresent(t -> {
model.put(OAuth20Constants.ACCESS_TOKEN, encodeAccessToken(t, result));
model.put(OAuth20Constants.SCOPE, t.getScopes().stream().collect(joining(" ")));
});
generatedToken.getRefreshToken().ifPresent(t -> model.put(OAuth20Constants.REFRESH_TOKEN, t.getId()));
model.put(OAuth20Constants.TOKEN_TYPE, OAuth20Constants.TOKEN_TYPE_BEARER);
model.put(OAuth20Constants.EXPIRES_IN, result.getAccessTokenTimeout());
return model;
}
/**
* Encode access token string.
*
* @param accessToken the access token
* @param result the result
* @return the string
*/
protected String encodeAccessToken(final AccessToken accessToken,
final OAuth20AccessTokenResponseResult result) {
return accessToken.getId();
}
}
|
package org.xwiki.sharepage.test.ui;
import javax.mail.internet.MimeMessage;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.xwiki.sharepage.test.po.ShareDialog;
import org.xwiki.sharepage.test.po.ShareResultDialog;
import org.xwiki.sharepage.test.po.ShareableViewPage;
import org.xwiki.test.docker.junit5.TestConfiguration;
import org.xwiki.test.docker.junit5.UITest;
import org.xwiki.test.docker.junit5.servletengine.ServletEngine;
import org.xwiki.test.ui.TestUtils;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetupTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* UI tests for the Share by Email application.
*
* @version $Id$
* @since 7.0RC1
*/
@UITest(
sshPorts = {
// Open the GreenMail port so that the XWiki instance inside a Docker container can use the SMTP server provided
// by GreenMail running on the host.
3025
},
properties = {
// Add the MailSender plugin used by the SharePage UI to send mails
"xwikiCfgPlugins=com.xpn.xwiki.plugin.mailsender.MailSenderPlugin"
},
extraJARs = {
// XWiki needs the mailsender plugin JAR to be present before it starts since it's not an extension and it
// cannot be provisioned after XWiki is started!
"org.xwiki.platform:xwiki-platform-mailsender",
// MailSender plugin uses MailSenderConfiguration from xwiki-platform-mail-api so we need to provide an
// implementation for it.
"org.xwiki.platform:xwiki-platform-mail-send-default"
}
)
public class SharePageIT
{
private GreenMail mail;
private String testClassName;
private String testMethodName;
@BeforeAll
public void startMail()
{
this.mail = new GreenMail(ServerSetupTest.SMTP);
this.mail.start();
}
@AfterAll
public void stopMail()
{
if (this.mail != null) {
this.mail.stop();
}
}
@BeforeEach
public void setup(TestUtils setup, TestInfo info)
{
this.testClassName = info.getTestClass().get().getSimpleName();
this.testMethodName = info.getTestMethod().get().getName();
this.mail.reset();
setup.loginAsSuperAdmin();
// Delete any existing test page
setup.deletePage(this.testClassName, this.testMethodName);
}
/**
* @todo move this test to a PageTest test (add support for testing templates first) and keep only 1 test in this
* functional test
*/
@Test
@Order(1)
public void shareByEmailWhenNoFromAddress(TestUtils setup, TestConfiguration configuration) throws Exception
{
setup.updateObject("Mail", "MailConfig", "Mail.SendMailConfigClass", 0,
"host", configuration.getServletEngine().getHostIP(),
"port", "3025",
"sendWaitTime", "0",
"from", "");
shareByEmail(String.format("=?UTF-8?Q?superadmin?= <noreply@%s>",
configuration.getServletEngine().getInternalIP()), setup);
}
@Test
@Order(2)
public void shareByEmailWhenFromAddressSpecified(TestUtils setup, TestConfiguration configuration) throws Exception
{
setup.updateObject("Mail", "MailConfig", "Mail.SendMailConfigClass", 0,
"host", configuration.getServletEngine().getHostIP(),
"port", "3025",
"sendWaitTime", "0",
"from", "noreply@localhost");
shareByEmail("noreply@localhost", setup);
}
private void shareByEmail(String expectedEmail, TestUtils setup) throws Exception
{
setup.createPage(this.testClassName, this.testMethodName, "something", "title");
ShareableViewPage svp = new ShareableViewPage();
svp.clickShareByEmail();
ShareDialog sd = new ShareDialog();
sd.setEmailField("john@doe.com");
sd.setMessage("test");
ShareResultDialog srd = sd.sendMail();
assertEquals("The message has been sent to john.", srd.getResultMessage());
srd.clickBackLink();
// Verify we received the email and that its content is valid
this.mail.waitForIncomingEmail(10000L, 1);
MimeMessage mimeMessage = this.mail.getReceivedMessages()[0];
assertEquals("superadmin wants to share a document with you", mimeMessage.getSubject());
// Since we didn't specify any from email address, one is computed automatically, verify it.
assertEquals(expectedEmail, mimeMessage.getFrom()[0].toString());
}
}
|
package org.geomajas.widget.searchandfilter.command.searchandfilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.geomajas.command.Command;
import org.geomajas.global.ExceptionCode;
import org.geomajas.global.GeomajasException;
import org.geomajas.layer.VectorLayer;
import org.geomajas.layer.VectorLayerService;
import org.geomajas.layer.feature.Feature;
import org.geomajas.layer.feature.InternalFeature;
import org.geomajas.security.SecurityContext;
import org.geomajas.service.DtoConverterService;
import org.geomajas.service.FilterService;
import org.geomajas.service.GeoService;
import org.geomajas.widget.searchandfilter.command.dto.FeatureSearchRequest;
import org.geomajas.widget.searchandfilter.command.dto.FeatureSearchResponse;
import org.geomajas.widget.searchandfilter.service.DtoSearchConverterService;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Command to retrieve features using a FeatureSearch Criterion.
* <p>
* criteria are combined to one filter (per layer).
* <p>
* Please note that AND does not (automatically) work over layers, eg. there are
* separate filters, one for every layer (geographic filters work on multiple
* layers however, so no need to define those multiple times).
*
* @author Kristof Heirwegh
*/
@Component
public class FeatureSearchCommand implements Command<FeatureSearchRequest, FeatureSearchResponse> {
@SuppressWarnings("unused")
private final Logger log = LoggerFactory.getLogger(FeatureSearchCommand.class);
@Autowired
private GeoService geoService;
@Autowired
private VectorLayerService layerService;
@Autowired
private DtoConverterService dtoConverterService;
@Autowired
private DtoSearchConverterService dtoSearchConverterService;
@Autowired
private FilterService filterService;
@Autowired
private SecurityContext securityContext;
public void execute(final FeatureSearchRequest request, final FeatureSearchResponse response) throws Exception {
if (request.getCriterion() == null) {
throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "criterion");
}
if (null == request.getMapCrs()) {
throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "mapCrs");
}
if (!request.getCriterion().isValid()) {
throw new GeomajasException(ExceptionCode.UNEXPECTED_PROBLEM, "criterion is not valid");
}
String mapCrsCode = request.getMapCrs();
CoordinateReferenceSystem mapCrs = geoService.getCrs2(request.getMapCrs());
Map<VectorLayer, Filter> filters = dtoSearchConverterService.dtoCriterionToFilters(request.getCriterion(),
mapCrs);
Map<String, String> layerFilters = request.getLayerFilters();
for (Entry<VectorLayer, Filter> entry : filters.entrySet()) {
String layerId = entry.getKey().getId();
if (securityContext.isLayerVisible(layerId)) {
Filter f = entry.getValue();
if (layerFilters.containsKey(layerId)) {
String layerFilter = layerFilters.get(layerId);
f = filterService.createAndFilter(filterService.parseFilter(layerFilter), f);
}
List<InternalFeature> temp = layerService.getFeatures(layerId, mapCrs, f, null,
request.getFeatureIncludes(), 0, request.getMax());
if (temp.size() > 0) {
List<Feature> features = new ArrayList<Feature>();
for (InternalFeature feature : temp) {
Feature dto = dtoConverterService.toDto(feature);
dto.setCrs(mapCrsCode);
features.add(dto);
}
response.addLayer(layerId, features);
}
}
}
}
public FeatureSearchResponse getEmptyCommandResponse() {
return new FeatureSearchResponse();
}
}
|
package BluebellAdventures.Characters;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.imageio.ImageIO;
import BluebellAdventures.Characters.GameMap;
import Megumin.Actions.Action;
import Megumin.Actions.Effect;
import Megumin.Nodes.Sprite;
import Megumin.Point;
public class Enemy extends Sprite {
private int attack;
private int detectionRange;
private int speed;
// Constructors //
public Enemy() {
super();
}
public Enemy(String filename) throws IOException {
super(filename, new Point(0, 0));
}
public Enemy(String filename, Point position) throws IOException {
super(ImageIO.read(new File(filename)), position);
}
public Enemy(BufferedImage image) {
super(image, new Point(0, 0));
}
public Enemy(BufferedImage image, Point position) {
super(image, position);
}
@Override
public void render(Graphics2D g) {
if (getVisible()) {
GameMap map = GameMap.getInstance();
g.drawImage(getImage(), map.getPosition().getX() + getPosition().getX(), map.getPosition().getY() + getPosition().getY(), null);
}
}
@Override
public boolean checkCrash(CopyOnWriteArrayList<Sprite> sprites, Action action) {
boolean crash = false;
int x1 = getPosition().getX();
int y1 = getPosition().getY();
int w1 = getSize().getX();
int h1 = getSize().getY();
Iterator it = sprites.iterator();
while (it.hasNext()) {
Sprite sprite = (Sprite)it.next();
int x2 = sprite.getPosition().getX() - GameMap.getInstance().getPosition().getX();
int y2 = sprite.getPosition().getY() - GameMap.getInstance().getPosition().getY();
int w2 = sprite.getSize().getX();
int h2 = sprite.getSize().getY();
if (Math.max(Math.abs(x2 - (x1 + w1)), Math.abs(x2 + w2 - x1)) < w1 + w2 &&
Math.max(Math.abs(y2 - (y1 + h1)), Math.abs(y2 + h2 - y1)) < h1 + h2) {
((Effect)action).setSprite(sprite);
runAction(action);
crash = true;
}
}
return crash;
}
// Get and Sets //
public Enemy setAttack(int attack) {
this.attack = attack;
return this;
}
public int getAttack() {
return attack;
}
public Enemy setDetectionRange(int detectionRange) {
this.detectionRange = detectionRange;
return this;
}
public int getDetectionRange() {
return detectionRange;
}
public Enemy setSpeed(int speed) {
this.speed = speed;
return this;
}
public int getSpeed() {
return speed;
}
}
|
package org.carlspring.strongbox.config;
import org.carlspring.strongbox.artifact.coordinates.MavenArtifactCoordinates;
import org.carlspring.strongbox.providers.layout.Maven2LayoutProvider;
import org.carlspring.strongbox.providers.search.MavenIndexerSearchProvider;
import org.carlspring.strongbox.repository.MavenRepositoryFeatures;
import org.carlspring.strongbox.repository.MavenRepositoryManagementStrategy;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.LinkedHashMap;
import java.util.Map;
import com.orientechnologies.orient.core.entity.OEntityManager;
import org.apache.maven.index.*;
import org.apache.maven.index.artifact.ArtifactPackagingMapper;
import org.apache.maven.index.artifact.DefaultArtifactPackagingMapper;
import org.apache.maven.index.creator.AbstractIndexCreator;
import org.apache.maven.index.creator.JarFileContentsIndexCreator;
import org.apache.maven.index.creator.MavenPluginArtifactInfoIndexCreator;
import org.apache.maven.index.creator.MinimalArtifactInfoIndexCreator;
import org.apache.maven.index.incremental.DefaultIncrementalHandler;
import org.apache.maven.index.packer.DefaultIndexPacker;
import org.apache.maven.index.packer.IndexPacker;
import org.apache.maven.index.updater.DefaultIndexUpdater;
import org.apache.maven.index.updater.IndexUpdater;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({ "org.carlspring.strongbox.repository",
"org.carlspring.strongbox.providers",
"org.carlspring.strongbox.services",
"org.carlspring.strongbox.storage",
})
public class Maven2LayoutProviderConfig
{
@Bean(name = "indexer")
Indexer indexer()
{
return new DefaultIndexer(searchEngine(), indexerEngine(), queryCreator());
}
@Bean(name = "scanner")
Scanner scanner()
{
return new DefaultScanner(artifactContextProducer());
}
@Bean(name = "indexPacker")
IndexPacker indexPacker()
{
return new DefaultIndexPacker(new DefaultIncrementalHandler());
}
@Bean(name = "indexUpdater")
IndexUpdater indexUpdater() { return new DefaultIndexUpdater(new DefaultIncrementalHandler(), null); }
@Bean(name = "searchEngine")
SearchEngine searchEngine()
{
return new DefaultSearchEngine();
}
@Bean(name = "indexerEngine")
IndexerEngine indexerEngine()
{
return new DefaultIndexerEngine();
}
@Bean(name = "queryCreator")
QueryCreator queryCreator()
{
return new DefaultQueryCreator();
}
@Bean(name = "mavenIndexerSearchProvider")
MavenIndexerSearchProvider mavenIndexerSearchProvider()
{
return new MavenIndexerSearchProvider();
}
@Bean(name = "maven2LayoutProvider")
Maven2LayoutProvider maven2LayoutProvider()
{
return new Maven2LayoutProvider();
}
@Bean(name = "mavenRepositoryFeatures")
MavenRepositoryFeatures mavenRepositoryFeatures()
{
return new MavenRepositoryFeatures();
}
@Inject
OEntityManager entityManager;
@PostConstruct
public void init()
{
// unable to replace with more generic one (ArtifactCoordinates) because of
// internal OrientDB exception: MavenArtifactCoordinates will not be serializable because
// it was not registered using registerEntityClass()
entityManager.registerEntityClass(MavenArtifactCoordinates.class);
}
@Bean(name = "mavenRepositoryManagementStrategy")
MavenRepositoryManagementStrategy mavenRepositoryManagementStrategy()
{
return new MavenRepositoryManagementStrategy();
}
@Bean(name = "artifactContextProducer")
ArtifactContextProducer artifactContextProducer()
{
return new DefaultArtifactContextProducer(artifactPackagingMapper());
}
@Bean(name = "artifactPackagingMapper")
ArtifactPackagingMapper artifactPackagingMapper()
{
return new DefaultArtifactPackagingMapper();
}
@Bean
MinimalArtifactInfoIndexCreator minimalArtifactInfoIndexCreator()
{
return new MinimalArtifactInfoIndexCreator();
}
@Bean
JarFileContentsIndexCreator jarFileContentsIndexCreator()
{
return new JarFileContentsIndexCreator();
}
@Bean
MavenPluginArtifactInfoIndexCreator mavenPluginArtifactInfoIndexCreator()
{
return new MavenPluginArtifactInfoIndexCreator();
}
@Bean(name = "indexers")
Map<String, AbstractIndexCreator> indexers()
{
LinkedHashMap<String, AbstractIndexCreator> indexers = new LinkedHashMap<>();
indexers.put("min", minimalArtifactInfoIndexCreator());
indexers.put("jarContent", jarFileContentsIndexCreator());
indexers.put("maven-plugin", mavenPluginArtifactInfoIndexCreator());
return indexers;
}
}
|
package org.xwiki.search.solr.internal.rest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.xwiki.component.annotation.Component;
import org.xwiki.localization.LocaleUtils;
import org.xwiki.query.Query;
import org.xwiki.query.QueryManager;
import org.xwiki.query.solr.internal.SolrQueryExecutor;
import org.xwiki.rest.Relations;
import org.xwiki.rest.internal.Utils;
import org.xwiki.rest.internal.resources.search.AbstractSearchSource;
import org.xwiki.rest.model.jaxb.Link;
import org.xwiki.rest.model.jaxb.SearchResult;
import org.xwiki.rest.resources.pages.PageResource;
import org.xwiki.rest.resources.pages.PageTranslationResource;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
/**
* @version $Id$
* @since 6.4M1
*/
@Component
@Named("solr")
@Singleton
public class SOLRSearchSource extends AbstractSearchSource
{
@Inject
protected Provider<XWikiContext> xcontextProvider;
@Inject
protected QueryManager queryManager;
@Override
public List<SearchResult> search(String queryString, String defaultWikiName, String wikis,
boolean hasProgrammingRights, String orderField, String order, boolean distinct, int number, int start,
Boolean withPrettyNames, String className, UriInfo uriInfo) throws Exception
{
List<SearchResult> result = new ArrayList<SearchResult>();
if (queryString == null) {
return result;
}
/*
* One of the two must be non-null. If default wiki name is non-null and wikis is null, then it's a local search
* in a specific wiki. If wiki name is null and wikis is non-null it's a global query on different wikis. If
* both of them are non-null then the wikis parameter takes the precedence.
*/
if (defaultWikiName == null && wikis == null) {
return result;
}
Query query = this.queryManager.createQuery(queryString, SolrQueryExecutor.SOLR);
List<String> fq = new ArrayList<String>();
// We want only documents
fq.add("{!tag=type}type:(\"DOCUMENT\")");
// Additional filter for non PR users
if (!hasProgrammingRights) {
fq.add("{!tag=hidden}hidden:(false)");
}
// Wikis
if (StringUtils.isNotBlank(wikis)) {
String[] strings = StringUtils.split(wikis, ',');
if (strings.length == 1) {
fq.add("{!tag=wiki}wiki:(\"" + strings[0] + "\")");
} else if (strings.length > 1) {
StringBuilder builder = new StringBuilder();
for (String str : strings) {
if (builder.length() > 0) {
builder.append(" OR ");
}
builder.append('\'');
builder.append(str);
builder.append('\'');
}
fq.add("{!tag=wiki}wiki:(" + builder + ")");
}
}
// Supported locales
XWikiContext xcontext = this.xcontextProvider.get();
query.bindValue("xwiki.supportedLocales",
StringUtils.join(xcontext.getWiki().getAvailableLocales(xcontext), ','));
// TODO: current locale filtering ?
query.bindValue("fq", fq);
// Boost
// FIXME: take it from configuration
query.bindValue("qf",
"title^10.0 name^10.0 doccontent^2.0 objcontent^0.4 filename^0.4 attcontent^0.4 doccontentraw^0.4 "
+ "author_display^0.08 creator_display^0.08 " + "comment^0.016 attauthor_display^0.016 space^0.016");
// Order
if (!StringUtils.isBlank(orderField)) {
if ("desc".equals(order)) {
query.bindValue("sort", orderField + " desc");
} else {
query.bindValue("sort", orderField + " asc");
}
}
// Limit
query.setLimit(number).setOffset(start);
try {
QueryResponse response = (QueryResponse) query.execute().get(0);
SolrDocumentList documents = response.getResults();
for (SolrDocument document : documents) {
SearchResult searchResult = this.objectFactory.createSearchResult();
searchResult.setPageFullName((String) document.get("fullname"));
searchResult.setTitle((String) document.get("title"));
searchResult.setWiki((String) document.get("wiki"));
searchResult.setSpace((String) document.get("space"));
searchResult.setPageName((String) document.get("name"));
searchResult.setVersion((String) document.get("version"));
searchResult.setType("page");
searchResult.setId(Utils.getPageId(searchResult.getWiki(), searchResult.getSpace(),
searchResult.getPageName()));
searchResult.setScore(((Number) document.get("score")).floatValue());
searchResult.setAuthor((String) document.get("author"));
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) document.get("date"));
searchResult.setModified(calendar);
if (withPrettyNames) {
searchResult.setAuthorName((String) document.get("author_display"));
}
Locale locale = LocaleUtils.toLocale((String) document.get("doclocale"));
String pageUri = null;
if (Locale.ROOT == locale) {
pageUri =
Utils.createURI(uriInfo.getBaseUri(), PageResource.class, searchResult.getWiki(),
searchResult.getSpace(), searchResult.getPageName()).toString();
} else {
searchResult.setLanguage(locale.toString());
pageUri =
Utils.createURI(uriInfo.getBaseUri(), PageTranslationResource.class, searchResult.getSpace(),
searchResult.getPageName(), locale).toString();
}
Link pageLink = new Link();
pageLink.setHref(pageUri);
pageLink.setRel(Relations.PAGE);
searchResult.getLinks().add(pageLink);
result.add(searchResult);
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_UNKNOWN,
"Error performing solr search", e);
}
return result;
}
}
|
package org.apache.hadoop.yarn.server.timeline;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.yarn.api.records.timeline.*;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
public class ElasticSearchTimelineStore extends AbstractService implements TimelineStore {
private static final Log LOG = LogFactory.getLog(ElasticSearchTimelineStore.class);
public static final String TIMELINE_SERVICE_ES_NODES = "yarn.timeline-service.es.nodes";
public static final String TIMELINE_SERVICE_CLUSTER_NAME = "yarn.timeline-service.es.cluster.name";
public static final int ES_BATCH_SIZE = 10000;
public static String ES_CLUSTER_NAME;
public static String ES_INDEX = "timelineserver";
public static String ES_TYPE_ENTITY = "entity";
public static String ES_TYPE_DOMAIN = "domain";
private static List<InetSocketAddress> ES_NODES = new ArrayList<>();
private BlockingQueue<TimelineEntity> esEntities = new LinkedBlockingDeque<>();
private BlockingQueue<TimelineDomain> esDomains = new LinkedBlockingDeque<>();
private Thread entityPoster;
private Thread domainPoster;
public ElasticSearchTimelineStore() {
super(ElasticSearchTimelineStore.class.getName());
}
@Override
protected void serviceInit(Configuration conf) throws Exception {
String esNodes = conf.get(TIMELINE_SERVICE_ES_NODES);
if (esNodes != null) {
String[] array = esNodes.split(",");
for (String address : array)
ES_NODES.add(NetUtils.createSocketAddr(address));
}
ES_CLUSTER_NAME = conf.get(TIMELINE_SERVICE_CLUSTER_NAME);
entityPoster = new Thread(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
// Deal with entity
TimelineEntity entity;
int i = 0;
long ts1 = System.currentTimeMillis();
BulkRequestBuilder bulkRequest = ESUtil.getEsClient(ES_CLUSTER_NAME, ES_NODES).prepareBulk();
while (true) {
try {
entity = esEntities.take();
String docId = entity.getEntityType() + "_" + entity.getEntityId();
// Just for es mapping
if ("TEZ_APPLICATION".equals(entity.getEntityType())) {
Map<String, String> config = (Map<String, String>) entity.getOtherInfo().get("config");
Map<String, String> newConfig = new HashMap<>(config.size());
for (String key : config.keySet()) {
newConfig.put(key.replaceAll("\\.", "__"), config.get(key));
}
entity.getOtherInfo().put("config", newConfig);
if (entity.getStartTime() == null)
entity.setStartTime(System.currentTimeMillis());
}
String json = gson.toJson(entity);
bulkRequest.add(new UpdateRequest(ES_INDEX, ES_TYPE_ENTITY, docId).doc(json).upsert(json));
LOG.debug("add entity id : " + docId);
if ("YARN_APPLICATION".equals(entity.getEntityType()))
LOG.info("YARN_APPLICATION : " + json);
i++;
if (i >= ES_BATCH_SIZE || System.currentTimeMillis() > (ts1 + 10000)) {
long ts2 = System.currentTimeMillis();
BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
LOG.error("Es Exception:" + bulkResponse.buildFailureMessage());
}
long ts3 = System.currentTimeMillis();
LOG.info("entity poster : prepare " + (ts2 - ts1) + ", post " + (ts3 - ts2));
ts1 = System.currentTimeMillis();
i = 0;
bulkRequest = ESUtil.getEsClient(ES_CLUSTER_NAME, ES_NODES).prepareBulk();
}
} catch (InterruptedException e) {
LOG.error("InterruptedException Exception:" + e);
}
}
}
});
entityPoster.start();
domainPoster = new Thread(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
// Deal with domain
TimelineDomain domain;
int i = 0;
long ts1 = System.currentTimeMillis();
BulkRequestBuilder bulkRequest = ESUtil.getEsClient(ES_CLUSTER_NAME, ES_NODES).prepareBulk();
while (true) {
try {
domain = esDomains.take();
String json = gson.toJson(domain);
bulkRequest.add(new UpdateRequest(ES_INDEX, ES_TYPE_DOMAIN, domain.getId()).doc(json).upsert(json));
i++;
if (i >= ES_BATCH_SIZE || System.currentTimeMillis() > (ts1 + 10000)) {
long ts2 = System.currentTimeMillis();
BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
LOG.error("Es Exception:" + bulkResponse.buildFailureMessage());
}
long ts3 = System.currentTimeMillis();
LOG.info("domain poster : prepare " + (ts2 - ts1) + ", post " + (ts3 - ts2));
ts1 = System.currentTimeMillis();
i = 0;
bulkRequest = ESUtil.getEsClient(ES_CLUSTER_NAME, ES_NODES).prepareBulk();
}
} catch (InterruptedException e) {
LOG.error("InterruptedException Exception:" + e);
}
}
}
});
domainPoster.start();
super.serviceInit(conf);
}
@Override
protected void serviceStop() throws Exception {
try {
entityPoster.interrupt();
} catch (Exception e) {
try {
entityPoster.join();
} catch (Exception e2) {
}
}
try {
domainPoster.interrupt();
} catch (Exception e) {
try {
domainPoster.join();
} catch (Exception e2) {
}
}
super.serviceStop();
}
@Override
public TimelinePutResponse put(TimelineEntities entities) throws IOException {
for (TimelineEntity entity : entities.getEntities()) {
try {
esEntities.put(entity);
} catch (InterruptedException e) {
LOG.error("put entity error!", e);
}
}
return new TimelinePutResponse();
}
@Override
public void put(TimelineDomain domain) throws IOException {
esDomains.add(domain);
}
private String[] esEntityFields(EnumSet<Field> fieldsToRetrieve) {
if (fieldsToRetrieve != null) {
String[] fields = new String[fieldsToRetrieve.size()];
int i = 0;
for (Field f : fieldsToRetrieve) {
switch (f) {
case EVENTS:
fields[i++] = "events";
break;
case RELATED_ENTITIES:
fields[i++] = "relatedEntities";
break;
case PRIMARY_FILTERS:
fields[i++] = "primaryFilters";
break;
case OTHER_INFO:
fields[i++] = "otherInfo";
break;
case LAST_EVENT_ONLY:
fields[i++] = "lastEventOnly";
break;
}
}
return fields;
}
return null;
}
private SearchResponse searchEsEntity(BoolQueryBuilder queryBuilder, String[] fields, Long limit) {
SearchRequestBuilder searchRequestBuilder = ESUtil.getEsClient(ES_CLUSTER_NAME, ES_NODES)
.prepareSearch(ES_INDEX)
.setTypes(ES_TYPE_ENTITY)
.setQuery(queryBuilder);
SortBuilder sort = SortBuilders.fieldSort("startTime")
.order(SortOrder.DESC)
.unmappedType("Long");
if (fields != null)
searchRequestBuilder.setFetchSource(fields, null);
if (limit != null)
searchRequestBuilder.setSize(limit.intValue());
searchRequestBuilder.addSort(sort);
return searchRequestBuilder.get();
}
private TimelineEntity parseEntity(Map<String, Object> source, EnumSet<Field> fieldsToRetrieve) {
TimelineEntity entity = new TimelineEntity();
entity.setEntityType((String) source.get("entityType"));
entity.setEntityId((String) source.get("entityId"));
entity.setStartTime((Long) source.get("startTime"));
if (source.get("events") != null) {
ArrayList<Object> esEvents = (ArrayList<Object>) source.get("events");
List<TimelineEvent> events = new ArrayList<>();
for (Object obj : esEvents) {
HashMap<String, Object> esEvent = (HashMap<String, Object>) obj;
TimelineEvent event = new TimelineEvent();
event.setEventInfo((Map<String, Object>) esEvent.get("eventInfo"));
event.setEventType((String) esEvent.get("eventType"));
event.setTimestamp((Long) esEvent.get("timestamp"));
events.add(event);
}
entity.setEvents(events);
}
if (source.get("relatedEntities") != null) {
Map<String, ArrayList<String>> esRelatedEntities = (Map<String, ArrayList<String>>) source.get("relatedEntities");
Map<String, Set<String>> relatedEntities = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> en : esRelatedEntities.entrySet()) {
relatedEntities.put(en.getKey(), new HashSet<>(en.getValue()));
}
entity.setRelatedEntities(relatedEntities);
}
if (source.get("primaryFilters") != null) {
Map<String, ArrayList<Object>> esPrimaryFilters = (Map<String, ArrayList<Object>>) source.get("primaryFilters");
Map<String, Set<Object>> primaryFilters = new HashMap<>();
for (Map.Entry<String, ArrayList<Object>> en : esPrimaryFilters.entrySet())
primaryFilters.put(en.getKey(), new HashSet<>(en.getValue()));
entity.setPrimaryFilters(primaryFilters);
}
if (source.get("otherInfo") != null) {
Map<String, Object> otherInfo = (Map<String, Object>) source.get("otherInfo");
// Just for es mapping
if ("TEZ_APPLICATION".equals(entity.getEntityType())) {
Map<String, String> config = (Map<String, String>) otherInfo.get("config");
Map<String, String> newConfig = new HashMap<>(config.size());
for (String key : config.keySet()) {
newConfig.put(key.replaceAll("__", "\\."), config.get(key));
}
otherInfo.put("config", newConfig);
}
entity.setOtherInfo(otherInfo);
}
entity.setDomainId((String) source.get("domainId"));
return entity;
}
@Override
public TimelineEntities getEntities(String entityType, Long limit, Long windowStart,
Long windowEnd, String fromId, Long fromTs, NameValuePair primaryFilter,
Collection<NameValuePair> secondaryFilters, EnumSet<Field> fieldsToRetrieve)
throws IOException {
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
if (entityType != null)
queryBuilder.must(QueryBuilders.termQuery("entityType", entityType));
// TODO window
if (windowStart != null)
queryBuilder.filter(QueryBuilders.rangeQuery("starttime").gte(windowStart));
if (windowEnd != null)
queryBuilder.filter(QueryBuilders.rangeQuery("starttime").lte(windowEnd));
if (fromId != null)
queryBuilder.filter(QueryBuilders.rangeQuery("entityId").lt(fromId));
// TODO fromTs
if (primaryFilter != null) {
queryBuilder.must(QueryBuilders.termQuery("primaryFilters." + primaryFilter.getName(),
primaryFilter.getValue()));
}
if (secondaryFilters != null) {
for (NameValuePair filter : secondaryFilters) {
if ("status".equals(filter.getName()) && "RUNNING".equals(filter.getValue()))
queryBuilder.mustNot(QueryBuilders.existsQuery("primaryFilters.status"));
else
queryBuilder.filter(QueryBuilders.termQuery("primaryFilters." + filter.getName(),
filter.getValue()));
}
}
// String[] fields = esEntityFields(fieldsToRetrieve);
SearchResponse response = searchEsEntity(queryBuilder, null, limit);
TimelineEntities timelineEntities = new TimelineEntities();
for (SearchHit hit : response.getHits().hits()) {
Map<String, Object> source = hit.getSource();
TimelineEntity timelineEntity = parseEntity(source, fieldsToRetrieve);
timelineEntities.addEntity(timelineEntity);
}
return timelineEntities;
}
@Override
public TimelineEntity getEntity(String entityId, String entityType,
EnumSet<Field> fieldsToRetrieve) throws IOException {
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
if (entityId != null)
queryBuilder.must(QueryBuilders.termQuery("entityId", entityId));
if (entityType != null)
queryBuilder.must(QueryBuilders.termQuery("entityType", entityType));
LOG.debug("getEntity queryBuilder : " + queryBuilder);
// String[] fields = esEntityFields(fieldsToRetrieve);
SearchResponse response = searchEsEntity(queryBuilder, null, 1l);
if (response.getHits().totalHits() > 0) {
SearchHit[] hits = response.getHits().hits();
return parseEntity(hits[0].getSource(), fieldsToRetrieve);
} else
return null;
}
@Override
public TimelineEvents getEntityTimelines(String entityType, SortedSet<String> entityIds,
Long limit, Long windowStart, Long windowEnd, Set<String> eventTypes) throws IOException {
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
if (entityType != null)
queryBuilder.must(QueryBuilders.termQuery("entityType", entityType));
// TODO window
if (windowStart != null)
queryBuilder.filter(QueryBuilders.rangeQuery("starttime").gte(windowStart));
if (windowEnd != null)
queryBuilder.filter(QueryBuilders.rangeQuery("starttime").lte(windowEnd));
if (entityIds != null) {
for (String id : entityIds) {
queryBuilder.should(QueryBuilders.termQuery("entityId", id));
}
}
if (eventTypes != null) {
for (String eventType : eventTypes) {
queryBuilder.must(QueryBuilders.termQuery("events.eventtype", eventType));
}
}
SortBuilder sort = SortBuilders.fieldSort("startTime")
.order(SortOrder.DESC)
.unmappedType("Long");
SearchResponse response = ESUtil.getEsClient(ES_CLUSTER_NAME, ES_NODES)
.prepareSearch(ES_INDEX)
.setTypes(ES_TYPE_ENTITY)
.setQuery(queryBuilder)
.addSort(sort)
.setSize(limit.intValue()).get();
TimelineEvents events = new TimelineEvents();
Gson gson = new Gson();
for (SearchHit hit : response.getHits().hits())
events.addEvent(gson.fromJson(hit.getSource().toString(), TimelineEvents.EventsOfOneEntity.class));
return events;
}
@Override
public TimelineDomain getDomain(String domainId) throws IOException {
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.termQuery("id", domainId));
SearchResponse response = ESUtil.getEsClient(ES_CLUSTER_NAME, ES_NODES)
.prepareSearch(ES_INDEX)
.setTypes(ES_TYPE_DOMAIN)
.setQuery(queryBuilder).get();
if (response.getHits().totalHits() > 0) {
Gson gson = new Gson();
SearchHit[] hits = response.getHits().hits();
return gson.fromJson(hits[0].getSourceAsString(), TimelineDomain.class);
} else
return null;
}
@Override
public TimelineDomains getDomains(String owner) throws IOException {
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.termQuery("owner", owner));
SearchResponse response = ESUtil.getEsClient(ES_CLUSTER_NAME, ES_NODES)
.prepareSearch(ES_INDEX)
.setTypes(ES_TYPE_DOMAIN)
.setQuery(queryBuilder).get();
TimelineDomains domains = new TimelineDomains();
SearchHit[] hits = response.getHits().hits();
Gson gson = new Gson();
for (SearchHit hit : hits)
domains.addDomain(gson.fromJson(hit.getSourceAsString(), TimelineDomain.class));
return domains;
}
static class ESUtil {
private static TransportClient transportClient = null;
public static TransportClient getEsClient(String clusterName, List<InetSocketAddress> esNodes) {
return getEsClient(clusterName, esNodes.toArray(new InetSocketAddress[esNodes.size()]));
}
public static TransportClient getEsClient(String clusterName, InetSocketAddress[] esNodes) {
if (transportClient == null) {
synchronized (ESUtil.class) {
if (transportClient == null) {
Settings setting =
Settings.settingsBuilder().put("cluster.name", clusterName)
.put("client.transport.sniff", true)
.build();
transportClient = TransportClient.builder().settings(setting).build();
for (InetSocketAddress node : esNodes) {
transportClient.addTransportAddress(new InetSocketTransportAddress(node));
}
}
}
}
return transportClient;
}
}
}
|
package com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.rightPanelTabs;
import cern.colt.matrix.tdouble.DoubleMatrix1D;
import com.google.common.collect.Sets;
import com.net2plan.gui.plugins.networkDesign.ParamValueTable;
import com.net2plan.gui.utils.*;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.specificTables.AdvancedJTable_layer;
import com.net2plan.gui.plugins.GUINetworkDesign;
import com.net2plan.interfaces.networkDesign.*;
import com.net2plan.internal.Constants.NetworkElementType;
import com.net2plan.libraries.GraphTheoryMetrics;
import com.net2plan.libraries.GraphUtils;
import com.net2plan.libraries.SRGUtils;
import com.net2plan.libraries.TrafficComputationEngine;
import com.net2plan.utils.CollectionUtils;
import com.net2plan.utils.Constants.RoutingCycleType;
import com.net2plan.utils.Constants.RoutingType;
import com.net2plan.utils.Pair;
import com.net2plan.utils.StringUtils;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
public class NetPlanViewTableComponent_layer extends JPanel {
private final static String[] layerSummaryTableHeader = StringUtils.arrayOf("Metric", "Value");
private final static String[] attributeTableHeader = StringUtils.arrayOf("Attribute", "Value");
private final static String[] attributeTableTips = attributeTableHeader;
private JTable layerAttributeTable;
private JTextField txt_layerName, txt_layerLinkCapacityUnits, txt_layerDemandTrafficUnits;
private JTextArea txt_layerDescription;
private JRadioButton sourceRoutingActivated, hopByHopRoutingActivated;
private ButtonGroup routingSchemes;
private JPanel layerMetricsInfo;
private ParamValueTable[] layerSummaryTables;
private JButton forceUpdate;
private final AdvancedJTable_layer layerTable;
private boolean insideUpdateView;
private final GUINetworkDesign networkViewer;
public NetPlanViewTableComponent_layer(final GUINetworkDesign networkViewer, final AdvancedJTable_layer layerTable) {
super(new MigLayout("", "[grow]", "[][][][][][grow]"));
this.layerTable = layerTable;
this.networkViewer = networkViewer;
txt_layerName = new JTextField();
txt_layerDescription = new JTextArea();
txt_layerDescription.setFont(new JLabel().getFont());
txt_layerDescription.setLineWrap(true);
txt_layerDescription.setWrapStyleWord(true);
txt_layerDemandTrafficUnits = new JTextField();
txt_layerLinkCapacityUnits = new JTextField();
sourceRoutingActivated = new JRadioButton("Source routing", false);
sourceRoutingActivated.setEnabled(networkViewer.getVisualizationState().isNetPlanEditable());
hopByHopRoutingActivated = new JRadioButton("Hop-by-hop routing", false);
hopByHopRoutingActivated.setEnabled(networkViewer.getVisualizationState().isNetPlanEditable());
if (networkViewer.getVisualizationState().isNetPlanEditable()) {
ItemListener itemRoutingTypeListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent event) {
JRadioButton button = (JRadioButton) event.getSource();
int state = event.getStateChange();
NetPlan netPlan = networkViewer.getDesign();
RoutingType previousRoutingType = netPlan.getRoutingType();
if (button == sourceRoutingActivated && state == ItemEvent.SELECTED) {
netPlan.setRoutingType(RoutingType.SOURCE_ROUTING);
if (previousRoutingType != RoutingType.SOURCE_ROUTING)
{
networkViewer.getVisualizationState().resetPickedState();
networkViewer.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LAYER));
networkViewer.getUndoRedoNavigationManager().addNetPlanChange();
}
}
if (button == hopByHopRoutingActivated && state == ItemEvent.SELECTED) {
netPlan.setRoutingType(RoutingType.HOP_BY_HOP_ROUTING);
if (previousRoutingType != RoutingType.HOP_BY_HOP_ROUTING)
{
networkViewer.getVisualizationState().resetPickedState();
networkViewer.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LAYER));
networkViewer.getUndoRedoNavigationManager().addNetPlanChange();
}
}
}
};
sourceRoutingActivated.addItemListener(itemRoutingTypeListener);
hopByHopRoutingActivated.addItemListener(itemRoutingTypeListener);
}
routingSchemes = new ButtonGroup();
routingSchemes.add(sourceRoutingActivated);
routingSchemes.add(hopByHopRoutingActivated);
txt_layerName.setEditable(networkViewer.getVisualizationState().isNetPlanEditable());
txt_layerDescription.setEditable(networkViewer.getVisualizationState().isNetPlanEditable());
txt_layerDemandTrafficUnits.setEditable(networkViewer.getVisualizationState().isNetPlanEditable());
txt_layerLinkCapacityUnits.setEditable(networkViewer.getVisualizationState().isNetPlanEditable());
if (networkViewer.getVisualizationState().isNetPlanEditable()) {
txt_layerName.getDocument().addDocumentListener(new DocumentAdapter(networkViewer) {
@Override
protected void updateInfo(String text) {
// allowDocumentUpdate = false;
NetworkLayer layer = networkViewer.getDesign().getNetworkLayerDefault();
JTable table = (JTable) layerTable;
TableModel model = table.getModel();
int numRows = model.getRowCount();
for (int row = 0; row < numRows; row++) {
if ((Long) model.getValueAt(row, AdvancedJTable_layer.COLUMN_ID) == layer.getId()) {
layer.setName(text);
model.setValueAt(text, row, AdvancedJTable_layer.COLUMN_NAME);
}
}
// allowDocumentUpdate = isEditable();
}
});
txt_layerName.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if (!insideUpdateView)
{
networkViewer.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LAYER));
networkViewer.getUndoRedoNavigationManager().addNetPlanChange();
}
}
});
txt_layerLinkCapacityUnits.getDocument().addDocumentListener(new DocumentAdapter(networkViewer) {
@Override
protected void updateInfo(String text) {
// allowDocumentUpdate = false;
NetworkLayer layer = networkViewer.getDesign().getNetworkLayerDefault();
JTable table = (JTable) layerTable;
TableModel model = table.getModel();
int numRows = model.getRowCount();
for (int row = 0; row < numRows; row++) {
if ((Long) model.getValueAt(row, AdvancedJTable_layer.COLUMN_ID) == layer.getId()) {
final String previousValue = model.getValueAt(row, AdvancedJTable_layer.COLUMN_LINKCAPUNITS).toString();
model.setValueAt(text, row, AdvancedJTable_layer.COLUMN_LINKCAPUNITS);
if (!text.equals(model.getValueAt(row, AdvancedJTable_layer.COLUMN_LINKCAPUNITS).toString())) {
final DocumentListener me = this;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
txt_layerLinkCapacityUnits.getDocument().removeDocumentListener(me);
txt_layerLinkCapacityUnits.setText(previousValue);
txt_layerLinkCapacityUnits.getDocument().addDocumentListener(me);
}
});
}
}
}
// allowDocumentUpdate = isEditable();
}
});
txt_layerDemandTrafficUnits.getDocument().addDocumentListener(new DocumentAdapter(networkViewer) {
@Override
protected void updateInfo(String text) {
// allowDocumentUpdate = false;
NetworkLayer layer = networkViewer.getDesign().getNetworkLayerDefault();
JTable table = (JTable) layerTable;
TableModel model = table.getModel();
int numRows = model.getRowCount();
for (int row = 0; row < numRows; row++) {
if ((Long) model.getValueAt(row, AdvancedJTable_layer.COLUMN_ID) == layer.getId()) {
final String previousValue = model.getValueAt(row, AdvancedJTable_layer.COLUMN_DEMANDTRAFUNITS).toString();
model.setValueAt(text, row, AdvancedJTable_layer.COLUMN_DEMANDTRAFUNITS);
if (!text.equals(model.getValueAt(row, AdvancedJTable_layer.COLUMN_DEMANDTRAFUNITS).toString())) {
final DocumentListener me = this;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
txt_layerDemandTrafficUnits.getDocument().removeDocumentListener(me);
txt_layerDemandTrafficUnits.setText(previousValue);
txt_layerDemandTrafficUnits.getDocument().addDocumentListener(me);
}
});
}
}
}
// allowDocumentUpdate = isEditable();
}
});
txt_layerDescription.getDocument().addDocumentListener(new DocumentAdapter(networkViewer) {
@Override
protected void updateInfo(String text) {
// allowDocumentUpdate = false;
NetworkLayer layer = networkViewer.getDesign().getNetworkLayerDefault();
JTable table = (JTable) layerTable;
TableModel model = table.getModel();
int numRows = model.getRowCount();
for (int row = 0; row < numRows; row++)
if ((Long) model.getValueAt(row, AdvancedJTable_layer.COLUMN_ID) == layer.getId())
model.setValueAt(text, row, AdvancedJTable_layer.COLUMN_DESCRIPTION);
// allowDocumentUpdate = isEditable();
}
});
}
layerAttributeTable = new AdvancedJTable(new ClassAwareTableModel(new Object[1][attributeTableHeader.length], attributeTableHeader));
if (networkViewer.getVisualizationState().isNetPlanEditable())
layerAttributeTable.addMouseListener(new SingleElementAttributeEditor(networkViewer, NetworkElementType.LAYER));
JTable table = layerAttributeTable;
String[] columnTips = attributeTableTips;
String[] columnHeader = attributeTableHeader;
ColumnHeaderToolTips tips = new ColumnHeaderToolTips();
for (int c = 0; c < columnHeader.length; c++) {
TableColumn col = table.getColumnModel().getColumn(c);
tips.setToolTip(col, columnTips[c]);
}
table.getTableHeader().addMouseMotionListener(tips);
JScrollPane scrollPane = new JScrollPane(table);
ScrollPaneLayout layout = new FullScrollPaneLayout();
scrollPane.setLayout(layout);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
KeyListener cursorNavigation = new TableCursorNavigation();
layerSummaryTables = new ParamValueTable[4];
for (int i = 0; i < layerSummaryTables.length; i++) {
layerSummaryTables[i] = new ParamValueTable(layerSummaryTableHeader);
layerSummaryTables[i].setAutoCreateRowSorter(true);
layerSummaryTables[i].addKeyListener(cursorNavigation);
}
table.addKeyListener(cursorNavigation);
layerMetricsInfo = new JPanel();
layerMetricsInfo.setLayout(new MigLayout("insets 0 0 0 0", "[grow]"));
layerMetricsInfo.add(new JLabel("Topology and link capacities"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[0]), "growx, wrap");
layerMetricsInfo.add(new JLabel("Traffic"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[1]), "growx, wrap");
layerMetricsInfo.add(new JLabel("Routing"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[2]), "growx, wrap");
layerMetricsInfo.add(new JLabel("Resilience information"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[3]), "growx");
JPanel layerPane = new JPanel(new MigLayout("", "[][grow]", "[][][][grow]"));
layerPane.add(new JLabel("Name"));
layerPane.add(txt_layerName, "grow, wrap");
layerPane.add(new JLabel("Description"), "aligny top");
layerPane.add(new JScrollPane(txt_layerDescription), "grow, wrap, height 100::");
layerPane.add(new JLabel("Link capacity units"));
layerPane.add(txt_layerLinkCapacityUnits, "grow, wrap");
layerPane.add(new JLabel("Demand traffic units"));
layerPane.add(txt_layerDemandTrafficUnits, "grow, wrap");
layerPane.add(new JLabel("Routing type"));
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(sourceRoutingActivated);
radioPanel.add(hopByHopRoutingActivated);
layerPane.add(radioPanel, "grow, wrap");
layerPane.add(scrollPane, "grow, spanx 2");
JScrollPane layerInfoScrollPane = new JScrollPane(layerMetricsInfo);
layerInfoScrollPane.setBorder(BorderFactory.createEmptyBorder());
forceUpdate = new JButton("Update all metrics");
forceUpdate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateLayerMetrics(networkViewer.getDesign(), true);
}
});
forceUpdate.setToolTipText("Use this button to update those metrics which not automatically computed in large netwokrs, since they involve quite time-consuming computations");
forceUpdate.setVisible(false);
JPanel layerInfoPane = new JPanel(new BorderLayout());
layerInfoPane.add(forceUpdate, BorderLayout.NORTH);
layerInfoPane.add(layerInfoScrollPane, BorderLayout.CENTER);
JSplitPane splitPaneTopology = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPaneTopology.setTopComponent(layerPane);
splitPaneTopology.setBottomComponent(layerInfoPane);
splitPaneTopology.setResizeWeight(0.3);
splitPaneTopology.addPropertyChangeListener(new ProportionalResizeJSplitPaneListener());
add(splitPaneTopology, "grow, wrap");
// netPlanViewTableComponent.put(elementType, splitPaneTopology);
}
public void updateNetPlanView(NetPlan currentState)
{
this.insideUpdateView = true;
layerAttributeTable.setEnabled(false);
((DefaultTableModel) layerAttributeTable.getModel()).setDataVector(new Object[1][attributeTableHeader.length], attributeTableHeader);
if (currentState.getRoutingType() == RoutingType.SOURCE_ROUTING) sourceRoutingActivated.setSelected(true);
else hopByHopRoutingActivated.setSelected(true);
NetworkLayer layer = currentState.getNetworkLayerDefault();
Map<String, String> layerAttributes = layer.getAttributes();
if (!layerAttributes.isEmpty()) {
int layerAttributeId = 0;
Object[][] layerData = new Object[layerAttributes.size()][2];
for (Map.Entry<String, String> entry : layerAttributes.entrySet()) {
layerData[layerAttributeId][0] = entry.getKey();
layerData[layerAttributeId][1] = entry.getValue();
layerAttributeId++;
}
((DefaultTableModel) layerAttributeTable.getModel()).setDataVector(layerData, attributeTableHeader);
}
if (!txt_layerName.getText().equals(layer.getName())) txt_layerName.setText(layer.getName());
if (!txt_layerDescription.getText().equals(layer.getDescription())) txt_layerDescription.setText(layer.getDescription());
if (!txt_layerLinkCapacityUnits.getText().equals(currentState.getLinkCapacityUnitsName())) txt_layerLinkCapacityUnits.setText(currentState.getLinkCapacityUnitsName());
if (!txt_layerDemandTrafficUnits.getText().equals(currentState.getDemandTrafficUnitsName())) txt_layerDemandTrafficUnits.setText(currentState.getDemandTrafficUnitsName());
boolean hardComputations = currentState.getNumberOfNodes() <= 100;
updateLayerMetrics(currentState, hardComputations);
this.insideUpdateView = false;
}
private void updateLayerMetrics(NetPlan netPlan, boolean applyHardComputations) {
List<Node> nodes = netPlan.getNodes();
List<Link> links = netPlan.getLinks();
int N = netPlan.getNumberOfNodes();
int E = netPlan.getNumberOfLinks();
int D = netPlan.getNumberOfDemands();
int MD = netPlan.getNumberOfMulticastDemands();
int numSRGs = netPlan.getNumberOfSRGs();
double U_e = netPlan.getVectorLinkCapacity().zSum();
double H_d = netPlan.getVectorDemandOfferedTraffic().zSum();
double u_e_avg = E == 0 ? 0 : U_e / E;
int E_limitedCapacityLinks = 0;
double totalCapacityInstalled_limitedCapacityLinks = 0;
for (Link link : links) {
double u_e = link.getCapacity();
if (u_e < Double.MAX_VALUE) {
E_limitedCapacityLinks++;
totalCapacityInstalled_limitedCapacityLinks += u_e;
}
}
double averageTotalCapacityInstalled_limitedCapacityLinks = E_limitedCapacityLinks == 0 ? 0 : totalCapacityInstalled_limitedCapacityLinks / E_limitedCapacityLinks;
GraphTheoryMetrics metrics = new GraphTheoryMetrics(nodes, links, null);
DoubleMatrix1D nodeOutDegree = metrics.getOutNodeDegree();
int[] maxMinOutDegree = new int[2];
maxMinOutDegree[0] = nodeOutDegree.size() == 0 ? 0 : (int) nodeOutDegree.getMaxLocation()[0];
maxMinOutDegree[1] = nodeOutDegree.size() == 0 ? 0 : (int) nodeOutDegree.getMinLocation()[0];
double avgOutDegree = metrics.getAverageOutNodeDegree();
Map<String, Object> topologyData = new LinkedHashMap<String, Object>();
topologyData.put("Number of nodes", N);
topologyData.put("Number of links", E);
topologyData.put("Node out-degree (max, min, avg)", String.format("%d, %d, %.3f", maxMinOutDegree[0], maxMinOutDegree[1], avgOutDegree));
topologyData.put("All links are bidirectional (yes/no)", GraphUtils.isBidirectional(nodes, links) ? "Yes" : "No");
if (applyHardComputations) {
int networkDiameter_hops = (int) metrics.getDiameter();
metrics.configureLinkCostMap((Map<Link, Double>) CollectionUtils.toMap(links, netPlan.getVectorLinkLengthInKm()));
double networkDiameter_km = metrics.getDiameter();
metrics.configureLinkCostMap((Map<Link, Double>) CollectionUtils.toMap(links, netPlan.getVectorLinkPropagationDelayInMiliseconds()));
double networkDiameter_ms = metrics.getDiameter();
topologyData.put("Layer diameter (hops, km, ms)", String.format("%d, %.3f, %.3g", networkDiameter_hops, networkDiameter_km, networkDiameter_ms));
} else {
topologyData.put("Layer diameter (hops, km, ms)", "- (use 'Update all metrics' button)");
}
topologyData.put("Capacity installed: total", String.format("%.3f", U_e));
topologyData.put("Capacity installed: average per link", String.format("%.3f", u_e_avg));
topologyData.put("Capacity installed (limited capacity links): total", String.format("%.3f", totalCapacityInstalled_limitedCapacityLinks));
topologyData.put("Capacity installed (limited capacity links): average per link", String.format("%.3f", averageTotalCapacityInstalled_limitedCapacityLinks));
List<Map<String, Object>> layerSummaryInfo = new LinkedList<Map<String, Object>>();
layerSummaryInfo.add(topologyData);
boolean isTrafficSymmetric = GraphUtils.isWeightedBidirectional(netPlan.getNodes(), netPlan.getDemands(), netPlan.getVectorDemandOfferedTraffic());
double averageNodePairOfferedTraffic = H_d == 0 ? 0 : H_d / (N * (N - 1));
double blockedTrafficPercentage = H_d == 0 ? 0 : 100 * (netPlan.getVectorDemandBlockedTraffic().zSum() / H_d);
Map<String, Object> trafficData = new LinkedHashMap<String, Object>();
trafficData.put("Number of UNICAST demands", D);
trafficData.put("Offered UNICAST traffic: total", String.format("%.3f", H_d));
trafficData.put("Offered UNICAST traffic: average per node pair", String.format("%.3f", averageNodePairOfferedTraffic));
trafficData.put("Blocked UNICAST traffic (%)", String.format("%.3f", blockedTrafficPercentage));
trafficData.put("Symmetric offered UNICAST traffic?", isTrafficSymmetric ? "Yes" : "No");
trafficData.put("Number of MULTICAST demands", MD);
trafficData.put("Offered MULTICAST traffic: total", String.format("%.3f", netPlan.getVectorMulticastDemandOfferedTraffic().zSum()));
trafficData.put("Blocked MULTICAST traffic (%)", String.format("%.3f", netPlan.getVectorMulticastDemandBlockedTraffic().zSum()));
layerSummaryInfo.add(trafficData);
DoubleMatrix1D vector_rhoe = netPlan.getVectorLinkUtilization();
double max_rho_e = vector_rhoe.size() == 0 ? 0 : vector_rhoe.getMaxLocation()[0];
RoutingType routingType = netPlan.getRoutingType();
if (routingType == RoutingType.SOURCE_ROUTING) {
int R = netPlan.getNumberOfRoutes();
boolean isUnicastRoutingBifurcated = netPlan.isUnicastRoutingBifurcated();
boolean hasUnicastRoutingLoops = netPlan.hasUnicastRoutingLoops();
double averageRouteLength_hops = TrafficComputationEngine.getRouteAverageLength(netPlan.getRoutes(), null);
double averageRouteLength_km = TrafficComputationEngine.getRouteAverageLength(netPlan.getRoutes(), netPlan.getVectorLinkLengthInKm());
double averageRouteLength_ms = TrafficComputationEngine.getRouteAverageLength(netPlan.getRoutes(), netPlan.getVectorLinkPropagationDelayInMiliseconds());
Map<String, Object> routingData = new LinkedHashMap<String, Object>();
routingData.put("Number of routes", R);
routingData.put("Unicast routing is bifurcated?", isUnicastRoutingBifurcated ? "Yes" : "No");
routingData.put("Network congestion - bottleneck utilization", String.format("%.3f, %.3f", max_rho_e, max_rho_e));
routingData.put("Average (unicast) route length (hops, km, ms)", String.format("%.3f, %.3f, %.3g", averageRouteLength_hops, averageRouteLength_km, averageRouteLength_ms));
routingData.put("Unicast routing has loops?", hasUnicastRoutingLoops ? "Yes" : "No");
routingData.put("Number of multicast trees", netPlan.getNumberOfMulticastTrees());
routingData.put("Multicast routing is bifurcated?", netPlan.isMulticastRoutingBifurcated() ? "Yes" : "No");
Pair<Double, Double> stats = TrafficComputationEngine.getAverageHopsAndLengthOfMulticastTrees(netPlan.getMulticastTrees());
routingData.put("Average multicast tree size (hops, km)", String.format("%.3f, %.3f", stats.getFirst(), stats.getSecond()));
layerSummaryInfo.add(routingData);
final double protectionPercentage = TrafficComputationEngine.getTrafficProtectionDegree(netPlan);
Pair<Double, Double> srgDisjointnessPercentage = SRGUtils.getSRGDisjointnessPercentage(netPlan);
String srgModel = SRGUtils.getSRGModel(netPlan);
Map<String, Object> protectionData = new LinkedHashMap<String, Object>();
protectionData.put("% of carried traffic with at least one backup path", String.format("%.3f", protectionPercentage));
protectionData.put("Number of SRGs in the network", numSRGs);
protectionData.put("SRG definition characteristic", srgModel);
protectionData.put("% routes protected with SRG disjoint backup paths (w. end nodes, w.o. end nodes)", String.format("%.3f, %.3f", srgDisjointnessPercentage.getFirst(), srgDisjointnessPercentage.getSecond()));
layerSummaryInfo.add(protectionData);
} else {
Map<String, Object> routingData = new LinkedHashMap<String, Object>();
routingData.put("Network congestion - bottleneck utilization", String.format("%.3f", max_rho_e));
RoutingCycleType routingCycleType = RoutingCycleType.LOOPLESS;
for (Demand demand : netPlan.getDemands()) {
if (demand.getRoutingCycleType() != RoutingCycleType.LOOPLESS)
routingCycleType = demand.getRoutingCycleType();
if (routingCycleType == RoutingCycleType.CLOSED_CYCLES) break;
}
routingData.put("Routing has loops?", routingCycleType);
layerSummaryInfo.add(routingData);
}
ListIterator<Map<String, Object>> it = layerSummaryInfo.listIterator();
while (it.hasNext()) {
int tableId = it.nextIndex();
layerSummaryTables[tableId].setData(it.next());
AdvancedJTable.setVisibleRowCount(layerSummaryTables[tableId], layerSummaryTables[tableId].getRowCount());
AdvancedJTable.setWidthAsPercentages(layerSummaryTables[tableId], 0.7, 0.3);
}
layerSummaryTables[0].setToolTipText(0, 0, "Indicates the number of defined nodes in the network");
layerSummaryTables[0].setToolTipText(1, 0, "Indicates the number of defined links in this layer");
layerSummaryTables[0].setToolTipText(2, 0, "Indicates the maximum/minimum/average value for the out-degree, that is, the number of outgoing links per node");
layerSummaryTables[0].setToolTipText(3, 0, "Indicates whether all links are bidirectional, that is, if there are the same number of links between each node pair in both directions (irrespective of the respective capacities)");
layerSummaryTables[0].setToolTipText(4, 0, "Indicates the layer diameter, that is, the length of the largest shortest-path in this layer");
layerSummaryTables[0].setToolTipText(5, 0, "Indicates the total capacity installed in this layer");
layerSummaryTables[0].setToolTipText(6, 0, "Indicates the average capacity installed per link");
layerSummaryTables[0].setToolTipText(7, 0, "Indicates the total capacity installed in this layer for links whose capacity is not infinite");
layerSummaryTables[0].setToolTipText(8, 0, "Indicates the average capacity installed in this layer for links whose capacity is not infinite");
layerSummaryTables[1].setToolTipText(0, 0, "Indicates the number of defined demands in this layer");
layerSummaryTables[1].setToolTipText(1, 0, "Indicates the total offered unicast traffic to the network in this layer");
layerSummaryTables[1].setToolTipText(2, 0, "Indicates the total offered unicast traffic to the network per each node pair in this layer");
layerSummaryTables[1].setToolTipText(3, 0, "Indicates the percentage of blocked unicast traffic from the total offered to the network in this layer");
layerSummaryTables[1].setToolTipText(4, 0, "Indicates whether the unicast offered traffic is symmetric, that is, if there are the same number of demands with the same offered traffic between each node pair in both directions");
layerSummaryTables[1].setToolTipText(5, 0, "Indicates the number of defined multicast demands in this layer");
layerSummaryTables[1].setToolTipText(6, 0, "Indicates the total offered multicast traffic to the network in this layer");
layerSummaryTables[1].setToolTipText(7, 0, "Indicates the percentage of blocked multicast traffic from the total offered to the network in this layer");
layerMetricsInfo.removeAll();
layerMetricsInfo.add(new JLabel("Topology and link capacities"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[0]), "growx, wrap");
layerMetricsInfo.add(new JLabel("Traffic"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[1]), "growx, wrap");
if (routingType == RoutingType.SOURCE_ROUTING) {
layerSummaryTables[2].setToolTipText(0, 0, "Indicates the number of defined routes");
layerSummaryTables[2].setToolTipText(1, 0, "<html>Indicates whether the unicast routing is bifurcated, that is, if at least there are more than one active (up) route <u>carrying</u> traffic from any demand</html>");
layerSummaryTables[2].setToolTipText(2, 0, "Indicates the network congestion, that is, the utilization of the busiest link");
layerSummaryTables[2].setToolTipText(3, 0, "Indicates the average route length (unicast traffic)");
layerSummaryTables[2].setToolTipText(4, 0, "Indicates whether the unicast routing has loops, that is, if at least a route visits a node more than once");
layerSummaryTables[2].setToolTipText(5, 0, "Indicates the number of defined multicast trees");
layerSummaryTables[2].setToolTipText(6, 0, "<html>Indicates whether the multicast routing is bifurcated, that is, if for at least one multicast demand is carried by more than one up multicast trees</html>");
layerSummaryTables[2].setToolTipText(7, 0, "Indicates the average number of links and average total length (summing all the links) of the multicast trees in the network");
layerSummaryTables[3].setToolTipText(0, 0, "Indicates the number of defined protection segments");
layerSummaryTables[3].setToolTipText(1, 0, "Indicates the average reserved bandwidth per protection segment");
layerSummaryTables[3].setToolTipText(2, 0, "Indicates the percentage of traffic (from the total) which is not protected by any segment");
layerSummaryTables[3].setToolTipText(3, 0, "Indicates the percentage of traffic (from the total) which is protected by dedicated segments reservating so the total traffic can be carried from origin to destination through currently unused and dedicated segments");
layerSummaryTables[3].setToolTipText(4, 0, "Indicates the percentage of traffic (from the total) which is neither unprotected nor full-and-dedicated protected");
layerSummaryTables[3].setToolTipText(5, 0, "Indicates the number of defined SRGs");
layerSummaryTables[3].setToolTipText(6, 0, "Indicates whether SRG definition follows one of the predefined models (per node, per link...), or 'Mixed' otherwise (or 'None' if no SRGs are defined)");
layerSummaryTables[3].setToolTipText(7, 0, "Indicates the percentage of routes from the total which have all protection segments SRG-disjoint, without taking into account the carried traffic per route");
layerMetricsInfo.add(new JLabel("Routing"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[2]), "growx, wrap");
layerMetricsInfo.add(new JLabel("Resilience information"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[3]), "growx");
} else {
layerSummaryTables[2].setToolTipText(0, 0, "Indicates the network congestion, that is, the utilization of the busiest link");
layerSummaryTables[2].setToolTipText(1, 0, "Indicates whether the routing has loops, that is, if at least a route visits a node more than once");
layerMetricsInfo.add(new JLabel("Routing"), "growx, wrap");
layerMetricsInfo.add(new JScrollPane(layerSummaryTables[2]), "growx, wrap");
}
forceUpdate.setVisible(!applyHardComputations);
}
}
|
package dk.itu.ai;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.newdawn.slick.util.Log;
import mu.nu.nullpo.game.component.Controller;
import mu.nu.nullpo.game.component.Piece;
import mu.nu.nullpo.game.component.RuleOptions;
import mu.nu.nullpo.game.play.GameEngine;
import mu.nu.nullpo.game.play.GameEngine.Status;
import mu.nu.nullpo.game.play.GameManager;
import mu.nu.nullpo.game.subsystem.ai.BasicAI;
import mu.nu.nullpo.game.subsystem.ai.DummyAI;
import mu.nu.nullpo.game.subsystem.mode.GameMode;
import mu.nu.nullpo.game.subsystem.mode.GradeMania3Mode;
import mu.nu.nullpo.gui.slick.LogSystemLog4j;
import mu.nu.nullpo.util.GeneralUtil;
public class Simulator {
public static void main(String[] args) {
// Logger initialization.
PropertyConfigurator.configure("config/etc/log_slick.cfg");
Log.setLogSystem(new LogSystemLog4j());
// NOTE(oliver): For other GameModes, look inside src/mu/nu/nullpo/game/subsystem/mode
GameMode mode =
new GradeMania3Mode();
// NOTE(oliver): For other rules, look inside config/rule.
String rulePath =
"config\\rule\\Classic3.rul";
// NOTE(oliver): For other AIs, look inside src/mu/nu/nullpo/game/subsystem/ai, or src/dk/itu/ai
DummyAI ai =
new BasicAI();
// Actual simulation.
Simulator simulator = new Simulator(mode, rulePath, ai);
simulator.setCustomSeed("-2fac0ecd9c988463");
simulator.runSimulations(100);
}
private GameManager gameManager;
private GameEngine gameEngine;
private String customSeed = null;
/**
* Make a new Simulator object, ready to go.
* @param mode Game mode Object
* @param rulePath path string to the rules file
* @param ai AI object to play (MAKE SURE IT SUPPORTS UNTHREADED !!! )
*/
public Simulator(GameMode mode, String rulePath, DummyAI ai)
{
this(mode, GeneralUtil.loadRule(rulePath), ai);
}
/**
* Make a new Simulator object, ready to go.
* @param mode Game mode Object
* @param rules Game rules Object
* @param ai AI object to play (MAKE SURE IT SUPPORTS UNTHREADED !!! )
*/
public Simulator(GameMode mode, RuleOptions rules, DummyAI ai)
{
/*
* NOTE(oliver): This code is a domain-specific version of
* mu.nu.nullpo.gui.slick.StateInGame.startNewGame(String strRulePath)
*/
// Manager setup
gameManager = new GameManager();
gameManager.mode = mode;
gameManager.init();
gameManager.showInput = false;
// Engine setup
gameEngine = gameManager.engine[0];
// - Rules
gameEngine.ruleopt = rules;
// - Randomizer
gameEngine.randomizer = GeneralUtil.loadRandomizer(rules.strRandomizer);
// - Wallkick
gameEngine.wallkick = GeneralUtil.loadWallkick(rules.strWallkick);
gameEngine.ai = ai;
gameEngine.aiMoveDelay = 0;
gameEngine.aiThinkDelay = 0;
gameEngine.aiUseThread = false;
gameEngine.aiShowHint = false;
gameEngine.aiPrethink = false;
gameEngine.aiShowState = false;
}
/**
* Performs a single simulation to completion (STATE == GAMEOVER)
*/
public void runSimulation()
{
// Start a new game.
gameEngine.init();
if(customSeed != null)
{
gameEngine.randSeed = Long.parseLong(customSeed, 16);
log.debug("Engine seed overwritten with " + customSeed);
}
// You have to spend at least 5 frames in the menu before you can start the game.
for(int i = 0; i < 5; ++i)
{
gameEngine.update();
}
// Press and release A to start game.
gameEngine.ctrl.setButtonPressed(Controller.BUTTON_A);
gameEngine.update();
gameEngine.ctrl.setButtonUnpressed(Controller.BUTTON_A);
// Run the game until Game Over.
while (gameEngine.stat != Status.GAMEOVER) {
gameEngine.update();
// logGameState();
}
log.info("Game is over!");
log.info("Final Level: " + gameEngine.statistics.level);
}
/**
* Performs multiple sequential simulations to completion (STATE == GAMEOVER)
*/
public void runSimulations(int count)
{
for(int i = 1; i <= count; ++i)
{
log.info(String.format("
runSimulation();
}
}
/**
* Sets a custom random seed for use in simulations.
*
* @param seed The seed.
*/
public void setCustomSeed(String seed)
{
customSeed = seed;
}
static Logger log = Logger.getLogger(Simulator.class);
private void logGameState()
{
int level = gameEngine.statistics.level;
String piece =
gameEngine.nowPieceObject == null
? " "
: Piece.PIECE_NAMES[gameEngine.nowPieceObject.id];
String state = gameEngine.stat.toString();
log.info(String.format("\tLevel: %3d \tPiece: %s \tState: %s", level, piece, state));
}
}
|
package org.jpos.ee;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.jpos.core.ConfigurationException;
import org.jpos.core.Environment;
import org.jpos.ee.support.ModuleUtils;
import org.jpos.space.Space;
import org.jpos.space.SpaceFactory;
import org.jpos.util.Log;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
@SuppressWarnings({"UnusedDeclaration"})
public class DB implements Closeable {
Session session;
Log log;
String configModifier;
private Dialect dialect;
private static Map<String,Semaphore> sfSems = Collections.synchronizedMap(new HashMap<>());
private static Map<String,Semaphore> mdSems = Collections.synchronizedMap(new HashMap<>());
private static Semaphore newSessionSem = new Semaphore(1);
private static String propFile;
private static final String MODULES_CONFIG_PATH = "META-INF/org/jpos/ee/modules/";
private static Map<String,SessionFactory> sessionFactories = Collections.synchronizedMap(new HashMap<>());
private static Map<String,Metadata> metadatas = Collections.synchronizedMap(new HashMap<>());
/**
* Creates DB Object using default Hibernate instance
*/
public DB() {
this((String) null);
}
/**
* Creates DB Object using a config <i>modifier</i>.
*
* The <i>configModifier</i> can take a number of different forms used to locate the <code>cfg/db.properties</code> file.
*
* <ul>
*
* <li>a filename prefix, i.e.: "mysql" used as modifier would pick the configuration from
* <code>cfg/mysql-db.properties</code> instead of the default <code>cfg/db.properties</code> </li>
*
* <li>if a colon and a second modifier is present (e.g.: "mysql:v1"), the metadata is picked from
* <code>META-INF/org/jpos/ee/modules/v1-*</code> instead of just
* <code>META-INF/org/jpos/ee/modules/</code> </li>
*
* <li>finally, if the modifier ends with <code>.hbm.xml</code> (case insensitive), then all configuration
* is picked from that config file.</li>
* </ul>
*
* @param configModifier modifier
*/
public DB (String configModifier) {
super();
this.configModifier = configModifier;
sfSems.putIfAbsent(configModifier, new Semaphore(1));
mdSems.putIfAbsent(configModifier, new Semaphore(1));
}
/**
* Creates DB Object using default Hibernate instance
*
* @param log Log object
*/
public DB(Log log) {
super();
setLog(log);
}
/**
* Creates DB Object using default Hibernate instance
*
* @param log Log object
* @param configModifier modifier
*/
public DB(Log log, String configModifier) {
this(configModifier);
setLog(log);
}
/**
* @return Hibernate's session factory
*/
public SessionFactory getSessionFactory() {
Semaphore sfSem = sfSems.get(configModifier);
SessionFactory sf;
String cm = configModifier != null ? configModifier : "";
try {
if (!sfSem.tryAcquire(60, TimeUnit.SECONDS)) {
throw new RuntimeException ("Unable to acquire lock");
}
sf = sessionFactories.get(cm);
if (sf == null)
sessionFactories.put(cm, sf = newSessionFactory());
if (sf instanceof SessionFactoryImpl) {
dialect = ((SessionFactoryImpl) sf).getJdbcServices().getDialect();
}
} catch (IOException | ConfigurationException | DocumentException | InterruptedException e) {
throw new RuntimeException("Could not configure session factory", e);
} finally {
sfSem.release();
}
return sf;
}
public Dialect getDialect() {
return dialect;
}
public static synchronized void invalidateSessionFactories() {
sessionFactories.clear();
}
private SessionFactory newSessionFactory() throws IOException, ConfigurationException, DocumentException, InterruptedException {
Metadata md = getMetadata();
try {
newSessionSem.acquireUninterruptibly();
return md.buildSessionFactory();
} finally {
newSessionSem.release();
}
}
private void configureProperties(Configuration cfg) throws IOException
{
String propFile = System.getProperty("DB_PROPERTIES", "cfg/db.properties");
Properties dbProps = loadProperties(propFile);
if (dbProps != null)
{
cfg.addProperties(dbProps);
}
}
private void configureMappings(Configuration cfg) throws ConfigurationException, IOException {
try {
List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/");
for (String moduleConfig : moduleConfigs) {
addMappings(cfg, moduleConfig);
}
} catch (DocumentException e) {
throw new ConfigurationException("Could not parse mappings document", e);
}
}
private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, DocumentException
{
Element module = readMappingElements(moduleConfig);
if (module != null)
{
for (Iterator l = module.elementIterator("mapping"); l.hasNext(); )
{
Element mapping = (Element) l.next();
parseMapping(cfg, mapping, moduleConfig);
}
}
}
private void parseMapping(Configuration cfg, Element mapping, String moduleName) throws ConfigurationException
{
final String resource = mapping.attributeValue("resource");
final String clazz = mapping.attributeValue("class");
if (resource != null)
{
cfg.addResource(resource);
}
else if (clazz != null)
{
try
{
cfg.addAnnotatedClass(ReflectHelper.classForName(clazz));
}
catch (ClassNotFoundException e)
{
throw new ConfigurationException("Class " + clazz + " specified in mapping for module " + moduleName + " cannot be found");
}
}
else
{
throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName);
}
}
private Element readMappingElements(String moduleConfig) throws DocumentException
{
SAXReader reader = new SAXReader();
final URL url = getClass().getClassLoader().getResource(moduleConfig);
assert url != null;
final Document doc = reader.read(url);
return doc.getRootElement().element("mappings");
}
private Properties loadProperties(String filename) throws IOException
{
Properties props = new Properties();
final String s = filename.replaceAll("/", "\\" + File.separator);
final File f = new File(s);
if (f.exists())
{
props.load(new FileReader(f));
}
return props;
}
/**
* Creates database schema
*
* @param outputFile optional output file (may be null)
* @param create true to actually issue the create statements
*/
public void createSchema(String outputFile, boolean create) throws HibernateException, DocumentException {
try {
// SchemaExport export = new SchemaExport(getMetadata());
SchemaExport export = new SchemaExport();
List<TargetType> targetTypes=new ArrayList<>();
if (outputFile != null) {
export.setDelimiter(";");
if(outputFile.trim().equals("-")) {
targetTypes.add(TargetType.STDOUT);
}
else {
export.setOutputFile(outputFile);
targetTypes.add(TargetType.SCRIPT);
}
}
if (create)
targetTypes.add(TargetType.DATABASE);
if(targetTypes.size()>0) {
// First, drop everything, disregarding errors
export.setHaltOnError(false);
export.drop(EnumSet.copyOf(targetTypes), getMetadata());
// Now attempt schema creation, but halting on error
export.setHaltOnError(true);
export.createOnly(EnumSet.copyOf(targetTypes), getMetadata());
}
}
catch (IOException | ConfigurationException | InterruptedException e)
{
throw new HibernateException("Could not create schema", e);
}
}
/**
* open a new HibernateSession if none exists
*
* @return HibernateSession associated with this DB object
* @throws HibernateException
*/
public synchronized Session open() throws HibernateException
{
if (session == null)
{
session = getSessionFactory().openSession();
}
return session;
}
/**
* close hibernate session
*
* @throws HibernateException
*/
public synchronized void close() throws HibernateException
{
if (session != null)
{
session.close();
session = null;
}
}
/**
* @return session hibernate Session
*/
public Session session()
{
return session;
}
/**
* handy method used to avoid having to call db.session().save (xxx)
*
* @param obj to save
*/
public void save(Object obj) throws HibernateException
{
session.save(obj);
}
/**
* handy method used to avoid having to call db.session().saveOrUpdate (xxx)
*
* @param obj to save or update
*/
public void saveOrUpdate(Object obj) throws HibernateException
{
session.saveOrUpdate(obj);
}
public void delete(Object obj)
{
session.delete(obj);
}
/**
* @return newly created Transaction
* @throws HibernateException
*/
public synchronized Transaction beginTransaction() throws HibernateException
{
return session.beginTransaction();
}
public synchronized void commit()
{
if (session() != null)
{
Transaction tx = session().getTransaction();
if (tx != null && tx.getStatus().isOneOf(TransactionStatus.ACTIVE))
{
tx.commit();
}
}
}
public synchronized void rollback()
{
if (session() != null)
{
Transaction tx = session().getTransaction();
if (tx != null && tx.getStatus().canRollback())
{
tx.rollback();
}
}
}
/**
* @param timeout in seconds
* @return newly created Transaction
* @throws HibernateException
*/
public synchronized Transaction beginTransaction(int timeout) throws HibernateException
{
Transaction tx = session.getTransaction();
if (timeout > 0)
tx.setTimeout(timeout);
tx.begin();
return tx;
}
public synchronized Log getLog()
{
if (log == null)
{
log = Log.getLog("Q2", "DB"); // Q2 standard Logger
}
return log;
}
public synchronized void setLog(Log log)
{
this.log = log;
}
public static <T> T exec(DBAction<T> action) throws Exception {
try (DB db = new DB()) {
db.open();
return action.exec(db);
}
}
public static <T> T exec(String configModifier, DBAction<T> action) throws Exception {
try (DB db = new DB(configModifier)) {
db.open();
return action.exec(db);
}
}
public static <T> T execWithTransaction(DBAction<T> action) throws Exception {
try (DB db = new DB()) {
db.open();
db.beginTransaction();
T obj = action.exec(db);
db.commit();
return obj;
}
}
public static <T> T execWithTransaction(String configModifier, DBAction<T> action) throws Exception {
try (DB db = new DB(configModifier)) {
db.open();
db.beginTransaction();
T obj = action.exec(db);
db.commit();
return obj;
}
}
@SuppressWarnings("unchecked")
public static <T> T unwrap (T proxy) {
Hibernate.getClass(proxy);
Hibernate.initialize(proxy);
return (proxy instanceof HibernateProxy) ?
(T) ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation() : proxy;
}
@SuppressWarnings({"unchecked"})
public void printStats()
{
if (getLog() != null)
{
LogEvent info = getLog().createInfo();
if (session != null)
{
info.addMessage("==== STATISTICS ====");
SessionStatistics statistics = session().getStatistics();
info.addMessage("==== ENTITIES ====");
Set<EntityKey> entityKeys = statistics.getEntityKeys();
for (EntityKey ek : entityKeys)
{
info.addMessage(String.format("[%s] %s", ek.getIdentifier(), ek.getEntityName()));
}
info.addMessage("==== COLLECTIONS ====");
Set<CollectionKey> collectionKeys = statistics.getCollectionKeys();
for (CollectionKey ck : collectionKeys)
{
info.addMessage(String.format("[%s] %s", ck.getKey(), ck.getRole()));
}
info.addMessage("=====================");
}
else
{
info.addMessage("Session is not open");
}
Logger.log(info);
}
}
@Override
public String toString() {
return "DB{" + (configModifier != null ? configModifier : "") + '}';
}
private Metadata getMetadata() throws IOException, ConfigurationException, DocumentException, InterruptedException {
Semaphore mdSem = mdSems.get(configModifier);
if (!mdSem.tryAcquire(60, TimeUnit.SECONDS))
throw new RuntimeException ("Unable to acquire lock");
String cm = configModifier != null ? configModifier : "";
Metadata md = metadatas.get(cm);
try {
if (md == null) {
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
String propFile;
String dbPropertiesPrefix = "";
String metadataPrefix = "";
String hibCfg = null;
if (cm.endsWith(".cfg.xml")) {
hibCfg = cm;
} else if (configModifier != null) {
String[] ss = configModifier.split(":");
if (ss.length > 0)
dbPropertiesPrefix = ss[0] + ":";
if (ss.length > 1)
metadataPrefix = ss[1] + ":";
hibCfg = System.getProperty("HIBERNATE_CFG","/" + dbPropertiesPrefix + "hibernate.cfg.xml");
if (getClass().getClassLoader().getResource(hibCfg) == null)
hibCfg = null;
}
if (hibCfg == null)
hibCfg = System.getProperty("HIBERNATE_CFG","/hibernate.cfg.xml");
ssrb.configure(hibCfg);
propFile = System.getProperty(dbPropertiesPrefix + "DB_PROPERTIES", "cfg/" + dbPropertiesPrefix + "db.properties");
Properties dbProps = loadProperties(propFile);
if (dbProps != null) {
for (Map.Entry entry : dbProps.entrySet()) {
ssrb.applySetting((String) entry.getKey(), Environment.get((String) entry.getValue()));
}
}
// if DBInstantiator has put db user name and/or password in Space, set Hibernate config accordingly
Space sp = SpaceFactory.getSpace("tspace:dbconfig");
String user = (String) sp.inp(dbPropertiesPrefix +"connection.username");
String pass = (String) sp.inp(dbPropertiesPrefix +"connection.password");
if (user != null)
ssrb.applySetting("hibernate.connection.username", user);
if (pass != null)
ssrb.applySetting("hibernate.connection.password", pass);
MetadataSources mds = new MetadataSources(ssrb.build());
List<String> moduleConfigs = ModuleUtils.getModuleEntries(MODULES_CONFIG_PATH);
for (String moduleConfig : moduleConfigs) {
if (metadataPrefix.length() == 0 || moduleConfig.substring(MODULES_CONFIG_PATH.length()).startsWith(metadataPrefix)) {
if ( (!metadataPrefix.contains(":") && moduleConfig.contains(":")) ||
(!moduleConfig.contains(":") && metadataPrefix.contains(":")))
continue;
addMappings(mds, moduleConfig);
}
}
md = mds.buildMetadata();
metadatas.put(cm, md);
}
} finally {
mdSem.release();
}
return md;
}
private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, DocumentException
{
Element module = readMappingElements(moduleConfig);
if (module != null)
{
for (Iterator l = module.elementIterator("mapping"); l.hasNext(); )
{
Element mapping = (Element) l.next();
parseMapping(mds, mapping, moduleConfig);
}
}
}
private void parseMapping (MetadataSources mds, Element mapping, String moduleName) throws ConfigurationException
{
final String resource = mapping.attributeValue("resource");
final String clazz = mapping.attributeValue("class");
if (resource != null)
mds.addResource(resource);
else if (clazz != null)
mds.addAnnotatedClassName(clazz);
else
throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName);
}
}
|
package org.jboss.qa.brms.performance.localsearch.projectjobscheduling.moveselector;
import org.jboss.qa.brms.performance.examples.projectjobscheduling.termination.ProjectJobSchedulingCalculateCountTermination;
import org.jboss.qa.brms.performance.configuration.AcceptorConfigurations;
import org.jboss.qa.brms.performance.localsearch.projectjobscheduling.AbstractProjectJobSchedulingLocalSearchBenchmark;
import org.optaplanner.core.config.heuristic.selector.value.ValueSelectorConfig;
import org.optaplanner.core.config.localsearch.decider.acceptor.LocalSearchAcceptorConfig;
import org.optaplanner.core.config.solver.termination.TerminationConfig;
public abstract class AbstractProjectJobSchedulingMoveSelectorBenchmark extends AbstractProjectJobSchedulingLocalSearchBenchmark {
protected ValueSelectorConfig getExecutionModeValueSelectorConfig() {
ValueSelectorConfig valueSelectorConfig = new ValueSelectorConfig();
valueSelectorConfig.setVariableName("executionMode");
return valueSelectorConfig;
}
protected ValueSelectorConfig getDelayValueSelectorConfig() {
ValueSelectorConfig valueSelectorConfig = new ValueSelectorConfig();
valueSelectorConfig.setVariableName("delay");
return valueSelectorConfig;
}
@Override
public LocalSearchAcceptorConfig createAcceptorConfig() {
return AcceptorConfigurations.createSimulatedAnnealingAcceptor("0hard/0medium/0soft");
}
@Override
public int getAcceptedCountLimit() {
return 1000000;
}
@Override
public TerminationConfig getTerminationConfig() {
TerminationConfig terminationConfig = new TerminationConfig();
terminationConfig.setTerminationClass(ProjectJobSchedulingCalculateCountTermination.class);
return terminationConfig;
}
}
|
package org.xwiki.rendering.internal.macro;
import org.junit.jupiter.api.Test;
import org.xwiki.model.EntityType;
import org.xwiki.rendering.macro.include.IncludeMacroParameters;
import static org.junit.jupiter.api.Assertions.assertSame;
/**
* Validate {@link IncludeMacroParameters}.
*
* @version $Id$
*/
public class IncludeMacroParametersTest
{
@Test
public void setPage()
{
IncludeMacroParameters parameters = new IncludeMacroParameters();
parameters.setPage("page");
assertSame(EntityType.PAGE, parameters.getType());
}
@Test
public void setExcludeFirstHeading()
{
IncludeMacroParameters parameters = new IncludeMacroParameters();
parameters.setExcludeFirstHeading(true);
assertTrue(parameters.excludeFirstHeading());
}
}
|
package org.xwiki.image.style.test.ui;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.httpclient.methods.GetMethod;
import org.junit.jupiter.api.Test;
import org.xwiki.image.style.rest.ImageStylesResource;
import org.xwiki.image.style.test.po.ImageStyleAdministrationPage;
import org.xwiki.image.style.test.po.ImageStyleConfigurationForm;
import org.xwiki.livedata.test.po.LiveDataElement;
import org.xwiki.livedata.test.po.TableLayoutElement;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.test.docker.junit5.UITest;
import org.xwiki.test.ui.TestUtils;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Docker tests for the image style administration, tests the user interface of the administation as well as the rest
* endpoints.
*
* @version $Id$
* @since 14.3RC1
*/
@UITest
class ImageStyleIT
{
@Test
void imageStyleAdministration(TestUtils testUtils) throws Exception
{
testUtils.loginAsSuperAdmin();
// Make sure that an icon theme is configured.
testUtils.setWikiPreference("iconTheme", "IconThemes.Silk");
testUtils.deletePage(
new DocumentReference("xwiki", List.of("Image", "Style", "Code", "ImageStyles"), "default"));
testUtils.updateObject(new DocumentReference("xwiki", List.of("Image", "Style", "Code"), "Configuration"),
"Image.Style.Code.ConfigurationClass", 0, "defaultStyle", "");
assertEquals("<MapN/>", getDefaultFromRest(testUtils));
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<styles xmlns=\"http:
ImageStyleAdministrationPage imageStyleAdministrationPage = ImageStyleAdministrationPage.getToAdminPage();
ImageStyleConfigurationForm imageStyleConfigurationForm =
imageStyleAdministrationPage.submitNewImageStyleForm("default");
imageStyleConfigurationForm
.setPrettyName("Default")
.setType("default-class")
.clickSaveAndView(true);
imageStyleAdministrationPage = imageStyleConfigurationForm.clickBackToTheAdministration();
assertEquals("", imageStyleAdministrationPage.getDefaultStyle());
imageStyleAdministrationPage.submitDefaultStyleForm("default");
assertEquals("default", imageStyleAdministrationPage.getDefaultStyle());
TableLayoutElement tableLayout = new LiveDataElement("imageStyles").getTableLayout();
assertEquals(1, tableLayout.countRows());
assertEquals("default", tableLayout.getCell("Identifier", 1).getText());
assertEquals("Default", tableLayout.getCell("Pretty Name", 1).getText());
assertEquals("default-class", tableLayout.getCell("Type", 1).getText());
assertEquals("<Map1><defaultStyle>default</defaultStyle></Map1>", getDefaultFromRest(testUtils));
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<styles xmlns=\"http:
+ "<imageStyle>"
+ "<identifier>default</identifier>"
+ "<prettyName>Default</prettyName>"
+ "<type>default-class</type>"
+ "<adjustableSize>false</adjustableSize>"
+ "<defaultWidth xsi:nil=\"true\" xmlns:xsi=\"http:
+ "<defaultHeight xsi:nil=\"true\" xmlns:xsi=\"http:
+ "<adjustableBorder>false</adjustableBorder>"
+ "<defaultBorder>false</defaultBorder>"
+ "<adjustableAlignment>false</adjustableAlignment>"
+ "<defaultAlignment>none</defaultAlignment>"
+ "<adjustableTextWrap>false</adjustableTextWrap>"
+ "<defaultTextWrap>false</defaultTextWrap>"
+ "</imageStyle>"
+ "</styles>", getImageStylesFromRest(testUtils));
}
private String getDefaultFromRest(TestUtils testUtils) throws Exception
{
URI imageStylesResourceURI = testUtils.rest().createUri(ImageStylesResource.class, new HashMap<>(), "xwiki");
GetMethod getMethod =
testUtils.rest().executeGet(UriBuilder.fromUri(imageStylesResourceURI).segment("default").build());
return getMethod.getResponseBodyAsString();
}
private String getImageStylesFromRest(TestUtils testUtils) throws Exception
{
URI imageStylesResourceURI = testUtils.rest().createUri(ImageStylesResource.class, new HashMap<>(), "xwiki");
GetMethod getMethod =
testUtils.rest().executeGet(imageStylesResourceURI);
return getMethod.getResponseBodyAsString().trim();
}
}
|
package com.google.mbdebian.springboot.playground.microservices.tutorial;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringMicroservicesSimpleService2Application {
@Value("${server.port}")
public String port;
@RequestMapping("/execute")
public String execute() {
return "Hello from the port " + this.port;
}
@RequestMapping("/")
public String status() {
return "Up";
}
public static void main(String[] args) {
SpringApplication.run(SpringMicroservicesSimpleService2Application.class, args);
}
}
|
package org.xwiki.wikistream.instance.internal.input;
import java.lang.reflect.ParameterizedType;
import java.util.Iterator;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.util.DefaultParameterizedType;
import org.xwiki.filter.FilterEventParameters;
import org.xwiki.wikistream.WikiStreamException;
import org.xwiki.wikistream.instance.input.DocumentInstanceInputProperties;
import org.xwiki.wikistream.instance.input.EntityEventGenerator;
import org.xwiki.wikistream.instance.internal.BaseObjectFilter;
import org.xwiki.wikistream.model.filter.WikiObjectFilter;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
/**
* @version $Id$
* @since 5.2M2
*/
@Component
@Singleton
public class BaseObjectEventGenerator extends
AbstractBeanEntityEventGenerator<BaseObject, BaseObjectFilter, DocumentInstanceInputProperties>
{
public static final ParameterizedType ROLE = new DefaultParameterizedType(null, EntityEventGenerator.class,
BaseObject.class, DocumentInstanceInputProperties.class);
@Inject
private Provider<XWikiContext> xcontextProvider;
@Inject
private EntityEventGenerator<BaseClass> classEventGenerator;
@Inject
private EntityEventGenerator<BaseProperty> propertyEventGenerator;
@Override
public void write(BaseObject xobject, Object filter, BaseObjectFilter objectFilter,
DocumentInstanceInputProperties properties) throws WikiStreamException
{
XWikiContext xcontext = this.xcontextProvider.get();
// > WikiObject
FilterEventParameters objectParameters = new FilterEventParameters();
objectParameters.put(WikiObjectFilter.PARAMETER_CLASS_REFERENCE, xobject.getClassName());
objectParameters.put(WikiObjectFilter.PARAMETER_GUID, xobject.getGuid());
objectParameters.put(WikiObjectFilter.PARAMETER_NUMBER, xobject.getNumber());
objectFilter.beginWikiObject(xobject.getReference().getName(), objectParameters);
// Object class
BaseClass xclass = xobject.getXClass(xcontext);
((BaseClassEventGenerator) this.classEventGenerator).write(xclass, filter, objectFilter, properties);
// Properties
// Iterate over values/properties sorted by field name so that the values are
// exported to XML in a consistent order.
Iterator<BaseProperty< ? >> it = xobject.getSortedIterator();
while (it.hasNext()) {
BaseProperty< ? > xproperty = it.next();
String pname = xproperty.getName();
if (pname != null && !pname.trim().equals("")) {
((BasePropertyEventGenerator) this.propertyEventGenerator).write(xproperty, filter, objectFilter,
(Map<String, Object>)properties);
}
}
// < WikiObject
objectFilter.endWikiObject(xobject.getReference().getName(), objectParameters);
}
}
|
package ysitd.ircbot.java.api;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class staticMethod {
public static void invokeOverrideEvent(CustomEvent e){
for( JIRCBOTListener event : JIRCBOTPlugin.jircbotlistenerlist ){
Method[] methods=event.getClass().getMethods();
for( Method method : methods ){
if( method.getParameterTypes().equals(e) ){ //contains?
try {
method.invoke(e); //Method
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e1) {
e1.printStackTrace();
}
}
}
}
}
public static void loadjar() throws ClassNotFoundException, IOException{
File folder=new File("./");
JarEntry je;
Enumeration<JarEntry> e;
ArrayList<JarFile> jarfile=new ArrayList<JarFile>();
ClassLoader loader;
for(File file : folder.listFiles()){
if( file.getName().matches(".*.jar$") )
jarfile.add(new JarFile(file.getAbsolutePath()));
}
URL[] url=new URL[jarfile.size()];
for(int i=0;i<jarfile.size();i++){
url[i]=new URL("jar:file:" + jarfile.get(i).getName() + "!/");
}
loader= URLClassLoader.newInstance(url); //resource, close?
for(JarFile j : jarfile){
e=j.entries();
while(e.hasMoreElements()){
je=e.nextElement();
if(je.isDirectory() || !je.getName().endsWith(".class")){
continue;
}
//-6 because of .class
String classname=je.getName().substring(0, je.getName().length() - 6);
classname=classname.replace('/', '.');
loader.loadClass(classname);
}
}
}
}
|
package org.xwiki.notifications.filters.internal;
import java.util.Arrays;
import java.util.List;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.text.StringUtils;
import com.xpn.xwiki.doc.AbstractMandatoryClassInitializer;
import com.xpn.xwiki.objects.classes.BaseClass;
/**
* Define the NotificationFilterPreferenceClass XClass.
* This XClass is used to store filters information in the user profile.
*
* @version $Id$
* @since 9.7RC1
*/
@Component
@Named("XWiki.Notifications.Code.NotificationFilterPreferenceClass")
@Singleton
public class NotificationFilterPreferenceDocumentInitializer extends AbstractMandatoryClassInitializer
{
/**
* The path to the class parent document.
*/
private static final List<String> PARENT_PATH = Arrays.asList("XWiki", "Notifications", "Code");
private static final String INPUT = "input";
private static final String SELECT = "select";
private static final String SEPARATORS = "|, ";
/**
* Default constructor.
*/
public NotificationFilterPreferenceDocumentInitializer()
{
super(new LocalDocumentReference(PARENT_PATH, "NotificationFilterPreferenceClass"));
}
@Override
protected void createClass(BaseClass xclass)
{
xclass.addTextField("filterPreferenceName", "Name of the filter preference", 256);
xclass.addBooleanField("isEnabled", "Is enabled ?", SELECT, true);
xclass.addTextField("filterName", "Filter name", 64);
xclass.addStaticListField("filterType", "Filter type", 5, false, true,
"inclusive=Inclusive|exclusive=Exclusive", SELECT, SEPARATORS);
xclass.addStaticListField("filterFormats", "Formats", 5, true, true,
"alert=Alert|email=E-mail", SELECT, SEPARATORS);
xclass.addStaticListField("applications", "Applications", 64, true,
true, StringUtils.EMPTY, INPUT, SEPARATORS);
xclass.addStaticListField("eventTypes", "Event types", 64, true,
true, StringUtils.EMPTY, INPUT, SEPARATORS);
xclass.addUsersField("users", "Users", true);
xclass.addStaticListField("pages", "Pages", 64, true,
true, StringUtils.EMPTY, INPUT, SEPARATORS);
xclass.addStaticListField("spaces", "Spaces", 64, true,
true, StringUtils.EMPTY, INPUT, SEPARATORS);
xclass.addStaticListField("wikis", "Wikis", 64, true,
true, StringUtils.EMPTY, INPUT, SEPARATORS);
}
}
|
package NewApproaches;
import static BlockBuilding.IBlockBuilding.DOC_ID;
import static BlockBuilding.IBlockBuilding.VALUE_LABEL;
import BlockBuilding.StandardBlocking;
import DataModel.Attribute;
import DataModel.EntityProfile;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
/**
*
* @author G.A.P. II
*/
public class RexaDBLPTokenBlocking extends StandardBlocking {
private static final Logger LOGGER = Logger.getLogger(RexaDBLPTokenBlocking.class.getName());
protected Set<String> labelPredicates;
public RexaDBLPTokenBlocking() {
labelPredicates = new HashSet<>();
labelPredicates.add("http://xmlns.com/foaf/0.1/name");
labelPredicates.add("http://www.w3.org/2000/01/rdf-schema#label");
}
@Override
protected void buildBlocks() {
setMemoryDirectory();
IndexWriter iWriter1 = openWriter(indexDirectoryD1);
indexEntities(iWriter1, entityProfilesD1);
closeWriter(iWriter1);
IndexWriter iWriter2 = openWriter(indexDirectoryD2);
indexEntities(iWriter2, entityProfilesD2);
closeWriter(iWriter2);
}
@Override
protected void indexEntities(IndexWriter index, List<EntityProfile> entities) {
try {
int counter = 0;
for (EntityProfile profile : entities) {
Document doc = new Document();
doc.add(new StoredField(DOC_ID, counter++));
for (Attribute attribute : profile.getAttributes()) {
getBlockingKeys(attribute.getValue()).stream().filter((key) -> (0 < key.trim().length())).forEach((key) -> {
doc.add(new StringField(VALUE_LABEL, key.trim(), Field.Store.YES));
});
//exact match on labels
if (labelPredicates.contains(attribute.getName())) {
doc.add(new StringField(VALUE_LABEL, attribute.getValue().toLowerCase().replaceAll("[^a-z0-9 ]", "").trim() + "_LP", Field.Store.YES));
}
//token blocking on labels
/*
if (labelPredicates.contains(attribute.getName())) {
getBlockingKeys(attribute.getValue()).stream().filter((key) -> (0 < key.trim().length())).forEach((key) -> {
doc.add(new StringField(VALUE_LABEL, key.trim() + "_LP", Field.Store.YES));
});
}*/
}
index.addDocument(doc);
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
|
package com.jake.sword;
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 javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.type.MirroredTypeException;
public class ElementModel {
private final List<InjectedClass> injectedClasses = new ArrayList<>();
private final Map<Provider, ExecutableElement> provides = new HashMap<>();
private final ElementHelper elementHelper;
private Map<Element, ExecutableElement> constructors = new HashMap<>();
private Map<Element, Element> bindings = new HashMap<>();
private List<Element> qualifiers = new ArrayList<>();
private List<Element> mocks = new ArrayList<>();
public ElementModel(ElementHelper elementHelper) {
this.elementHelper = elementHelper;
}
public void addField(PackageElement packageElement, Element fieldElement) {
injectedClasses.add(new InjectedClass(packageElement, fieldElement.getEnclosingElement(), fieldElement));
}
public Set<PackageElement> getPackageElements() {
Set<PackageElement> packageElements = new HashSet<>();
for (InjectedClass injectedClass : injectedClasses) {
packageElements.add(injectedClass.getPackageElement());
}
return packageElements;
}
public Set<Element> getClassElements(PackageElement packageElement) {
Set<Element> classElements = new HashSet<>();
for (InjectedClass injectedClass : injectedClasses) {
if (injectedClass.getPackageElement().equals(packageElement)) {
classElements.add(injectedClass.getClassElement());
}
}
return classElements;
}
public List<Element> getFieldElements(PackageElement packageElement, Element classElement) {
List<Element> fieldElements = new ArrayList<>();
for (InjectedClass injectedClass : injectedClasses) {
if (injectedClass.getPackageElement().equals(packageElement) && injectedClass.getClassElement().equals(classElement)) {
Element fieldElement = injectedClass.getFieldElement();
if (fieldElement != null) {
fieldElements.add(fieldElement);
}
}
}
return fieldElements;
}
public boolean containsClassElement(PackageElement packageElement, Element classElement) {
for (InjectedClass injectedClass : injectedClasses) {
if (injectedClass.getPackageElement().equals(packageElement) && injectedClass.getClassElement().equals(classElement)) {
return true;
}
}
return false;
}
public void addConstructor(PackageElement packageElement, ExecutableElement constructorElement) {
Element classElement = constructorElement.getEnclosingElement();
if (constructors.containsKey(classElement)) {
elementHelper.error(constructorElement, "Only one constructor can have @Inject tag");
return;
}
constructors.put(classElement, constructorElement);
addClassWithZeroFields(classElement);
}
public void addProvides(Element returnElement, ExecutableElement providesMethodElement) {
Provider classAndName = new Provider(returnElement, providesMethodElement, this);
if (provides.containsKey(classAndName)) {
elementHelper.error(providesMethodElement,
"Duplicate Provides, cannot figure out which Injection to match. Use @Named or a custom Qualifier");
}
provides.put(classAndName, providesMethodElement);
}
public boolean isProvidingClass(Element classElement, String name) {
for (Provider classAndName : provides.keySet()) {
if (classAndName.getClassElement().equals(classElement) && classAndName.getName().equals(name)) {
return true;
}
}
for (ExecutableElement providerMethodElement : provides.values()) {
if (providerMethodElement.getEnclosingElement().equals(classElement)) {
return true;
}
}
return false;
}
public void addSingleton(Element singletonElement) {
addClassWithZeroFields(singletonElement);
}
private void addClassWithZeroFields(Element classElement) {
PackageElement packageElement = elementHelper.getPackageElement(classElement);
injectedClasses.add(new InjectedClass(packageElement, classElement, null));
}
private ExecutableElement getProvidesMethod(Element classElement, Element fieldElement) {
return provides.get(new Provider(classElement, fieldElement, this));
}
public Set<Element> getClassElements() {
Set<Element> classElements = new HashSet<>();
for (PackageElement packageElement : getPackageElements()) {
classElements.addAll(getClassElements(packageElement));
}
return classElements;
}
public ExecutableElement getInjectedConstructor(Element classElement) {
return constructors.get(classElement);
}
public void addBind(Element element) {
Bind bind = element.getAnnotation(Bind.class);
try {
bind.from();
} catch (MirroredTypeException e) {
Element fromElement = elementHelper.asElement(e.getTypeMirror());
ExecutableElement providesMethod = getProvidesMethod(fromElement, element);
if (providesMethod != null) {
elementHelper.error(providesMethod, "Bind conflicts with Provides, cannot figure out which Injection to match.");
elementHelper.error(element, "Bind conflicts with Provides, cannot figure out which Injection to match.");
return;
}
try {
bind.to();
} catch (MirroredTypeException e2) {
Element toElement = elementHelper.asElement(e2.getTypeMirror());
if(!constructors.containsKey(toElement) && !provides.containsKey(new Provider(toElement, element, this))) {
elementHelper.error(element, "Bind to class with missing @Provides or @Inject constructor");
return;
}
bindings.put(fromElement, toElement);
}
}
}
public void addQualifier(Element element) {
qualifiers.add(element);
}
public List<Element> getQualifiers() {
return qualifiers;
}
public Element rebind(Element classElement) {
Element boundElement = bindings.get(classElement);
if (boundElement != null) {
return boundElement;
}
return classElement;
}
public void addMock(Element element) {
mocks.add(element);
}
public Element getMock(Element classElement, Element fieldElement) {
for (Element mockElement : mocks) {
// if the current field's type matches the mock type
if (fieldElement.asType().equals(mockElement.asType()) && fieldElement.getSimpleName().equals(mockElement.getSimpleName())) {
for (InjectedClass injectedClass : injectedClasses) {
if (injectedClass.getFieldElement() != null) {
Element fieldTypeElement = elementHelper.asElement(injectedClass.getFieldElement().asType());
// if test class (BlahTest) matches where the real
// injected object was
if (injectedClass.getClassElement().equals(mockElement.getEnclosingElement())) {
// if the current class (Blah) matches the class
// where the injection that is getting
// replace with a mock is
if (classElement.equals(fieldTypeElement)) {
return mockElement;
}
}
}
}
}
}
return null;
}
public boolean isMockClass(Element classElement) {
for (Element mock : mocks) {
if (mock.getEnclosingElement().equals(classElement)) {
return true;
}
}
return false;
}
public ExecutableElement getProvidedMethod(Element fieldElement) {
return getProvidesMethod(elementHelper.asElement(fieldElement.asType()), fieldElement);
}
}
|
/*
* Formerly a camera controller, now provides calculations to support
* PlanetAppState as a camera controller.
*/
package engine;
import celestial.Celestial;
import com.jme3.app.Application;
import com.jme3.asset.AssetManager;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.light.DirectionalLight;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.post.filters.BloomFilter;
import com.jme3.post.filters.FogFilter;
import com.jme3.renderer.Camera;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import com.jme3.shadow.CompareMode;
import com.jme3.shadow.DirectionalLightShadowRenderer;
import com.jme3.shadow.EdgeFilteringMode;
import java.io.IOException;
import java.util.LinkedList;
import jmeplanet.Planet;
/**
*
* @author nwiehoff, Geoff Hibbert
*/
public class AstralCamera implements Control {
//engine resources
private final Camera farCam;
private final Camera nearCam;
protected FilterPostProcessor chaseFilter;
protected FogFilter chaseFog;
protected BloomFilter chaseBloom;
protected ViewPort farViewPort;
protected ViewPort nearViewPort;
protected boolean shadowsEnabled = true;
protected DirectionalLightShadowRenderer dlsr;
private Celestial target;
private final LinkedList<TargetPlacement> cachedTargetPlacements;
private final RenderManager renderManager;
private int trailingCount = 0;
private int trailingFactor = 0;
private Vector3f lastTargetVelocity = new Vector3f();
public static int TRAILING_FACTOR = 8;
@Override
public void update(float f) {
if (target != null) {
if (mode == Mode.COCKPIT) {
//TODO: Handle using a different cam for cockpit
} else if (mode == Mode.NORMAL) {
Quaternion rotation = target.getPhysicsRotation().clone();
Vector3f lookAtUpVector = rotation.mult(Vector3f.UNIT_Y).clone();
Vector3f currentVelocity = target.getLinearVelocity().clone();
//record position for camera to follow
TargetPlacement newPlacement = new TargetPlacement(target.getCameraRestPoint().getWorldTranslation().clone(), rotation.clone());
cachedTargetPlacements.add(newPlacement);
trailingCount++;
if (trailingCount >= trailingFactor) {
//check if we are no longer accelerating
if ((lastTargetVelocity.subtract(currentVelocity).length()) == 0
&& target.getAngularVelocity().length() < 0.05) {
if (trailingFactor > 1) {
cachedTargetPlacements.remove(0);
trailingFactor
trailingCount
}
} else {
//increase the "rope"
if (trailingFactor < TRAILING_FACTOR) {
trailingFactor++;
}
}
//we've moved enough to matter
//get the oldest placement in buffer
TargetPlacement placementToLookAt = cachedTargetPlacements.remove(0);
trailingCount
nearCam.setLocation(placementToLookAt.location.clone());
farCam.setLocation(placementToLookAt.location.clone());
lookAtUpVector = rotation.mult(Vector3f.UNIT_Y);
}
lastTargetVelocity = currentVelocity;
farCam.lookAt(target.getLineOfSightPoint(), lookAtUpVector.clone());
nearCam.lookAt(target.getLineOfSightPoint(), lookAtUpVector.clone());
} else if (mode == Mode.RTS) {
//TODO: Handle rotations to camera and distance to make viewport look right
}
}
}
@Override
public Control cloneForSpatial(Spatial sptl) {
return this;
}
@Override
public void setSpatial(Spatial sptl) {
}
@Override
public void render(RenderManager rm, ViewPort vp) {
}
@Override
public void write(JmeExporter je) throws IOException {
}
@Override
public void read(JmeImporter ji) throws IOException {
}
private float getShiftAmount(float inputAmount) {
float shift;
float sign = Math.signum(inputAmount) * -1;
float amount = Math.abs(inputAmount);
if (amount > 20000) {
shift = 10000 * sign;
} else if (amount > 10000) {
shift = 2000 * sign;
} else if (amount > 5000) {
shift = 500 * sign;
} else if (amount > 2000) {
shift = 200 * sign;
} else if (amount > 1000) {
shift = 100 * sign;
} else if (amount > 100) {
shift = 20 * sign;
} else if (amount > 10) {
shift = 5 * sign;
} else {
shift = 1 * sign;
}
return shift;
}
enum Mode {
COCKPIT,
NORMAL,
RTS
}
Mode mode = Mode.NORMAL;
public AstralCamera(Application app) {
this.farCam = app.getCamera();
this.renderManager = app.getRenderManager();
farViewPort = app.getViewPort();
farCam.setViewPort(0f, 1f, 0f, 1f);
nearCam = this.farCam.clone();
farCam.setFrustumPerspective(45f, (float) farCam.getWidth() / farCam.getHeight(), 300f, 1e7f);
nearCam.setFrustumPerspective(45f, (float) nearCam.getWidth() / nearCam.getHeight(), 1f, 310f);
chaseFilter = new FilterPostProcessor(app.getAssetManager());
farViewPort.addProcessor(chaseFilter);
chaseFog = new FogFilter();
chaseFilter.addFilter(chaseFog);
chaseBloom = new BloomFilter();
chaseBloom.setDownSamplingFactor(2);
chaseBloom.setBlurScale(1.37f);
chaseBloom.setExposurePower(3.30f);
chaseBloom.setExposureCutOff(0.1f);
chaseBloom.setBloomIntensity(1.45f);
//chaseFilter.addFilter(chaseBloom);
cachedTargetPlacements = new LinkedList<>();
}
public Celestial getTarget() {
return target;
}
public void setTarget(Celestial target) {
freeCamera();
this.target = target;
this.target.getSpatial().addControl(this);
trailingCount = 0;
trailingFactor = TRAILING_FACTOR;
}
public void addLight(DirectionalLight light, AssetManager assetManager) {
dlsr = new DirectionalLightShadowRenderer(assetManager, 1024, 3);
dlsr.setLight(light);
dlsr.setLambda(0.55f);
dlsr.setShadowIntensity(0.6f);
dlsr.setEdgeFilteringMode(EdgeFilteringMode.PCFPOISSON);
dlsr.setShadowCompareMode(CompareMode.Hardware);
dlsr.setShadowZExtend(100f);
if (shadowsEnabled) {
farViewPort.addProcessor(dlsr);
nearViewPort.addProcessor(dlsr);
}
}
public void updateFogAndBloom(Planet planet) {
if (planet.getIsInOcean()) {
// turn on underwater fogging
chaseFog.setFogColor(planet.getUnderwaterFogColor());
chaseFog.setFogDistance(planet.getUnderwaterFogDistance());
chaseFog.setFogDensity(planet.getUnderwaterFogDensity());
chaseFog.setEnabled(true);
chaseBloom.setEnabled(true);
} else {
if (planet.getIsInAtmosphere()) {
// turn on atomosphere fogging
chaseFog.setFogColor(planet.getAtmosphereFogColor());
chaseFog.setFogDistance(planet.getAtmosphereFogDistance());
chaseFog.setFogDensity(planet.getAtmosphereFogDensity());
chaseFog.setEnabled(true);
chaseBloom.setEnabled(false);
} else {
// in space
chaseFog.setEnabled(false);
chaseBloom.setEnabled(true);
}
}
}
public void stopFogAndBloom() {
chaseFog.setEnabled(false);
chaseBloom.setEnabled(true);
}
public void setShadowsEnabled(boolean enabled) {
this.shadowsEnabled = enabled;
if (dlsr != null) {
if (enabled) {
farViewPort.addProcessor(dlsr);
nearViewPort.addProcessor(dlsr);
} else {
farViewPort.removeProcessor(dlsr);
nearViewPort.removeProcessor(dlsr);
}
}
}
public void freeCamera() {
if (target != null) {
target.getSpatial().removeControl(this);
target.getCameraRestPoint().detachAllChildren();
target = null;
}
}
public Vector3f getScreenCoordinates(Vector3f position) {
return farCam.getScreenCoordinates(position);
}
public Vector3f getLocation() {
return farCam.getLocation();
}
public Vector3f getDirection() {
return farCam.getDirection();
}
public void attachScene(Spatial scene) {
farCam.setViewPort(0f, 1f, 0.0f, 1f);
farViewPort = renderManager.createMainView("FarView", farCam);
farViewPort.setBackgroundColor(ColorRGBA.BlackNoAlpha);
farViewPort.attachScene(scene);
nearCam.setViewPort(0f, 1f, 0.0f, 1f);
nearViewPort = renderManager.createMainView("NearView", nearCam);
nearViewPort.setBackgroundColor(ColorRGBA.BlackNoAlpha);
nearViewPort.setClearFlags(false, true, true);
nearViewPort.attachScene(scene);
}
}
|
package entity.model;
import entity.model.strategies.FeedingStrategy;
import entity.model.strategies.MoveStrategy;
import entity.model.strategies.RandomMoveStrategy;
import entity.model.util.AnimalAnim;
import io.Window;
import org.joml.Vector2f;
import render.Animation;
import render.Camera;
import world.World;
public abstract class Animal extends LivingThing {
protected FeedingStrategy feeding;
protected MoveStrategy movement;
private AnimalAnim currentAnim;
private Vector2f currentDirection;
private double hunger;
private double thirst;
private boolean isMoving;
private float movementSpeed;
public Animal(String name, World world, Vector2f scale, Vector2f position) {
super(name, world, AnimalAnim.AMOUNT, scale, position);
this.currentAnim = AnimalAnim.IDLE_E;
this.currentDirection = new Vector2f(.0f, .0f);
this.movementSpeed = 5.0f; // default movement speed
this.isMoving = false;
this.movement = new RandomMoveStrategy(this);
for (AnimalAnim anim : AnimalAnim.values()) {
setAnimation(anim.index(),
new Animation(anim.amount(), 8,
"entities/" + name + "/" + anim.path()));
}
}
public Vector2f getCurrentDirection() {return this.currentDirection;}
public void setCurrentDirection(Vector2f direction) {
this.currentDirection = direction.normalize();
updateAnimation(currentDirection);
}
public float getMovementSpeed() {return this.movementSpeed;}
public boolean isMoving() {return this.isMoving;}
public void setMovementSpeed(float movementSpeed) {this.movementSpeed = movementSpeed;}
protected void move(float delta) {move(delta, this.currentDirection);}
protected void move(float delta, Vector2f direction) {
Vector2f movement = new Vector2f();
movement.add(movementSpeed * delta * direction.x,
movementSpeed * delta * direction.y);
this.isMoving = movementSpeed != 0;
this.currentDirection = direction;
updateAnimation(direction);
super.move(movement);
}
public void updateAnimation(Vector2f direction) {
if (movementSpeed > 0) {
if (Math.abs(direction.x) > Math.abs(direction.y)) {
if (direction.x > 0) selectAnimation(AnimalAnim.WALK_E);
else selectAnimation(AnimalAnim.WALK_W);
} else {
if (direction.y > 0) selectAnimation(AnimalAnim.WALK_N);
else selectAnimation(AnimalAnim.WALK_S);
}
} else {
if (currentAnim.isWalking())
selectAnimation(currentAnim.idle());
}
}
public void selectAnimation(AnimalAnim anim) {
this.currentAnim = anim;
super.useAnimation(anim.index());
}
@Override
public void update(float delta, Window window, Camera camera) {
move(delta, this.movement.getMovement(delta));
}
}
|
package com.creedon.cordova.plugin.captioninput;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static org.apache.cordova.PluginResult.Status.OK;
/**
* This class echoes a string called from JavaScript.
*/
public class PhotoCaptionInputViewPlugin extends CordovaPlugin {
private CallbackContext callbackContext;
private int maxImages;
private String options;
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
if (action.equals("showCaptionInput")) {
JSONObject options = args.getJSONObject(0);
this.showCaptionInput(options, callbackContext);
return true;
}
return false;
}
private void showCaptionInput(JSONObject jsonoptions, CallbackContext callbackContext) throws JSONException {
if (jsonoptions != null && jsonoptions.length() > 0) {
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
ActivityManager activityManager = (ActivityManager) this.cordova.getActivity().getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long totalMegs = mi.totalMem / 1048576L;
System.out.println("[NIX] totalMegs: " + totalMegs);
Intent intent = new Intent(cordova.getActivity(), PhotoCaptionInputViewActivity.class);
if (jsonoptions.has("maximumImagesCount")) {
this.maxImages = jsonoptions.getInt("maximumImagesCount");
} else {
this.maxImages = 100;
}
this.options = jsonoptions.toString();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("options", options.toString());
intent.putExtra("MAX_IMAGES", this.maxImages);
this.cordova.startActivityForResult(this, intent, 0);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && data != null) {
String result = data.getStringExtra(Constants.RESULT);
JSONObject res = null;
try {
res = new JSONObject(result);
if(res != null){
this.callbackContext.success(res);
PluginResult pluginResult = new PluginResult(OK, res);
pluginResult.setKeepCallback(false);
this.callbackContext.sendPluginResult(pluginResult);
}else{
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
}
} catch (JSONException e) {
e.printStackTrace();
res = new JSONObject();
if (this.callbackContext != null) {
this.callbackContext.error(res);
}
}
} else if (resultCode == Activity.RESULT_CANCELED && data != null) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
} else if (resultCode == Activity.RESULT_CANCELED) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
} else {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
}
}
public Bundle onSaveInstanceState() {
Bundle state = new Bundle();
state.putInt("maxImages", this.maxImages);
state.putString("options", this.options);
return state;
}
public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext) {
this.maxImages = state.getInt("maxImages");
this.options = state.getString("options");
this.callbackContext = callbackContext;
}
}
|
package com.mbppower;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Base64;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import org.apache.cordova.LOG;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Exception;
import java.lang.Integer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class CameraActivity extends Fragment {
public interface CameraPreviewListener {
void onPictureTaken(String originalPicture);
}
private CameraPreviewListener eventListener;
private static final String TAG = "CameraPreview";
public FrameLayout mainLayout;
public FrameLayout frameContainerLayout;
private Preview mPreview;
private boolean canTakePicture = true;
private View view;
private Camera.Parameters cameraParameters;
private Camera mCamera;
private int numberOfCameras;
private int cameraCurrentlyLocked;
// The first rear facing camera
private int defaultCameraId;
public String defaultCamera;
public boolean tapToTakePicture;
public boolean dragEnabled;
public int width;
public int height;
public int x;
public int y;
public void setEventListener(CameraPreviewListener listener) {
eventListener = listener;
}
private String appResourcesPackage;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
appResourcesPackage = getActivity().getPackageName();
// Inflate the layout for this fragment
view = inflater.inflate(getResources().getIdentifier("camera_activity", "layout", appResourcesPackage), container, false);
createCameraPreview();
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public void setRect(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
private void createCameraPreview() {
if (mPreview == null) {
setDefaultCameraId();
//set box position and size
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
layoutParams.setMargins(x, y, 0, 0);
frameContainerLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("frame_container", "id", appResourcesPackage));
frameContainerLayout.setLayoutParams(layoutParams);
//video view
mPreview = new Preview(getActivity());
mainLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("video_view", "id", appResourcesPackage));
mainLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
mainLayout.addView(mPreview);
mainLayout.setEnabled(false);
}
}
private void setDefaultCameraId() {
// Find the total number of cameras available
numberOfCameras = Camera.getNumberOfCameras();
int camId = defaultCamera.equals("front") ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK;
// Find the ID of the default camera
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == camId) {
defaultCameraId = camId;
break;
}
}
}
@Override
public void onResume() {
super.onResume();
mCamera = Camera.open(defaultCameraId);
// TODO: set camera parametrs here
if (cameraParameters != null) {
mCamera.setParameters(cameraParameters);
}
cameraCurrentlyLocked = defaultCameraId;
mPreview.setCamera(mCamera, cameraCurrentlyLocked);
Log.d(TAG, "cameraCurrentlyLocked:" + cameraCurrentlyLocked);
final FrameLayout frameContainerLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("frame_container", "id", appResourcesPackage));
ViewTreeObserver viewTreeObserver = frameContainerLayout.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
frameContainerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
frameContainerLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
final RelativeLayout frameCamContainerLayout = (RelativeLayout) view.findViewById(getResources().getIdentifier("frame_camera_cont", "id", appResourcesPackage));
FrameLayout.LayoutParams camViewLayout = new FrameLayout.LayoutParams(frameContainerLayout.getWidth(), frameContainerLayout.getHeight());
camViewLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
frameCamContainerLayout.setLayoutParams(camViewLayout);
}
});
}
}
@Override
public void onPause() {
super.onPause();
// Because the Camera object is a shared resource, it's very
// important to release it when the activity is paused.
if (mCamera != null) {
mPreview.setCamera(null, -1);
mCamera.release();
mCamera = null;
}
}
public Camera getCamera() {
return mCamera;
}
public void switchCamera() {
// check for availability of multiple cameras
if (numberOfCameras < 2) {
//There is only one camera available
} else {
Log.d(TAG, "numberOfCameras: " + numberOfCameras);
// OK, we have multiple cameras.
// Release this camera -> cameraCurrentlyLocked
if (mCamera != null) {
mCamera.stopPreview();
mPreview.setCamera(null, -1);
mCamera.release();
mCamera = null;
}
// Acquire the next camera and request Preview to reconfigure
// parameters.
Log.d(TAG, "cameraCurrentlyLocked := " + Integer.toString(cameraCurrentlyLocked));
try {
cameraCurrentlyLocked = (cameraCurrentlyLocked + 1) % numberOfCameras;
Log.d(TAG, "cameraCurrentlyLocked new: " + cameraCurrentlyLocked);
mCamera = Camera.open(cameraCurrentlyLocked);
if (cameraParameters != null) {
Log.d(TAG, "camera parameter not null");
mCamera.setParameters(cameraParameters);
} else {
Log.d(TAG, "camera parameter NULL");
}
mPreview.switchCamera(mCamera, cameraCurrentlyLocked);
// Start the preview
mCamera.startPreview();
} catch (Exception exception) {
Log.d(TAG, exception.getMessage());
}
}
}
public void setCameraParameters(Camera.Parameters params) {
cameraParameters = params;
if (mCamera != null && cameraParameters != null) {
mCamera.setParameters(cameraParameters);
}
}
public boolean hasFrontCamera() {
return getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
}
public Bitmap cropBitmap(Bitmap bitmap, Rect rect) {
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
Bitmap ret = Bitmap.createBitmap(w, h, bitmap.getConfig());
Canvas canvas = new Canvas(ret);
canvas.drawBitmap(bitmap, -rect.left, -rect.top, null);
return ret;
}
public void takePicture(final double maxWidth, final double maxHeight) {
Log.d(TAG, "picture taken");
final ImageView pictureView = (ImageView) view.findViewById(getResources().getIdentifier("picture_view", "id", appResourcesPackage));
if (mPreview != null) {
if (!canTakePicture)
return;
canTakePicture = false;
mPreview.setOneShotPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(final byte[] data, final Camera camera) {
new Thread() {
public void run() {
//raw picture
byte[] bytes = mPreview.getFramePicture(data, camera); // raw bytes from preview
final Bitmap pic = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); // Bitmap from preview
//scale down
float scale = (float) pictureView.getWidth() / (float) pic.getWidth();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int) (pic.getWidth() * scale), (int) (pic.getHeight() * scale), false);
final Matrix matrix = new Matrix();
if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT) {
Log.d(TAG, "mirror y axis");
matrix.preScale(-1.0f, 1.0f);
}
Log.d(TAG, "preRotate " + mPreview.getDisplayOrientation() + "deg");
matrix.postRotate(mPreview.getDisplayOrientation());
final Bitmap fixedPic = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, false);
final Rect rect = new Rect(mPreview.mSurfaceView.getLeft(), mPreview.mSurfaceView.getTop(), mPreview.mSurfaceView.getRight(), mPreview.mSurfaceView.getBottom());
Log.d(TAG, mPreview.mSurfaceView.getLeft() + " " + mPreview.mSurfaceView.getTop() + " " + mPreview.mSurfaceView.getRight() + " " + mPreview.mSurfaceView.getBottom());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
pictureView.setImageBitmap(fixedPic);
pictureView.layout(rect.left, rect.top, rect.right, rect.bottom);
Bitmap finalPic = pic;
Bitmap originalPicture = Bitmap.createBitmap(finalPic, 0, 0, (int) (finalPic.getWidth()), (int) (finalPic.getHeight()), matrix, false);
generatePictureFromView(originalPicture);
canTakePicture = true;
}
});
}
}.start();
}
});
} else {
canTakePicture = true;
}
}
private void processPicture(Bitmap bitmap) {
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
CompressFormat compressFormat = CompressFormat.PNG;
int mQuality = 90;
try {
if (bitmap.compress(compressFormat, mQuality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encode(code, Base64.NO_WRAP);
String js_out = new String(output);
eventListener.onPictureTaken(js_out);
js_out = null;
output = null;
code = null;
}
} catch (Exception e) {
// this.failPicture("Error compressing image.");
}
jpeg_data = null;
}
private void generatePictureFromView(final Bitmap originalPicture) {
// final Bitmap image;
final FrameLayout cameraLoader = (FrameLayout) view.findViewById(getResources().getIdentifier("camera_loader", "id", appResourcesPackage));
cameraLoader.setVisibility(View.VISIBLE);
final ImageView pictureView = (ImageView) view.findViewById(getResources().getIdentifier("picture_view", "id", appResourcesPackage));
new Thread() {
public void run() {
try {
// final File picFile = storeImage(picture, "_preview");
// final File originalPictureFile = storeImage(originalPicture, "_original");
// image = BitmapFactory.decodeFile(originalPictureFile.getAbsolutePath());
// processPicture(BitmapFactory.decodeFile(originalPictureFile.getAbsolutePath()));
// eventListener.onPictureTaken(originalPictureFile.getAbsolutePath(), picFile.getAbsolutePath());
processPicture(originalPicture);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
cameraLoader.setVisibility(View.INVISIBLE);
pictureView.setImageBitmap(null);
}
});
} catch (Exception e) {
//An unexpected error occurred while saving the picture.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
cameraLoader.setVisibility(View.INVISIBLE);
pictureView.setImageBitmap(null);
}
});
}
}
}.start();
}
private File getOutputMediaFile(String suffix) {
File mediaStorageDir = getActivity().getApplicationContext().getFilesDir();
/*if(Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED && Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED_READ_ONLY) {
mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/" + getActivity().getApplicationContext().getPackageName() + "/Files");
}*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("dd_MM_yyyy_HHmm_ss").format(new Date());
File mediaFile;
String mImageName = "camerapreview_" + timeStamp + suffix + ".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
private File storeImage(Bitmap image, String suffix) {
File pictureFile = getOutputMediaFile(suffix);
if (pictureFile != null) {
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.JPEG, 80, fos);
fos.close();
return pictureFile;
} catch (Exception ex) {
}
}
return null;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
class Preview extends RelativeLayout implements SurfaceHolder.Callback {
private final String TAG = "CameraPreview";
CustomSurfaceView mSurfaceView;
SurfaceHolder mHolder;
Camera.Size mPreviewSize;
List<Camera.Size> mSupportedPreviewSizes;
Camera mCamera;
int cameraId;
int displayOrientation;
Preview(Context context) {
super(context);
mSurfaceView = new CustomSurfaceView(context);
addView(mSurfaceView);
requestLayout();
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera, int cameraId) {
if (camera != null) {
mCamera = camera;
this.cameraId = cameraId;
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
setCameraDisplayOrientation();
//mCamera.getParameters().setRotation(getDisplayOrientation());
//requestLayout();
}
}
public int getDisplayOrientation() {
return displayOrientation;
}
public void printPreviewSize(String from) {
Log.d(TAG, "printPreviewSize from " + from + ": > width: " + mPreviewSize.width + " height: " + mPreviewSize.height);
}
private void setCameraDisplayOrientation() {
Camera.CameraInfo info = new Camera.CameraInfo();
int rotation =
((Activity) getContext()).getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
DisplayMetrics dm = new DisplayMetrics();
Camera.getCameraInfo(cameraId, info);
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
displayOrientation = (info.orientation + degrees) % 360;
displayOrientation = (360 - displayOrientation) % 360;
} else {
displayOrientation = (info.orientation - degrees + 360) % 360;
}
Log.d(TAG, "screen is rotated " + degrees + "deg from natural");
Log.d(TAG, (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ? "front" : "back")
+ " camera is oriented -" + info.orientation + "deg from natural");
Log.d(TAG, "need to rotate preview " + displayOrientation + "deg");
mCamera.setDisplayOrientation(displayOrientation);
}
public void switchCamera(Camera camera, int cameraId) {
try {
setCamera(camera, cameraId);
Log.d("CameraPreview", "before set camera");
camera.setPreviewDisplay(mHolder);
Log.d("CameraPreview", "before getParameters");
Camera.Parameters parameters = camera.getParameters();
Log.d("CameraPreview", "before setPreviewSize");
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
Log.d(TAG, mPreviewSize.width + " " + mPreviewSize.height);
camera.setParameters(parameters);
} catch (IOException exception) {
Log.e(TAG, exception.getMessage());
}
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
/* Log.d(TAG, "onMeasure: > width: " + mPreviewSize.width + " height: " + mPreviewSize.height);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(parameters);*/
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && getChildCount() > 0) {
final View child = getChildAt(0);
int width = r - l;
int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
if (displayOrientation == 90 || displayOrientation == 270) {
previewWidth = mPreviewSize.height;
previewHeight = mPreviewSize.width;
}
LOG.d(TAG, "previewWidth:" + previewWidth + " previewHeight:" + previewHeight);
}
int nW;
int nH;
int top;
int left;
float scale = 1.0f;
// Center the child SurfaceView within the parent.
if (width * previewHeight < height * previewWidth) {
Log.d(TAG, "center horizontally");
int scaledChildWidth = (int) ((previewWidth * height / previewHeight) * scale);
nW = (width + scaledChildWidth) / 2;
nH = (int) (height * scale);
top = 0;
left = (width - scaledChildWidth) / 2;
} else {
Log.d(TAG, "center vertically");
int scaledChildHeight = (int) ((previewHeight * width / previewWidth) * scale);
nW = (int) (width * scale);
nH = (height + scaledChildHeight) / 2;
top = (height - scaledChildHeight) / 2;
left = 0;
}
child.layout(left, top, nW, nH);
Log.d("layout", "left:" + left);
Log.d("layout", "top:" + top);
Log.d("layout", "right:" + nW);
Log.d("layout", "bottom:" + nH);
}
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera != null) {
mSurfaceView.setWillNotDraw(false);
mCamera.setPreviewDisplay(holder);
}
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
try {
if (mCamera != null) {
mCamera.stopPreview();
}
} catch (Exception exception) {
Log.e(TAG, "Exception caused by surfaceDestroyed()", exception);
}
}
/*private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (displayOrientation == 90 || displayOrientation == 270) {
targetRatio = (double) h / w;
}
if (sizes == null) return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
Log.d(TAG, "optimal preview size: w: " + optimalSize.width + " h: " + optimalSize.height);
return optimalSize;
}*/
public Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
if (sizes == null) return null;
Camera.Size optimalSize = null;
int maxWidth = 0;
// Try to find an size match aspect ratio and size
// Select max size
for (Camera.Size size : sizes) {
if (size.width > maxWidth) {
maxWidth = size.width;
optimalSize = size;
}
}
Log.d(TAG, "optimal preview size: w: " + optimalSize.width + " h: " + optimalSize.height);
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mCamera != null) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
//mCamera.setDisplayOrientation(90);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
public byte[] getFramePicture(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
int format = parameters.getPreviewFormat();
//YUV formats require conversion
if (format == ImageFormat.NV21 || format == ImageFormat.YUY2 || format == ImageFormat.NV16) {
int w = parameters.getPreviewSize().width;
int h = parameters.getPreviewSize().height;
// Get the YuV image
YuvImage yuvImage = new YuvImage(data, format, w, h, null);
// Convert YuV to Jpeg
Rect rect = new Rect(0, 0, w, h);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
yuvImage.compressToJpeg(rect, 80, outputStream);
return outputStream.toByteArray();
}
return data;
}
public void setOneShotPreviewCallback(Camera.PreviewCallback callback) {
if (mCamera != null) {
mCamera.setOneShotPreviewCallback(callback);
}
}
}
class CustomSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private final String TAG = "CameraPreview";
CustomSurfaceView(Context context) {
super(context);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
|
package fractalFlameV3;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.imageio.stream.FileImageInputStream;
import com.google.gson.GsonBuilder;
import fractalFlameV3.fractalGenome.FractalGenome;
import fractalFlameV3.fractalThread.FractalThread;
import fractalFlameV3.fractalThread.ThreadSignal;
import processing.core.PApplet;
import processing.core.PConstants;
public class Main extends PApplet {
static boolean fullscreen = true;
int swid = 512;
int shei = 512;
int ss = 1;
int SS_MAX = 12;
int fr = 60;
Histogram h;
FractalGenome genome;
FractalThread[] threads;
ThreadSignal threadSignal;
final int SYSTEM_THREADS = Runtime.getRuntime().availableProcessors();
// by running SYSTEM_THREADS - 2 threads we can hopefully avoid making the system unusalbe while
// the flame is generating. There is of course a tradeoff in generation speed, which doesn't
// really matter to me as I have a 12 thread system.
final int maxFlameThreads = (SYSTEM_THREADS > 3) ? SYSTEM_THREADS - 2 : 1;
public static final void main(final String args[]) {
if (Main.fullscreen) {
PApplet.main(new String[] { "--present", "fractalFlameV3.Main" });
} else {
PApplet.main(new String[] { "fractalFlameV3.Main" });
}
}
@Override
public void setup() {
swid = (fullscreen) ? displayWidth : swid;
shei = (fullscreen) ? displayHeight : shei;
this.size(swid, shei);
frameRate(fr);
h = newHistogram();
genome = loadLastGenome();
threads = new FractalThread[1];
threadSignal = new ThreadSignal();
startThreads();
}
private FractalGenome loadLastGenome() {
String fullGenomeString = "";
GsonBuilder gb = new GsonBuilder();
try {
FileReader fileReader = new FileReader("images/last.fractalgenome");
BufferedReader lastGenomeReader = new BufferedReader(fileReader);
String line;
while ((line = lastGenomeReader.readLine()) != null) {
fullGenomeString += line;
}
lastGenomeReader.close();
fileReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return gb.create().fromJson(fullGenomeString, new FractalGenome(3, 3).getClass());
}
private FractalGenome newGenome() {
final FractalGenome fg = new FractalGenome(3, 10);
fg.variationToggle = true;
fg.finalTransformToggle = true;
genome.center = true;
return fg;
}
private Histogram newHistogram() {
final Histogram h = new Histogram(swid, shei, ss);
return h;
}
@Override
public void keyPressed() {
stopThreads();
switch (keyCode) {
case 'h':
case 'H':
ss = (ss == 1) ? SS_MAX : 1;
h = null;
System.gc();
h = newHistogram();
System.out.println("# SS\t|\t " + ss);
break;
case 'r':
case 'R':
genome = newGenome();
h.reset();
break;
case 't':
case 'T':
threads = new FractalThread[(threads.length == 8) ? 1 : 8];
System.out.println("# TH\t|\t " + threads.length);
break;
case 'f':
case 'F':
genome.finalTransformToggle = !genome.finalTransformToggle;
System.out.println("# FT\t|\t " + genome.finalTransformToggle);
h.reset();
break;
case 'v':
case 'V':
genome.variationToggle = !genome.variationToggle;
System.out.println("# VT\t|\t " + genome.variationToggle);
h.reset();
break;
case 's':
case 'S':
String fileName = "images/" + genome.hashCode() + ".bmp";
saveFrame(fileName);
genome.saveGsonRepresentation();
break;
case 'c':
case 'C':
genome.resetColors();
h.reset();
break;
case '+':
case '=':
genome.cameraXShrink /= 1.01;
genome.cameraYShrink /= 1.01;
h.reset();
break;
case '-':
case '_':
genome.cameraXShrink *= 1.01;
genome.cameraYShrink *= 1.01;
h.reset();
break;
case PConstants.UP:
genome.cameraYOffset += .01 * genome.cameraYShrink;
h.reset();
break;
case PConstants.DOWN:
genome.cameraYOffset -= .01 * genome.cameraYShrink;
h.reset();
break;
case PConstants.LEFT:
genome.cameraXOffset += .01 * genome.cameraXShrink;
h.reset();
break;
case PConstants.RIGHT:
genome.cameraXOffset -= .01 * genome.cameraXShrink;
h.reset();
break;
}
startThreads();
}
private void stopThreads() {
threadSignal.running = false;
for (final Thread t : threads) {
try {
t.join();
} catch (final InterruptedException e) {
System.out.println(e.getLocalizedMessage());
}
}
}
private void startThreads() {
threadSignal.running = true;
for (final int i : Utils.range(threads.length)) {
threads[i] = new FractalThread(genome, threadSignal, h);
}
for (final Thread t : threads) {
t.start();
}
}
@Override
public void draw() {
if (frameCount == 1) {
loadPixels();
} else {
h.updatePixels(pixels, genome);
this.updatePixels();
}
}
}
|
package gamepack;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
public class WindowGame extends BasicGame
{
// ATTRIBUTES
private GameContainer container;
private final int windowSizeX = 800;
private final int windowSizeY = 600;
private TileList board;
private Tile yolo;
// METHODS
public WindowGame()
{
super("2C0A");
}
public int getWindowSizeX()
{
return windowSizeX;
}
public int getWindowSizeY()
{
return windowSizeY;
}
@Override
public void init(GameContainer container) throws SlickException
{
this.container = container;
// A modifier board = new TileList(4, container.getHeight(), container.getWidth());
// container.setTargetFrameRate(60);
yolo = new Tile(1,1);
}
public void render(GameContainer container, Graphics g) throws SlickException
{
yolo.beDrawn(g);
}
@Override
public void update(GameContainer gc, int delta) throws SlickException {
}
@Override
public void keyPressed(int key, char c)
{
System.out.println(key);
}
public static void main(String[] args) throws SlickException
{
AppGameContainer appgc;
WindowGame wGame = new WindowGame();
appgc = new AppGameContainer(wGame);
appgc.setDisplayMode(wGame.getWindowSizeX(), wGame.getWindowSizeY(), false);
appgc.setShowFPS(false);
appgc.setVSync(true);
appgc.start();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.