answer
stringlengths 17
10.2M
|
|---|
package nl.hsac.fitnesse.fixture.slim.web;
import nl.hsac.fitnesse.fixture.slim.StopTestException;
import nl.hsac.fitnesse.fixture.util.NgClientSideScripts;
import nl.hsac.fitnesse.slim.interaction.ReflectionHelper;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* Browser Test targeted to test AngularJs apps.
*/
public class NgBrowserTest extends BrowserTest {
private final static Set<String> METHODS_NO_WAIT;
private String angularRoot = null;
static {
METHODS_NO_WAIT = ReflectionHelper.validateMethodNames(
NgBrowserTest.class,
"open",
"takeScreenshot",
"openInNewTab",
"ensureActiveTabIsNotClosed",
"currentTabIndex",
"tabCount",
"ensureOnlyOneTab",
"closeTab",
"setAngularRoot",
"switchToNextTab",
"switchToPreviousTab",
"waitForAngularRequestsToFinish",
"secondsBeforeTimeout",
"waitForPage",
"waitForTagWithText",
"waitForClassWithText",
"waitForClass",
"waitSeconds",
"waitMilliseconds",
"waitMilliSecondAfterScroll",
"screenshotBaseDirectory",
"screenshotShowHeight",
"setBrowserWidth",
"setBrowserHeight",
"setBrowserSizeToBy",
"setGlobalValueTo",
"globalValue",
"setAngularRoot",
"getAngularRoot");
}
@Override
protected void beforeInvoke(Method method, Object[] arguments) {
if (requiresWaitForAngular(method)) {
waitForAngularRequestsToFinish();
}
super.beforeInvoke(method, arguments);
}
/**
* Determines whether method requires waiting for all Angular requests to finish
* before it is invoked.
* @param method method to be invoked.
* @return true, if waiting for Angular is required, false otherwise.
*/
protected boolean requiresWaitForAngular(Method method) {
String methodName = method.getName();
return !METHODS_NO_WAIT.contains(methodName);
}
@Override
public boolean open(String address) {
boolean result = super.open(address);
if (result) {
waitForAngularRequestsToFinish();
}
return result;
}
public void waitForAngularRequestsToFinish() {
String root = getAngularRoot();
if (root == null) {
root = "body";
}
Object result = waitForJavascriptCallback(NgClientSideScripts.WaitForAngular, root);
if (result != null) {
throw new StopTestException(false, result.toString());
}
}
@Override
public String valueFor(String place) {
String result;
WebElement angularModelBinding = getAngularElement(place);
if (angularModelBinding == null) {
result = super.valueFor(place);
} else {
result = valueFor(angularModelBinding);
}
return result;
}
@Override
public boolean selectFor(String value, String place) {
boolean result;
WebElement angularModelSelect = findSelect(place);
if (angularModelSelect == null) {
result = super.selectFor(value, place);
} else {
result = clickSelectOption(angularModelSelect, value);
}
return result;
}
@Override
public boolean enterAs(String value, String place) {
boolean result;
WebElement angularModelInput = getAngularElementToEnterIn(place);
if (angularModelInput == null) {
result = super.enterAs(value, place);
} else {
angularModelInput.clear();
sendValue(angularModelInput, value);
result = true;
}
return result;
}
public int numberOf(String repeater) {
waitForAngularRequestsToFinish();
return findRepeaterRows(repeater).size();
}
public String valueOfColumnNumberInRowNumberOf(int columnIndex, int rowIndex, String repeater) {
return getTextInRepeaterColumn(Integer.toString(columnIndex), rowIndex, repeater);
}
public String valueOfInRowNumberOf(String columnName, int rowIndex, String repeater) {
String columnIndex = getXPathForColumnIndex(columnName);
return getTextInRepeaterColumn(columnIndex, rowIndex, repeater);
}
public String valueOfInRowWhereIsOf(String requestedColumnName, String selectOnColumn, String selectOnValue, String repeater) {
String result = null;
String compareIndex = getXPathForColumnIndex(selectOnColumn);
List<WebElement> rows = findRepeaterRows(repeater);
for (WebElement row : rows) {
String compareValue = getColumnText(row, compareIndex);
if ((selectOnValue == null && compareValue == null)
|| selectOnValue != null && selectOnValue.equals(compareValue)) {
String requestedIndex = getXPathForColumnIndex(requestedColumnName);
result = getColumnText(row, requestedIndex);
break;
}
}
return result;
}
protected String getTextInRepeaterColumn(String columnIndexXPath, int rowIndex, String repeater) {
String result = null;
List<WebElement> rows = findRepeaterRows(repeater);
if (rows.size() >= rowIndex) {
WebElement row = rows.get(rowIndex - 1);
result = getColumnText(row, columnIndexXPath);
}
return result;
}
private String getColumnText(WebElement row, String columnIndexXPath) {
By xPath = getSeleniumHelper().byXpath("td[%s]", columnIndexXPath);
WebElement cell = row.findElement(xPath);
return getElementText(cell);
}
protected WebElement getAngularElementToEnterIn(String place) {
return findElement(place);
}
protected WebElement getAngularElement(String place) {
WebElement element = findBinding(place);
if (element == null) {
element = findElement(place);
}
return element;
}
protected WebElement findBinding(String place) {
return findNgElementByJavascript(NgClientSideScripts.FindBindings, place, true, null);
}
protected WebElement findSelect(String place) {
return findNgElementByJavascript(NgClientSideScripts.FindSelects, place);
}
protected WebElement findElement(String place) {
return findNgElementByJavascript(NgClientSideScripts.FindElements, place, null);
}
protected List<WebElement> findRepeaterRows(String repeater) {
return findNgElementsByJavascript(NgClientSideScripts.FindAllRepeaterRows, repeater, true);
}
protected List<WebElement> findNgElementsByJavascript(String script, Object... parameters) {
Object[] arguments = getFindArguments(parameters);
return findAllByJavascript(script, arguments);
}
protected WebElement findNgElementByJavascript(String script, Object... parameters) {
Object[] arguments = getFindArguments(parameters);
return findByJavascript(script, arguments);
}
private Object[] getFindArguments(Object[] parameters) {
List<Object> params = new ArrayList<Object>(parameters.length + 1);
params.addAll(Arrays.asList(parameters));
params.add(getAngularRoot());
return params.toArray();
}
public String getAngularRoot() {
return angularRoot;
}
public void setAngularRoot(String anAngularRoot) {
angularRoot = anAngularRoot;
}
}
|
package lucee.runtime.debug;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.SystemUtil.TemplateLine;
import lucee.commons.io.res.util.ResourceSnippet;
import lucee.commons.io.res.util.ResourceSnippetsMap;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringUtil;
import lucee.runtime.Component;
import lucee.runtime.Page;
import lucee.runtime.PageContext;
import lucee.runtime.PageContextImpl;
import lucee.runtime.PageSource;
import lucee.runtime.PageSourceImpl;
import lucee.runtime.config.Config;
import lucee.runtime.config.ConfigPro;
import lucee.runtime.config.ConfigWebPro;
import lucee.runtime.db.SQL;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.CatchBlock;
import lucee.runtime.exp.DatabaseException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.PageExceptionImpl;
import lucee.runtime.op.Caster;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.DebugQueryColumn;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Query;
import lucee.runtime.type.QueryColumn;
import lucee.runtime.type.QueryImpl;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.dt.DateTimeImpl;
import lucee.runtime.type.query.QueryResult;
import lucee.runtime.type.util.KeyConstants;
import lucee.runtime.type.util.ListUtil;
/**
* Class to debug the application
*/
public final class DebuggerImpl implements Debugger {
private static final long serialVersionUID = 3957043879267494311L;
private static final Collection.Key IMPLICIT_ACCESS = KeyImpl.getInstance("implicitAccess");
private static final Collection.Key GENERIC_DATA = KeyImpl.getInstance("genericData");
private static final Collection.Key PAGE_PARTS = KeyImpl.getInstance("pageParts");
// private static final Collection.Key OUTPUT_LOG= KeyImpl.intern("outputLog");
private static final int MAX_PARTS = 100;
private final Map<String, DebugEntryTemplateImpl> entries = new HashMap<String, DebugEntryTemplateImpl>();
private Map<String, DebugEntryTemplatePartImpl> partEntries;
private ResourceSnippetsMap snippetsMap = new ResourceSnippetsMap(1024, 128);
private final List<QueryEntry> queries = new ArrayList<QueryEntry>();
private final List<DebugTimerImpl> timers = new ArrayList<DebugTimerImpl>();
private final List<DebugTraceImpl> traces = new ArrayList<DebugTraceImpl>();
private final List<DebugDump> dumps = new ArrayList<DebugDump>();
private final List<CatchBlock> exceptions = new ArrayList<CatchBlock>();
private final Map<String, ImplicitAccessImpl> implicitAccesses = new HashMap<String, ImplicitAccessImpl>();
private boolean output = true;
private long lastEntry;
private long lastTrace;
private final Array historyId = new ArrayImpl();
private final Array historyLevel = new ArrayImpl();
private long starttime = System.currentTimeMillis();
private DebugOutputLog outputLog;
private Map<String, Map<String, List<String>>> genericData;
private TemplateLine abort;
private ApplicationException outputContext;
private long queryTime = 0;
final static Comparator DEBUG_ENTRY_TEMPLATE_COMPARATOR = new DebugEntryTemplateComparator();
final static Comparator DEBUG_ENTRY_TEMPLATE_PART_COMPARATOR = new DebugEntryTemplatePartComparator();
private static final Key CACHE_TYPE = KeyImpl.getInstance("cacheType");
private static final Key[] PAGE_COLUMNS = new Collection.Key[] { KeyConstants._id, KeyConstants._count, KeyConstants._min, KeyConstants._max, KeyConstants._avg,
KeyConstants._app, KeyConstants._load, KeyConstants._query, KeyConstants._total, KeyConstants._src };
private static final Key[] QUERY_COLUMNS = new Collection.Key[] { KeyConstants._name, KeyConstants._time, KeyConstants._sql, KeyConstants._src, KeyConstants._line,
KeyConstants._count, KeyConstants._datasource, KeyConstants._usage, CACHE_TYPE };
private static final String[] QUERY_COLUMN_TYPES = new String[] { "VARCHAR", "DOUBLE", "VARCHAR", "VARCHAR", "DOUBLE", "DOUBLE", "VARCHAR", "ANY", "VARCHAR" };
private static final Key[] GEN_DATA_COLUMNS = new Collection.Key[] { KeyConstants._category, KeyConstants._name, KeyConstants._value };
private static final Key[] TIMER_COLUMNS = new Collection.Key[] { KeyConstants._label, KeyConstants._time, KeyConstants._template };
private static final Key[] DUMP_COLUMNS = new Collection.Key[] { KeyConstants._output, KeyConstants._template, KeyConstants._line };
private static final Key[] PAGE_PART_COLUMNS = new Collection.Key[] { KeyConstants._id, KeyConstants._count, KeyConstants._min, KeyConstants._max, KeyConstants._avg,
KeyConstants._total, KeyConstants._path, KeyConstants._start, KeyConstants._end, KeyConstants._startLine, KeyConstants._endLine, KeyConstants._snippet };
private static final Key[] TRACES_COLUMNS = new Collection.Key[] { KeyConstants._type, KeyConstants._category, KeyConstants._text, KeyConstants._template, KeyConstants._line,
KeyConstants._action, KeyConstants._varname, KeyConstants._varvalue, KeyConstants._time };
private static final Key[] IMPLICIT_ACCESS_COLUMNS = new Collection.Key[] { KeyConstants._template, KeyConstants._line, KeyConstants._scope, KeyConstants._count,
KeyConstants._name };
private static final Double ZERO = Double.valueOf(0);
@Override
public void reset() {
entries.clear();
if (partEntries != null) partEntries.clear();
queries.clear();
implicitAccesses.clear();
if (genericData != null) genericData.clear();
timers.clear();
traces.clear();
dumps.clear();
exceptions.clear();
historyId.clear();
historyLevel.clear();
output = true;
outputLog = null;
abort = null;
outputContext = null;
queryTime = 0;
}
public DebuggerImpl() {}
@Override
public DebugEntryTemplate getEntry(PageContext pc, PageSource source) {
return getEntry(pc, source, null);
}
@Override
public DebugEntryTemplate getEntry(PageContext pc, PageSource source, String key) {
lastEntry = System.currentTimeMillis();
String src = DebugEntryTemplateImpl.getSrc(source == null ? "" : source.getDisplayPath(), key);
DebugEntryTemplateImpl de = entries.get(src);
if (de != null) {
de.countPP();
historyId.appendEL(de.getId());
historyLevel.appendEL(Caster.toInteger(pc.getCurrentLevel()));
return de;
}
de = new DebugEntryTemplateImpl(source, key);
entries.put(src, de);
historyId.appendEL(de.getId());
historyLevel.appendEL(Caster.toInteger(pc.getCurrentLevel()));
return de;
}
@Override
public DebugEntryTemplatePart getEntry(PageContext pc, PageSource source, int startPos, int endPos) {
String src = DebugEntryTemplatePartImpl.getSrc(source == null ? "" : source.getDisplayPath(), startPos, endPos);
DebugEntryTemplatePartImpl de = null;
if (partEntries != null) {
de = partEntries.get(src);
if (de != null) {
de.countPP();
return de;
}
}
else {
partEntries = new HashMap<String, DebugEntryTemplatePartImpl>();
}
ResourceSnippet snippet = snippetsMap.getSnippet(source, startPos, endPos, ((PageContextImpl) pc).getResourceCharset().name());
de = new DebugEntryTemplatePartImpl(source, startPos, endPos, snippet.getStartLine(), snippet.getEndLine(), snippet.getContent());
partEntries.put(src, de);
return de;
}
private ArrayList<DebugEntryTemplate> toArray() {
ArrayList<DebugEntryTemplate> arrPages = new ArrayList<DebugEntryTemplate>(entries.size());
Iterator<String> it = entries.keySet().iterator();
while (it.hasNext()) {
DebugEntryTemplate page = entries.get(it.next());
page.resetQueryTime();
arrPages.add(page);
}
Collections.sort(arrPages, DEBUG_ENTRY_TEMPLATE_COMPARATOR);
// Queries
int len = queries.size();
QueryEntry entry;
for (int i = 0; i < len; i++) {
entry = queries.get(i);
String path = entry.getSrc();
Object o = entries.get(path);
if (o != null) {
DebugEntryTemplate oe = (DebugEntryTemplate) o;
oe.updateQueryTime(entry.getExecutionTime());
}
}
return arrPages;
}
public static boolean debugQueryUsage(PageContext pageContext, QueryResult qr) {
if (pageContext.getConfig().debug() && qr instanceof Query) {
if (((ConfigWebPro) pageContext.getConfig()).hasDebugOptions(ConfigPro.DEBUG_QUERY_USAGE)) {
((Query) qr).enableShowQueryUsage();
return true;
}
}
return false;
}
public static boolean debugQueryUsage(PageContext pageContext, Query qry) {
if (pageContext.getConfig().debug() && qry instanceof Query) {
if (((ConfigWebPro) pageContext.getConfig()).hasDebugOptions(ConfigPro.DEBUG_QUERY_USAGE)) {
qry.enableShowQueryUsage();
return true;
}
}
return false;
}
private Double _toDouble(long value) {
if (value <= 0) return ZERO;
return Double.valueOf(value);
}
private Double _toDouble(int value) {
if (value <= 0) return ZERO;
return Double.valueOf(value);
}
@Override
public void addQuery(Query query, String datasource, String name, SQL sql, int recordcount, PageSource src, int time) {
addQuery(query, datasource, name, sql, recordcount, src, (long) time);
}
@Override
public void addQuery(Query query, String datasource, String name, SQL sql, int recordcount, PageSource src, long time) {
TemplateLine tl = null;
if (src != null) tl = new TemplateLine(src.getDisplayPath(), 0);
queries.add(new QueryResultEntryImpl((QueryResult) query, datasource, name, sql, recordcount, tl, time));
}
public void addQuery(QueryResult qr, String datasource, String name, SQL sql, int recordcount, TemplateLine tl, long time) {
queries.add(new QueryResultEntryImpl(qr, datasource, name, sql, recordcount, tl, time));
}
public void addQuery(long time) {
queryTime += time;
}
@Override
public void setOutput(boolean output) {
setOutput(output, false);
}
public void setOutput(boolean output, boolean listen) {
this.output = output;
if (listen) {
this.outputContext = new ApplicationException("");
}
}
// FUTURE add to inzerface
public boolean getOutput() {
return output;
}
public PageException getOutputContext() {
return outputContext;
}
@Override
public List<QueryEntry> getQueries() {
return queries;
}
/**
* returns the DebugEntry for the current request's IP address, or null if no template matches the
* address
*
* @param pc
* @return
*/
public static lucee.runtime.config.DebugEntry getDebugEntry(PageContext pc) {
String addr = pc.getHttpServletRequest().getRemoteAddr();
lucee.runtime.config.DebugEntry debugEntry = ((ConfigPro) pc.getConfig()).getDebugEntry(addr, null);
return debugEntry;
}
@Override
public void writeOut(PageContext pc) throws IOException {
// stop();
if (!output) return;
lucee.runtime.config.DebugEntry debugEntry = getDebugEntry(pc);
if (debugEntry == null) {
// pc.forceWrite(pc.getConfig().getDefaultDumpWriter().toString(pc,toDumpData(pc,
// 9999,DumpUtil.toDumpProperties()),true));
return;
}
Struct args = new StructImpl();
args.setEL(KeyConstants._custom, debugEntry.getCustom());
try {
args.setEL(KeyConstants._debugging, pc.getDebugger().getDebuggingData(pc));
}
catch (PageException e1) {}
try {
String path = debugEntry.getPath();
PageSource[] arr = ((PageContextImpl) pc).getPageSources(path);
Page p = PageSourceImpl.loadPage(pc, arr, null);
// patch for old path
String fullname = debugEntry.getFullname();
if (p == null) {
if (path != null) {
boolean changed = false;
if (path.endsWith("/Modern.cfc") || path.endsWith("\\Modern.cfc")) {
path = "/lucee-server-context/admin/debug/Modern.cfc";
fullname = "lucee-server-context.admin.debug.Modern";
changed = true;
}
else if (path.endsWith("/Classic.cfc") || path.endsWith("\\Classic.cfc")) {
path = "/lucee-server-context/admin/debug/Classic.cfc";
fullname = "lucee-server-context.admin.debug.Classic";
changed = true;
}
else if (path.endsWith("/Comment.cfc") || path.endsWith("\\Comment.cfc")) {
path = "/lucee-server-context/admin/debug/Comment.cfc";
fullname = "lucee-server-context.admin.debug.Comment";
changed = true;
}
if (changed) pc.write(
"<span style='color:red'>Please update your debug template definitions in the Lucee admin by going into the detail view and hit the \"update\" button.</span>");
}
arr = ((PageContextImpl) pc).getPageSources(path);
p = PageSourceImpl.loadPage(pc, arr);
}
pc.addPageSource(p.getPageSource(), true);
try {
Component c = pc.loadComponent(fullname);
c.callWithNamedValues(pc, "output", args);
}
finally {
pc.removeLastPageSource(true);
}
}
catch (PageException e) {
pc.handlePageException(e);
}
}
@Override
public Struct getDebuggingData(PageContext pc) throws DatabaseException {
return getDebuggingData(pc, false);
}
@Override
public Struct getDebuggingData(PageContext pc, boolean addAddionalInfo) throws DatabaseException {
PageContextImpl pci = (PageContextImpl) pc;
Struct debugging = new StructImpl();
// datasources
debugging.setEL(KeyConstants._datasources, ((ConfigPro) pc.getConfig()).getDatasourceConnectionPool().meta());
ConfigPro ci = (ConfigPro) ThreadLocalPageContext.getConfig(pc);
//////// QUERIES ///////////////////////////
long queryTime = 0;
if (ci.hasDebugOptions(ConfigPro.DEBUG_DATABASE)) {
List<QueryEntry> queries = getQueries();
Query qryQueries = null;
try {
qryQueries = new QueryImpl(QUERY_COLUMNS, QUERY_COLUMN_TYPES, queries.size(), "query");
}
catch (DatabaseException e) {
qryQueries = new QueryImpl(QUERY_COLUMNS, queries.size(), "query");
}
debugging.setEL(KeyConstants._queries, qryQueries);
Struct qryExe = new StructImpl();
ListIterator<QueryEntry> qryIt = queries.listIterator();
int row = 0;
try {
QueryEntry qe;
while (qryIt.hasNext()) {
row++;
qe = qryIt.next();
queryTime += qe.getExecutionTime();
qryQueries.setAt(KeyConstants._name, row, qe.getName() == null ? "" : qe.getName());
qryQueries.setAt(KeyConstants._time, row, Long.valueOf(qe.getExecutionTime()));
qryQueries.setAt(KeyConstants._sql, row, qe.getSQL().toString());
if (qe instanceof QueryResultEntryImpl) {
TemplateLine tl = ((QueryResultEntryImpl) qe).getTemplateLine();
if (tl != null) {
qryQueries.setAt(KeyConstants._src, row, tl.template);
qryQueries.setAt(KeyConstants._line, row, tl.line);
}
}
else qryQueries.setAt(KeyConstants._src, row, qe.getSrc());
qryQueries.setAt(KeyConstants._count, row, Integer.valueOf(qe.getRecordcount()));
qryQueries.setAt(KeyConstants._datasource, row, qe.getDatasource());
qryQueries.setAt(CACHE_TYPE, row, qe.getCacheType());
Struct usage = getUsage(qe);
if (usage != null) qryQueries.setAt(KeyConstants._usage, row, usage);
Object o = qryExe.get(KeyImpl.init(qe.getSrc()), null);
if (o == null) qryExe.setEL(KeyImpl.init(qe.getSrc()), Long.valueOf(qe.getExecutionTime()));
else qryExe.setEL(KeyImpl.init(qe.getSrc()), Long.valueOf(((Long) o).longValue() + qe.getExecutionTime()));
}
}
catch (PageException dbe) {}
}
else {
queryTime = this.queryTime;
}
//////// PAGES ///////////////////////////
long totalTime = 0;
ArrayList<DebugEntryTemplate> arrPages = null;
if (ci.hasDebugOptions(ConfigPro.DEBUG_TEMPLATE)) {
int row = 0;
arrPages = toArray();
int len = arrPages.size();
Query qryPage = new QueryImpl(PAGE_COLUMNS, len, "query");
debugging.setEL(KeyConstants._pages, qryPage);
if (len > 0) {
try {
DebugEntryTemplate de;
// PageSource ps;
for (int i = 0; i < len; i++) {
row++;
de = arrPages.get(i);
// ps = de.getPageSource();
totalTime += de.getFileLoadTime() + de.getExeTime();
qryPage.setAt(KeyConstants._id, row, de.getId());
qryPage.setAt(KeyConstants._count, row, _toDouble(de.getCount()));
qryPage.setAt(KeyConstants._min, row, _toDouble(de.getMin()));
qryPage.setAt(KeyConstants._max, row, _toDouble(de.getMax()));
qryPage.setAt(KeyConstants._avg, row, _toDouble(de.getExeTime() / de.getCount()));
qryPage.setAt(KeyConstants._app, row, _toDouble(de.getExeTime() - de.getQueryTime()));
qryPage.setAt(KeyConstants._load, row, _toDouble(de.getFileLoadTime()));
qryPage.setAt(KeyConstants._query, row, _toDouble(de.getQueryTime()));
qryPage.setAt(KeyConstants._total, row, _toDouble(de.getFileLoadTime() + de.getExeTime()));
qryPage.setAt(KeyConstants._src, row, de.getSrc());
}
}
catch (PageException dbe) {}
}
}
else {
totalTime = pci.getEndTimeNS() > pci.getStartTimeNS() ? pci.getEndTimeNS() - pci.getStartTimeNS() : 0;
}
//////// TIMES ///////////////////////////
Struct times = new StructImpl();
times.setEL(KeyConstants._total, Caster.toDouble(totalTime));
times.setEL(KeyConstants._query, Caster.toDouble(queryTime));
debugging.setEL(KeyConstants._times, times);
//////// PAGE PARTS ///////////////////////////
boolean hasParts = partEntries != null && !partEntries.isEmpty() && arrPages != null && !arrPages.isEmpty();
int qrySize = 0;
Query qryPart = null;
if (hasParts) {
qryPart = new QueryImpl(PAGE_PART_COLUMNS, qrySize, "query");
debugging.setEL(PAGE_PARTS, qryPart);
String slowestTemplate = arrPages.get(0).getPath();
List<DebugEntryTemplatePart> filteredPartEntries = new ArrayList();
java.util.Collection<DebugEntryTemplatePartImpl> col = partEntries.values();
for (DebugEntryTemplatePart detp: col) {
if (detp.getPath().equals(slowestTemplate)) filteredPartEntries.add(detp);
}
qrySize = Math.min(filteredPartEntries.size(), MAX_PARTS);
int row = 0;
Collections.sort(filteredPartEntries, DEBUG_ENTRY_TEMPLATE_PART_COMPARATOR);
DebugEntryTemplatePart[] parts = new DebugEntryTemplatePart[qrySize];
if (filteredPartEntries.size() > MAX_PARTS) parts = filteredPartEntries.subList(0, MAX_PARTS).toArray(parts);
else parts = filteredPartEntries.toArray(parts);
try {
DebugEntryTemplatePart de;
// PageSource ps;
for (int i = 0; i < parts.length; i++) {
row++;
de = parts[i];
qryPart.setAt(KeyConstants._id, row, de.getId());
qryPart.setAt(KeyConstants._count, row, _toDouble(de.getCount()));
qryPart.setAt(KeyConstants._min, row, _toDouble(de.getMin()));
qryPart.setAt(KeyConstants._max, row, _toDouble(de.getMax()));
qryPart.setAt(KeyConstants._avg, row, _toDouble(de.getExeTime() / de.getCount()));
qryPart.setAt(KeyConstants._start, row, _toDouble(de.getStartPosition()));
qryPart.setAt(KeyConstants._end, row, _toDouble(de.getEndPosition()));
qryPart.setAt(KeyConstants._total, row, _toDouble(de.getExeTime()));
qryPart.setAt(KeyConstants._path, row, de.getPath());
if (de instanceof DebugEntryTemplatePartImpl) {
qryPart.setAt(KeyConstants._startLine, row, _toDouble(((DebugEntryTemplatePartImpl) de).getStartLine()));
qryPart.setAt(KeyConstants._endLine, row, _toDouble(((DebugEntryTemplatePartImpl) de).getEndLine()));
qryPart.setAt(KeyConstants._snippet, row, ((DebugEntryTemplatePartImpl) de).getSnippet());
}
}
}
catch (PageException dbe) {}
}
//////// EXCEPTIONS ///////////////////////////
if (ci.hasDebugOptions(ConfigPro.DEBUG_EXCEPTION)) {
int len = exceptions == null ? 0 : exceptions.size();
Array arrExceptions = new ArrayImpl();
debugging.setEL(KeyConstants._exceptions, arrExceptions);
if (len > 0) {
Iterator<CatchBlock> it = exceptions.iterator();
while (it.hasNext()) {
arrExceptions.appendEL(it.next());
}
}
}
//////// GENERIC DATA ///////////////////////////
Query qryGenData = null;
Map<String, Map<String, List<String>>> genData = getGenericData();
if (genData != null && genData.size() > 0) {
qryGenData = new QueryImpl(GEN_DATA_COLUMNS, 0, "query");
debugging.setEL(GENERIC_DATA, qryGenData);
Iterator<Entry<String, Map<String, List<String>>>> it = genData.entrySet().iterator();
Entry<String, Map<String, List<String>>> e;
Iterator<Entry<String, List<String>>> itt;
Entry<String, List<String>> ee;
String cat;
int r;
List<String> list;
Object val;
while (it.hasNext()) {
e = it.next();
cat = e.getKey();
itt = e.getValue().entrySet().iterator();
while (itt.hasNext()) {
ee = itt.next();
r = qryGenData.addRow();
list = ee.getValue();
if (list.size() == 1) val = list.get(0);
else val = ListUtil.listToListEL(list, ", ");
qryGenData.setAtEL(KeyConstants._category, r, cat);
qryGenData.setAtEL(KeyConstants._name, r, ee.getKey());
qryGenData.setAtEL(KeyConstants._value, r, val);
}
}
}
//////// TIMERS ///////////////////////////
if (ci.hasDebugOptions(ConfigPro.DEBUG_TIMER)) {
int len = timers == null ? 0 : timers.size();
Query qryTimers = new QueryImpl(TIMER_COLUMNS, len, "timers");
debugging.setEL(KeyConstants._timers, qryTimers);
if (len > 0) {
try {
Iterator<DebugTimerImpl> it = timers.iterator();
DebugTimer timer;
int row = 0;
while (it.hasNext()) {
timer = it.next();
row++;
qryTimers.setAt(KeyConstants._label, row, timer.getLabel());
qryTimers.setAt(KeyConstants._template, row, timer.getTemplate());
qryTimers.setAt(KeyConstants._time, row, Caster.toDouble(timer.getTime()));
}
}
catch (PageException dbe) {}
}
}
//////// HISTORY ///////////////////////////
Query history = new QueryImpl(new Collection.Key[] {}, 0, "history");
debugging.setEL(KeyConstants._history, history);
try {
history.addColumn(KeyConstants._id, historyId);
history.addColumn(KeyConstants._level, historyLevel);
}
catch (PageException e) {}
//////// DUMPS ///////////////////////////
if (ci.hasDebugOptions(ConfigPro.DEBUG_DUMP)) {
int len = dumps == null ? 0 : dumps.size();
if (!((ConfigPro) pc.getConfig()).hasDebugOptions(ConfigPro.DEBUG_DUMP)) len = 0;
Query qryDumps = null;
qryDumps = new QueryImpl(DUMP_COLUMNS, len, "dumps");
debugging.setEL(KeyConstants._dumps, qryDumps);
if (len > 0) {
try {
Iterator<DebugDump> it = dumps.iterator();
DebugDump dd;
int row = 0;
while (it.hasNext()) {
dd = it.next();
row++;
qryDumps.setAt(KeyConstants._output, row, dd.getOutput());
if (!StringUtil.isEmpty(dd.getTemplate())) qryDumps.setAt(KeyConstants._template, row, dd.getTemplate());
if (dd.getLine() > 0) qryDumps.setAt(KeyConstants._line, row, new Double(dd.getLine()));
}
}
catch (PageException dbe) {}
}
}
//////// TRACES ///////////////////////////
if (ci.hasDebugOptions(ConfigPro.DEBUG_TRACING)) {
int len = traces == null ? 0 : traces.size();
if (!((ConfigPro) pc.getConfig()).hasDebugOptions(ConfigPro.DEBUG_TRACING)) len = 0;
Query qryTraces = null;
qryTraces = new QueryImpl(TRACES_COLUMNS, len, "traces");
debugging.setEL(KeyConstants._traces, qryTraces);
if (len > 0) {
try {
Iterator<DebugTraceImpl> it = traces.iterator();
DebugTraceImpl trace;
int row = 0;
while (it.hasNext()) {
trace = it.next();
row++;
qryTraces.setAt(KeyConstants._type, row, DebugTraceImpl.toType(trace.getType(), "INFO"));
if (!StringUtil.isEmpty(trace.getCategory())) qryTraces.setAt(KeyConstants._category, row, trace.getCategory());
if (!StringUtil.isEmpty(trace.getText())) qryTraces.setAt(KeyConstants._text, row, trace.getText());
if (!StringUtil.isEmpty(trace.getTemplate())) qryTraces.setAt(KeyConstants._template, row, trace.getTemplate());
if (trace.getLine() > 0) qryTraces.setAt(KeyConstants._line, row, new Double(trace.getLine()));
if (!StringUtil.isEmpty(trace.getAction())) qryTraces.setAt(KeyConstants._action, row, trace.getAction());
if (!StringUtil.isEmpty(trace.getVarName())) qryTraces.setAt(KeyImpl.getInstance("varname"), row, trace.getVarName());
if (!StringUtil.isEmpty(trace.getVarValue())) qryTraces.setAt(KeyImpl.getInstance("varvalue"), row, trace.getVarValue());
qryTraces.setAt(KeyConstants._time, row, new Double(trace.getTime()));
}
}
catch (PageException dbe) {}
}
}
//////// SCOPE ACCESS ////////////////////
if (ci.hasDebugOptions(ConfigPro.DEBUG_IMPLICIT_ACCESS)) {
int len = implicitAccesses == null ? 0 : implicitAccesses.size();
Query qryImplicitAccesseses = new QueryImpl(IMPLICIT_ACCESS_COLUMNS, len, "implicitAccess");
debugging.setEL(IMPLICIT_ACCESS, qryImplicitAccesseses);
if (len > 0) {
try {
Iterator<ImplicitAccessImpl> it = implicitAccesses.values().iterator();
ImplicitAccessImpl das;
int row = 0;
while (it.hasNext()) {
das = it.next();
row++;
qryImplicitAccesseses.setAt(KeyConstants._template, row, das.getTemplate());
qryImplicitAccesseses.setAt(KeyConstants._line, row, new Double(das.getLine()));
qryImplicitAccesseses.setAt(KeyConstants._scope, row, das.getScope());
qryImplicitAccesseses.setAt(KeyConstants._count, row, new Double(das.getCount()));
qryImplicitAccesseses.setAt(KeyConstants._name, row, das.getName());
}
}
catch (PageException dbe) {}
}
}
//////// ABORT /////////////////////////
if (abort != null) {
Struct sct = new StructImpl();
sct.setEL(KeyConstants._template, abort.template);
sct.setEL(KeyConstants._line, new Double(abort.line));
debugging.setEL(KeyConstants._abort, sct);
}
//////// SCOPES /////////////////////////
if (addAddionalInfo) {
Struct scopes = new StructImpl();
scopes.setEL(KeyConstants._cgi, pc.cgiScope());
debugging.setEL(KeyConstants._scope, scopes);
}
debugging.setEL(KeyImpl.getInstance("starttime"), new DateTimeImpl(starttime, false));
debugging.setEL(KeyConstants._id, pci.getRequestId() + "-" + pci.getId());
return debugging;
}
public void setAbort(TemplateLine abort) {
this.abort = abort;
}
public TemplateLine getAbort() {
return this.abort;
}
private static Struct getUsage(QueryEntry qe) throws PageException {
Query qry = qe.getQry();
QueryColumn c;
DebugQueryColumn dqc;
outer: if (qry != null) {
Struct usage = null;
Collection.Key[] columnNames = qry.getColumnNames();
Collection.Key columnName;
for (int i = 0; i < columnNames.length; i++) {
columnName = columnNames[i];
c = qry.getColumn(columnName);
if (!(c instanceof DebugQueryColumn)) break outer;
dqc = (DebugQueryColumn) c;
if (usage == null) usage = new StructImpl();
usage.setEL(columnName, Caster.toBoolean(dqc.isUsed()));
}
return usage;
}
return null;
}
@Override
public DebugTimer addTimer(String label, long time, String template) {
DebugTimerImpl t;
timers.add(t = new DebugTimerImpl(label, time, template));
return t;
}
@Override
public DebugTrace addTrace(int type, String category, String text, PageSource ps, String varName, String varValue) {
long _lastTrace = (traces.isEmpty()) ? lastEntry : lastTrace;
lastTrace = System.currentTimeMillis();
DebugTraceImpl t = new DebugTraceImpl(type, category, text, ps == null ? "unknown template" : ps.getDisplayPath(), SystemUtil.getCurrentContext(null).line, "", varName,
varValue, lastTrace - _lastTrace);
traces.add(t);
return t;
}
@Override
public DebugDump addDump(PageSource ps, String dump) {
DebugDump dt = new DebugDumpImpl(ps.getDisplayPath(), SystemUtil.getCurrentContext(null).line, dump);
dumps.add(dt);
return dt;
}
@Override
public DebugTrace addTrace(int type, String category, String text, String template, int line, String action, String varName, String varValue) {
long _lastTrace = (traces.isEmpty()) ? lastEntry : lastTrace;
lastTrace = System.currentTimeMillis();
DebugTraceImpl t = new DebugTraceImpl(type, category, text, template, line, action, varName, varValue, lastTrace - _lastTrace);
traces.add(t);
return t;
}
@Override
public DebugTrace[] getTraces() {
return getTraces(ThreadLocalPageContext.get());
}
@Override
public DebugTrace[] getTraces(PageContext pc) {
if (pc != null && ((ConfigPro) pc.getConfig()).hasDebugOptions(ConfigPro.DEBUG_TRACING)) return traces.toArray(new DebugTrace[traces.size()]);
return new DebugTrace[0];
}
@Override
public void addException(Config config, PageException pe) {
if (exceptions.size() > 1000) return;
try {
exceptions.add(((PageExceptionImpl) pe).getCatchBlock(config));
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
@Override
public CatchBlock[] getExceptions() {
return exceptions.toArray(new CatchBlock[exceptions.size()]);
}
@Override
public void init(Config config) {
this.starttime = System.currentTimeMillis() + config.getTimeServerOffset();
}
@Override
public void addImplicitAccess(String scope, String name) {
addImplicitAccess(null, scope, name);
}
// FUTURE add to interface
public void addImplicitAccess(PageContext pc, String scope, String name) {
if (implicitAccesses.size() > 1000) return;
try {
SystemUtil.TemplateLine tl = SystemUtil.getCurrentContext(pc);
String key = tl.toString(new StringBuilder()).append(':').append(scope).append(':').append(name).toString();
ImplicitAccessImpl dsc = implicitAccesses.get(key);
if (dsc != null) dsc.inc();
else implicitAccesses.put(key, new ImplicitAccessImpl(scope, name, tl.template, tl.line));
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
@Override
public ImplicitAccess[] getImplicitAccesses(int scope, String name) {
return implicitAccesses.values().toArray(new ImplicitAccessImpl[implicitAccesses.size()]);
}
@Override
public void setOutputLog(DebugOutputLog outputLog) {
this.outputLog = outputLog;
}
public DebugTextFragment[] getOutputTextFragments() {
return this.outputLog.getFragments();
}
public Query getOutputText() throws DatabaseException {
DebugTextFragment[] fragments = outputLog.getFragments();
int len = fragments == null ? 0 : fragments.length;
Query qryOutputLog = new QueryImpl(new Collection.Key[] { KeyConstants._line, KeyConstants._template, KeyConstants._text }, len, "query");
if (len > 0) {
for (int i = 0; i < fragments.length; i++) {
qryOutputLog.setAtEL(KeyConstants._line, i + 1, fragments[i].getLine());
qryOutputLog.setAtEL(KeyConstants._template, i + 1, fragments[i].getTemplate());
qryOutputLog.setAtEL(KeyConstants._text, i + 1, fragments[i].getText());
}
}
return qryOutputLog;
}
public void resetTraces() {
traces.clear();
}
@Override
public void addGenericData(String labelCategory, Map<String, String> data) {
// init generic data if necessary
if (genericData == null) genericData = new ConcurrentHashMap<String, Map<String, List<String>>>();
// category
Map<String, List<String>> cat = genericData.get(labelCategory);
if (cat == null) genericData.put(labelCategory, cat = new ConcurrentHashMap<String, List<String>>());
// data
Iterator<Entry<String, String>> it = data.entrySet().iterator();
Entry<String, String> e;
List<String> entry;
while (it.hasNext()) {
e = it.next();
entry = cat.get(e.getKey());
if (entry == null) {
cat.put(e.getKey(), entry = new ArrayList<String>());
}
entry.add(e.getValue());
}
}
/*
* private List<String> createAndFillList(Map<String, List<String>> cat) { Iterator<List<String>> it
* = cat.values().iterator(); int size=0; while(it.hasNext()){ size=it.next().size(); break; }
* ArrayList<String> list = new ArrayList<String>();
*
* // fill with empty values to be on the same level as other columns for(int
* i=0;i<size;i++)list.add("");
*
* return list; }
*/
@Override
public Map<String, Map<String, List<String>>> getGenericData() {
return genericData;
}
public static void deprecated(PageContext pc, String key, String msg) {
if (pc.getConfig().debug()) {
// do we already have set?
boolean exists = false;
Map<String, Map<String, List<String>>> gd = pc.getDebugger().getGenericData();
if (gd != null) {
Map<String, List<String>> warning = gd.get("Warning");
if (warning != null) {
exists = warning.containsKey(key);
}
}
if (!exists) {
Map<String, String> map = new HashMap<>();
map.put(key, msg);
pc.getDebugger().addGenericData("Warning", map);
}
}
}
}
final class DebugEntryTemplateComparator implements Comparator<DebugEntryTemplate> {
@Override
public int compare(DebugEntryTemplate de1, DebugEntryTemplate de2) {
long result = ((de2.getExeTime() + de2.getFileLoadTime()) - (de1.getExeTime() + de1.getFileLoadTime()));
// we do this additional step to try to avoid ticket LUCEE-2076
return result > 0L ? 1 : (result < 0L ? -1 : 0);
}
}
final class DebugEntryTemplatePartComparator implements Comparator<DebugEntryTemplatePart> {
@Override
public int compare(DebugEntryTemplatePart de1, DebugEntryTemplatePart de2) {
long result = de2.getExeTime() - de1.getExeTime();
// we do this additional step to try to avoid ticket LUCEE-2076
return result > 0L ? 1 : (result < 0L ? -1 : 0);
}
}
|
package me.ziccard.secureit;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.Display;
import android.view.View;
public class MicrophoneVolumePicker extends View {
Paint paint = new Paint();
final int GREEN = 8453888;
final int ORANGE = 16744448;
final int RED = 14549506;
public MicrophoneVolumePicker(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
int paddingBorder = 30; // padding from border
int scaleSize = canvas.getWidth()-paddingBorder*2; // due bordi destro e sinistro.
int zeroDBPoint = scaleSize/3*2; // 0db is placed 2/3 of the available screen
int ambientNoisePoint = scaleSize/3;
final int bottomScale = -50;
final int ambientDBValue = -10; // in db;
int currentValue = 2; //value recorded by mic
double currentValueWithinScale = currentValue - bottomScale; // bottomscale = 0
if(currentValue < ambientDBValue){
final double underAmbientGrain = Math.abs(bottomScale-ambientDBValue);
paint.setColor(GREEN);
//(currentValueWithinScale)*ambientNoisePoint
canvas.drawRect(new Rect(paddingBorder,
paddingBorder,
(int) (paddingBorder+(currentValueWithinScale/underAmbientGrain)*ambientNoisePoint),
paddingBorder+30),
paint);
Log.i("DEBUG:",""+(currentValueWithinScale/underAmbientGrain)+":"+ambientNoisePoint);
} else {
// paint the undernoise part
paint.setColor(Color.GREEN);
canvas.drawRect(new Rect(paddingBorder,
paddingBorder,
paddingBorder+ambientNoisePoint,
paddingBorder+30), paint);
if(currentValue < 0){
// paint the noise to 0 db part
} else {
paint.setColor(Color.YELLOW);
canvas.drawRect(paddingBorder+ambientNoisePoint,
paddingBorder,
paddingBorder+zeroDBPoint,
paddingBorder+30,
paint );
}
}
/*
paint.setColor(Color.YELLOW);
canvas.drawRect(33, 60, 77, 77, paint );
paint.setColor(Color.RED);
canvas.drawRect(33, 33, 77, 60, paint );
*/
}
}
|
package nom.bdezonia.zorbage.type.character;
import java.util.concurrent.ThreadLocalRandom;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Bounded;
import nom.bdezonia.zorbage.algebra.Ordered;
import nom.bdezonia.zorbage.algebra.PredSucc;
import nom.bdezonia.zorbage.algebra.Random;
import nom.bdezonia.zorbage.function.Function1;
import nom.bdezonia.zorbage.function.Function2;
import nom.bdezonia.zorbage.procedure.Procedure1;
import nom.bdezonia.zorbage.procedure.Procedure2;
import nom.bdezonia.zorbage.procedure.Procedure3;
/**
*
* @author Barry DeZonia
*
*/
public class CharAlgebra
implements
Algebra<CharAlgebra, CharMember>,
Ordered<CharMember>,
PredSucc<CharMember>,
Random<CharMember>,
Bounded<CharMember>
{
@Override
public CharMember construct() {
return new CharMember();
}
@Override
public CharMember construct(CharMember other) {
return new CharMember(other);
}
@Override
public CharMember construct(String str) {
return new CharMember(str);
}
private final Function2<Boolean, CharMember, CharMember> EQ =
new Function2<Boolean, CharMember, CharMember>()
{
@Override
public Boolean call(CharMember a, CharMember b) {
return a.v() == b.v();
}
};
@Override
public Function2<Boolean, CharMember, CharMember> isEqual() {
return EQ;
}
private final Function2<Boolean, CharMember, CharMember> NEQ =
new Function2<Boolean, CharMember, CharMember>()
{
@Override
public Boolean call(CharMember a, CharMember b) {
return a.v() != b.v();
}
};
@Override
public Function2<Boolean, CharMember, CharMember> isNotEqual() {
return NEQ;
}
private final Procedure2<CharMember, CharMember> ASS =
new Procedure2<CharMember, CharMember>()
{
@Override
public void call(CharMember a, CharMember b) {
b.set(a);
}
};
@Override
public Procedure2<CharMember, CharMember> assign() {
return ASS;
}
private final Procedure1<CharMember> ZER =
new Procedure1<CharMember>()
{
@Override
public void call(CharMember a) {
a.setV((char)0);
}
};
@Override
public Procedure1<CharMember> zero() {
return ZER;
}
private final Function1<Boolean, CharMember> ISZER =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember a) {
return a.v() == 0;
}
};
@Override
public Function1<Boolean, CharMember> isZero() {
return ISZER;
}
private final Function2<Boolean, CharMember, CharMember> LESS =
new Function2<Boolean, CharMember, CharMember>()
{
@Override
public Boolean call(CharMember a, CharMember b) {
return a.v() < b.v();
}
};
@Override
public Function2<Boolean, CharMember, CharMember> isLess() {
return LESS;
}
private final Function2<Boolean, CharMember, CharMember> LE =
new Function2<Boolean, CharMember, CharMember>()
{
@Override
public Boolean call(CharMember a, CharMember b) {
return a.v() <= b.v();
}
};
@Override
public Function2<Boolean, CharMember, CharMember> isLessEqual() {
return LE;
}
private final Function2<Boolean, CharMember, CharMember> GREATER =
new Function2<Boolean, CharMember, CharMember>()
{
@Override
public Boolean call(CharMember a, CharMember b) {
return a.v() > b.v();
}
};
@Override
public Function2<Boolean, CharMember, CharMember> isGreater() {
return GREATER;
}
private final Function2<Boolean, CharMember, CharMember> GE =
new Function2<Boolean, CharMember, CharMember>()
{
@Override
public Boolean call(CharMember a, CharMember b) {
return a.v() >= b.v();
}
};
@Override
public Function2<Boolean, CharMember, CharMember> isGreaterEqual() {
return GE;
}
private final Function2<Integer, CharMember, CharMember> CMP =
new Function2<Integer, CharMember, CharMember>()
{
@Override
public Integer call(CharMember a, CharMember b) {
if (a.v() < b.v())
return -1;
else if (a.v() > b.v())
return 1;
else
return 0;
}
};
@Override
public Function2<Integer, CharMember, CharMember> compare() {
return CMP;
}
private final Function1<Integer, CharMember> SIG =
new Function1<Integer, CharMember>()
{
@Override
public Integer call(CharMember a) {
if (a.v() < 0)
return -1;
else if (a.v() > 9)
return 1;
else
return 0;
}
};
@Override
public Function1<Integer, CharMember> signum() {
return SIG;
}
private final Procedure3<CharMember, CharMember, CharMember> MIN =
new Procedure3<CharMember, CharMember, CharMember>()
{
@Override
public void call(CharMember a, CharMember b, CharMember c) {
if (a.v() < b.v())
c.set(a);
else
c.set(b);
}
};
@Override
public Procedure3<CharMember, CharMember, CharMember> min() {
return MIN;
}
private final Procedure3<CharMember, CharMember, CharMember> MAX =
new Procedure3<CharMember, CharMember, CharMember>()
{
@Override
public void call(CharMember a, CharMember b, CharMember c) {
if (a.v() > b.v())
c.set(a);
else
c.set(b);
}
};
@Override
public Procedure3<CharMember, CharMember, CharMember> max() {
return MAX;
}
private final Procedure1<CharMember> RAND =
new Procedure1<CharMember>()
{
@Override
public void call(CharMember a) {
int c = ThreadLocalRandom.current().nextInt(65536);
a.setV((char)c);
}
};
@Override
public Procedure1<CharMember> random() {
return RAND;
}
private final Procedure2<CharMember, CharMember> PRED =
new Procedure2<CharMember, CharMember>()
{
@Override
public void call(CharMember a, CharMember b) {
if (a.v() == Character.MIN_VALUE)
b.setV(Character.MAX_VALUE);
else
b.setV((char)(a.v() - 1));
}
};
@Override
public Procedure2<CharMember, CharMember> pred() {
return PRED;
}
private final Procedure2<CharMember, CharMember> SUCC =
new Procedure2<CharMember, CharMember>()
{
@Override
public void call(CharMember a, CharMember b) {
if (a.v() == Character.MAX_VALUE)
b.setV(Character.MIN_VALUE);
else
b.setV((char)(a.v() + 1));
}
};
@Override
public Procedure2<CharMember, CharMember> succ() {
return SUCC;
}
private final Procedure1<CharMember> MAXB =
new Procedure1<CharMember>()
{
@Override
public void call(CharMember a) {
a.setV(Character.MAX_VALUE);
}
};
@Override
public Procedure1<CharMember> maxBound() {
return MAXB;
}
private final Procedure1<CharMember> MINB =
new Procedure1<CharMember>()
{
@Override
public void call(CharMember a) {
a.setV(Character.MIN_VALUE);
}
};
@Override
public Procedure1<CharMember> minBound() {
return MINB;
}
private static Function1<Boolean,CharMember> DEF =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isDefined(ch.v());
}
};
public static Function1<Boolean,CharMember> isDefined() {
return DEF;
}
private static Function1<Boolean,CharMember> DIG =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isDigit(ch.v());
}
};
public static Function1<Boolean,CharMember> isDigit() {
return DIG;
}
private static Function1<Boolean,CharMember> HS =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isHighSurrogate(ch.v());
}
};
public static Function1<Boolean,CharMember> isHighSurrogate() {
return HS;
}
private static Function1<Boolean,CharMember> II =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isIdentifierIgnorable(ch.v());
}
};
public static Function1<Boolean,CharMember> isIdentifierIgnorable() {
return II;
}
private static Function1<Boolean,CharMember> ISOC =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isISOControl(ch.v());
}
};
public static Function1<Boolean,CharMember> isISOControl() {
return ISOC;
}
private static Function1<Boolean,CharMember> JIS =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isJavaIdentifierStart(ch.v());
}
};
public static Function1<Boolean,CharMember> isJavaIdentifierStart() {
return JIS;
}
private static Function1<Boolean,CharMember> JIP =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isJavaIdentifierPart(ch.v());
}
};
public static Function1<Boolean,CharMember> isJavaIdentifierPart() {
return JIP;
}
private static Function1<Boolean,CharMember> LET =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isLetter(ch.v());
}
};
public static Function1<Boolean,CharMember> isLetter() {
return LET;
}
private static Function1<Boolean,CharMember> LETD =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isLetterOrDigit(ch.v());
}
};
public static Function1<Boolean,CharMember> isLetterOrDigit() {
return LETD;
}
private static Function1<Boolean,CharMember> LOWER =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isLowerCase(ch.v());
}
};
public static Function1<Boolean,CharMember> isLowerCase() {
return LOWER;
}
private static Function1<Boolean,CharMember> UPPER =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isUpperCase(ch.v());
}
};
public static Function1<Boolean,CharMember> isUpperCase() {
return UPPER;
}
private static Function1<Boolean,CharMember> WS =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isWhitespace(ch.v());
}
};
public static Function1<Boolean,CharMember> isWhitespace() {
return WS;
}
private static Function1<Boolean,CharMember> TTL =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isTitleCase(ch.v());
}
};
public static Function1<Boolean,CharMember> isTitleCase() {
return TTL;
}
private static Function1<Boolean,CharMember> MIR =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isMirrored(ch.v());
}
};
public static Function1<Boolean,CharMember> isMirrored() {
return MIR;
}
private static Function1<Boolean,CharMember> SURR =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isSurrogate(ch.v());
}
};
public static Function1<Boolean,CharMember> isSurrogate() {
return SURR;
}
private static Function2<Boolean,CharMember,CharMember> SURRP =
new Function2<Boolean, CharMember, CharMember>()
{
@Override
public Boolean call(CharMember high, CharMember low) {
return Character.isSurrogatePair(high.v(), low.v());
}
};
public static Function2<Boolean,CharMember,CharMember> isSurrogatePair() {
return SURRP;
}
private static Function1<Boolean,CharMember> LSURR =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isLowSurrogate(ch.v());
}
};
public static Function1<Boolean,CharMember> isLowSurrogate() {
return LSURR;
}
private static Function1<Boolean,CharMember> UIP =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isUnicodeIdentifierPart(ch.v());
}
};
public static Function1<Boolean,CharMember> isUnicodeIdentifierPart() {
return UIP;
}
private static Function1<Boolean,CharMember> UIS =
new Function1<Boolean, CharMember>()
{
@Override
public Boolean call(CharMember ch) {
return Character.isUnicodeIdentifierStart(ch.v());
}
};
public static Function1<Boolean,CharMember> isUnicodeIdentifierStart() {
return UIS;
}
}
|
package to.etc.domui.component.lookup;
import java.util.*;
import javax.annotation.*;
import to.etc.domui.component.buttons.*;
import to.etc.domui.component.controlfactory.*;
import to.etc.domui.component.input.*;
import to.etc.domui.component.layout.*;
import to.etc.domui.component.lookup.ILookupControlInstance.AppendCriteriaResult;
import to.etc.domui.component.meta.*;
import to.etc.domui.component.meta.impl.*;
import to.etc.domui.dom.css.*;
import to.etc.domui.dom.html.*;
import to.etc.domui.server.*;
import to.etc.domui.util.*;
import to.etc.webapp.*;
import to.etc.webapp.query.*;
public class LookupForm<T> extends Div {
/** The data class we're looking for */
@Nonnull
private Class<T> m_lookupClass;
/** The metamodel for the class. */
@Nonnull
private ClassMetaModel m_metaModel;
private String m_title;
IClicked<LookupForm<T>> m_clicker;
private IClicked<LookupForm<T>> m_onNew;
private DefaultButton m_newBtn;
private IClicked< ? extends LookupForm<T>> m_onClear;
private IClicked<LookupForm<T>> m_onCancel;
private DefaultButton m_cancelBtn;
private DefaultButton m_collapseButton;
private Table m_table;
private TBody m_tbody;
private Div m_content;
private NodeContainer m_collapsedPanel;
private NodeContainer m_buttonRow;
private ControlBuilder m_builder;
/**
* T in case that control is rendered as collapsed (meaning that search panel is hidden).
* It is usually used when lookup form have to popup with initial search results already shown.
*/
private boolean m_collapsed;
/**
* Calculated by entered search criterias, T in case that exists any field resulting with {@link AppendCriteriaResult#VALID} in LookupForm fields.
*/
private boolean m_hasUserDefinedCriteria;
/**
* After restore action on LookupForm.
*/
private IClicked<NodeBase> m_onAfterRestore;
/**
* After collpase action on LookupForm.
*/
private IClicked<NodeBase> m_onAfterCollapse;
private IQueryFactory<T> m_queryFactory;
public static class Item implements SearchPropertyMetaModel {
enum InputBehaviorType {
/**
* Unchanged behavior.
*/
DEFAULT,
/**
* Force all input controls for certain lookup field to become enabled for user input.
*/
FORCE_ENABLED,
/**
* Force all input controls for certain lookup field to become disabled for user input.
*/
FORCE_DISABLED;
}
private String m_propertyName;
private List<PropertyMetaModel< ? >> m_propertyPath;
private ILookupControlInstance m_instance;
private boolean m_ignoreCase = true;
private int m_minLength;
private String m_labelText;
private String m_lookupHint;
private String m_errorLocation;
private int m_order;
private String testId;
private InputBehaviorType m_inputsBehavior = InputBehaviorType.DEFAULT;
@Override
public String getPropertyName() {
return m_propertyName;
}
public void setPropertyName(String propertyName) {
m_propertyName = propertyName;
}
@Override
public List<PropertyMetaModel< ? >> getPropertyPath() {
return m_propertyPath;
}
public void setPropertyPath(List<PropertyMetaModel< ? >> propertyPath) {
m_propertyPath = propertyPath;
}
public PropertyMetaModel< ? > getLastProperty() {
if(m_propertyPath == null || m_propertyPath.size() == 0)
return null;
return m_propertyPath.get(m_propertyPath.size() - 1);
}
@Override
public boolean isIgnoreCase() {
return m_ignoreCase;
}
public void setIgnoreCase(boolean ignoreCase) {
m_ignoreCase = ignoreCase;
}
@Override
public int getMinLength() {
return m_minLength;
}
public void setMinLength(int minLength) {
m_minLength = minLength;
}
public String getLabelText() {
return m_labelText;
}
public void setLabelText(String labelText) {
m_labelText = labelText;
}
@Override
public String getLookupLabel() {
return m_labelText;
}
public String getErrorLocation() {
return m_errorLocation;
}
public void setErrorLocation(String errorLocation) {
m_errorLocation = errorLocation;
}
ILookupControlInstance getInstance() {
return m_instance;
}
void setInstance(ILookupControlInstance instance) {
m_instance = instance;
}
/**
* Unused; only present to satisfy the interface.
* @see to.etc.domui.component.meta.SearchPropertyMetaModel#getOrder()
*/
@Override
public int getOrder() {
return m_order;
}
void setOrder(int order) {
m_order = order;
}
@Override
public String getLookupHint() {
return m_lookupHint;
}
public void setLookupHint(String lookupHint) {
m_lookupHint = lookupHint;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Item:");
if(m_propertyName != null) {
sb.append(" property: ");
sb.append(m_propertyName);
}
if(m_labelText != null) {
sb.append(" label: ");
sb.append(m_labelText);
}
return sb.toString();
}
public String getTestId() {
return testId;
}
public void setTestId(String testId) {
this.testId = testId;
}
public void setDisabled(boolean disabled) {
m_inputsBehavior = disabled ? InputBehaviorType.FORCE_DISABLED : InputBehaviorType.FORCE_ENABLED;
m_instance.setDisabled(disabled);
}
public boolean isForcedDisabled() {
return m_inputsBehavior == InputBehaviorType.FORCE_DISABLED;
}
public boolean isForcedEnabled() {
return m_inputsBehavior == InputBehaviorType.FORCE_ENABLED;
}
public void clear() {
m_instance.clearInput();
}
}
/**
* Sets rendering of search fields into two columns. It is in use only in case when search fields are loaded from metadata and loaded items count is bigger then one specified in m_twoColumnsModeMinimalItems.
*/
private boolean m_twoColumnsMode;
/**
* Minimal number of items that would cause two column rendering. Always set with m_twoColumnsMode.
*/
private int m_minSizeForTwoColumnsMode;
static private class ItemBreak extends Item {
public ItemBreak() {}
}
/** The primary list of defined lookup items. */
private List<Item> m_itemList = new ArrayList<Item>(20);
static public enum ButtonMode {
/** Show this button only when the lookup form is expanded */
NORMAL,
/** Show this button only when the lookup form is collapsed */
COLLAPSED,
/** Always show this button. */
BOTH
}
private static class ButtonRowItem {
private int m_order;
private ButtonMode m_mode;
private NodeBase m_thingy;
public ButtonRowItem(int order, ButtonMode mode, NodeBase thingy) {
m_order = order;
m_mode = mode;
m_thingy = thingy;
}
public ButtonMode getMode() {
return m_mode;
}
public int getOrder() {
return m_order;
}
public NodeBase getThingy() {
return m_thingy;
}
}
/** The list of buttons to show on the button row. */
private List<ButtonRowItem> m_buttonItemList = Collections.EMPTY_LIST;
public LookupForm(@Nonnull final Class<T> lookupClass, String... propertyList) {
this(lookupClass, (ClassMetaModel) null, propertyList);
}
/**
* Create a LookupForm to find instances of the specified class.
* @param lookupClass
*/
public LookupForm(@Nonnull final Class<T> lookupClass, @Nullable final ClassMetaModel cmm, String... propertyList) {
m_lookupClass = lookupClass;
m_metaModel = cmm != null ? cmm : MetaManager.findClassMeta(lookupClass);
m_builder = DomApplication.get().getControlBuilder();
for(String prop : propertyList)
addProperty(prop);
defineDefaultButtons();
}
/**
* Return the metamodel that this class uses to get it's data from.
* @return
*/
@Nonnull
public ClassMetaModel getMetaModel() {
return m_metaModel;
}
/**
* Returns the class whose instances we're looking up (a persistent class somehow).
* @return
*/
@Nonnull
public Class<T> getLookupClass() {
if(null == m_lookupClass)
throw new NullPointerException("The LookupForm's 'lookupClass' cannot be null");
return m_lookupClass;
}
/**
* Actually show the thingy.
* @see to.etc.domui.dom.html.NodeBase#createContent()
*/
@Override
public void createContent() throws Exception {
//-- If a page title is present render the search block in a CaptionedPanel, else present in it;s own div.
Div sroot = new Div();
sroot.setCssClass("ui-lf-mainContent");
if(getPageTitle() != null) {
CaptionedPanel cp = new CaptionedPanel(getPageTitle(), sroot);
add(cp);
m_content = cp;
} else {
add(sroot);
m_content = sroot;
}
//-- Ok, we need the items we're going to show now.
if(m_itemList.size() == 0) // If we don't have an item set yet....
setItems(); // ..define it from metadata, and abort if there is nothing there
NodeContainer searchContainer = sroot;
if(containsItemBreaks(m_itemList)) {
Table searchRootTable = new Table();
searchRootTable.setCssClass("ui-lf-multi");
sroot.add(searchRootTable);
TBody searchRootTableBody = new TBody();
searchRootTable.add(searchRootTableBody);
TR searchRootRow = new TR();
searchRootTableBody.add(searchRootRow);
TD searchRootCell = new TD();
searchRootCell.setValign(TableVAlign.TOP);
searchRootRow.add(searchRootCell);
searchContainer = searchRootCell;
}
//-- Walk all search fields
m_table = new Table();
m_table.setCssClass("ui-lf-st");
searchContainer.add(m_table);
m_tbody = new TBody();
m_tbody.setTestID("tableBodyLookupForm");
m_table.add(m_tbody);
//-- Start populating the lookup form with lookup items.
for(Item it : m_itemList) {
if(it instanceof ItemBreak) {
TD anotherSearchRootCell = new TD();
anotherSearchRootCell.setValign(TableVAlign.TOP);
searchContainer.appendAfterMe(anotherSearchRootCell);
searchContainer = anotherSearchRootCell;
m_table = new Table();
m_table.setCssClass("ui-lf-st");
searchContainer.add(m_table);
m_tbody = new TBody();
m_tbody.setTestID("tableBodyLookupForm");
m_table.add(m_tbody);
} else {
internalAddLookupItem(it);
}
}
//-- The button bar.
Div d = new Div();
d.setTestID("buttonBar");
d.setCssClass("ui-lf-ebb");
sroot.add(d);
m_buttonRow = d;
//20091127 vmijic - since LookupForm can be reused each new rebuild should execute restore if previous state of form was collapsed.
//20100118 vmijic - since LookupForm can be by default rendered as collapsed check for m_collapsed is added.
if(!m_collapsed && m_collapsedPanel != null) {
restore();
} else if(m_collapsed && m_content.getDisplay() != DisplayType.NONE) {
collapse();
//Focus must be set, otherwise IE reports javascript problem since focus is requested on not displayed input tag.
if(m_cancelBtn != null) {
m_cancelBtn.setFocus();
} else if(m_collapseButton != null) {
m_collapseButton.setFocus();
}
} else {
createButtonRow(d, false);
}
//-- Add a RETURN PRESSED handler to allow pressing RETURN on search fields.
setReturnPressed(new IReturnPressed() {
@Override
public void returnPressed(final Div node) throws Exception {
if(m_clicker != null)
m_clicker.clicked(LookupForm.this);
}
});
}
protected void defineDefaultButtons() {
DefaultButton b = new DefaultButton(Msgs.BUNDLE.getString(Msgs.LOOKUP_FORM_SEARCH));
b.setIcon("THEME/btnFind.png");
b.setTestID("searchButton");
b.setClicked(new IClicked<NodeBase>() {
@Override
public void clicked(final NodeBase bx) throws Exception {
if(m_clicker != null)
m_clicker.clicked(LookupForm.this);
}
});
addButtonItem(b, 100, ButtonMode.NORMAL);
b = new DefaultButton(Msgs.BUNDLE.getString(Msgs.LOOKUP_FORM_CLEAR));
b.setIcon("THEME/btnClear.png");
b.setTestID("clearButton");
b.setClicked(new IClicked<NodeBase>() {
@Override
public void clicked(final NodeBase xb) throws Exception {
clearInput();
if(getOnClear() != null)
((IClicked<LookupForm<T>>) getOnClear()).clicked(LookupForm.this); // FIXME Another generics snafu, fix.
}
});
addButtonItem(b, 200, ButtonMode.NORMAL);
//-- Collapse button thingy
m_collapseButton = new DefaultButton(Msgs.BUNDLE.getString(Msgs.LOOKUP_FORM_COLLAPSE), "THEME/btnHideLookup.png", new IClicked<DefaultButton>() {
@Override
public void clicked(DefaultButton bx) throws Exception {
collapse();
}
});
m_collapseButton.setTestID("hideButton");
addButtonItem(m_collapseButton, 500, ButtonMode.BOTH);
}
private boolean containsItemBreaks(List<Item> itemList) {
for(Item item : itemList) {
if(item instanceof ItemBreak) {
return true;
}
}
return false;
}
/**
* This hides the search panel and adds a small div containing only the (optional) new and restore buttons.
* @throws Exception
*/
void collapse() throws Exception {
if((m_content.getDisplay() == DisplayType.NONE))
return;
m_content.slideUp();
m_collapsedPanel = new Div();
m_collapsedPanel.setCssClass("ui-lf-coll");
add(m_collapsedPanel);
m_collapsed = true;
//-- Collapse button thingy
m_collapseButton.setText(Msgs.BUNDLE.getString(Msgs.LOOKUP_FORM_RESTORE));
m_collapseButton.setClicked(new IClicked<DefaultButton>() {
@Override
public void clicked(DefaultButton bx) throws Exception {
restore();
}
});
createButtonRow(m_collapsedPanel, true);
//trigger after collapse event is set
if(getOnAfterCollapse() != null) {
getOnAfterCollapse().clicked(this);
}
}
void restore() throws Exception {
if(m_collapsedPanel == null)
return;
m_collapsedPanel.remove();
m_collapsedPanel = null;
createButtonRow(m_buttonRow, false);
m_collapseButton.setText(Msgs.BUNDLE.getString(Msgs.LOOKUP_FORM_COLLAPSE));
m_collapseButton.setClicked(new IClicked<DefaultButton>() {
@Override
public void clicked(DefaultButton bx) throws Exception {
collapse();
}
});
m_content.setDisplay(DisplayType.BLOCK);
m_collapsed = false;
//trigger after restore event is set
if(getOnAfterRestore() != null) {
getOnAfterRestore().clicked(this);
}
}
/* CODING: Altering/defining the lookup items. */
/**
* This adds all properties that are defined as "search" properties in either this control or the metadata
* to the item list. The list is cleared before that!
*/
private void setItems() {
m_itemList.clear();
List<SearchPropertyMetaModel> list = getMetaModel().getSearchProperties();
if(list == null || list.size() == 0) {
list = MetaManager.calculateSearchProperties(getMetaModel()); // 20100416 jal EXPERIMENTAL
if(list == null || list.size() == 0)
throw new IllegalStateException(getMetaModel() + " has no search properties defined in it's meta data.");
}
setSearchProperties(list);
}
/**
* Set the search properties to use from a list of metadata properties.
* @param list
*/
public void setSearchProperties(List<SearchPropertyMetaModel> list) {
int totalCount = list.size();
for(SearchPropertyMetaModel sp : list) { // The list is already in ascending order, so just add items;
Item it = new Item();
it.setIgnoreCase(sp.isIgnoreCase());
it.setMinLength(sp.getMinLength());
it.setPropertyName(sp.getPropertyName());
it.setPropertyPath(sp.getPropertyPath());
it.setLabelText(sp.getLookupLabel()); // If a lookup label is defined use it.
it.setLookupHint(sp.getLookupHint()); // If a lookup hint is defined use it.
addAndFinish(it);
if(m_twoColumnsMode && (totalCount >= m_minSizeForTwoColumnsMode) && m_itemList.size() == (totalCount + 1) / 2) {
m_itemList.add(new ItemBreak());
}
}
}
/**
* Add a property to look up to the list. The controls et al will be added using the factories.
* @param path The property name (or path to some PARENT property) to search on, relative to the lookup class.
* @param minlen
* @param ignorecase
*/
public Item addProperty(String path, int minlen, boolean ignorecase) {
return addProperty(path, null, minlen, Boolean.valueOf(ignorecase));
}
/**
* Add a property to look up to the list. The controls et al will be added using the factories.
* @param path The property name (or path to some PARENT property) to search on, relative to the lookup class.
* @param minlen
*/
public Item addProperty(String path, int minlen) {
return addProperty(path, null, minlen, null);
}
/**
* Add a property to look up to the list with user-specified label. The controls et al will be added using the factories.
* @param path The property name (or path to some PARENT property) to search on, relative to the lookup class.
* @param label The label text to use. Use the empty string to prevent a label from being generated. This still adds an empty cell for the label though.
*/
public Item addProperty(String path, String label) {
return addProperty(path, label, 0, null);
}
/**
* Add a property to look up to the list. The controls et al will be added using the factories.
* @param path The property name (or path to some PARENT property) to search on, relative to the lookup class.
*/
public Item addProperty(String path) {
return addProperty(path, null, 0, null);
}
/**
* Add a property manually.
* @param path The property name (or path to some PARENT property) to search on, relative to the lookup class.
* @param minlen
* @param ignorecase
*/
private Item addProperty(String path, String label, int minlen, Boolean ignorecase) {
for(Item it : m_itemList) { // FIXME Useful?
if(it.getPropertyName() != null && path.equals(it.getPropertyName())) // Already present there?
throw new ProgrammerErrorException("The property " + path + " is already part of the search field list.");
}
//-- Define the item.
Item it = new Item();
it.setPropertyName(path);
it.setLabelText(label);
it.setIgnoreCase(ignorecase == null ? true : ignorecase.booleanValue());
it.setMinLength(minlen);
addAndFinish(it);
return it;
}
public void addItemBreak() {
ItemBreak itemBreak = new ItemBreak();
m_itemList.add(itemBreak);
}
/**
* Add a manually-created lookup control instance to the item list.
* @return
*/
public Item addManual(ILookupControlInstance lci) {
Item it = new Item();
it.setInstance(lci);
addAndFinish(it);
return it;
}
/**
* Add a manually created control and link it to some property. The controls's configuration must be fully
* done by the caller; this will ask control factories to provide an ILookupControlInstance for the property
* and control passed in. The label for the lookup will come from property metadata.
*
* @param <X>
* @param property
* @param control
* @return
*/
public <VT, X extends NodeBase & IControl<VT>> Item addManual(String property, X control) {
Item it = new Item();
it.setPropertyName(property);
addAndFinish(it);
//-- Add the generic thingy
ILookupControlFactory lcf = m_builder.getLookupQueryFactory(it, control);
ILookupControlInstance qt = lcf.createControl(it, control);
if(qt == null || qt.getInputControls() == null || qt.getInputControls().length == 0)
throw new IllegalStateException("Lookup factory " + lcf + " did not link thenlookup thingy for property " + it.getPropertyName());
it.setInstance(qt);
return it;
}
/**
* Add a manually-created lookup control instance with user-specified label to the item list.
* @return
*/
public Item addManualTextLabel(String labelText, ILookupControlInstance lci) {
Item it = new Item();
it.setInstance(lci);
it.setLabelText(labelText);
addAndFinish(it);
return it;
}
/**
* Adds a manually-defined control, and use the specified property as the source for it's default label.
* @param property
* @param lci
* @return
*/
public Item addManualPropertyLabel(String property, ILookupControlInstance lci) {
PropertyMetaModel< ? > pmm = getMetaModel().findProperty(property);
if(null == pmm)
throw new ProgrammerErrorException(property + ": undefined property for class=" + getLookupClass());
return addManualTextLabel(pmm.getDefaultLabel(), lci);
}
public Item addChildProperty(String propPath) {
return addChildPropertyLabel(null, propPath);
}
public Item addChildPropertyLabel(String label, String propPath) {
final List<PropertyMetaModel< ? >> pl = MetaManager.parsePropertyPath(m_metaModel, propPath);
if(pl.size() != 2) {
throw new ProgrammerErrorException("Property path does not contain parent.child path: " + propPath);
}
final PropertyMetaModel< ? > parentPmm = pl.get(0);
final PropertyMetaModel< ? > childPmm = pl.get(1);
SearchPropertyMetaModelImpl spmm = new SearchPropertyMetaModelImpl(m_metaModel);
spmm.setPropertyName(childPmm.getName());
spmm.setPropertyPath(pl);
ILookupControlFactory lcf = m_builder.getLookupControlFactory(spmm);
final ILookupControlInstance lookupInstance = lcf.createControl(spmm, null);
AbstractLookupControlImpl thingy = new AbstractLookupControlImpl(lookupInstance.getInputControls()) {
@Override
public AppendCriteriaResult appendCriteria(QCriteria< ? > crit) throws Exception {
QCriteria< ? > r = QCriteria.create(childPmm.getClassModel().getActualClass());
AppendCriteriaResult subRes = lookupInstance.appendCriteria(r);
if(subRes == AppendCriteriaResult.INVALID) {
return subRes;
} else if(r.hasRestrictions()) {
QRestrictor< ? > exists = crit.exists(childPmm.getClassModel().getActualClass(), parentPmm.getName());
exists.setRestrictions(r.getRestrictions());
return AppendCriteriaResult.VALID;
} else {
return AppendCriteriaResult.EMPTY;
}
}
@Override
public void clearInput() {
lookupInstance.clearInput();
}
};
return this.addManualTextLabel(label == null ? parentPmm.getDefaultLabel() : label, thingy);
}
/**
* Clear out the entire definition for this lookup form. After this it needs to be recreated completely.
*/
public void reset() {
forceRebuild();
m_itemList.clear();
}
/* CODING: Internal. */
/**
* This adds the item to the item list, and tries to resolve all of the stuff needed to display
* the item. This means that the default label and the hint are calculated if missing, and that
* the lookup property is resolved if needed etc.
*/
private void addAndFinish(Item it) {
m_itemList.add(it);
//-- 1. If a property name is present but the path is unknown calculate the path
if(it.getPropertyPath() == null && it.getPropertyName() != null && it.getPropertyName().length() > 0) {
List<PropertyMetaModel< ? >> pl = MetaManager.parsePropertyPath(getMetaModel(), it.getPropertyName());
if(pl.size() == 0)
throw new ProgrammerErrorException("Unknown/unresolvable lookup property " + it.getPropertyName() + " on class=" + getLookupClass());
it.setPropertyPath(pl);
}
//-- 2. Calculate/determine a label text if empty from metadata, else ignore
PropertyMetaModel< ? > pmm = MetaUtils.findLastProperty(it); // Try to get metamodel
if(it.getLabelText() == null) {
if(pmm == null)
it.setLabelText(it.getPropertyName()); // Last resort: default to property name if available
else
it.setLabelText(pmm.getDefaultLabel());
}
//-- 3. Calculate a default hint
if(it.getLookupHint() == null) {
if(pmm != null)
it.setLookupHint(pmm.getDefaultHint());
}
//-- 4. Set an errorLocation
if(it.getErrorLocation() == null) {
it.setErrorLocation(it.getLabelText());
}
}
/**
* Create the lookup item, depending on it's kind.
* @param it
*/
private void internalAddLookupItem(Item it) {
if(it.getInstance() == null) {
//-- Create everything using a control creation factory,
ILookupControlInstance lci = createControlFor(it);
if(lci == null)
return;
it.setInstance(lci);
}
if(it.getInstance() == null)
throw new IllegalStateException("No idea how to create a lookup control for " + it);
//-- Assign error locations to all input controls
if(!DomUtil.isBlank(it.getErrorLocation()) ) {
for(NodeBase ic : it.getInstance().getInputControls())
ic.setErrorLocation(it.getErrorLocation());
}
if(it.isForcedDisabled()) {
it.getInstance().setDisabled(true);
} else if(it.isForcedEnabled()) {
it.getInstance().setDisabled(false);
}
//-- Assign test id. If single control is created, testId as it is will be applied,
// if multiple component control is created, testId with suffix number will be applied.
if(!DomUtil.isBlank(it.getTestId())) {
if(it.getInstance().getInputControls().length == 1) {
it.getInstance().getInputControls()[0].setTestID(it.getTestId());
} else if(it.getInstance().getInputControls().length > 1) {
int controlCounter = 1;
for(NodeBase ic : it.getInstance().getInputControls()) {
ic.setTestID(it.getTestId() + "_" + controlCounter);
controlCounter++;
}
}
}
addItemToTable(it); // Create visuals.
}
/**
* Add the visual representation of the item: add a row with a cell containing a label
* and another cell containing the lookup controls. This tries all the myriad ways of
* getting the label for the control.
*
* @param it The fully completed item definition to add.
*/
private void addItemToTable(Item it) {
ILookupControlInstance qt = it.getInstance();
//-- Create control && label cells,
TR tr = new TR();
m_tbody.add(tr);
TD lcell = new TD(); // Label cell
tr.add(lcell);
lcell.setCssClass("ui-f-lbl");
TD ccell = new TD(); // Control cell
tr.add(ccell);
ccell.setCssClass("ui-f-in");
//-- Now add the controls and shtuff..
NodeBase labelcontrol = qt.getLabelControl();
for(NodeBase b : qt.getInputControls()) { // Add all nodes && try to find label control if unknown.
ccell.add(b);
if(labelcontrol == null && b instanceof IControl< ? >)
labelcontrol = b;
}
if(labelcontrol == null)
labelcontrol = qt.getInputControls()[0];
//-- Finally: add the label
if(it.getLabelText() != null && it.getLabelText().length() > 0) {
Label l = new Label(labelcontrol, it.getLabelText());
// if(l.getForNode() == null)
// l.setForNode(labelcontrol);
lcell.add(l);
}
}
/**
* Create the optimal control using metadata for a property. This can only be called for an item
* containing a property with metadata.
*
* @param container
* @param name
* @param pmm
* @return
*/
private ILookupControlInstance createControlFor(Item it) {
PropertyMetaModel< ? > pmm = it.getLastProperty();
if(pmm == null)
throw new IllegalStateException("property cannot be null when creating using factory.");
ILookupControlFactory lcf = m_builder.getLookupControlFactory(it);
ILookupControlInstance qt = lcf.createControl(it, null);
if(qt == null || qt.getInputControls() == null || qt.getInputControls().length == 0)
throw new IllegalStateException("Lookup factory " + lcf + " did not create a lookup thingy for property " + it.getPropertyName());
return qt;
}
/**
* This checks all of the search fields for data. For every field that contains search
* data we check if the data is suitable for searching (not too short for instance); if
* it is we report errors. If the data is suitable <b>and</b> at least one field is filled
* we create a Criteria containing the search criteria.
*
* If anything goes wrong (one of the above mentioned errors occurs) ths returns null.
* If none of the input fields have data this will return a Criteria object, but the
* restrictions count in it will be zero. This can be used to query but will return all
* records.
*
* <h2>Internal working</h2>
* <p>Internally this just walks the list of thingies added when the components were added
* to the form. Each thingy refers to the input components used to register the search on a
* property, and knows how to convert that thingy to a criteria fragment.
* </p>
*
* @return
*/
public QCriteria<T> getEnteredCriteria() throws Exception {
m_hasUserDefinedCriteria = false;
QCriteria<T> root;
if(getQueryFactory() != null) {
root = getQueryFactory().createQuery();
} else {
root = (QCriteria<T>) getMetaModel().createCriteria();
}
boolean success = true;
for(Item it : m_itemList) {
ILookupControlInstance li = it.getInstance();
if(li != null) { // FIXME Is it reasonable to allow null here?? Should we not abort?
AppendCriteriaResult res = li.appendCriteria(root);
if(res == AppendCriteriaResult.INVALID) {
success = false;
} else if(res == AppendCriteriaResult.VALID) {
m_hasUserDefinedCriteria = true;
}
}
}
if(!success) { // Some input failed to validate their input criteria?
m_hasUserDefinedCriteria = false;
return null; // Then exit null -> should only display errors.
}
return root;
}
/* CODING: Silly and small methods. */
/**
* Tells all input items to clear their content, clearing all user choices from the form. After
* this call, the form should return an empty QCriteria without any restrictions.
*/
public void clearInput() {
for(Item it : m_itemList) {
if(it.getInstance() != null)
it.getInstance().clearInput();
}
}
/**
* Sets the onNew handler. When set this will render a "new" button in the form's button bar.
* @return
*/
public IClicked<LookupForm<T>> getOnNew() {
return m_onNew;
}
/**
* Returns the onNew handler. When set this will render a "new" button in the form's button bar.
* @param onNew
*/
public void setOnNew(final IClicked<LookupForm<T>> onNew) {
if(m_onNew != onNew) {
m_onNew = onNew;
if(m_onNew != null && m_newBtn == null) {
m_newBtn = new DefaultButton(Msgs.BUNDLE.getString(Msgs.LOOKUP_FORM_NEW));
m_newBtn.setIcon("THEME/btnNew.png");
m_newBtn.setTestID("newButton");
m_newBtn.setClicked(new IClicked<NodeBase>() {
@Override
public void clicked(final NodeBase xb) throws Exception {
if(getOnNew() != null) {
getOnNew().clicked(LookupForm.this);
}
}
});
addButtonItem(m_newBtn, 300, ButtonMode.BOTH);
} else if(m_onNew == null && m_newBtn != null) {
for(ButtonRowItem bri : m_buttonItemList) {
if(bri.getThingy() == m_newBtn) {
m_buttonItemList.remove(bri);
break;
}
}
m_newBtn = null;
}
forceRebuild();
}
}
/**
* Returns the search block's part title, if present. Returns null if the title is not set.
*/
public String getPageTitle() {
return m_title;
}
/**
* Sets a part title for this search block. When unset the search block does not have a title, when set
* the search block will be shown inside a CaptionedPanel.
* @param title
*/
public void setPageTitle(final String title) {
m_title = title;
}
/**
* Set the handler to call when the "Search" button is clicked.
* @see to.etc.domui.dom.html.NodeBase#setClicked(to.etc.domui.dom.html.IClicked)
*/
@Override
public void setClicked(final @Nullable IClickBase< ? > clicked) {
m_clicker = (IClicked<LookupForm<T>>) clicked;
}
public IClicked<LookupForm<T>> getSearchClicked() {
return m_clicker;
}
public IClicked< ? extends LookupForm<T>> getOnClear() {
return m_onClear;
}
/**
* Listener to call when the "clear" button is pressed.
* @param onClear
*/
public void setOnClear(IClicked< ? extends LookupForm<T>> onClear) {
m_onClear = onClear;
}
/**
* When set, this causes a "cancel" button to be added to the form. When that button is pressed this handler gets called.
* @param onCancel
*/
public void setOnCancel(IClicked<LookupForm<T>> onCancel) {
if(m_onCancel != onCancel) {
m_onCancel = onCancel;
if(m_onCancel != null && m_cancelBtn == null) {
m_cancelBtn = new DefaultButton(Msgs.BUNDLE.getString(Msgs.LOOKUP_FORM_CANCEL));
m_cancelBtn.setIcon("THEME/btnCancel.png");
m_cancelBtn.setTestID("cancelButton");
m_cancelBtn.setClicked(new IClicked<NodeBase>() {
@Override
public void clicked(final NodeBase xb) throws Exception {
if(getOnCancel() != null) {
getOnCancel().clicked(LookupForm.this);
}
}
});
addButtonItem(m_cancelBtn, 400, ButtonMode.BOTH);
} else if(m_onCancel == null && m_cancelBtn != null) {
for(ButtonRowItem bri : m_buttonItemList) {
if(bri.getThingy() == m_cancelBtn) {
m_buttonItemList.remove(bri);
break;
}
}
m_cancelBtn = null;
}
forceRebuild();
}
}
public IClicked<LookupForm<T>> getOnCancel() {
return m_onCancel;
}
/* CODING: Button row code. */
public void addButtonItem(NodeBase b) {
addButtonItem(b, m_buttonItemList.size(), ButtonMode.BOTH);
}
/**
* Add a button (or other item) to show on the button row. The item will
* be visible always.
* @param b
* @param order
*/
public void addButtonItem(NodeBase b, int order) {
addButtonItem(b, order, ButtonMode.BOTH);
}
/**
* Add a button (or other item) to show on the button row.
*
* @param b
* @param order
* @param both
*/
public void addButtonItem(NodeBase b, int order, ButtonMode both) {
if(m_buttonItemList == Collections.EMPTY_LIST)
m_buttonItemList = new ArrayList<ButtonRowItem>(10);
m_buttonItemList.add(new ButtonRowItem(order, both, b));
}
/**
* Add all buttons, both default and custom to buttom row.
* @param c
* @param iscollapsed
*/
private void createButtonRow(NodeContainer c, boolean iscollapsed) {
Collections.sort(m_buttonItemList, new Comparator<ButtonRowItem>() { // Sort in ascending order,
@Override
public int compare(ButtonRowItem o1, ButtonRowItem o2) {
return o1.getOrder() - o2.getOrder();
}
});
for(ButtonRowItem bi : m_buttonItemList) {
if((iscollapsed && (bi.getMode() == ButtonMode.BOTH || bi.getMode() == ButtonMode.COLLAPSED)) || (!iscollapsed && (bi.getMode() == ButtonMode.BOTH || bi.getMode() == ButtonMode.NORMAL))) {
c.add(bi.getThingy());
}
}
}
/**
* Sets rendering of search fields into two columns. It is in use only in case when search fields are loaded from metadata and search fields count reach minSizeForTwoColumnsMode value.
* @param minSizeForTwoColumnsMode
*/
public void setTwoColumnsMode(int minSizeForTwoColumnsMode) {
m_twoColumnsMode = true;
m_minSizeForTwoColumnsMode = minSizeForTwoColumnsMode;
}
/**
* Method {@link LookupForm#getEnteredCriteria} MUST BE EXECUTED BEFORE checking for this property value!
* This is T when the user has actually entered something in one of the search components. Any restriction
* that has been added by code that is not depending on user input is ignored.
* @return
*/
public boolean hasUserDefinedCriteria() {
return m_hasUserDefinedCriteria;
}
/**
* Returns if LookupForm is collapsed.
* See {@link Lookuporm#m_collapsed}.
*
* @return
*/
public boolean isCollapsed() {
return m_collapsed;
}
/**
* Use to collapse/restore LookupForm search pannel.
* See {@link Lookuporm#m_collapsed}.
*
* @param collapsed
* @throws Exception
*/
public void setCollapsed(boolean collapsed) throws Exception {
if(m_collapsed == collapsed)
return;
if(!isBuilt()) {
m_collapsed = collapsed;
return;
}
if(isBuilt()) {
if(collapsed) {
collapse();
} else {
restore();
}
}
}
/**
* Returns listener to after restore event.
*
* @return the onAfterRestore
*/
public IClicked<NodeBase> getOnAfterRestore() {
return m_onAfterRestore;
}
/**
* Attach listener to after restore event.
*
* @param onAfterRestore the onAfterRestore to set
*/
public void setOnAfterRestore(IClicked<NodeBase> onAfterRestore) {
m_onAfterRestore = onAfterRestore;
}
/**
* Returns listener to after collapse event.
*
* @return the onAfterCollpase
*/
public IClicked<NodeBase> getOnAfterCollapse() {
return m_onAfterCollapse;
}
/**
* Attach listener to after collpase event.
*
* @param onAfterCollapse the onAfterCollapse to set
*/
public void setOnAfterCollapse(IClicked<NodeBase> onAfterCollapse) {
m_onAfterCollapse = onAfterCollapse;
}
/**
* Returns custom query factory.
* @return
*/
public IQueryFactory<T> getQueryFactory() {
return m_queryFactory;
}
/**
* Specifies custom query factory.
* @param queryFactory
*/
public void setQueryFactory(IQueryFactory<T> queryFactory) {
m_queryFactory = queryFactory;
}
}
|
package org.bouncycastle.asn1.x9;
import java.math.BigInteger;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.math.ec.ECAlgorithms;
import org.bouncycastle.math.ec.ECCurve;
/**
* ASN.1 def for Elliptic-Curve Curve structure. See
* X9.62, for further details.
*/
public class X9Curve
extends ASN1Object
implements X9ObjectIdentifiers
{
private ECCurve curve;
private byte[] seed;
private ASN1ObjectIdentifier fieldIdentifier = null;
public X9Curve(
ECCurve curve)
{
this.curve = curve;
this.seed = null;
setFieldIdentifier();
}
public X9Curve(
ECCurve curve,
byte[] seed)
{
this.curve = curve;
this.seed = seed;
setFieldIdentifier();
}
public X9Curve(
X9FieldID fieldID,
BigInteger order,
BigInteger cofactor,
ASN1Sequence seq)
{
fieldIdentifier = fieldID.getIdentifier();
if (fieldIdentifier.equals(prime_field))
{
BigInteger p = ((ASN1Integer)fieldID.getParameters()).getValue();
BigInteger A = new BigInteger(1, ASN1OctetString.getInstance(seq.getObjectAt(0)).getOctets());
BigInteger B = new BigInteger(1, ASN1OctetString.getInstance(seq.getObjectAt(1)).getOctets());
curve = new ECCurve.Fp(p, A, B, order, cofactor);
}
else if (fieldIdentifier.equals(characteristic_two_field))
{
// Characteristic two field
ASN1Sequence parameters = ASN1Sequence.getInstance(fieldID.getParameters());
int m = ((ASN1Integer)parameters.getObjectAt(0)).getValue().
intValue();
ASN1ObjectIdentifier representation
= (ASN1ObjectIdentifier)parameters.getObjectAt(1);
int k1 = 0;
int k2 = 0;
int k3 = 0;
if (representation.equals(tpBasis))
{
// Trinomial basis representation
k1 = ASN1Integer.getInstance(parameters.getObjectAt(2)).getValue().intValue();
}
else if (representation.equals(ppBasis))
{
// Pentanomial basis representation
ASN1Sequence pentanomial = ASN1Sequence.getInstance(parameters.getObjectAt(2));
k1 = ASN1Integer.getInstance(pentanomial.getObjectAt(0)).getValue().intValue();
k2 = ASN1Integer.getInstance(pentanomial.getObjectAt(1)).getValue().intValue();
k3 = ASN1Integer.getInstance(pentanomial.getObjectAt(2)).getValue().intValue();
}
else
{
throw new IllegalArgumentException("This type of EC basis is not implemented");
}
BigInteger A = new BigInteger(1, ASN1OctetString.getInstance(seq.getObjectAt(0)).getOctets());
BigInteger B = new BigInteger(1, ASN1OctetString.getInstance(seq.getObjectAt(1)).getOctets());
curve = new ECCurve.F2m(m, k1, k2, k3, A, B, order, cofactor);
}
else
{
throw new IllegalArgumentException("This type of ECCurve is not implemented");
}
if (seq.size() == 3)
{
seed = ((DERBitString)seq.getObjectAt(2)).getBytes();
}
}
private void setFieldIdentifier()
{
if (ECAlgorithms.isFpCurve(curve))
{
fieldIdentifier = prime_field;
}
else if (ECAlgorithms.isF2mCurve(curve))
{
fieldIdentifier = characteristic_two_field;
}
else
{
throw new IllegalArgumentException("This type of ECCurve is not implemented");
}
}
public ECCurve getCurve()
{
return curve;
}
public byte[] getSeed()
{
return seed;
}
/**
* Produce an object suitable for an ASN1OutputStream.
* <pre>
* Curve ::= SEQUENCE {
* a FieldElement,
* b FieldElement,
* seed BIT STRING OPTIONAL
* }
* </pre>
*/
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector v = new ASN1EncodableVector();
if (fieldIdentifier.equals(prime_field))
{
v.add(new X9FieldElement(curve.getA()).toASN1Primitive());
v.add(new X9FieldElement(curve.getB()).toASN1Primitive());
}
else if (fieldIdentifier.equals(characteristic_two_field))
{
v.add(new X9FieldElement(curve.getA()).toASN1Primitive());
v.add(new X9FieldElement(curve.getB()).toASN1Primitive());
}
if (seed != null)
{
v.add(new DERBitString(seed));
}
return new DERSequence(v);
}
}
|
@API(owner = "boatcraft:api", provides = "boatcraft:api:traits", apiVersion = "2.0")
package boatcraft.api.modifiers;
import cpw.mods.fml.common.API;
|
package gov.nih.nci.cagrid.data.upgrades.from1pt0.system;
import gov.nih.nci.cagrid.data.creation.DataTestCaseInfo;
import gov.nih.nci.cagrid.data.system.AddBookstoreStep;
import gov.nih.nci.cagrid.data.system.CreateCleanGlobusStep;
import gov.nih.nci.cagrid.data.system.DeployDataServiceStep;
import gov.nih.nci.cagrid.data.system.DestroyTempGlobusStep;
import gov.nih.nci.cagrid.data.system.EnableValidationStep;
import gov.nih.nci.cagrid.data.system.InvokeDataServiceStep;
import gov.nih.nci.cagrid.data.system.RebuildServiceStep;
import gov.nih.nci.cagrid.data.system.SetQueryProcessorStep;
import gov.nih.nci.cagrid.data.system.StartGlobusStep;
import gov.nih.nci.cagrid.data.system.StopGlobusStep;
import gov.nih.nci.cagrid.data.upgrades.from1pt0.UpgradeTo1pt2Tests;
import gov.nih.nci.cagrid.introduce.test.IntroduceTestConstants;
import gov.nih.nci.cagrid.introduce.test.util.GlobusHelper;
import java.io.File;
import java.util.Vector;
import com.atomicobject.haste.framework.Step;
import com.atomicobject.haste.framework.Story;
/**
* UpgradedServiceSystemTest
* Tests the upgraded data service
*
* @author <A HREF="MAILTO:ervin@bmi.osu.edu">David W. Ervin</A> *
* @created Feb 21, 2007
* @version $Id: UpgradedServiceSystemTest.java,v 1.8 2007-10-02 14:39:10 hastings Exp $
*/
public class UpgradedServiceSystemTest extends Story {
public static final String INTRODUCE_DIR_PROPERTY = "introduce.base.dir";
private static GlobusHelper globusHelper =
new GlobusHelper(false,
new File(IntroduceTestConstants.TEST_TEMP), IntroduceTestConstants.TEST_PORT + 5);
public String getName() {
return "Data Service 1_0 to 1_2 Upgraded System Tests";
}
protected boolean storySetUp() {
assertFalse("Globus should NOT be running yet", globusHelper.isGlobusRunning());
return true;
}
public String getDescription() {
return "Deploys and invokes the upgraded data service";
}
protected Vector steps() {
DataTestCaseInfo info = new UpgradeTo1pt2Tests.Upgrade1pt0to1pt1TestServiceInfo();
Vector steps = new Vector();
// steps to invoke the upgraded service
// by the data service creation tests
// 1) Add the bookstore schema to the data service
steps.add(new AddBookstoreStep(info));
// 2) change out query processor
steps.add(new SetQueryProcessorStep(info.getDir()));
// 3) remove anything thats not the query method
// steps.add(new RemoveNonQueryMethodsStep(info.getDir()));
// 4) Turn on query validation
steps.add(new EnableValidationStep(info.getDir()));
// 5) Rebuild the service to pick up the bookstore beans
steps.add(new RebuildServiceStep(info, getIntroduceBaseDir()));
// 6) set up a clean, temporary Globus
steps.add(new CreateCleanGlobusStep(globusHelper));
// 7) deploy data service
steps.add(new DeployDataServiceStep(globusHelper, info.getDir()));
// 8) start globus
steps.add(new StartGlobusStep(globusHelper));
// 9) test data service
steps.add(new InvokeDataServiceStep(
"localhost", IntroduceTestConstants.TEST_PORT + 5, info.getName()));
return steps;
}
protected void storyTearDown() throws Throwable {
super.storyTearDown();
// 10) stop globus
Step stopStep = new StopGlobusStep(globusHelper);
try {
stopStep.runStep();
} catch (Throwable ex) {
ex.printStackTrace();
}
// 11) throw away globus
Step destroyStep = new DestroyTempGlobusStep(globusHelper);
try {
destroyStep.runStep();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
// used to make sure that if we are going to use a junit testsuite to
// test this that the test suite will not error out
// looking for a single test......
public void testDummy() throws Throwable {
}
private String getIntroduceBaseDir() {
String dir = System.getProperty(INTRODUCE_DIR_PROPERTY);
if (dir == null) {
fail("Introduce base dir environment variable " + INTRODUCE_DIR_PROPERTY + " is required");
}
return dir;
}
}
|
package mobi.hsz.idea.gitignore.ui;
import com.intellij.icons.AllIcons;
import com.intellij.ide.CommonActionsManager;
import com.intellij.ide.DefaultTreeExpander;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.OptionAction;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiFile;
import com.intellij.ui.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import mobi.hsz.idea.gitignore.IgnoreBundle;
import mobi.hsz.idea.gitignore.command.AppendFileCommandAction;
import mobi.hsz.idea.gitignore.command.CreateFileCommandAction;
import mobi.hsz.idea.gitignore.settings.IgnoreSettings;
import mobi.hsz.idea.gitignore.util.Resources;
import mobi.hsz.idea.gitignore.util.Utils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.Set;
import static mobi.hsz.idea.gitignore.util.Resources.Template.Container.*;
/**
* {@link GeneratorDialog} responsible for displaying list of all available templates and adding selected ones
* to the specified file.
*
* @author Jakub Chrzanowski <jakub@hsz.mobi>
* @since 0.2
*/
public class GeneratorDialog extends DialogWrapper {
/** {@link FilterComponent} search history key. */
private static final String TEMPLATES_FILTER_HISTORY = "TEMPLATES_FILTER_HISTORY";
/** Star icon for the favorites action. */
private static final Icon STAR = AllIcons.Ide.Rating;
/** Cache set to store checked templates for the current action. */
private final Set<Resources.Template> checked = ContainerUtil.newHashSet();
/** Set of the starred templates. */
private final Set<String> starred = ContainerUtil.newHashSet();
/** Current working project. */
@NotNull
private final Project project;
/** Settings instance. */
@NotNull
private final IgnoreSettings settings;
/** Current working file. */
@Nullable
private PsiFile file;
/** Templates tree root node. */
@NotNull
private final TemplateTreeNode root;
/** {@link CreateFileCommandAction} action instance to generate new file in the proper time. */
@Nullable
private CreateFileCommandAction action;
/** Templates tree with checkbox feature. */
private CheckboxTree tree;
/** Tree expander responsible for expanding and collapsing tree structure. */
private DefaultTreeExpander treeExpander;
/** Dynamic templates filter. */
private FilterComponent profileFilter;
/** Preview editor with syntax highlight. */
private Editor preview;
/** {@link Document} related to the {@link Editor} feature. */
private Document previewDocument;
/**
* Builds a new instance of {@link GeneratorDialog}.
*
* @param project current working project
* @param file current working file
*/
public GeneratorDialog(@NotNull Project project, @Nullable PsiFile file) {
super(project, false);
this.project = project;
this.file = file;
this.root = new TemplateTreeNode();
this.action = null;
this.settings = IgnoreSettings.getInstance();
setTitle(IgnoreBundle.message("dialog.generator.title"));
setOKButtonText(IgnoreBundle.message("global.generate"));
setCancelButtonText(IgnoreBundle.message("global.cancel"));
init();
}
/**
* Builds a new instance of {@link GeneratorDialog}.
*
* @param project current working project
* @param action {@link CreateFileCommandAction} action instance to generate new file in the proper time
*/
public GeneratorDialog(@NotNull Project project, @Nullable CreateFileCommandAction action) {
this(project, (PsiFile) null);
this.action = action;
}
/**
* Returns component which should be focused when the dialog appears on the screen.
*
* @return component to focus
*/
@Nullable
@Override
public JComponent getPreferredFocusedComponent() {
return profileFilter;
}
@Override
protected void dispose() {
EditorFactory.getInstance().releaseEditor(preview);
super.dispose();
}
@Override
public void show() {
if (ApplicationManager.getApplication().isUnitTestMode()) {
dispose();
return;
}
super.show();
}
/**
* This method is invoked by default implementation of "OK" action. It just closes dialog
* with <code>OK_EXIT_CODE</code>. This is convenient place to override functionality of "OK" action.
* Note that the method does nothing if "OK" action isn't enabled.
*/
@Override
protected void doOKAction() {
if (isOKActionEnabled()) {
performAppendAction(false);
}
}
/**
* Performs {@link AppendFileCommandAction} action.
*
* @param ignoreDuplicates ignores duplicated rules
*/
private void performAppendAction(boolean ignoreDuplicates) {
String content = "";
for (Resources.Template template : checked) {
if (template == null) {
continue;
}
content += IgnoreBundle.message("file.templateSection", template.getName());
content += "\n" + template.getContent();
}
if (file == null && action != null) {
file = action.execute().getResultObject();
}
if (file != null && !content.isEmpty()) {
new AppendFileCommandAction(project, file, content, ignoreDuplicates).execute();
}
super.doOKAction();
}
/** Creates default actions with appended {@link OptionOkAction} instance. */
@Override
protected void createDefaultActions() {
super.createDefaultActions();
myOKAction = new OptionOkAction();
}
/**
* Factory method. It creates panel with dialog options. Options panel is located at the
* center of the dialog's content pane. The implementation can return <code>null</code>
* value. In this case there will be no options panel.
*
* @return center panel
*/
@Nullable
@Override
protected JComponent createCenterPanel() {
// general panel
final JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.setPreferredSize(new Dimension(800, 500));
// splitter panel - contains tree panel and preview component
final JBSplitter splitter = new JBSplitter(false, 0.4f);
centerPanel.add(splitter, BorderLayout.CENTER);
final JPanel treePanel = new JPanel(new BorderLayout());
previewDocument = EditorFactory.getInstance().createDocument("");
preview = Utils.createPreviewEditor(previewDocument, project, true);
splitter.setFirstComponent(treePanel);
splitter.setSecondComponent(preview.getComponent());
/* Scroll panel for the templates tree. */
JScrollPane treeScrollPanel = createTreeScrollPanel();
treePanel.add(treeScrollPanel, BorderLayout.CENTER);
final JPanel northPanel = new JPanel(new GridBagLayout());
northPanel.setBorder(IdeBorderFactory.createEmptyBorder(2, 0, 2, 0));
northPanel.add(createTreeActionsToolbarPanel(treeScrollPanel).getComponent(), new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
northPanel.add(profileFilter, new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.BASELINE_TRAILING, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
treePanel.add(northPanel, BorderLayout.NORTH);
return centerPanel;
}
/**
* Creates scroll panel with templates tree in it.
*
* @return scroll panel
*/
private JScrollPane createTreeScrollPanel() {
fillTreeData(null, true);
final TemplateTreeRenderer renderer = new TemplateTreeRenderer() {
protected String getFilter() {
return profileFilter != null ? profileFilter.getFilter() : null;
}
};
tree = new CheckboxTree(renderer, root) {
public Dimension getPreferredScrollableViewportSize() {
Dimension size = super.getPreferredScrollableViewportSize();
size = new Dimension(size.width + 10, size.height);
return size;
}
@Override
protected void onNodeStateChanged(CheckedTreeNode node) {
super.onNodeStateChanged(node);
Resources.Template template = ((TemplateTreeNode) node).getTemplate();
if (node.isChecked()) {
checked.add(template);
} else {
checked.remove(template);
}
}
};
tree.setCellRenderer(renderer);
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
UIUtil.setLineStyleAngled(tree);
TreeUtil.installActions(tree);
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
final TreePath path = getCurrentPath();
if (path != null) {
updateDescriptionPanel(path);
}
}
});
final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(tree);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
TreeUtil.expandAll(tree);
treeExpander = new DefaultTreeExpander(tree);
profileFilter = new TemplatesFilterComponent();
return scrollPane;
}
@Nullable
private TreePath getCurrentPath() {
if (tree.getSelectionPaths() != null && tree.getSelectionPaths().length == 1) {
return tree.getSelectionPaths()[0];
}
return null;
}
/**
* Creates tree toolbar panel with actions for working with templates tree.
*
* @param target templates tree
* @return action toolbar
*/
private ActionToolbar createTreeActionsToolbarPanel(@NotNull JComponent target) {
final CommonActionsManager actionManager = CommonActionsManager.getInstance();
DefaultActionGroup actions = new DefaultActionGroup();
actions.add(actionManager.createExpandAllAction(treeExpander, tree));
actions.add(actionManager.createCollapseAllAction(treeExpander, tree));
actions.add(new AnAction(IgnoreBundle.message("dialog.generator.unselectAll"), null, AllIcons.Actions.Unselectall) {
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(!checked.isEmpty());
}
@Override
public void actionPerformed(AnActionEvent e) {
checked.clear();
filterTree(profileFilter.getTextEditor().getText());
}
});
actions.add(new AnAction(IgnoreBundle.message("dialog.generator.star"), null, STAR) {
@Override
public void update(AnActionEvent e) {
final TemplateTreeNode node = getCurrentNode();
boolean disabled = node == null || USER.equals(node.getContainer()) || !node.isLeaf();
boolean unstar = node != null && STARRED.equals(node.getContainer());
final Icon icon = disabled ? IconLoader.getDisabledIcon(STAR) : (unstar ? IconLoader.getTransparentIcon(STAR) : STAR);
final String text = IgnoreBundle.message(unstar ? "dialog.generator.unstar" : "dialog.generator.star");
final Presentation presentation = e.getPresentation();
presentation.setEnabled(!disabled);
presentation.setIcon(icon);
presentation.setText(text);
}
@Override
public void actionPerformed(AnActionEvent e) {
final TemplateTreeNode node = getCurrentNode();
if (node == null) {
return;
}
final Resources.Template template = node.getTemplate();
if (template != null) {
boolean isStarred = !template.isStarred();
template.setStarred(isStarred);
refreshTree();
if (isStarred) {
starred.add(template.getName());
} else {
starred.remove(template.getName());
}
settings.setStarredTemplates(ContainerUtil.newArrayList(starred));
}
}
/**
* Returns current {@link TemplateTreeNode} node if available.
*
* @return current node
*/
@Nullable
private TemplateTreeNode getCurrentNode() {
final TreePath path = getCurrentPath();
return path == null ? null : (TemplateTreeNode) path.getLastPathComponent();
}
});
final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, true);
actionToolbar.setTargetComponent(target);
return actionToolbar;
}
/**
* Updates editor's content depending on the selected {@link TreePath}.
*
* @param path selected tree path
*/
private void updateDescriptionPanel(@NotNull TreePath path) {
final TemplateTreeNode node = (TemplateTreeNode) path.getLastPathComponent();
final Resources.Template template = node.getTemplate();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
String content = template != null ? StringUtil.replaceChar(StringUtil.notNullize(template.getContent()), '\r', '\0') : "";
previewDocument.replaceString(0, previewDocument.getTextLength(), content);
List<Pair<Integer, Integer>> pairs = getFilterRanges(profileFilter.getTextEditor().getText(), content);
highlightWords(pairs);
}
});
}
});
}
/**
* Fills templates tree with templates fetched with {@link Resources#getGitignoreTemplates()}.
*
* @param filter templates filter
* @param forceInclude force include
*/
private void fillTreeData(@Nullable String filter, boolean forceInclude) {
root.removeAllChildren();
root.setChecked(false);
for (Resources.Template.Container container : Resources.Template.Container.values()) {
TemplateTreeNode node = new TemplateTreeNode(container);
node.setChecked(false);
root.add(node);
}
List<Resources.Template> templatesList = Resources.getGitignoreTemplates();
for (Resources.Template template : templatesList) {
if (filter != null && filter.length() > 0 && !isTemplateAccepted(template, filter)) {
continue;
}
final TemplateTreeNode node = new TemplateTreeNode(template);
node.setChecked(checked.contains(template));
getGroupNode(root, template.getContainer()).add(node);
}
if (filter != null && forceInclude && root.getChildCount() == 0) {
fillTreeData(filter, false);
}
TreeUtil.sort(root, new TemplateTreeComparator());
}
/**
* Creates or gets existing group node for specified element.
*
* @param root tree root node
* @param container container type to search
* @return group node
*/
private static TemplateTreeNode getGroupNode(@NotNull TemplateTreeNode root, @NotNull Resources.Template.Container container) {
final int childCount = root.getChildCount();
for (int i = 0; i < childCount; i++) {
TemplateTreeNode child = (TemplateTreeNode) root.getChildAt(i);
if (container.equals(child.getContainer())) {
return child;
}
}
TemplateTreeNode child = new TemplateTreeNode(container);
root.add(child);
return child;
}
/**
* Finds for the filter's words in the given content and returns their positions.
*
* @param filter templates filter
* @param content templates content
* @return text ranges
*/
private List<Pair<Integer, Integer>> getFilterRanges(@NotNull String filter, @NotNull String content) {
List<Pair<Integer, Integer>> pairs = ContainerUtil.newArrayList();
content = content.toLowerCase();
for (String word : Utils.getWords(filter)) {
for (int index = content.indexOf(word); index >= 0; index = content.indexOf(word, index + 1)) {
pairs.add(Pair.create(index, index + word.length()));
}
}
return pairs;
}
/**
* Checks if given template is accepted by passed filter.
*
* @param template to check
* @param filter templates filter
* @return template is accepted
*/
private boolean isTemplateAccepted(@NotNull Resources.Template template, @NotNull String filter) {
filter = filter.toLowerCase();
if (StringUtil.containsIgnoreCase(template.getName(), filter)) {
return true;
}
boolean nameAccepted = true;
for (String word : Utils.getWords(filter)) {
if (!StringUtil.containsIgnoreCase(template.getName(), word)) {
nameAccepted = false;
}
}
List<Pair<Integer, Integer>> ranges = getFilterRanges(filter, StringUtil.notNullize(template.getContent()));
return nameAccepted || ranges.size() > 0;
}
/**
* Filters templates tree.
*
* @param filter text
*/
private void filterTree(@Nullable String filter) {
if (tree != null) {
fillTreeData(filter, true);
reloadModel();
TreeUtil.expandAll(tree);
if (tree.getSelectionPath() == null) {
TreeUtil.selectFirstNode(tree);
}
}
}
/** Refreshes current tree. */
private void refreshTree() {
filterTree(profileFilter.getTextEditor().getText());
}
/**
* Highlights given text ranges in {@link #preview} content.
*
* @param pairs text ranges
*/
private void highlightWords(@NotNull List<Pair<Integer, Integer>> pairs) {
final TextAttributes attr = new TextAttributes();
attr.setBackgroundColor(UIUtil.getTreeSelectionBackground());
attr.setForegroundColor(UIUtil.getTreeSelectionForeground());
for (Pair<Integer, Integer> pair : pairs) {
preview.getMarkupModel().addRangeHighlighter(pair.first, pair.second, 0, attr, HighlighterTargetArea.EXACT_RANGE);
}
}
/** Reloads tree model. */
private void reloadModel() {
((DefaultTreeModel) tree.getModel()).reload();
}
/**
* Returns current file.
*
* @return file
*/
@Nullable
public PsiFile getFile() {
return file;
}
/** Custom templates {@link FilterComponent}. */
private class TemplatesFilterComponent extends FilterComponent {
/** Builds a new instance of {@link TemplatesFilterComponent}. */
public TemplatesFilterComponent() {
super(TEMPLATES_FILTER_HISTORY, 10);
}
/** Filters tree using current filter's value. */
@Override
public void filter() {
filterTree(getFilter());
}
}
/** {@link OkAction} instance with additional `Generate without duplicates` action. */
protected class OptionOkAction extends OkAction implements OptionAction {
@NotNull
@Override
public Action[] getOptions() {
return new Action[]{new DialogWrapperAction(IgnoreBundle.message("global.generate.without.duplicates")) {
@Override
protected void doAction(ActionEvent e) {
performAppendAction(true);
}
}};
}
}
}
|
// This file is part of the Whiley-to-Java Compiler (wyjc).
// The Whiley-to-Java Compiler is free software; you can redistribute
// it and/or modify it under the terms of the GNU General Public
// The Whiley-to-Java Compiler is distributed in the hope that it
// You should have received a copy of the GNU General Public
package wyc.testing.tests;
import org.junit.*;
import wyc.testing.TestHarness;
public class ExtendedInvalidTests extends TestHarness {
public ExtendedInvalidTests() {
super("../../tests/ext/invalid","../../tests/ext/invalid","sysout");
}
@Ignore("Known Issue") @Test public void ConstrainedDictionary_Invalid_1_StaticTest() { verifyFailTest("ConstrainedDictionary_Invalid_1"); }
@Test public void ConstrainedInt_Invalid_1_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_1"); }
@Test public void ConstrainedInt_Invalid_10_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_10"); }
@Test public void ConstrainedInt_Invalid_11_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_11"); }
@Test public void ConstrainedInt_Invalid_12_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_12"); }
@Test public void ConstrainedInt_Invalid_2_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_2"); }
@Test public void ConstrainedInt_Invalid_3_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_3"); }
@Test public void ConstrainedInt_Invalid_4_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_4"); }
@Test public void ConstrainedInt_Invalid_5_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_5"); }
@Test public void ConstrainedInt_Invalid_6_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_6"); }
@Ignore("Issue #299") @Test public void ConstrainedInt_Invalid_7_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_7"); }
@Ignore("Known Issue") @Test public void ConstrainedInt_Invalid_8_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_8"); }
@Test public void ConstrainedInt_Invalid_9_StaticFailTest() { verifyFailTest("ConstrainedInt_Invalid_9"); }
@Test public void ConstrainedList_Invalid_1_StaticFailTest() { verifyFailTest("ConstrainedList_Invalid_1"); }
@Test public void ConstrainedList_Invalid_2_StaticFailTest() { verifyFailTest("ConstrainedList_Invalid_2"); }
@Ignore("Known Issue") @Test public void ConstrainedList_Invalid_3_StaticFailTest() { verifyFailTest("ConstrainedList_Invalid_3"); }
@Test public void ConstrainedSet_Invalid_1_StaticFailTest() { verifyFailTest("ConstrainedSet_Invalid_1"); }
@Test public void ConstrainedSet_Invalid_2_StaticFailTest() { verifyFailTest("ConstrainedSet_Invalid_2"); }
@Test public void ConstrainedSet_Invalid_3_StaticFailTest() { verifyFailTest("ConstrainedSet_Invalid_3"); }
@Test public void ConstrainedTuple_Invalid_1_StaticFailTest() { verifyFailTest("ConstrainedTuple_Invalid_1"); }
@Test public void Ensures_CompileFail_1_StaticFailTest() { verifyFailTest("Ensures_CompileFail_1"); }
@Test public void Ensures_CompileFail_3_StaticFailTest() { verifyFailTest("Ensures_CompileFail_3"); }
@Test public void Ensures_Invalid_1_StaticFailTest() { verifyFailTest("Ensures_Invalid_1"); }
@Test public void For_Invalid_1_StaticFailTest() { verifyFailTest("For_Invalid_1"); }
@Ignore("Issue #300") @Test public void For_Invalid_2_StaticFailTest() { verifyFailTest("For_Invalid_2"); }
@Ignore("Issue #300") @Test public void For_Invalid_3_StaticFailTest() { verifyFailTest("For_Invalid_3"); }
@Test public void For_Invalid_4_StaticFailTest() { verifyFailTest("For_Invalid_4"); }
@Ignore("Known Issue") @Test public void Function_CompileFail_5_StaticFailTest() { verifyFailTest("Function_CompileFail_5"); }
@Ignore("Known Issue") @Test public void Function_CompileFail_6_StaticFailTest() { verifyFailTest("Function_CompileFail_6"); }
@Test public void IntDiv_Invalid_1_StaticFailTest() { verifyFailTest("IntDiv_Invalid_1"); }
@Ignore("Known Issue") @Test public void Lambda_Invalid_1_RuntimeTest() { verifyPassTest("Lambda_Invalid_1"); }
@Test public void ListAccess_CompileFail_2_StaticFailTest() { verifyFailTest("ListAccess_CompileFail_2"); }
@Test public void ListAccess_Invalid_1_StaticFailTest() { verifyFailTest("ListAccess_Invalid_1"); }
@Test public void ListAccess_Invalid_2_StaticFailTest() { verifyFailTest("ListAccess_Invalid_2"); }
@Test public void ListAppend_Invalid_3_StaticFailTest() { verifyFailTest("ListAppend_Invalid_3"); }
@Test public void ListAppend_Invalid_4_StaticFailTest() { verifyFailTest("ListAppend_Invalid_4"); }
@Test public void ListAppend_Invalid_5_StaticFailTest() { verifyFailTest("ListAppend_Invalid_5"); }
@Test public void ListAssign_Invalid_1_StaticFailTest() { verifyFailTest("ListAssign_Invalid_1"); }
@Test public void ListAssign_Invalid_2_StaticFailTest() { verifyFailTest("ListAssign_Invalid_2"); }
@Test public void ListElemOf_Invalid_1_StaticFailTest() { verifyFailTest("ListElemOf_Invalid_1"); }
@Test public void ListEmpty_Invalid_1_StaticFailTest() { verifyFailTest("ListEmpty_Invalid_1"); }
@Test public void ListEquals_CompileFail_1_StaticFailTest() { verifyFailTest("ListEquals_CompileFail_1"); }
@Test public void ListLength_Invalid_1_StaticFailTest() { verifyFailTest("ListLength_Invalid_1"); }
@Test public void ListLength_Invalid_2_StaticFailTest() { verifyFailTest("ListLength_Invalid_2"); }
@Test public void ListLength_Invalid_3_StaticFailTest() { verifyFailTest("ListLength_Invalid_3"); }
@Ignore("Known Issue") @Test public void ListSublist_CompileFail_2_StaticFailTest() { verifyFailTest("ListSublist_CompileFail_2"); }
@Ignore("Issue #291") @Test public void ListUpdate_Invalid_1_StaticFailTest() { verifyFailTest("ListUpdate_Invalid_1"); }
@Ignore("Known Issue") @Test public void Process_Invalid_2_StaticFailTest() { verifyFailTest("Process_Invalid_2"); }
@Test public void Quantifiers_CompileFail_1_StaticFailTest() { verifyFailTest("Quantifiers_CompileFail_1"); }
@Test public void Quantifiers_CompileFail_2_StaticFailTest() { verifyFailTest("Quantifiers_CompileFail_2"); }
@Test public void Quantifiers_CompileFail_3_StaticFailTest() { verifyFailTest("Quantifiers_CompileFail_3"); }
@Test public void Quantifiers_CompileFail_4_StaticFailTest() { verifyFailTest("Quantifiers_CompileFail_4"); }
@Test public void Quantifiers_Invalid_1_StaticFailTest() { verifyFailTest("Quantifiers_Invalid_1"); }
@Test public void Quantifiers_Invalid_2_StaticFailTest() { verifyFailTest("Quantifiers_Invalid_2"); }
@Test public void Quantifiers_Invalid_3_StaticFailTest() { verifyFailTest("Quantifiers_Invalid_3"); }
@Test public void Quantifiers_Invalid_4_StaticFailTest() { verifyFailTest("Quantifiers_Invalid_4"); }
@Test public void RealConvert_CompileFail_1_StaticFailTest() { verifyFailTest("RealConvert_CompileFail_1"); }
@Test public void RealConvert_CompileFail_2_StaticFailTest() { verifyFailTest("RealConvert_CompileFail_2"); }
@Test public void RealDiv_Invalid_1_StaticFailTest() { verifyFailTest("RealDiv_Invalid_1"); }
@Test public void RealMul_Invalid_1_StaticFailTest() { verifyFailTest("RealMul_Invalid_1"); }
@Ignore("Known Issue") @Test public void RecursiveType_Invalid_10_StaticFailTest() { verifyFailTest("RecursiveType_Invalid_10"); }
@Ignore("Known Issue") @Test public void RecursiveType_Invalid_3_StaticFailTest() { verifyFailTest("RecursiveType_Invalid_3"); }
@Ignore("Known Issue") @Test public void RecursiveType_Invalid_5_StaticFailTest() { verifyFailTest("RecursiveType_Invalid_5"); }
@Ignore("Known Issue") @Test public void RecursiveType_Invalid_6_StaticFailTest() { verifyFailTest("RecursiveType_Invalid_6"); }
@Ignore("Known Issue") @Test public void RecursiveType_Invalid_7_StaticFailTest() { verifyFailTest("RecursiveType_Invalid_7"); }
@Ignore("Known Issue") @Test public void RecursiveType_Invalid_8_StaticFailTest() { verifyFailTest("RecursiveType_Invalid_8"); }
@Ignore("Known Issue") @Test public void RecursiveType_Invalid_9_StaticFailTest() { verifyFailTest("RecursiveType_Invalid_9"); }
@Test public void Requires_Invalid_1_StaticFailTest() { verifyFailTest("Requires_Invalid_1"); }
@Test public void SetAssign_Invalid_1_StaticFailTest() { verifyFailTest("SetAssign_Invalid_1"); }
@Test public void SetComprehension_Invalid_1_StaticFailTest() { verifyFailTest("SetComprehension_Invalid_1"); }
@Test public void SetElemOf_Invalid_1_StaticFailTest() { verifyFailTest("SetElemOf_Invalid_1"); }
@Test public void SetEmpty_Invalid_1_StaticFailTest() { verifyFailTest("SetEmpty_Invalid_1"); }
@Test public void SetIntersection_Invalid_1_StaticFailTest() { verifyFailTest("SetIntersection_Invalid_1"); }
@Test public void SetIntersection_Invalid_2_StaticFailTest() { verifyFailTest("SetIntersection_Invalid_2"); }
@Test public void SetSubset_CompileFail_1_StaticFailTest() { verifyFailTest("SetSubset_CompileFail_1"); }
@Test public void SetSubset_CompileFail_2_StaticFailTest() { verifyFailTest("SetSubset_CompileFail_2"); }
@Test public void SetSubset_CompileFail_3_StaticFailTest() { verifyFailTest("SetSubset_CompileFail_3"); }
@Test public void SetSubset_CompileFail_4_StaticFailTest() { verifyFailTest("SetSubset_CompileFail_4"); }
@Test public void SetSubset_Invalid_1_StaticFailTest() { verifyFailTest("SetSubset_Invalid_1"); }
@Test public void SetSubset_Invalid_2_StaticFailTest() { verifyFailTest("SetSubset_Invalid_2"); }
@Test public void SetSubset_Invalid_3_StaticFailTest() { verifyFailTest("SetSubset_Invalid_3"); }
@Test public void SetSubset_Invalid_4_StaticFailTest() { verifyFailTest("SetSubset_Invalid_4"); }
@Test public void SetSubset_Invalid_5_StaticFailTest() { verifyFailTest("SetSubset_Invalid_5"); }
@Test public void SetSubset_Invalid_6_StaticFailTest() { verifyFailTest("SetSubset_Invalid_6"); }
@Test public void SetUnion_Invalid_1_StaticFailTest() { verifyFailTest("SetUnion_Invalid_1"); }
@Test public void SetUnion_Invalid_2_StaticFailTest() { verifyFailTest("SetUnion_Invalid_2"); }
@Test public void String_Invalid_1_StaticFailTest() { verifyFailTest("String_Invalid_1"); }
@Test public void Subtype_CompileFail_1_StaticFailTest() { verifyFailTest("Subtype_CompileFail_1"); }
@Test public void Subtype_CompileFail_2_StaticFailTest() { verifyFailTest("Subtype_CompileFail_2"); }
@Test public void Subtype_CompileFail_3_StaticFailTest() { verifyFailTest("Subtype_CompileFail_3"); }
@Test public void Subtype_CompileFail_4_StaticFailTest() { verifyFailTest("Subtype_CompileFail_4"); }
@Test public void Subtype_CompileFail_5_StaticFailTest() { verifyFailTest("Subtype_CompileFail_5"); }
@Test public void Subtype_CompileFail_6_StaticFailTest() { verifyFailTest("Subtype_CompileFail_6"); }
@Test public void Subtype_CompileFail_7_StaticFailTest() { verifyFailTest("Subtype_CompileFail_7"); }
@Ignore("Known Issue") @Test public void Subtype_CompileFail_8_StaticFailTest() { verifyFailTest("Subtype_CompileFail_8"); }
@Ignore("Known Issue") @Test public void Subtype_CompileFail_9_StaticFailTest() { verifyFailTest("Subtype_CompileFail_9"); }
@Test public void Tuple_Invalid_1_StaticFailTest() { verifyFailTest("Tuple_Invalid_1"); }
@Test public void Tuple_Invalid_2_StaticFailTest() { verifyFailTest("Tuple_Invalid_2"); }
@Test public void Tuple_Invalid_3_StaticFailTest() { verifyFailTest("Tuple_Invalid_3"); }
@Test public void Tuple_Invalid_4_StaticFailTest() { verifyFailTest("Tuple_Invalid_4"); }
@Test public void TupleAssign_Invalid_1_StaticFailTest() { verifyFailTest("TupleAssign_Invalid_1"); }
@Test public void TupleAssign_Invalid_2_StaticFailTest() { verifyFailTest("TupleAssign_Invalid_2"); }
@Test public void TupleAssign_Invalid_3_StaticFailTest() { verifyFailTest("TupleAssign_Invalid_3"); }
@Test public void TupleDefine_CompileFail_2_StaticFailTest() { verifyFailTest("TupleDefine_CompileFail_2"); }
@Test public void TypeEquals_Invalid_3_StaticFailTest() { verifyFailTest("TypeEquals_Invalid_3"); }
@Ignore("Known Issue") @Test public void TypeEquals_Invalid_4_StaticFailTest() { verifyFailTest("TypeEquals_Invalid_4"); }
@Test public void UnionType_CompileFail_8_StaticFailTest() { verifyFailTest("UnionType_CompileFail_8"); }
@Ignore("Known Issue") @Test public void UnionType_Invalid_1_StaticFailTest() { verifyFailTest("UnionType_Invalid_1"); }
@Ignore("Known Issue") @Test public void UnionType_Invalid_2_StaticFailTest() { verifyFailTest("UnionType_Invalid_2"); }
@Ignore("Known Issue") @Test public void UnionType_Invalid_3_StaticFailTest() { verifyFailTest("UnionType_Invalid_3"); }
@Test public void VarDecl_Invalid_1_StaticFailTest() { verifyFailTest("VarDecl_Invalid_1"); }
@Test public void While_CompileFail_6_StaticFailTest() { verifyFailTest("While_CompileFail_6"); }
@Ignore("Issue #300") @Test public void While_Invalid_2_StaticFailTest() { verifyFailTest("While_Invalid_2"); }
@Test public void While_Invalid_3_StaticFailTest() { verifyFailTest("While_Invalid_3"); }
@Test public void While_Invalid_4_StaticFailTest() { verifyFailTest("While_Invalid_4"); }
@Test public void While_Invalid_5_StaticFailTest() { verifyFailTest("While_Invalid_5"); }
@Test public void While_Invalid_6_StaticFailTest() { verifyFailTest("While_Invalid_6"); }
}
|
package com.github.sebhoss.contract.example;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.github.sebhoss.common.annotation.CompilerWarnings;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Test cases for the {@link InsuranceCompany}.
*/
@SuppressWarnings({ CompilerWarnings.NLS, CompilerWarnings.NULL, CompilerWarnings.STATIC_METHOD })
public class JuelInsuranceCompanyTest {
/** Catches expected exceptions */
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Ensures that the insurance company can calculate payouts based on a positive damage input.
*/
@Test
public void shouldAcceptPositiveDamages() {
// Given
final Injector injector = Guice.createInjector(new CompanyModule());
final InsuranceCompany instance = injector.getInstance(InsuranceCompany.class);
// When
final double result = instance.calculateCover(10);
// Then
Assert.assertEquals(5.0, result, 0d);
}
/**
* Ensures that the insurance company cannot calculate payouts based on negative input.
*/
@Test
public void shouldNotAcceptNegativeDamages() {
// Given
final Injector injector = Guice.createInjector(new CompanyModule());
final InsuranceCompany instance = injector.getInstance(InsuranceCompany.class);
// When
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Reported damage must be positive!");
// Then
instance.calculateCover(-10);
}
/**
* Ensures that the insurance company cannot calculate payouts based on high inputs.
*/
@Test
public void shouldNotAcceptHighDamages() {
// Given
final Injector injector = Guice.createInjector(new CompanyModule());
final InsuranceCompany instance = injector.getInstance(InsuranceCompany.class);
// When
thrown.expect(IllegalArgumentException.class);
// Then
instance.calculateCover(5001);
}
/**
* Ensures that the insurance company cannot pay a high amount of money.
*/
@Test
public void shouldNotPerformHighPayout() {
// Given
final Injector injector = Guice.createInjector(new CompanyModule());
final InsuranceCompany instance = injector.getInstance(InsuranceCompany.class);
// When
thrown.expect(IllegalArgumentException.class);
// Then
instance.calculateCover(5000);
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-01-02");
this.setApiVersion("14.11.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package org.csstudio.diirt.util.preferences;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.preference.StringButtonFieldEditor;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
/**
* Preference page for configuring diirt preferences primarily the Location of
* the diirt configuration folder.
*
* In addition it has a directory view which shows all the individual
* configuration files. Double click on any file will result in opening that
* file with the configured default editor
*
* @author Kunal Shroff
*
*/
public class DiirtPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private ScopedPreferenceStore store;
private TreeViewer tv;
private StringButtonFieldEditor diirtPathEditor;
private Composite top;
public DiirtPreferencePage() {
}
@Override
protected Control createContents(Composite parent) {
top = new Composite(parent, SWT.LEFT);
top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
top.setLayout(new GridLayout());
diirtPathEditor = new StringButtonFieldEditor("diirt.home", "&Diirt configuration directory:", top) {
private String lastPath = store.getString("diirt.home");
@Override
protected String changePressed() {
DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SHEET);
if (lastPath != null) {
try {
lastPath = DiirtStartup.getSubstitutedPath(lastPath);
if (new File(lastPath).exists()) {
File lastDir = new File(lastPath);
dialog.setFilterPath(lastDir.getCanonicalPath());
}
} catch (IOException e) {
dialog.setFilterPath(lastPath);
}
}
String dir = dialog.open();
if (dir != null) {
dir = dir.trim();
if (dir.length() == 0) {
return null;
}
lastPath = dir;
}
tv.setInput(dir);
tv.refresh();
return dir;
}
};
diirtPathEditor.setChangeButtonText("Browse");
diirtPathEditor.setPage(this);
diirtPathEditor.setPreferenceStore(getPreferenceStore());
diirtPathEditor.load();
// Detailed view of all the configuration files
Composite treeComposite = new Composite(parent, SWT.NONE);
treeComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
treeComposite.setLayout(new GridLayout(1, false));
// Create the tree viewer to display the file tree
tv = new TreeViewer(treeComposite);
tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
tv.setContentProvider(new FileTreeContentProvider());
tv.setLabelProvider(new FileTreeLabelProvider());
try {
final String configPath = DiirtStartup.getSubstitutedPath(store.getString("diirt.home"));
if (Files.exists(Paths.get(configPath))) {
tv.setInput(configPath);
}
} catch (IOException e1) {
setErrorMessage(e1.getMessage());
}
tv.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
TreeSelection selection = (TreeSelection) event.getSelection();
File sel = (File) selection.getFirstElement();
try {
if (sel.isFile()) {
Program.launch(sel.getCanonicalPath());
}
} catch (IOException e) {
setErrorMessage(e.getMessage());
}
}
});
return parent;
}
@Override
public void init(IWorkbench workbench) {
store = new ScopedPreferenceStore(InstanceScope.INSTANCE, "org.csstudio.diirt.util.preferences");
store.addPropertyChangeListener((PropertyChangeEvent event) -> {
if (event.getProperty() == "diirt.home") {
if (!getControl().isDisposed()) {
try {
String fullPath = DiirtStartup.getSubstitutedPath(store.getString("diirt.home"));
if (verifyDiirtPath(fullPath)) {
tv.setInput(fullPath);
setMessage("Restart is needed", ERROR);
}
} catch (IOException e) {
setMessage("Diirt home not understood", ERROR);
}
}
}
});
setPreferenceStore(store);
setDescription("Diirt preference page");
}
/**
* Verify the selected path is a valid location for DIIRT config:
* i) path exists
* ii) path contains the datasources.xml file
*
* @param configPath
* @return
*/
private boolean verifyDiirtPath(String configPath) {
boolean isValid = true;
if (!Files.exists(Paths.get(configPath))) {
setErrorMessage("Diirt home not found");
isValid = false;
} else {
final Path datasourcePath = Paths.get(configPath, "datasources/datasources.xml");
isValid = Files.exists(datasourcePath);
if (!isValid) {
setErrorMessage("No Diirt configuration found");
}
}
return isValid;
}
@Override
public boolean performOk() {
try {
final String lastDir = DiirtStartup.getSubstitutedPath(diirtPathEditor.getStringValue());
if (verifyDiirtPath(lastDir)) {
diirtPathEditor.store();
}
} catch (Exception e1) {
setErrorMessage("Invalid config location : " + diirtPathEditor.getStringValue());
}
return super.performOk();
}
@Override
protected void performDefaults() {
diirtPathEditor.loadDefault();
super.performDefaults();
};
/**
* This class provides the content for the tree in FileTree
*/
class FileTreeContentProvider implements ITreeContentProvider {
File root = new File("root");
/**
* Gets the children of the specified object
*
* @param arg0 the parent object
* @return Object[]
*/
public Object[] getChildren(Object arg0) {
// Return the files and subdirectories in this directory
return ((File) arg0).listFiles();
}
/**
* Gets the parent of the specified object
*
* @param arg0
* the object
* @return Object
*/
public Object getParent(Object arg0) {
// Return this file's parent file
return ((File) arg0).getParentFile();
}
/**
* Returns whether the passed object has children
*
* @param arg0 the parent object
* @return boolean
*/
public boolean hasChildren(Object arg0) {
// Get the children
Object[] obj = getChildren(arg0);
// Return whether the parent has children
return obj == null ? false : obj.length > 0;
}
/**
* Gets the root element(s) of the tree
*
* @param arg0 the input data
* @return Object[]
*/
public Object[] getElements(Object arg0) {
return root.listFiles();
}
/**
* Disposes any created resources
*/
public void dispose() {
// Nothing to dispose
}
/**
* Called when the input changes
*
* @param arg0 the viewer
* @param arg1 the old input
* @param arg2 the new input
*/
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
try {
root = new File((String)arg2);
} catch (Exception e) {
root = new File("root");
}
}
}
/**
* This class provides the labels for the file tree
*/
class FileTreeLabelProvider implements ILabelProvider {
/**
* Constructs a FileTreeLabelProvider
*/
public FileTreeLabelProvider() {
}
/**
* Gets the text to display for a node in the tree
*
* @param arg0
* the node
* @return String
*/
public String getText(Object arg0) {
// Get the name of the file
String text = ((File) arg0).getName();
// If name is blank, get the path
if (text.length() == 0) {
text = ((File) arg0).getPath();
}
return text;
}
/**
* Called when this LabelProvider is being disposed
*/
public void dispose() {
}
/**
* Returns whether changes to the specified property on the specified
* element would affect the label for the element
*
* @param arg0
* the element
* @param arg1
* the property
* @return boolean
*/
public boolean isLabelProperty(Object arg0, String arg1) {
return false;
}
/**
* Removes the listener
*
* @param arg0 the listener to remove
*/
public void removeListener(ILabelProviderListener arg0) {
}
@Override
public Image getImage(Object element) {
return null;
}
@Override
public void addListener(ILabelProviderListener listener) {
}
}
}
|
package org.basex.query.func.fn;
import java.util.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.iter.*;
import org.basex.query.util.list.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
import org.basex.util.list.*;
public final class FnPath extends ContextFn {
/** Root function string. */
private static final byte[] ROOT = QNm.eqName(QueryText.FN_URI, Token.token("root()"));
/** Path cache. Caches the 1000 last accessed elements. */
private final Map<ANode, byte[]> paths = Collections.synchronizedMap(
new LinkedHashMap<ANode, byte[]>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(final Map.Entry<ANode, byte[]> eldest) {
return size() > 1000;
}
}
);
@Override
public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
ANode node = toNodeOrNull(ctxArg(0, qc), qc);
if(node == null) return Empty.VALUE;
final TokenBuilder tb = new TokenBuilder();
final TokenList steps = new TokenList();
final ANodeList nodes = new ANodeList();
while(true) {
// skip ancestor traversal if cached path is found
final byte[] path = paths.get(node);
if(path != null) {
tb.add(path);
break;
}
// root node: finalize traversal
ANode parent = node.parent();
if(parent == null) {
if(node.type != NodeType.DOC) tb.add(ROOT);
break;
}
final QNm qname = node.qname();
final Type type = node.type;
if(type == NodeType.ATT) {
tb.add('@').add(qname.id());
} else if(type == NodeType.ELM) {
tb.add(qname.eqName()).add('[').addInt(element(node, qname, qc)).add(']');
} else if(type == NodeType.COM || type == NodeType.TXT) {
tb.add(node.seqType().toString()).add('[').addInt(textComment(node, qc)).add(']');
} else if(type == NodeType.PI) {
tb.add(type.string()).add('(').add(qname.local());
tb.add(")[").addInt(pi(node, qname, qc)).add(']');
}
steps.add(tb.next());
nodes.add(node);
node = parent;
}
// add all steps in reverse order; cache element paths
for(int s = steps.size() - 1; s >= 0; --s) {
tb.add('/').add(steps.get(s));
node = nodes.get(s);
if(node.type == NodeType.ELM) paths.put(node, tb.toArray());
}
return Str.get(tb.isEmpty() ? Token.SLASH : tb.finish());
}
/**
* Returns the child index of an element.
* @param node node
* @param qname QName
* @param qc query context
* @return index
*/
private int element(final ANode node, final QNm qname, final QueryContext qc) {
int p = 1;
final BasicNodeIter iter = node.precedingSiblingIter();
for(ANode fs; (fs = iter.next()) != null;) {
qc.checkStop();
final QNm qnm = fs.qname();
if(qnm != null && qnm.eq(qname)) p++;
}
return p;
}
/**
* Returns the child index of an text or comment.
* @param node node
* @param qc query context
* @return index
*/
private int textComment(final ANode node, final QueryContext qc) {
int p = 1;
final BasicNodeIter iter = node.precedingSiblingIter();
for(ANode fs; (fs = iter.next()) != null;) {
qc.checkStop();
if(fs.type == node.type) p++;
}
return p;
}
/**
* Returns the child index of a processing instruction.
* @param node node
* @param qname QName
* @param qc query context
* @return index
*/
private int pi(final ANode node, final QNm qname, final QueryContext qc) {
final BasicNodeIter iter = node.precedingSiblingIter();
int p = 1;
for(ANode fs; (fs = iter.next()) != null;) {
qc.checkStop();
if(fs.type == node.type && fs.qname().eq(qname)) p++;
}
return p;
}
@Override
protected Expr opt(final CompileContext cc) {
return optFirst(true, false, cc.qc.focus.value);
}
}
|
package nlptools.lexicalization.tui;
import java.io.File;
import java.io.IOException;
import nlptools.lexicalization.KeyPhraseChunkExtractor;
import nlptools.lexicalization.WordTokenRetriever;
import org.apache.commons.io.FileUtils;
/**
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class NLTokenizerTUI {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Usage <filepath> tokens|keyphrases");
return;
}
final String text = FileUtils.readFileToString(new File(args[0]));
if (args[1].equals("tokens")) {
final WordTokenRetriever wr = new WordTokenRetriever();
System.out.println(wr.getTokensFrom(text));
} else {
final KeyPhraseChunkExtractor kpe = new KeyPhraseChunkExtractor();
System.out.println(kpe.getPhraseChunks(text));
}
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-12-18");
this.setApiVersion("17.16.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package org.basex.util.options;
import static java.lang.Integer.*;
import static org.basex.util.Prop.*;
import static org.basex.util.Token.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.Map.Entry;
import org.basex.core.*;
import org.basex.io.*;
import org.basex.io.in.*;
import org.basex.query.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.map.Map;
import org.basex.query.value.type.*;
import org.basex.util.*;
import org.basex.util.http.*;
import org.basex.util.list.*;
public class Options implements Iterable<Option<?>> {
/** Yes/No enumeration. */
public enum YesNo {
/** Yes. */ YES,
NO;
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ENGLISH);
}
}
/** Yes/No/Omit enumeration. */
public enum YesNoOmit {
/** Yes. */ YES,
NO,
/** Omit. */ OMIT;
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ENGLISH);
}
}
/** Comment in configuration file. */
private static final String PROPUSER = "# Local Options";
/** Map with option names and definition. */
protected final TreeMap<String, Option<?>> options = new TreeMap<>();
/** Map with option names and values. */
private final TreeMap<String, Object> values = new TreeMap<>();
/** Free option definitions. */
private final HashMap<String, String> free = new HashMap<>();
/** Options, cached from an input file. */
private final StringList user = new StringList();
/** Options file. */
private IOFile file;
/**
* Default constructor.
*/
public Options() {
this((IOFile) null);
}
/**
* Constructor with options file.
* @param opts options file
*/
protected Options(final IOFile opts) {
try {
for(final Option<?> opt : options(getClass())) {
if(opt instanceof Comment) continue;
final String name = opt.name();
values.put(name, opt.value());
options.put(name, opt);
}
} catch(final Exception ex) {
throw Util.notExpected(ex);
}
if(opts != null) read(opts);
}
/**
* Constructor with options to be copied.
* @param opts options
*/
protected Options(final Options opts) {
for(final Entry<String, Option<?>> e : opts.options.entrySet())
options.put(e.getKey(), e.getValue());
for(final Entry<String, Object> e : opts.values.entrySet())
values.put(e.getKey(), e.getValue());
for(final Entry<String, String> e : opts.free.entrySet())
free.put(e.getKey(), e.getValue());
user.add(opts.user);
file = opts.file;
}
/**
* Writes the options to disk.
*/
public final synchronized void write() {
final StringList lines = new StringList();
try {
for(final Option<?> opt : options(getClass())) {
final String name = opt.name();
if(opt instanceof Comment) {
if(!lines.isEmpty()) lines.add("");
lines.add("# " + name);
} else if(opt instanceof NumbersOption) {
final int[] ints = get((NumbersOption) opt);
final int is = ints == null ? 0 : ints.length;
for(int i = 0; i < is; ++i) lines.add(name + i + " = " + ints[i]);
} else if(opt instanceof StringsOption) {
final String[] strings = get((StringsOption) opt);
final int ss = strings == null ? 0 : strings.length;
lines.add(name + " = " + ss);
for(int i = 0; i < ss; ++i) lines.add(name + (i + 1) + " = " + strings[i]);
} else {
lines.add(name + " = " + get(opt));
}
}
lines.add("").add(PROPUSER).add(user);
// only write file if contents have changed
if(update(lines)) {
final TokenBuilder tb = new TokenBuilder();
for(final String line : lines) tb.add(line).add(NL);
file.write(tb.finish());
}
} catch(final Exception ex) {
Util.errln("% could not be written.", file);
Util.debug(ex);
}
}
/**
* Returns the option with the specified name.
* @param name name of the option
* @return value (may be {@code null})
*/
public final synchronized Option<?> option(final String name) {
return options.get(name);
}
/**
* Returns the value of the specified option.
* @param option option
* @return value (may be {@code null})
*/
public final synchronized Object get(final Option<?> option) {
return values.get(option.name());
}
/**
* Sets an option to a value without checking its type.
* @param option option
* @param value value to be assigned
*/
public final synchronized void put(final Option<?> option, final Object value) {
values.put(option.name(), value);
}
/**
* Checks if a value was set for the specified option.
* @param option option
* @return result of check
*/
public final synchronized boolean contains(final Option<?> option) {
return get(option) != null;
}
/**
* Returns the requested string.
* @param option option to be found
* @return value
*/
public final synchronized String get(final StringOption option) {
return (String) get((Option<?>) option);
}
/**
* Returns the requested number.
* @param option option to be found
* @return value
*/
public final synchronized Integer get(final NumberOption option) {
return (Integer) get((Option<?>) option);
}
/**
* Returns the requested boolean.
* @param option option to be found
* @return value
*/
public final synchronized Boolean get(final BooleanOption option) {
return (Boolean) get((Option<?>) option);
}
/**
* Returns the requested map.
* @param option option to be found
* @return value
*/
public final synchronized Map get(final MapOption option) {
return (Map) get((Option<?>) option);
}
/**
* Returns the requested function.
* @param option option to be found
* @return value
*/
public final synchronized FuncItem get(final FuncOption option) {
return (FuncItem) get((Option<?>) option);
}
/**
* Returns the original instance of the requested string array.
* @param option option to be found
* @return value
*/
public final synchronized String[] get(final StringsOption option) {
return (String[]) get((Option<?>) option);
}
/**
* Returns the original instance of the requested integer array.
* @param option option to be found
* @return value
*/
public final synchronized int[] get(final NumbersOption option) {
return (int[]) get((Option<?>) option);
}
/**
* Returns the original instance of the requested options.
* @param option option to be found
* @param <O> options
* @return value
*/
@SuppressWarnings("unchecked")
public final synchronized <O extends Options> O get(final OptionsOption<O> option) {
return (O) get((Option<?>) option);
}
/**
* Returns the requested enum value.
* @param option option to be found
* @param <V> enumeration value
* @return value
*/
@SuppressWarnings("unchecked")
public final synchronized <V extends Enum<V>> V get(final EnumOption<V> option) {
return (V) get((Option<?>) option);
}
/**
* Sets the string value of an option.
* @param option option to be set
* @param value value to be written
*/
public final synchronized void set(final StringOption option, final String value) {
put(option, value);
}
/**
* Sets the integer value of an option.
* @param option option to be set
* @param value value to be written
*/
public final synchronized void set(final NumberOption option, final int value) {
put(option, value);
}
/**
* Sets the boolean value of an option.
* @param option option to be set
* @param value value to be written
*/
public final synchronized void set(final BooleanOption option, final boolean value) {
put(option, value);
}
/**
* Sets the string array value of an option.
* @param option option to be set
* @param value value to be written
*/
public final synchronized void set(final StringsOption option, final String[] value) {
put(option, value);
}
/**
* Sets the integer array value of an option.
* @param option option to be set
* @param value value to be written
*/
public final synchronized void set(final NumbersOption option, final int[] value) {
put(option, value);
}
/**
* Sets the options of an option.
* @param option option to be set
* @param value value to be set
* @param <O> options
*/
public final synchronized <O extends Options> void set(final OptionsOption<O> option,
final O value) {
put(option, value);
}
/**
* Sets the enumeration of an option.
* @param option option to be set
* @param value value to be set
* @param <V> enumeration value
*/
public final synchronized <V extends Enum<V>> void set(final EnumOption<V> option,
final Enum<V> value) {
put(option, value);
}
/**
* Sets the enumeration of an option.
* @param option option to be set
* @param value string value, which will be converted to an enum value or {@code null}
* @param <V> enumeration value
*/
public final synchronized <V extends Enum<V>> void set(final EnumOption<V> option,
final String value) {
put(option, option.get(value));
}
/**
* Assigns a value after casting it to the correct type. If the option is unknown,
* it will be added as free option.
* @param name name of option
* @param val value
* @throws BaseXException database exception
*/
public synchronized void assign(final String name, final String val) throws BaseXException {
if(options.isEmpty()) {
free.put(name, val);
} else {
assign(name, val, -1, true);
}
}
/**
* Assigns a value after casting it to the correct type. If the option is unknown,
* it will be added as free option.
* @param name name of option
* @param val value
* @param error error
* @throws BaseXException database exception
* @throws QueryException query exception
*/
public synchronized void assign(final Item name, final Item val, final boolean error)
throws BaseXException, QueryException {
final String key = string(name.string(null));
if(options.isEmpty()) {
free.put(key, string(val.string(null)));
} else {
assign(key, val, error);
}
}
/**
* Returns all name/value pairs without pre-defined option.
* @return options
*/
public final synchronized HashMap<String, String> free() {
return free;
}
/**
* Returns an error string for an unknown option.
* @param name name of option
* @return error string
*/
public final synchronized String error(final String name) {
final String sim = similar(name);
return Util.info(sim != null ? Text.UNKNOWN_OPT_SIMILAR_X_X : Text.UNKNOWN_OPTION_X, name, sim);
}
/**
* Inverts the boolean value of an option.
* @param option option
* @return new value
*/
public final synchronized boolean invert(final BooleanOption option) {
final boolean val = !get(option);
set(option, val);
return val;
}
/**
* Overwrites the options with system properties.
* All properties starting with {@code org.basex.} will be assigned as options.
*/
public final void setSystem() {
// assign global options
for(final Entry<String, String> entry : Prop.entries()) {
final String n = entry.getKey(), v = entry.getValue().toString();
try {
if(assign(n, v, -1, false)) Util.debug(n + Text.COLS + v);
} catch(final BaseXException ex) {
Util.errln(ex);
}
}
}
/**
* Parses the specified options.
* @param type media type
* @throws BaseXException database exception
*/
public synchronized void parse(final MediaType type) throws BaseXException {
for(final Entry<String, String> entry : type.parameters().entrySet()) {
if(options.isEmpty()) {
free.put(entry.getKey(), entry.getValue());
} else {
// ignore unknown options
assign(entry.getKey(), entry.getValue(), -1, false);
}
}
}
/**
* Parses an option string and sets the options accordingly.
* @param string options string
* @throws BaseXException database exception
*/
public synchronized void parse(final String string) throws BaseXException {
final int sl = string.length();
int i = 0;
while(i < sl) {
int k = string.indexOf('=', i);
if(k == -1) k = sl;
final String key = string.substring(i, k).trim();
final StringBuilder val = new StringBuilder();
i = k;
while(++i < sl) {
final char ch = string.charAt(i);
if(ch == ',' && (++i == sl || string.charAt(i) != ',')) break;
val.append(ch);
}
assign(key, val.toString());
}
}
/**
* Parses options in the specified map.
* @param map map
* @param error raise error if option is unknown
* @throws BaseXException database exception
* @throws QueryException query exception
*/
public synchronized void parse(final Map map, final boolean error)
throws BaseXException, QueryException {
for(final Item name : map.keys()) {
if(!name.type.isStringOrUntyped())
throw new BaseXException(Text.OPT_EXPECT, AtomType.STR, name.type, name);
final Value value = map.get(name, null);
if(!(value instanceof Item))
throw new BaseXException(Text.OPT_EXPECT, AtomType.ITEM, value.seqType(), value);
assign(name, (Item) value, error);
}
}
@Override
public final synchronized Iterator<Option<?>> iterator() {
return options.values().iterator();
}
@Override
public final synchronized String toString() {
// only those options are listed whose value differs from default value
final StringBuilder sb = new StringBuilder();
for(final Entry<String, Object> e : values.entrySet()) {
final String name = e.getKey();
final Object value = e.getValue();
if(value == null) continue;
final StringList sl = new StringList();
final Object value2 = options.get(name).value();
if(value instanceof String[]) {
for(final String s : (String[]) value) sl.add(s);
} else if(value instanceof int[]) {
for(final int s : (int[]) value) sl.add(Integer.toString(s));
} else if(value instanceof Options) {
final String s = value.toString();
if(value2 == null || !s.equals(value2.toString())) sl.add(s);
} else if(!value.equals(value2)) {
sl.add(value.toString());
}
for(final String s : sl) {
if(sb.length() != 0) sb.append(',');
sb.append(name).append('=').append(s.replace(",", ",,"));
}
}
return sb.toString();
}
/**
* Returns a list of allowed keys.
* @param option option
* @param all allowed values
* @return exception
*/
public static String allowed(final Option<?> option, final Object... all) {
final TokenBuilder vals = new TokenBuilder();
for(final Object a : all) vals.add(vals.isEmpty() ? "" : ",").add(a.toString());
return Util.info(Text.OPT_ONEOF, option.name(), vals);
}
private static Option<?>[] options(final Class<? extends Options> clz)
throws IllegalAccessException {
final ArrayList<Option<?>> opts = new ArrayList<>();
for(final Field f : clz.getFields()) {
if(!Modifier.isStatic(f.getModifiers())) continue;
final Object obj = f.get(null);
if(obj instanceof Option) opts.add((Option<?>) obj);
}
return opts.toArray(new Option[opts.size()]);
}
/**
* Reads the configuration file and initializes the options.
* The file is located in the project home directory.
* @param opts options file
*/
private synchronized void read(final IOFile opts) {
file = opts;
final StringList read = new StringList();
final StringList errs = new StringList();
final boolean exists = file.exists();
if(exists) {
try(final NewlineInput nli = new NewlineInput(opts)) {
boolean local = false;
for(String line; (line = nli.readLine()) != null;) {
line = line.trim();
// start of local options
if(line.equals(PROPUSER)) {
local = true;
continue;
}
if(local) user.add(line);
if(line.isEmpty() || line.charAt(0) == '#') continue;
final int d = line.indexOf('=');
if(d < 0) {
errs.add("line \"" + line + "\" ignored.");
continue;
}
final String val = line.substring(d + 1).trim();
String name = line.substring(0, d).trim();
// extract numeric value in key
int num = 0;
final int ss = name.length();
for(int s = 0; s < ss; ++s) {
if(Character.isDigit(name.charAt(s))) {
num = Strings.toInt(name.substring(s));
name = name.substring(0, s);
break;
}
}
if(local) {
// cache local options as system properties
Prop.put(name, val);
} else {
try {
assign(name, val, num, true);
read.add(name);
} catch(final BaseXException ex) {
errs.add(ex.getMessage());
}
}
}
} catch(final IOException ex) {
errs.add("file could not be parsed.");
Util.errln(ex);
}
}
// check if all mandatory files have been read
boolean ok = true;
if(errs.isEmpty()) {
try {
for(final Option<?> opt : options(getClass())) {
if(ok && !(opt instanceof Comment)) ok = read.contains(opt.name());
}
} catch(final IllegalAccessException ex) {
throw Util.notExpected(ex);
}
}
if(!ok || !exists || !errs.isEmpty()) {
write();
errs.add("writing new configuration file.");
for(final String s : errs) Util.errln(file + ": " + s);
}
}
/**
* Checks if the options file needs to be updated.
* @param lines lines of new file
* @return result of check
* @throws IOException I/O exception
*/
private boolean update(final StringList lines) throws IOException {
if(!file.exists()) return true;
int l = 0;
final int ls = lines.size();
try(final NewlineInput nli = new NewlineInput(file)) {
for(String line; (line = nli.readLine()) != null;) {
if(l == ls || !lines.get(l++).equals(line)) return true;
}
}
return l != ls;
}
/**
* Assigns the specified name and value.
* @param name name of option
* @param item value of option
* @param error raise error if option is unknown
* @return success flag
* @throws BaseXException database exception
* @throws QueryException query exception
*/
private synchronized boolean assign(final String name, final Item item, final boolean error)
throws BaseXException, QueryException {
final Option<?> option = options.get(name);
if(option == null) {
if(error) throw new BaseXException(error(name));
return false;
}
if(option instanceof BooleanOption) {
final boolean v;
if(item.type.isStringOrUntyped()) {
v = Strings.yes(string(item.string(null)));
if(!v && !Strings.no(string(item.string(null))))
throw new BaseXException(Text.OPT_BOOLEAN, option.name());
} else if(item instanceof Bln) {
v = ((Bln) item).bool(null);
} else {
throw new BaseXException(Text.OPT_BOOLEAN, option.name());
}
put(option, v);
} else if(option instanceof NumberOption) {
if(item instanceof ANum) {
put(option, (int) ((ANum) item).itr(null));
} else {
throw new BaseXException(Text.OPT_NUMBER, option.name());
}
} else if(option instanceof StringOption) {
if(item.type.isStringOrUntyped()) {
put(option, string(item.string(null)));
} else {
throw new BaseXException(Text.OPT_STRING, option.name());
}
} else if(option instanceof EnumOption) {
if(item.type.isStringOrUntyped()) {
final EnumOption<?> eo = (EnumOption<?>) option;
final Object v = eo.get(string(item.string(null)));
if(v == null) throw new BaseXException(allowed(option, (Object[]) eo.values()));
put(option, v);
} else {
throw new BaseXException(Text.OPT_STRING, option.name());
}
} else if(option instanceof OptionsOption) {
final Options o = ((OptionsOption<?>) option).newInstance();
if(item instanceof Map) {
o.parse((Map) item, error);
} else {
throw new BaseXException(Text.OPT_MAP, option.name());
}
put(option, o);
} else if(option instanceof MapOption) {
if(!(item instanceof Map)) throw new BaseXException(Text.OPT_FUNC, option.name());
put(option, item);
} else if(option instanceof FuncOption) {
if(!(item instanceof FuncItem)) throw new BaseXException(Text.OPT_FUNC, option.name());
put(option, item);
} else {
throw Util.notExpected("Unsupported option: " + option);
}
return true;
}
/**
* Assigns the specified name and value.
* @param name name of option
* @param val value of option
* @param index index (optional, can be {@code -1})
* @param error raise error if option is unknown
* @return success flag
* @throws BaseXException database exception
*/
private synchronized boolean assign(final String name, final String val, final int index,
final boolean error) throws BaseXException {
final Option<?> option = options.get(name);
if(option == null) {
if(error) throw new BaseXException(error(name));
return false;
}
if(option instanceof BooleanOption) {
final boolean v;
if(val == null || val.isEmpty()) {
final Boolean b = get((BooleanOption) option);
if(b == null) throw new BaseXException(Text.OPT_BOOLEAN, option.name());
v = !b;
} else {
v = Strings.yes(val);
if(!v && !Strings.no(val)) throw new BaseXException(Text.OPT_BOOLEAN, option.name());
}
put(option, v);
} else if(option instanceof NumberOption) {
final int v = Strings.toInt(val);
if(v == MIN_VALUE) throw new BaseXException(Text.OPT_NUMBER, option.name());
put(option, v);
} else if(option instanceof StringOption) {
put(option, val);
} else if(option instanceof EnumOption) {
final EnumOption<?> eo = (EnumOption<?>) option;
final Object v = eo.get(val);
if(v == null) throw new BaseXException(allowed(option, (Object[]) eo.values()));
put(option, v);
} else if(option instanceof OptionsOption) {
final Options o = ((OptionsOption<?>) option).newInstance();
o.parse(val);
put(option, o);
} else if(option instanceof NumbersOption) {
final int v = Strings.toInt(val);
if(v == MIN_VALUE) throw new BaseXException(Text.OPT_NUMBER, option.name());
int[] ii = (int[]) get(option);
if(index == -1) {
if(ii == null) ii = new int[0];
final IntList il = new IntList(ii.length + 1);
for(final int i : ii) il.add(i);
put(option, il.add(v).finish());
} else {
if(index < 0 || index >= ii.length)
throw new BaseXException(Text.OPT_OFFSET, option.name());
ii[index] = v;
}
} else if(option instanceof StringsOption) {
String[] ss = (String[]) get(option);
if(index == -1) {
if(ss == null) ss = new String[0];
final StringList sl = new StringList(ss.length + 1);
for(final String s : ss) sl.add(s);
put(option, sl.add(val).finish());
} else if(index == 0) {
final int v = Strings.toInt(val);
if(v == MIN_VALUE) throw new BaseXException(Text.OPT_NUMBER, option.name());
values.put(name, new String[v]);
} else {
if(index <= 0 || index > ss.length)
throw new BaseXException(Text.OPT_OFFSET, option.name());
ss[index - 1] = val;
}
} else {
throw Util.notExpected("Unsupported option: " + option);
}
return true;
}
/**
* Returns an option name similar to the specified string or {@code null}.
* @param name name to be found
* @return similar name
*/
private String similar(final String name) {
final byte[] nm = token(name);
final Levenshtein ls = new Levenshtein();
for(final String opts : options.keySet()) {
if(ls.similar(nm, token(opts))) return opts;
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-02-15");
this.setApiVersion("15.17.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package org.fungsi.concurrent;
import org.fungsi.Unit;
import org.fungsi.function.UnsafeSupplier;
import org.junit.Test;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import static org.fungsi.Matchers.isFailure;
import static org.fungsi.Matchers.isSuccess;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class FutureTest {
@Test(expected = IllegalStateException.class)
public void testFilter() throws Exception {
Future<Unit> fut = Futures.unit();
fut.filter(it -> false).get();
}
@Test
public void testMap() throws Exception {
Future<String> fut = Futures.success("lol");
int res = fut.map(String::length).get();
assertThat(res, is(3));
}
@Test
public void testCollect() throws Exception {
Future<List<String>> fut = Futures.collect(Arrays.asList(
Futures.success("lol"),
Futures.success("mdr"),
Futures.success("lmao")
));
assertThat(fut, isSuccess());
assertThat(fut.get(), hasItems("lol", "mdr", "lmao"));
}
@Test
public void testCollect_threaded() throws Exception {
Worker worker = Workers.wrap(Executors.newFixedThreadPool(3));
Future<List<String>> fut = Futures.collect(Arrays.asList(
worker.submit(sleepThenReturn("lol", 1000L)),
worker.submit(sleepThenReturn("mdr", 1000L)),
worker.submit(sleepThenReturn("lmao", 1000L))
));
assertThat(fut.get(Duration.ofMillis(1100L)), hasItems("lol", "mdr", "lmao"));
assertThat(fut, isSuccess());
}
private static <T> UnsafeSupplier<T> sleepThenReturn(T val, long millis) {
return () -> { Thread.sleep(millis); return val; };
}
@Test
public void testCollect_withFailure() throws Exception {
Future<List<String>> fut = Futures.collect(Arrays.asList(
Futures.<String>failure(new Exception()),
Futures.success("mdr"),
Futures.success("lmao")
));
assertThat(fut, isFailure());
}
}
|
package be.raildelays.batch;
import be.raildelays.batch.service.BatchStartAndRecoveryService;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.PropertyConfigurator;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.Configurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.converter.DefaultJobParametersConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.util.Assert;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;
public class Bootstrap {
private static final Logger LOGGER = LoggerFactory.getLogger(Bootstrap.class);
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
final String[] contextPaths = new String[]{"/spring/bootstrap-context.xml"};
final CommandLineParser parser = new BasicParser();
final Options options = new Options();
final List<Date> dates;
options.addOption("offline", false, "activate offline mode");
options.addOption("norecovery", false, "do not execute recovery");
options.addOption("date", false, "search delays for only on date passed as parameter");
final CommandLine cmd = parser.parse(options, args);
final boolean online = !cmd.hasOption("offline");
final boolean recovery = !cmd.hasOption("norecovery");
final String searchDate = cmd.getOptionValue("date", "");
if (StringUtils.isNotEmpty(searchDate)) {
dates = Arrays.asList(DateUtils.parseDate(searchDate, new String[]{"dd/MM/yyyy", "dd-MM-yyyy", "yyyyMMdd"}));
} else {
dates = generateListOfDates();
}
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
contextPaths);
//-- Initialize contexts
applicationContext.registerShutdownHook(); // Register close of this Spring context to shutdown of the JVM
applicationContext.start();
final BatchStartAndRecoveryService service = applicationContext.getBean("BatchStartAndRecoveryService", BatchStartAndRecoveryService.class);
try {
Properties configuration = applicationContext.getBean("configuration",
Properties.class);
final DefaultJobParametersConverter converter = new DefaultJobParametersConverter();
converter.setDateFormat(new SimpleDateFormat("dd/MM/yyyy"));
final String departure = configuration.getProperty("departure");
final String arrival = configuration.getProperty("arrival");
final String excelInputTemplate = configuration.getProperty("excel.input.template");
final String textOutputPath = configuration.getProperty("text.output.path");
final String excelOutputPath = configuration.getProperty("excel.output.path");
Assert.notNull(departure, "You must add a 'departure' property into the ./conf/raildelays.properties");
Assert.notNull(arrival, "You must add a 'arrival' property into the ./conf/raildelays.properties");
Assert.notNull(excelInputTemplate, "You must add a 'excel.input.template' property into the ./conf/raildelays.properties");
Assert.notNull(textOutputPath, "You must add a 'text.output.path' property into the ./conf/raildelays.properties");
Assert.notNull(excelOutputPath, "You must add a 'excel.output.path' property into the ./conf/raildelays.properties");
if (recovery) {
LOGGER.info("[Recovery activated]");
//service.restartAllStoppedJobs();
service.markInconsistentJobsAsFailed();
// FIXME this method below should never throw JobInstanceAlreadyCompleteException
//service.restartAllFailedJobs();
}
//-- Launch one Job per date
for (Date date : dates) {
Map<String, JobParameter> parameters = new HashMap<>();
parameters.put("date", new JobParameter(date));
parameters.put("station.a.name", new JobParameter(departure));
parameters.put("station.b.name", new JobParameter(arrival));
parameters.put("excel.input.template", new JobParameter(excelInputTemplate));
parameters.put("excel.output.path", new JobParameter(excelOutputPath));
parameters.put("output.file.path", new JobParameter(textOutputPath));
JobParameters jobParameters = new JobParameters(parameters);
try {
service.start("mainJob", jobParameters);
} catch (JobInstanceAlreadyCompleteException e) {
LOGGER.warn("Job already completed for this date {}", new SimpleDateFormat("dd/MM/yyyy").format(date));
}
}
} finally {
if (service != null) {
service.stopAllRunningJobs();
}
if (applicationContext != null) {
applicationContext.stop();
applicationContext.close();
}
}
System.exit(0);
}
/**
* Generate a list of day of week from today to 7 in the past.
*
* @return a list of {@link Date} from Monday to Friday.
*/
private static List<Date> generateListOfDates() {
List<Date> result = new ArrayList<>();
Calendar date = DateUtils.truncate(Calendar.getInstance(),
Calendar.DAY_OF_MONTH);
date.setLenient(false);
Date monday = null;
Date tuesday = null;
Date wednesday = null;
Date thursday = null;
Date friday = null;
for (int i = 0; i < 7; i++) {
date.add(Calendar.DAY_OF_MONTH, -1);
switch (date.get(Calendar.DAY_OF_WEEK)) {
case Calendar.MONDAY:
monday = date.getTime();
break;
case Calendar.TUESDAY:
tuesday = date.getTime();
break;
case Calendar.WEDNESDAY:
wednesday = date.getTime();
break;
case Calendar.THURSDAY:
thursday = date.getTime();
break;
case Calendar.FRIDAY:
friday = date.getTime();
break;
default:
break;
}
}
result.add(monday);
result.add(tuesday);
result.add(wednesday);
result.add(thursday);
result.add(friday);
Collections.sort(result); //-- To order outcomes
return result;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:17-12-13");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package org.deviceconnect.android.deviceplugin.hvc;
import org.deviceconnect.android.deviceplugin.hvc.profile.HvcLocationAlertDialog;
import org.deviceconnect.android.profile.BatteryProfile;
import org.deviceconnect.message.DConnectMessage;
import org.deviceconnect.message.intent.message.IntentDConnectMessage;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
/**
* HVC Device Plugin Application.
*
* @author NTT DOCOMO, INC.
*/
public class HvcDeviceApplication extends Application {
private static HvcDeviceApplication instance = null;
@Override
public void onCreate() {
super.onCreate();
instance = this;
// start accept service
Intent request = new Intent(IntentDConnectMessage.ACTION_PUT);
request.setClass(this, HvcDeviceProvider.class);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfile.PROFILE_NAME);
sendBroadcast(request);
}
public static HvcDeviceApplication getInstance() {
return instance;
}
public void checkLocationEnable() {
Context context = getApplicationContext();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
&& !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Intent intent = new Intent(context, HvcLocationAlertDialog.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-08-23");
this.setApiVersion("18.13.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package io.spine.server;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import io.spine.annotation.Internal;
import io.spine.annotation.SPI;
import io.spine.core.BoundedContextName;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.core.BoundedContextNames.newName;
/**
* Specification of a bounded context.
*
* <p>The spec includes the values required to build a {@link BoundedContext}.
*/
@SPI
public final class ContextSpec {
private final BoundedContextName name;
private final boolean multitenant;
private final boolean storeEvents;
private ContextSpec(BoundedContextName name, boolean multitenant, boolean storeEvents) {
this.name = checkNotNull(name);
this.multitenant = multitenant;
this.storeEvents = storeEvents;
}
/**
* Creates a spec of a single tenant context with the given name.
*/
@VisibleForTesting
public static ContextSpec singleTenant(String name) {
return createDomain(name, false);
}
/**
* Creates a spec of a multitenant context with the given name.
*/
@VisibleForTesting
public static ContextSpec multitenant(String name) {
return createDomain(name, true);
}
private static ContextSpec createDomain(String name, boolean multitenant) {
checkNotNull(name);
BoundedContextName contextName = newName(name);
return new ContextSpec(contextName, multitenant, true);
}
/**
* Obtains the context name.
*/
public BoundedContextName name() {
return name;
}
/**
* Checks if the context is multitenant or not.
*/
public boolean isMultitenant() {
return multitenant;
}
/**
* Checks if the specified context stores its event log.
*
* <p>All domain-specific contexts store their events. A System context may be configured
* to store or not to store its events.
*
* @return {@code true} if the context persists its event log, {@code false otherwise}
*/
@Internal
public boolean storesEvents() {
return storeEvents;
}
/**
* Converts this spec into the System spec for the counterpart of this domain context.
*/
ContextSpec toSystem() {
return new ContextSpec(name.toSystem(), multitenant, storeEvents);
}
/**
* Creates a spec which has all the attributes of this instance and does NOT
* {@linkplain #storesEvents() store events}.
*/
ContextSpec notStoringEvents() {
return new ContextSpec(name, multitenant, false);
}
/**
* Returns a single-tenant version of this instance, if it is multitenant, or
* this instance if it is single-tenant.
*/
public ContextSpec toSingleTenant() {
if (isMultitenant()) {
ContextSpec result = singleTenant(name.getValue());
return result;
}
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ContextSpec)) {
return false;
}
ContextSpec spec = (ContextSpec) o;
return isMultitenant() == spec.isMultitenant() &&
storeEvents == spec.storeEvents &&
Objects.equal(name, spec.name);
}
@Override
public int hashCode() {
return Objects.hashCode(name, isMultitenant(), storeEvents);
}
@Override
public String toString() {
String tenancy = multitenant
? "Multitenant"
: "Single tenant";
return String.format("%s context %s", tenancy, name.getValue());
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:17-12-28");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package org.eclipse.birt.report.engine.emitter.excel;
import java.util.List;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Calendar;
import java.sql.Time;
import java.util.Date;
import java.lang.Number;
import java.lang.String;
import java.math.BigDecimal;
import org.eclipse.birt.report.engine.emitter.excel.GroupInfo.Position;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.core.format.StringFormatter;
import org.eclipse.birt.core.format.NumberFormatter;
import org.eclipse.birt.chart.util.CDateTime;
import com.ibm.icu.text.DecimalFormat;
import com.ibm.icu.text.SimpleDateFormat;
public class ExcelUtil
{
public static String ridQuote( String val )
{
if ( val.charAt( 0 ) == '"' && val.charAt( val.length( ) - 1 ) == '"' )
{
return val.substring( 1, val.length( ) - 1 );
}
return val;
}
public static String formatDate( Object data )
{
if(data == null) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss" );
Date date = null;
if(data instanceof com.ibm.icu.util.Calendar) {
date = ((com.ibm.icu.util.Calendar) data).getTime( );
}
else if(data instanceof Date) {
date = (Date) data;
}
else {
return null;
}
return dateFormat.format( date );
}
public static String formatNumber( Object data)
{
DecimalFormat numberFormat = new DecimalFormat("0.00E00");
return numberFormat.format( (Number)data);
}
public static String getType(Object val)
{
if ( val instanceof Number )
{
if(isNumber(val.toString( ))){
return Data.NUMBER;
}
else{
return Data.STRING;
}
}
else if(val instanceof Date)
{
return Data.DATE;
}
else if (val instanceof Calendar)
{
return Data.CALENDAR;
}
else if(val instanceof CDateTime)
{
return Data.CDATETIME;
}
else
{
return Data.STRING;
}
}
private static String replaceDateFormat( String pattern )
{
if ( pattern == null )
{
String rg = "";
return rg;
}
StringBuffer toAppendTo = new StringBuffer( );
boolean inQuote = false;
char prevCh = 0;
int count = 0;
for ( int i = 0; i < pattern.length( ); ++i )
{
char ch = pattern.charAt( i );
if ( ch != prevCh && count > 0 )
{
toAppendTo.append( subReplaceDateFormat( prevCh, count ) );
count = 0;
}
if ( ch == '/' )
{
toAppendTo.append( '\\' );
toAppendTo.append( ch );
}
else if ( ch == '\'' )
{
if ( ( i + 1 ) < pattern.length( )
&& pattern.charAt( i + 1 ) == '\'' )
{
toAppendTo.append( "\"" );
++i;
}
else
{
inQuote = !inQuote;
}
}
else if ( !inQuote )
{
prevCh = ch;
++count;
}
else
{
toAppendTo.append( ch );
}
}
if ( count > 0 )
{
toAppendTo.append( subReplaceDateFormat( prevCh, count ) );
}
return toAppendTo.toString( );
}
/**
* only used in the method replaceDataFormat().
*/
private static String subReplaceDateFormat( char ch, int count )
{
String current = "";
int patternCharIndex = -1;
String datePatternChars = "GyMdkHmsSEDFwWahKz";
if ( ( patternCharIndex = datePatternChars.indexOf( ch ) ) == -1 )
{
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
return current;
}
switch ( patternCharIndex )
{
case 0 : // 'G' - ERA
current = "";
break;
case 1 : // 'y' - YEAR
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 2 : // 'M' - MONTH
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 3 : // 'd' - Date
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 4 : // 'k' - HOUR_OF_DAY: 1-based. eg, 23:59 + 1 hour =>>
// 24:59
current = "h";
break;
case 5 : // case 5: // 'H'-HOUR_OF_DAY:0-based.eg, 23:59+1
// hour=>>00:59
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 6 : // case 6: // 'm' - MINUTE
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 7 : // case 7: // 's' - SECOND
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 8 : // case 8: // 'S' - MILLISECOND
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 9 : // 'E' - DAY_OF_WEEK
for ( int i = 0; i < count; i++ )
{
current += "a";
}
break;
case 14 : // 'a' - AM_PM
current = "AM/PM";
break;
case 15 : // 'h' - HOUR:1-based. eg, 11PM + 1 hour =>> 12 AM
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 17 : // 'z' - ZONE_OFFSET
current = "";
break;
default :
// case 10: // 'D' - DAY_OF_YEAR
// case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
// case 12: // 'w' - WEEK_OF_YEAR
// case 13: // 'W' - WEEK_OF_MONTH
// case 16: // 'K' - HOUR: 0-based. eg, 11PM + 1 hour =>> 0 AM
current = "";
break;
}
return current;
}
public static String getPattern(Object data, String val)
{
if(val != null && data instanceof Date) {
return replaceDateFormat(val);
}
else if(val == null && data instanceof Time) {
return "Long Time";
}
else if(val == null && data instanceof java.sql.Date)
{
// According to java SDK 1.4.2-16, sql.Date doesn't have
// a time component.
return "mmm d, yyyy";// hh:mm AM/PM";
}
else if(val == null && data instanceof java.util.Date)
{
return "mmm d, yyyy hh:mm AM/PM";
}
else if(val != null && data instanceof Number)
{
if(val.indexOf( "E" ) >= 0){
return "Scientific";
}
return new NumberFormatter(val).getPattern( );
}
else if(val != null && data instanceof String)
{
return new StringFormatter(val).getPattern( );
}
return null;
}
public static String replaceAll(String str, String old, String news) {
if(str == null) {
return str;
}
int begin = 0;
int idx = 0;
int len = old.length();
StringBuffer buf = new StringBuffer();
while((idx = str.indexOf(old, begin)) >= 0) {
buf.append(str.substring(begin, idx));
buf.append(news);
begin = idx + len;
}
return new String(buf.append(str.substring(begin)));
}
// TODO
public static String getValue( String val )
{
if ( val == null )
{
return StyleConstant.NULL;
}
if ( val.charAt( 0 ) == '"' && val.charAt( val.length( ) - 1 ) == '"' )
{
return val.substring( 1, val.length( ) - 1 );
}
return val;
}
public static int convertToPt( String size )
{
try
{
int s = Integer.valueOf( size.substring( 0, size.length( ) - 2 ) )
.intValue( );
if ( size.endsWith( "in" ) )
{
return s * 72;
}
else if ( size.endsWith( "cm" ) )
{
return (int) ( s / 2.54 * 72 );
}
else if ( size.endsWith( "mm" ) )
{
return (int) ( s * 10 / 2.54 * 72 );
}
else if ( size.endsWith( "pc" ) )
{
return s;
}
else
{
return s;
}
}
catch ( Exception e )
{
e.printStackTrace( );
return 0;
}
}
// the parse method can just see if the start of the String is a number
// like "123 bbs"
// it will parse successful and returns the value of 123 in number
public static boolean isNumber( String val )
{
try
{
new BigDecimal(val);
return true;
}
catch ( Exception e )
{
return false;
}
}
public static String getColumnOfExp( String exp )
{
return exp.substring( exp.indexOf( "dataSetRow[" ), exp
.lastIndexOf( "]" ) + 1 );
}
private static final int max_formula_length = 512;
public static String createFormula( String txt, String exp, List positions )
{
exp = getFormulaName( exp );
StringBuffer sb = new StringBuffer( exp + "(" );
for ( int i = 0; i < positions.size( ); i++ )
{
Position p = (Position) positions.get( i );
sb.append( "R" + p.row + "C" + p.column + "," );
}
sb.setCharAt( sb.length( ) - 1, ')' );
if ( sb.length( ) > max_formula_length || positions.size( ) == 0 )
{
return txt;
}
return sb.toString( );
}
private static String getFormulaName( String expression )
{
if ( expression.startsWith( "Total.sum" ) )
{
return "=SUM";
}
else if ( expression.startsWith( "Total.ave" ) )
{
return "=AVERAGE";
}
else if ( expression.startsWith( "Total.max" ) )
{
return "=MAX";
}
else if ( expression.startsWith( "Total.min" ) )
{
return "=MIN";
}
else if ( expression.startsWith( "Total.count" ) )
{
return "=COUNT";
}
throw new RuntimeException( "Cannot parse the expression" + expression );
}
private static final String reg1 = "Total." + "(count|ave|sum|max|min)"
+ "\\(", reg2 = "\\)", reg3 = "\\[", reg4 = "\\]";
public static boolean isValidExp( String exp, String[] columnNames )
{
StringBuffer sb = new StringBuffer( );
for ( int i = 0; i < columnNames.length; i++ )
{
sb.append( columnNames[i] + "|" );
}
String columnRegExp = "(" + sb.substring( 0, sb.length( ) - 1 ) + ")";
columnRegExp = columnRegExp.replaceAll( reg3, "Z" );
columnRegExp = columnRegExp.replaceAll( reg4, "Z" );
String aggregateRegExp = reg1 + columnRegExp + reg2;
exp = exp.replaceAll( reg3, "Z" );
exp = exp.replaceAll( reg4, "Z" );
Pattern p = Pattern.compile( aggregateRegExp );
Matcher m = p.matcher( exp );
boolean agg = m.matches( );
p = Pattern.compile( columnRegExp );
m = p.matcher( exp );
return agg || m.matches( );
}
public static String expression( String val, String target, String[] res,
boolean casesenstive )
{
boolean flag = casesenstive ? target.equals( val ) : target
.equalsIgnoreCase( val );
return flag ? res[1] : res[0];
}
public static int covertDimensionType( DimensionType value, int parent )
{
if ( DimensionType.UNITS_PERCENTAGE.equals( value.getUnits( ) ) )
{
return (int) (value.getMeasure( ) / 100 * parent);
}
else
{
return (int) (value.convertTo( DimensionType.UNITS_PT ));
}
}
}
|
package net.drewke.tdme.gui.elements;
import net.drewke.tdme.gui.events.GUIKeyboardEvent;
import net.drewke.tdme.gui.events.GUIMouseEvent;
import net.drewke.tdme.gui.events.GUIMouseEvent.Type;
import net.drewke.tdme.gui.nodes.GUIElementNode;
import net.drewke.tdme.gui.nodes.GUINode;
import net.drewke.tdme.gui.nodes.GUINodeController;
/**
* GUI input controller
* @author Andreas Drewke
* @version $Id$
*/
public final class GUIInputController extends GUINodeController {
/**
* GUI Checkbox controller
* @param node
*/
protected GUIInputController(GUINode node) {
super(node);
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.GUINodeController#init()
*/
public void init() {
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.GUINodeController#dispose()
*/
public void dispose() {
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#handleMouseEvent(net.drewke.tdme.gui.nodes.GUINode, net.drewke.tdme.gui.events.GUIMouseEvent)
*/
public void handleMouseEvent(GUINode node, GUIMouseEvent event) {
if (node == this.node &&
node.isEventBelongingToNode(event) &&
event.getButton() == 1) {
// set focussed node
node.getScreenNode().setFoccussedNode((GUIElementNode)node);
// set event processed
event.setProcessed(true);
}
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#handleKeyboardEvent(net.drewke.tdme.gui.nodes.GUINode, net.drewke.tdme.gui.events.GUIKeyboardEvent)
*/
public void handleKeyboardEvent(GUINode node, GUIKeyboardEvent event) {
// no op for now
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#onFocusGained()
*/
public void onFocusGained() {
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#onFocusLost()
*/
public void onFocusLost() {
}
}
|
package org.elasticsearch.index.analysis;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
public class PhoneTokenizer extends Tokenizer {
// The raw input
private String stringToTokenize = null;
// Position in the tokens array. We build all the tokens and return them one at a time as incrementToken
// gets called.
private int position = 0;
/**
* The tokens are determined on the first iteration and then returned one at a time thereafter.
*/
private List<String> tokens = null;
// The base class grabs the charTermAttribute each time incrementToken returns
protected CharTermAttribute charTermAttribute = addAttribute(CharTermAttribute.class);
public PhoneTokenizer() {
}
@Override
public final boolean incrementToken() throws IOException {
// Clear anything that is already saved in this.charTermAttribute
this.charTermAttribute.setEmpty();
if (tokens == null) {
// It's the 1st iteration, chop it up into tokens.
generateTokens();
}
// Return those tokens
return returnTokensOneAtATime();
}
private boolean returnTokensOneAtATime() {
// Token have already been generated. Return them 1 at a time
if (tokens != null) {
if (this.position == tokens.size()) {
// No more tokens
return false;
}
// return each token, 1 at a time
this.charTermAttribute.append(tokens.get(this.position));
this.position += 1;
return true;
}
return false;
}
private void generateTokens() {
String uri = getStringToTokenize();
tokens = new ArrayList<String>();
tokens.add(getStringToTokenize());
// Rip off the "tel:" or "sip:" prefix
if (uri.indexOf("tel:") != -1 || uri.indexOf("sip:") != -1) {
uri = uri.substring(4);
} else {
// If it's not formatted at least this correctly then the whole string is 1 token. Sorry, put a
// tel: or sip: at the beginning so we know how to treat it
tokens.add(getStringToTokenize());
return;
}
// Drop anything after @. Most likely there's nothing of interest
String[] parts = StringUtils.split(uri, "@");
if (parts.length == 0) {
return;
}
String number = parts[0];
// Add a token for the raw unmanipulated address. Note this could be a username (sip) instead of
// telephone number so take it as is
tokens.add(number);
// Let google's libphone try to parse it
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber numberProto = null;
String countryCode = null;
try {
// ZZ is the generic "I don't know the country code" region. Google's libphone library will try to
// infer it.
//>>>>>>>>>>>>>>test
int indexOfPhoneContext = number.indexOf(";phone-context=");
if (indexOfPhoneContext > 0) {
int phoneContextStart = indexOfPhoneContext + ";phone-context=".length();
if (number.length() <= phoneContextStart) {
System.out.println(">>>test number = "+number+", phoneContextStart= "+phoneContextStart+", number len= "+number.length());
}
}
numberProto = phoneUtil.parse(number, "ZZ");
if (numberProto != null) {
// Libphone likes it!
countryCode = String.valueOf(numberProto.getCountryCode());
number = String.valueOf(numberProto.getNationalNumber());
// Add Country code, extension, and the number as tokens
tokens.add(countryCode);
if (!StringUtils.isEmpty(numberProto.getExtension())) {
tokens.add(numberProto.getExtension());
}
tokens.add(number);
}
} catch (NumberParseException e) {
// Libphone didn't like it, no biggie. We'll just ngram the number as it is.
}
// ngram the phone number EG 19198243333 produces 9, 91, 919, etc
if (NumberUtils.isNumber(number)) {
for (int count = 1; count <= number.length(); count++) {
String token = number.substring(0, count);
tokens.add(token);
if (countryCode != null) {
// If there was a country code, add more ngrams such that 19198243333 produces 19, 191,
// 1919, etc
tokens.add(countryCode + token);
}
}
}
}
/**
* Read the input into a local variable
*
* @return
*/
private String getStringToTokenize() {
if (this.stringToTokenize == null) {
try {
this.stringToTokenize = IOUtils.toString(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return this.stringToTokenize;
}
/**
* Nuke all state after each use (lucene will re-use an instance of this tokenizer over and over again)
*/
@Override
public final void reset() throws IOException {
super.reset();
this.position = 0;
tokens = null;
this.stringToTokenize = null;
clearAttributes();
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-08-13");
this.setApiVersion("17.5.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package org.eclipse.birt.report.engine.emitter.excel;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import org.eclipse.birt.chart.util.CDateTime;
import org.eclipse.birt.core.format.NumberFormatter;
import org.eclipse.birt.core.format.StringFormatter;
import org.eclipse.birt.report.engine.emitter.excel.GroupInfo.Position;
import org.eclipse.birt.report.engine.ir.DimensionType;
import com.ibm.icu.text.DecimalFormat;
import com.ibm.icu.text.SimpleDateFormat;
public class ExcelUtil
{
protected static Logger log = Logger.getLogger( ExcelUtil.class.getName( ) );
public static String ridQuote( String val )
{
if ( val.charAt( 0 ) == '"' && val.charAt( val.length( ) - 1 ) == '"' )
{
return val.substring( 1, val.length( ) - 1 );
}
return val;
}
private static String invalidBookmarkChars =
"`~!@#$%^&*()-=+\\|[]{};:'\",./?>< \t\n\r";
// This check can not cover all cases, cause we do not know exactly the
// excel range name restraint.
public static boolean isValidBookmarkName( String name )
{
if( name.equalsIgnoreCase( "r" ) )
{
return false;
}
if( name.equalsIgnoreCase( "c" ) )
{
return false;
}
for ( int i = 0; i < name.length( ); i++ )
{
if( invalidBookmarkChars.indexOf( name.charAt( i ) ) != -1 )
{
return false;
}
}
//The bookmark name can not start with a digit.
if (name.matches( "[0-9].*" ))
{
return false;
}
//columnID<=IV, rowID<=65536 can not be used as bookmark.
if( name.matches("([A-Za-z]|[A-Ha-h][A-Za-z]|[Ii][A-Va-v])[0-9]{1,5}" ))
{
String[] strs = name.split( "[A-Za-z]" );
if (strs.length>0)
{
int rowId = 0;
try
{
rowId = Integer.parseInt( strs[strs.length-1]);
}
catch( NumberFormatException e )
{
return true;
}
if (rowId<=65536)
{
return false;
}
else
{
return true;
}
}
return true;
}
return true;
}
public static String formatDate( Object data )
{
if(data == null) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss" );
Date date = null;
if(data instanceof com.ibm.icu.util.Calendar) {
date = ((com.ibm.icu.util.Calendar) data).getTime( );
}
else if(data instanceof Date) {
date = (Date) data;
}
else {
return null;
}
return dateFormat.format( date );
}
public static String formatNumber( Object data)
{
DecimalFormat numberFormat = new DecimalFormat("0.00E00");
return numberFormat.format( (Number)data);
}
public static String getType(Object val)
{
if ( val instanceof Number )
{
if(isNumber(val.toString( ))){
return Data.NUMBER;
}
else{
return Data.STRING;
}
}
else if(val instanceof Date)
{
return Data.DATE;
}
else if (val instanceof Calendar)
{
return Data.CALENDAR;
}
// else if(val instanceof CDateTime)
// return Data.CDATETIME;
else
{
return Data.STRING;
}
}
private static String replaceDateFormat( String pattern )
{
if ( pattern == null )
{
String rg = "";
return rg;
}
StringBuffer toAppendTo = new StringBuffer( );
boolean inQuote = false;
char prevCh = 0;
int count = 0;
for ( int i = 0; i < pattern.length( ); ++i )
{
char ch = pattern.charAt( i );
if ( ch != prevCh && count > 0 )
{
toAppendTo.append( subReplaceDateFormat( prevCh, count ) );
count = 0;
}
if ( ch == '/' )
{
toAppendTo.append( '\\' );
toAppendTo.append( ch );
}
else if ( ch == '\'' )
{
if ( ( i + 1 ) < pattern.length( )
&& pattern.charAt( i + 1 ) == '\'' )
{
toAppendTo.append( "\"" );
++i;
}
else
{
inQuote = !inQuote;
}
}
else if ( !inQuote )
{
prevCh = ch;
++count;
}
else
{
toAppendTo.append( ch );
}
}
if ( count > 0 )
{
toAppendTo.append( subReplaceDateFormat( prevCh, count ) );
}
return toAppendTo.toString( );
}
/**
* only used in the method replaceDataFormat().
*/
private static String subReplaceDateFormat( char ch, int count )
{
String current = "";
int patternCharIndex = -1;
String datePatternChars = "GyMdkHmsSEDFwWahKz";
if ( ( patternCharIndex = datePatternChars.indexOf( ch ) ) == -1 )
{
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
return current;
}
switch ( patternCharIndex )
{
case 0 : // 'G' - ERA
current = "";
break;
case 1 : // 'y' - YEAR
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 2 : // 'M' - MONTH
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 3 : // 'd' - Date
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 4 : // 'k' - HOUR_OF_DAY: 1-based. eg, 23:59 + 1 hour =>>
// 24:59
current = "h";
break;
case 5 : // case 5: // 'H'-HOUR_OF_DAY:0-based.eg, 23:59+1
// hour=>>00:59
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 6 : // case 6: // 'm' - MINUTE
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 7 : // case 7: // 's' - SECOND
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 8 : // case 8: // 'S' - MILLISECOND
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 9 : // 'E' - DAY_OF_WEEK
for ( int i = 0; i < count; i++ )
{
current += "a";
}
break;
case 14 : // 'a' - AM_PM
current = "AM/PM";
break;
case 15 : // 'h' - HOUR:1-based. eg, 11PM + 1 hour =>> 12 AM
for ( int i = 0; i < count; i++ )
{
current += "" + ch;
}
break;
case 17 : // 'z' - ZONE_OFFSET
current = "";
break;
default :
// case 10: // 'D' - DAY_OF_YEAR
// case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
// case 12: // 'w' - WEEK_OF_YEAR
// case 13: // 'W' - WEEK_OF_MONTH
// case 16: // 'K' - HOUR: 0-based. eg, 11PM + 1 hour =>> 0 AM
current = "";
break;
}
return current;
}
public static String getPattern(Object data, String val)
{
if(val != null && data instanceof Date) {
return replaceDateFormat(val);
}
else if(val == null && data instanceof Time) {
return "Long Time";
}
else if(val == null && data instanceof java.sql.Date)
{
// According to java SDK 1.4.2-16, sql.Date doesn't have
// a time component.
return "mmm d, yyyy";// hh:mm AM/PM";
}
else if(val == null && data instanceof java.util.Date)
{
return "mmm d, yyyy h:mm AM/PM";
}
else if(val != null && data instanceof Number)
{
if(val.indexOf( "E" ) >= 0){
return "Scientific";
}
return new NumberFormatter(val).getPattern( );
}
else if(val != null && data instanceof String)
{
return new StringFormatter(val).getPattern( );
}
return null;
}
public static String replaceAll(String str, String old, String news) {
if(str == null) {
return str;
}
int begin = 0;
int idx = 0;
int len = old.length();
StringBuffer buf = new StringBuffer();
while((idx = str.indexOf(old, begin)) >= 0) {
buf.append(str.substring(begin, idx));
buf.append(news);
begin = idx + len;
}
return new String(buf.append(str.substring(begin)));
}
// TODO
public static String getValue( String val )
{
if ( val == null )
{
return StyleConstant.NULL;
}
if ( val.charAt( 0 ) == '"' && val.charAt( val.length( ) - 1 ) == '"' )
{
return val.substring( 1, val.length( ) - 1 );
}
return val;
}
public static int convertToPt( String size )
{
try
{
int s = Integer.valueOf( size.substring( 0, size.length( ) - 2 ) )
.intValue( );
if ( size.endsWith( "in" ) )
{
return s * 72;
}
else if ( size.endsWith( "cm" ) )
{
return (int) ( s / 2.54 * 72 );
}
else if ( size.endsWith( "mm" ) )
{
return (int) ( s * 10 / 2.54 * 72 );
}
else if ( size.endsWith( "pc" ) )
{
return s;
}
else
{
return s;
}
}
catch ( Exception e )
{
log.log(Level.WARNING, "unknown size: " + size);
// e.printStackTrace( );
return 0;
}
}
// the parse method can just see if the start of the String is a number
// like "123 bbs"
// it will parse successful and returns the value of 123 in number
public static boolean isNumber( String val )
{
try
{
new BigDecimal(val);
return true;
}
catch ( Exception e )
{
return false;
}
}
public static String getColumnOfExp( String exp )
{
return exp.substring( exp.indexOf( "dataSetRow[" ), exp
.lastIndexOf( "]" ) + 1 );
}
private static final int max_formula_length = 512;
public static String createFormula( String txt, String exp, List positions )
{
exp = getFormulaName( exp );
StringBuffer sb = new StringBuffer( exp + "(" );
for ( int i = 0; i < positions.size( ); i++ )
{
Position p = (Position) positions.get( i );
sb.append( "R" + p.row + "C" + p.column + "," );
}
sb.setCharAt( sb.length( ) - 1, ')' );
if ( sb.length( ) > max_formula_length || positions.size( ) == 0 )
{
return txt;
}
return sb.toString( );
}
private static String getFormulaName( String expression )
{
if ( expression.startsWith( "Total.sum" ) )
{
return "=SUM";
}
else if ( expression.startsWith( "Total.ave" ) )
{
return "=AVERAGE";
}
else if ( expression.startsWith( "Total.max" ) )
{
return "=MAX";
}
else if ( expression.startsWith( "Total.min" ) )
{
return "=MIN";
}
else if ( expression.startsWith( "Total.count" ) )
{
return "=COUNT";
}
throw new RuntimeException( "Cannot parse the expression" + expression );
}
private static final String reg1 = "Total." + "(count|ave|sum|max|min)"
+ "\\(", reg2 = "\\)", reg3 = "\\[", reg4 = "\\]";
public static boolean isValidExp( String exp, String[] columnNames )
{
StringBuffer sb = new StringBuffer( );
for ( int i = 0; i < columnNames.length; i++ )
{
sb.append( columnNames[i] + "|" );
}
String columnRegExp = "(" + sb.substring( 0, sb.length( ) - 1 ) + ")";
columnRegExp = columnRegExp.replaceAll( reg3, "Z" );
columnRegExp = columnRegExp.replaceAll( reg4, "Z" );
String aggregateRegExp = reg1 + columnRegExp + reg2;
exp = exp.replaceAll( reg3, "Z" );
exp = exp.replaceAll( reg4, "Z" );
Pattern p = Pattern.compile( aggregateRegExp );
Matcher m = p.matcher( exp );
boolean agg = m.matches( );
p = Pattern.compile( columnRegExp );
m = p.matcher( exp );
return agg || m.matches( );
}
public static String expression( String val, String target, String[] res,
boolean casesenstive )
{
boolean flag = casesenstive ? target.equals( val ) : target
.equalsIgnoreCase( val );
return flag ? res[1] : res[0];
}
public static int covertDimensionType( DimensionType value, int parent )
{
if ( DimensionType.UNITS_PERCENTAGE.equals( value.getUnits( ) ) )
{
return (int) (value.getMeasure( ) / 100 * parent);
}
else
{
return (int) (value.convertTo( DimensionType.UNITS_PT ));
}
}
public static String parse(String dateTime)
{
if(dateTime == null)
{
return "";
}
if(dateTime.indexOf( "Date" ) != -1)
{
return dateTime;
}
StringBuffer buffer = new StringBuffer();
boolean inQuto = false;
for(int count = 0 ; count < dateTime.length(); count ++)
{
char tempChar = dateTime.charAt(count);
if(inQuto)
{
if(tempChar == '\'' && nextIsQuto(dateTime , count))
{
buffer.append( tempChar );
count ++;
}
else
{
if(tempChar == '\'')
{
inQuto = false;
}
else
{
buffer.append( tempChar );
}
}
}
else
{
if(tempChar == '\'')
{
if(nextIsQuto(dateTime , count))
{
buffer.append( tempChar );
count ++;
}
else
{
inQuto = true;
}
}
else
{
if(tempChar == 'a')
{
buffer.append( "AM/PM" );
continue;
}
if("zZ,kKFWwGE".indexOf( tempChar ) != -1)
{
continue;
}
buffer.append( tempChar );
}
}
}
return buffer.toString( );
}
private static boolean nextIsQuto(String forPar , int index)
{
if( forPar.length() - 1 == index )
{
return false;
}
if(forPar.charAt(index + 1) == '\'')
{
return true;
}
return false;
}
}
|
package net.sf.mzmine.userinterface.mainwindow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import net.sf.mzmine.io.IOController;
import net.sf.mzmine.io.MZmineProject;
import net.sf.mzmine.io.RawDataFile;
import net.sf.mzmine.io.RawDataFile.PreloadLevel;
import net.sf.mzmine.methods.alignment.AlignmentResult;
import net.sf.mzmine.visualizers.alignmentresult.AlignmentResultVisualizerCDAPlotView;
import net.sf.mzmine.visualizers.alignmentresult.AlignmentResultVisualizerCoVarPlotView;
import net.sf.mzmine.visualizers.alignmentresult.AlignmentResultVisualizerLogratioPlotView;
import net.sf.mzmine.visualizers.alignmentresult.AlignmentResultVisualizerSammonsPlotView;
import net.sf.mzmine.visualizers.rawdata.spectra.SpectrumVisualizer;
import net.sf.mzmine.visualizers.rawdata.tic.TICVisualizer;
import net.sf.mzmine.visualizers.rawdata.twod.TwoDVisualizer;
import sunutils.ExampleFileFilter;
class MainMenu extends JMenuBar implements ActionListener {
private JMenu fileMenu;
private JMenuItem fileOpen;
private JMenuItem fileClose;
private JMenuItem fileExportPeakList;
private JMenuItem fileImportAlignmentResult;
private JMenuItem fileSaveParameters;
private JMenuItem fileLoadParameters;
private JMenuItem filePrint;
private JMenuItem fileExit;
private JMenu editMenu;
private JMenuItem editCopy;
private JMenu filterMenu;
private JMenuItem ssMeanFilter;
private JMenuItem ssSGFilter;
private JMenuItem ssChromatographicMedianFilter;
private JMenuItem ssCropFilter;
private JMenuItem ssZoomScanFilter;
private JMenu peakMenu;
private JMenuItem ssRecursiveThresholdPicker;
private JMenuItem ssLocalPicker;
private JMenuItem ssCentroidPicker;
private JMenuItem ssSimpleDeisotoping;
private JMenuItem ssCombinatorialDeisotoping;
private JMenuItem ssIncompleteIsotopePatternFilter;
private JMenu alignmentMenu;
private JMenuItem tsJoinAligner;
private JMenuItem tsFastAligner;
private JMenuItem tsAlignmentFilter;
private JMenuItem tsEmptySlotFiller;
private JMenu normalizationMenu;
private JMenuItem normLinear;
private JMenuItem normStdComp;
private JMenu batchMenu;
private JMenuItem batDefine;
private JMenu analysisMenu;
private JMenuItem anOpenSRView;
private JMenuItem anOpenSCVView;
private JMenuItem anOpenCDAView;
private JMenuItem anOpenSammonsView;
private JMenu toolsMenu;
private JMenuItem toolsOptions;
private JMenu windowMenu;
private JMenuItem windowTileWindows;
private JMenu helpMenu;
private JMenuItem hlpAbout;
private Statusbar statBar;
private MainWindow mainWin;
private ItemSelector itemSelector;
MainMenu() {
mainWin = MainWindow.getInstance();
statBar = mainWin.getStatusBar();
itemSelector = mainWin.getItemSelector();
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
fileOpen = new JMenuItem("Open...", KeyEvent.VK_O);
fileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
ActionEvent.CTRL_MASK));
fileOpen.addActionListener(this);
fileClose = new JMenuItem("Close", KeyEvent.VK_C);
fileClose.addActionListener(this);
fileClose.setEnabled(false);
fileExportPeakList = new JMenuItem("Export...", KeyEvent.VK_E);
fileExportPeakList.addActionListener(this);
fileExportPeakList.setEnabled(false);
fileImportAlignmentResult = new JMenuItem("Import alignment result...",
KeyEvent.VK_I);
fileImportAlignmentResult.addActionListener(this);
fileImportAlignmentResult.setEnabled(true);
fileSaveParameters = new JMenuItem("Save parameters...", KeyEvent.VK_S);
fileSaveParameters.addActionListener(this);
fileSaveParameters.setEnabled(true);
fileLoadParameters = new JMenuItem("Load parameters...", KeyEvent.VK_S);
fileLoadParameters.addActionListener(this);
fileLoadParameters.setEnabled(true);
filePrint = new JMenuItem("Print figure...", KeyEvent.VK_P);
filePrint.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
ActionEvent.CTRL_MASK));
filePrint.addActionListener(this);
filePrint.setEnabled(false);
fileExit = new JMenuItem("Exit", KeyEvent.VK_X);
fileExit.addActionListener(this);
fileMenu.add(fileOpen);
fileMenu.add(fileClose);
fileMenu.addSeparator();
fileMenu.add(fileExportPeakList);
fileMenu.add(fileImportAlignmentResult);
fileMenu.addSeparator();
fileMenu.add(fileLoadParameters);
fileMenu.add(fileSaveParameters);
fileMenu.addSeparator();
fileMenu.add(filePrint);
fileMenu.addSeparator();
fileMenu.add(fileExit);
this.add(fileMenu);
editMenu = new JMenu();
editMenu.setText("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
editMenu.addActionListener(this);
editCopy = new JMenuItem("Copy", KeyEvent.VK_C);
editCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
ActionEvent.CTRL_MASK));
editCopy.addActionListener(this);
editCopy.setEnabled(false);
editMenu.add(editCopy);
this.add(editMenu);
filterMenu = new JMenu();
filterMenu.setText("Raw data filtering");
filterMenu.setMnemonic(KeyEvent.VK_R);
filterMenu.addActionListener(this);
ssMeanFilter = new JMenuItem("Mean filter spectra", KeyEvent.VK_M);
ssMeanFilter.addActionListener(this);
ssMeanFilter.setEnabled(false);
ssSGFilter = new JMenuItem("Savitzky-Golay filter spectra",
KeyEvent.VK_S);
ssSGFilter.addActionListener(this);
ssSGFilter.setEnabled(false);
ssChromatographicMedianFilter = new JMenuItem(
"Chromatographic median filter", KeyEvent.VK_S);
ssChromatographicMedianFilter.addActionListener(this);
ssChromatographicMedianFilter.setEnabled(false);
ssCropFilter = new JMenuItem("Cropping filter", KeyEvent.VK_C);
ssCropFilter.addActionListener(this);
ssCropFilter.setEnabled(false);
ssZoomScanFilter = new JMenuItem("Zoom scan filter", KeyEvent.VK_Z);
ssZoomScanFilter.addActionListener(this);
ssZoomScanFilter.setEnabled(false);
filterMenu.add(ssMeanFilter);
filterMenu.add(ssSGFilter);
filterMenu.add(ssChromatographicMedianFilter);
filterMenu.add(ssCropFilter);
filterMenu.add(ssZoomScanFilter);
this.add(filterMenu);
peakMenu = new JMenu();
peakMenu.setText("Peak detection");
peakMenu.setMnemonic(KeyEvent.VK_P);
peakMenu.addActionListener(this);
ssRecursiveThresholdPicker = new JMenuItem();
ssRecursiveThresholdPicker.setText("Recursive threshold peak detector");
ssRecursiveThresholdPicker.addActionListener(this);
ssRecursiveThresholdPicker.setEnabled(false);
ssLocalPicker = new JMenuItem();
ssLocalPicker.setText("Local maxima peak detector");
ssLocalPicker.addActionListener(this);
ssLocalPicker.setEnabled(false);
ssCentroidPicker = new JMenuItem();
ssCentroidPicker.setText("Centroid peak detector");
ssCentroidPicker.addActionListener(this);
ssCentroidPicker.setEnabled(false);
ssSimpleDeisotoping = new JMenuItem();
ssSimpleDeisotoping.setText("Simple deisotoper");
ssSimpleDeisotoping.addActionListener(this);
ssSimpleDeisotoping.setEnabled(false);
ssCombinatorialDeisotoping = new JMenuItem();
ssCombinatorialDeisotoping.setText("Combinatorial deisotoping");
ssCombinatorialDeisotoping.addActionListener(this);
ssCombinatorialDeisotoping.setEnabled(false);
ssIncompleteIsotopePatternFilter = new JMenuItem();
ssIncompleteIsotopePatternFilter
.setText("Filter incomplete isotope patterns");
ssIncompleteIsotopePatternFilter.addActionListener(this);
ssIncompleteIsotopePatternFilter.setEnabled(false);
peakMenu.add(ssRecursiveThresholdPicker);
peakMenu.add(ssLocalPicker);
peakMenu.add(ssCentroidPicker);
peakMenu.addSeparator();
peakMenu.add(ssSimpleDeisotoping);
peakMenu.add(ssIncompleteIsotopePatternFilter);
this.add(peakMenu);
alignmentMenu = new JMenu();
alignmentMenu.setText("Alignment");
alignmentMenu.setMnemonic(KeyEvent.VK_A);
alignmentMenu.addActionListener(this);
tsJoinAligner = new JMenuItem("Slow aligner", KeyEvent.VK_S);
tsJoinAligner.addActionListener(this);
tsFastAligner = new JMenuItem("Fast aligner", KeyEvent.VK_A);
tsFastAligner.addActionListener(this);
tsAlignmentFilter = new JMenuItem("Filter out rare peaks",
KeyEvent.VK_R);
tsAlignmentFilter.addActionListener(this);
tsEmptySlotFiller = new JMenuItem("Fill-in empty gaps", KeyEvent.VK_F);
tsEmptySlotFiller.addActionListener(this);
alignmentMenu.add(tsJoinAligner);
alignmentMenu.add(tsFastAligner);
alignmentMenu.addSeparator();
alignmentMenu.add(tsAlignmentFilter);
alignmentMenu.add(tsEmptySlotFiller);
this.add(alignmentMenu);
normalizationMenu = new JMenu();
normalizationMenu.setText("Normalization");
normalizationMenu.setMnemonic(KeyEvent.VK_N);
normalizationMenu.addActionListener(this);
normLinear = new JMenuItem("Linear normalization", KeyEvent.VK_L);
normLinear.addActionListener(this);
normStdComp = new JMenuItem("Normalization using standards",
KeyEvent.VK_N);
normStdComp.addActionListener(this);
normalizationMenu.add(normLinear);
normalizationMenu.add(normStdComp);
this.add(normalizationMenu);
batchMenu = new JMenu();
batchMenu.setText("Batch mode");
batchMenu.setMnemonic(KeyEvent.VK_B);
batchMenu.addActionListener(this);
batDefine = new JMenuItem("Define batch operations", KeyEvent.VK_R);
batDefine.addActionListener(this);
batchMenu.add(batDefine);
this.add(batchMenu);
analysisMenu = new JMenu();
analysisMenu.setText("Visualization");
analysisMenu.setMnemonic(KeyEvent.VK_V);
analysisMenu.addActionListener(this);
anOpenSRView = new JMenuItem("Logratio plot", KeyEvent.VK_L);
anOpenSRView.addActionListener(this);
anOpenSCVView = new JMenuItem("Coefficient of variation plot",
KeyEvent.VK_V);
anOpenSCVView.addActionListener(this);
anOpenCDAView = new JMenuItem("CDA plot of samples", KeyEvent.VK_C);
anOpenCDAView.addActionListener(this);
anOpenCDAView.setEnabled(false);
anOpenSammonsView = new JMenuItem("Sammons plot of samples",
KeyEvent.VK_S);
anOpenSammonsView.addActionListener(this);
anOpenSammonsView.setEnabled(false);
analysisMenu.add(anOpenSRView);
analysisMenu.add(anOpenSCVView);
analysisMenu.add(anOpenCDAView);
analysisMenu.add(anOpenSammonsView);
this.add(analysisMenu);
toolsMenu = new JMenu();
toolsMenu.setText("Configure");
toolsMenu.setMnemonic(KeyEvent.VK_C);
toolsMenu.addActionListener(this);
toolsOptions = new JMenuItem("Preferences...", KeyEvent.VK_P);
toolsOptions.addActionListener(this);
toolsMenu.add(toolsOptions);
this.add(toolsMenu);
windowMenu = new JMenu();
windowMenu.setText("Window");
windowMenu.setMnemonic(KeyEvent.VK_W);
windowMenu.addActionListener(this);
windowTileWindows = new JMenuItem("Tile Windows", KeyEvent.VK_T);
windowTileWindows.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
ActionEvent.CTRL_MASK));
windowTileWindows.addActionListener(this);// windowTileWindows.setEnabled(false);
windowMenu.add(windowTileWindows);
this.add(windowMenu);
helpMenu = new JMenu();
helpMenu.setText("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.addActionListener(this);
hlpAbout = new JMenuItem("About MZmine...", KeyEvent.VK_A);
hlpAbout.addActionListener(this);
hlpAbout.setEnabled(true);
helpMenu.add(hlpAbout);
this.add(helpMenu);
}
/**
* ActionListener interface implementation
*/
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
// File -> Open
if (src == fileOpen) {
// statBar.setStatusText("Please select a data file to open");
// Open file dialog
JFileChooser fileOpenChooser = new JFileChooser();
fileOpenChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileOpenChooser.setMultiSelectionEnabled(true);
fileOpenChooser.setDialogTitle("Please select data files to open");
JCheckBox preloadCheckBox = new JCheckBox(
"Preload all data into memory? (use with caution)");
fileOpenChooser.setAccessory(preloadCheckBox);
/*
* if (dataDirectory == null) { dataDirectory =
* clientForCluster.getDataRootPath(); }
*/
// fileOpenChooser.setCurrentDirectory(new File(dataDirectory));
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension("CDF");
filter.addExtension("nc");
filter.addExtension("XML");
filter.addExtension("mzXML");
filter.setDescription("Raw data files");
fileOpenChooser.setFileFilter(filter);
int retval = fileOpenChooser.showOpenDialog(this);
// If ok to go on with file open
if (retval == JFileChooser.APPROVE_OPTION) {
File[] selectedFiles = fileOpenChooser.getSelectedFiles();
PreloadLevel preloadLevel = PreloadLevel.NO_PRELOAD;
if (preloadCheckBox.isSelected()) preloadLevel = PreloadLevel.PRELOAD_ALL_SCANS;
IOController.getInstance().openFiles(selectedFiles,
preloadLevel);
/*
* String[] dataFilePaths = new String[selectedFiles.length];
*
*
* for (int i=0; i<selectedFiles.length; i++) { File f =
* selectedFiles[i];
*
* if (f.exists()) { dataFilePaths[i] = f.getPath(); // Update
* dataDirectory String tmppath = f.getPath().substring(0,
* f.getPath().length()-f.getName().length()); dataDirectory =
* new String(tmppath); } else { displayErrorMessage("File " + f + "
* does not exist."); return; } }
*
* clientForCluster.openRawDataFiles(dataFilePaths);
*/
} else {
statBar.setStatusText("File open cancelled.");
}
}
// File->Close
if (src == fileClose) {
// Grab selected raw data files
RawDataFile[] selectedFiles = itemSelector.getSelectedRawData();
for (RawDataFile file : selectedFiles)
MZmineProject.getCurrentProject().removeFile(file);
// mainWin.closeRawDataFiles(rawDataIDs);
// int[] alignmentResultIDs = itemSelector
// .getSelectedAlignmentResultIDs();
// mainWin.closeAlignmentResults(alignmentResultIDs);
}
// File->Export table
/*
* if (src == fileExportPeakList) {
*
* RawDataAtClient[] rawDatas = itemSelector.getSelectedRawDatas();
*
* for (RawDataAtClient r : rawDatas) {
*
* statBar.setStatusText("Writing peak list for file " +
* r.getNiceName());
*
* if (!r.hasPeakData()) { // No peak list available for active run try {
* JOptionPane.showInternalMessageDialog( mainWin.mainWin.getDesktop,
* "No peak data available for " + r.getNiceName() + ". Please run a
* peak picker first.", "Sorry", JOptionPane.ERROR_MESSAGE ); } catch
* (Exception exce ) {}
*
* statBar.setStatusText("Peak list export failed."); } else { //
* Generate name for the peak list file StringTokenizer st = new
* StringTokenizer(r.getNiceName(),"."); String peakListName=""; String
* peakListPath=""; String toke = ""; while (st.hasMoreTokens()) { toke =
* st.nextToken(); if (st.hasMoreTokens()) { peakListName += toke; } }
* peakListName += "_MZminePeakList" + "." + "txt"; // Save file dialog
* JFileChooser fileSaveChooser = new JFileChooser();
* fileSaveChooser.setDialogType(JFileChooser.SAVE_DIALOG);
* fileSaveChooser.setMultiSelectionEnabled(false);
* fileSaveChooser.setDialogTitle("Please give file name for peak list
* of " + r.getNiceName()); statBar.setStatusText("Please give file name
* for peak list of " + r.getNiceName()); //if (dataDirectory!=null) {
* //fileSaveChooser.setCurrentDirectory(new File(dataDirectory)); //}
*
* fileSaveChooser.setSelectedFile(new File(peakListName));
*
* ExampleFileFilter filter = new ExampleFileFilter();
* filter.addExtension("txt"); filter.setDescription("Peak list as
* tab-delimitted text file");
*
* fileSaveChooser.setFileFilter(filter); int retval =
* fileSaveChooser.showSaveDialog(this);
*
* if(retval == JFileChooser.APPROVE_OPTION) { File selectedFile =
* fileSaveChooser.getSelectedFile();
*
* String tmpfullpath = selectedFile.getPath(); String datafilename =
* selectedFile.getName(); String datafilepath =
* tmpfullpath.substring(0, tmpfullpath.length()-datafilename.length()); //
* dataDirectory = new String(datafilepath);
*
* peakListName = tmpfullpath;
*
* if (PeakListExporter.writePeakListToFile(r, peakListName)) {
* statBar.setStatusText("Peak list export done."); } else {
* mainWin.displayErrorMessage("Failed to write peak list for raw data " +
* r.getNiceName()); statBar.setStatusText("Peak list export failed."); } }
* else { statBar.setStatusText("Peak list export cancelled."); } } }
*
*
* Vector<AlignmentResult> results =
* itemSelector.getSelectedAlignmentResults();
*
* if (results.size()>0) { AlignmentResultExporterParameters areParams =
* mainWin.getParameterStorage().getAlignmentResultExporterParameters();
* GeneralParameters genParams =
* mainWin.getParameterStorage().getGeneralParameters();
* AlignmentResultExporterParameterSetupDialog arepsd = new
* AlignmentResultExporterParameterSetupDialog(genParams, areParams);
* statBar.setStatusText("Please select columns for alignment result
* exporting."); arepsd.showModal(mainWin.getDesktop);
*
* if (arepsd.getExitCode()==-1) { statBar.setStatusText("Alignment
* result export cancelled."); return; }
*
* parameterStorage.setAlignmentResultExporterParameters(areParams);
*
*
*
* for (int i=0; i<results.size(); i++) { AlignmentResult result =
* results.get(i);
*
* statBar.setStatusText("Writing alignment result " +
* result.getNiceName() + " to file.");
*
* String resultName = result.getNiceName() + ".txt"; // Save file
* dialog JFileChooser fileSaveChooser = new JFileChooser();
* fileSaveChooser.setDialogType(JFileChooser.SAVE_DIALOG);
* fileSaveChooser.setMultiSelectionEnabled(false);
* fileSaveChooser.setDialogTitle("Please give file name for alignment
* result " + result.getNiceName()); if (dataDirectory!=null) {
* fileSaveChooser.setCurrentDirectory(new File(dataDirectory)); }
*
* fileSaveChooser.setSelectedFile(new File(resultName));
*
* ExampleFileFilter filter = new ExampleFileFilter();
* filter.addExtension("txt"); filter.setDescription("Alignment results
* as tab-delimitted text file");
*
* fileSaveChooser.setFileFilter(filter); int retval =
* fileSaveChooser.showSaveDialog(this);
*
* if(retval == JFileChooser.APPROVE_OPTION) { File selectedFile =
* fileSaveChooser.getSelectedFile();
*
* String tmpfullpath = selectedFile.getPath(); String datafilename =
* selectedFile.getName(); String datafilepath =
* tmpfullpath.substring(0, tmpfullpath.length()-datafilename.length());
* dataDirectory = new String(datafilepath);
*
* resultName = datafilepath + datafilename;
*
*
* //result.writeResultsToFile(resultName, areParams, this);
* AlignmentResultExporter.exportAlignmentResultToFile(result,
* resultName, areParams, this); statBar.setStatusText("Alignment result
* export done."); } else { statBar.setStatusText("Alignment result
* export cancelled."); } } }
*
* }
*
* if (src == fileLoadParameters) { statBar.setStatusText("Please select
* a parameter file"); // Open file dialog JFileChooser fileOpenChooser =
* new JFileChooser();
* fileOpenChooser.setDialogType(JFileChooser.OPEN_DIALOG);
* fileOpenChooser.setMultiSelectionEnabled(false);
* fileOpenChooser.setDialogTitle("Please select parameter file"); //
* fileOpenChooser.setCurrentDirectory(new
* File(clientForCluster.getDataRootPath()));
*
* ExampleFileFilter filter = new ExampleFileFilter();
* filter.addExtension("XML"); filter.setDescription("MZmine parameters
* file");
*
* fileOpenChooser.setFileFilter(filter); int retval =
* fileOpenChooser.showOpenDialog(this); // If ok to go on with file
* open if(retval == JFileChooser.APPROVE_OPTION) {
*
* File selectedFile = fileOpenChooser.getSelectedFile(); if
* (!(selectedFile.exists())) { displayErrorMessage("Parameter file " +
* selectedFile + " does not exist!"); statBar.setStatusText("Parameter
* file loading failed."); return; } if
* (mainWin.getParameterStorage().readParametesFromFile(selectedFile)) {
* statBar.setStatusText("Parameter file loading done."); } else {
* displayErrorMessage("Parameter file " + selectedFile + " loading
* failed!"); statBar.setStatusText("Parameter file loading failed."); } }
* else { statBar.setStatusText("Parameter file loading cancelled."); } }
*
*
* if (src == fileSaveParameters) { // Save file dialog JFileChooser
* fileSaveChooser = new JFileChooser();
* fileSaveChooser.setDialogType(JFileChooser.SAVE_DIALOG);
* fileSaveChooser.setMultiSelectionEnabled(false);
* fileSaveChooser.setDialogTitle("Please give file name for parameters
* file.");
*
* ExampleFileFilter filter = new ExampleFileFilter();
* filter.addExtension("xml"); filter.setDescription("MZmine parameters
* file");
*
* fileSaveChooser.setFileFilter(filter); int retval =
* fileSaveChooser.showSaveDialog(this);
*
* if(retval == JFileChooser.APPROVE_OPTION) { File selectedFile =
* fileSaveChooser.getSelectedFile(); // Ask for overwrite? if
* (selectedFile.exists()) { } // Write parameters
* mainWin.getParameterStorage().writeParametersToFile(selectedFile);
*
*
* statBar.setStatusText("Parameters written to file."); } else {
* statBar.setStatusText("Parameter saving cancelled."); } }
*
*
* if (src == fileImportAlignmentResult) {
*
* statBar.setStatusText("Please select a result file to import"); //
* Open file dialog JFileChooser fileOpenChooser = new JFileChooser();
* fileOpenChooser.setDialogType(JFileChooser.OPEN_DIALOG);
* fileOpenChooser.setMultiSelectionEnabled(false);
* fileOpenChooser.setDialogTitle("Please select alignment result file
* to open"); if (dataDirectory!=null) {
* fileOpenChooser.setCurrentDirectory(new File(dataDirectory)); }
*
* ExampleFileFilter filter = new ExampleFileFilter();
* filter.addExtension("txt"); filter.setDescription("Tab-delimitted
* text files"); fileOpenChooser.addChoosableFileFilter(filter);
*
* int retval = fileOpenChooser.showOpenDialog(this); // If ok to go on
* with file open if(retval == JFileChooser.APPROVE_OPTION) {
*
* File f = fileOpenChooser.getSelectedFile(); String fpath =
* f.getPath(); String fname = f.getName();
*
* String tmpfullpath = f.getPath(); String datafilename = f.getName();
* String datafilepath = tmpfullpath.substring(0,
* tmpfullpath.length()-datafilename.length()); dataDirectory = new
* String(datafilepath); // Create new alignment result AlignmentResult
* ar =
* AlignmentResultExporter.importAlignmentResultFromFile(datafilepath,
* datafilename);
*
* if (ar == null) { displayErrorMessage("Could not import alignment
* result from file " + datafilename + "\n" + "(Maybe it was not
* exported in Wide format?)"); return; }
*
* itemSelector.addAlignmentResult(ar);
* addAlignmentResultVisualizerList(ar); // tileWindows();
*
* statBar.setStatusText("Result file imported."); } else {
* statBar.setStatusText("Result import cancelled"); } }
*
* if (src == filePrint) {
*
* JInternalFrame activeWindow = desktop.getSelectedFrame(); if
* (activeWindow!=null) { if ((activeWindow.getClass() ==
* RawDataVisualizerTICView.class) || (activeWindow.getClass() ==
* RawDataVisualizerTwoDView.class) || (activeWindow.getClass() ==
* RawDataVisualizerSpectrumView.class) ) {
*
* ((RawDataVisualizer)activeWindow).printMe(); }
*
* if (activeWindow!=null) { if ((activeWindow.getClass() ==
* AlignmentResultVisualizerLogratioPlotView.class) ||
* (activeWindow.getClass() ==
* AlignmentResultVisualizerCoVarPlotView.class) ||
* (activeWindow.getClass() ==
* AlignmentResultVisualizerCDAPlotView.class) ) {
* ((AlignmentResultVisualizer)activeWindow).printMe(); } } } }
*
* if (src == editCopy) { JInternalFrame activeWindow =
* desktop.getSelectedFrame(); if (activeWindow!=null) { if
* ((activeWindow.getClass() == RawDataVisualizerTICView.class) ||
* (activeWindow.getClass() == RawDataVisualizerTwoDView.class) ||
* (activeWindow.getClass() == RawDataVisualizerSpectrumView.class) ) {
*
* ((RawDataVisualizer)activeWindow).copyMe(); }
*
* if (activeWindow!=null) { if ((activeWindow.getClass() ==
* AlignmentResultVisualizerLogratioPlotView.class) ||
* (activeWindow.getClass() ==
* AlignmentResultVisualizerCoVarPlotView.class) ||
* (activeWindow.getClass() ==
* AlignmentResultVisualizerCDAPlotView.class) ) {
* ((AlignmentResultVisualizer)activeWindow).copyMe(); } } } } // File ->
* Exit if (src == fileExit) {
*
* statBar.setStatusText("Exiting."); exitMZmine(); }
*
* if (src == toolsOptions) {
*
* new OptionsWindow(this); }
*
* if (src == ssMeanFilter) { // Ask parameters from user MeanFilter mf =
* new MeanFilter(); MeanFilterParameters mfParam =
* mf.askParameters(this, parameterStorage.getMeanFilterParameters());
* if (mfParam==null) { statBar.setStatusText("Mean filtering
* cancelled."); return; }
* parameterStorage.setMeanFilterParameters(mfParam); // It seems user
* didn't cancel statBar.setStatusText("Mean filtering spectra.");
* paintNow(); // Collect raw data IDs and initiate filtering on the
* cluster int[] selectedRawDataIDs =
* itemSelector.getSelectedRawDataIDs(); //
* clientForCluster.filterRawDataFiles(selectedRawDataIDs, mfParam); }
*
* if (src == ssSGFilter) { // Ask parameters from user
* SavitzkyGolayFilter sf = new SavitzkyGolayFilter();
* SavitzkyGolayFilterParameters sfParam = sf.askParameters(this,
* parameterStorage.getSavitzkyGolayFilterParameters()); if
* (sfParam==null) { statBar.setStatusText("Savitzky-Golay filtering
* cancelled."); return; }
* parameterStorage.setSavitzkyGolayFilterParameters(sfParam); // It
* seems user didn't cancel statBar.setStatusText("Savitzky-Golay
* filtering spectra."); paintNow(); // Collect raw data IDs and
* initiate filtering on the cluster int[] selectedRawDataIDs =
* itemSelector.getSelectedRawDataIDs(); //
* clientForCluster.filterRawDataFiles(selectedRawDataIDs, sfParam); }
*
* if (src == ssChromatographicMedianFilter) { // Ask parameters from
* user ChromatographicMedianFilter cmf = new
* ChromatographicMedianFilter(); ChromatographicMedianFilterParameters
* cmfParam = cmf.askParameters(this,
* parameterStorage.getChromatographicMedianFilterParameters()); if
* (cmfParam==null) { statBar.setStatusText("Chromatographic median
* filtering cancelled."); return; }
* parameterStorage.setChromatographicMedianFilterParameters(cmfParam); //
* It seems user didn't cancel statBar.setStatusText("Filtering with
* chromatographic median filter."); paintNow(); // Collect raw data IDs
* and initiate filtering on the cluster int[] selectedRawDataIDs =
* itemSelector.getSelectedRawDataIDs(); //
* clientForCluster.filterRawDataFiles(selectedRawDataIDs, cmfParam); }
*
* if (src == ssCropFilter) { // Ask parameters from user CropFilter cf =
* new CropFilter(); CropFilterParameters cfParam =
* cf.askParameters(this, parameterStorage.getCropFilterParameters());
* if (cfParam==null) { statBar.setStatusText("Crop filtering
* cancelled."); return; }
* parameterStorage.setCropFilterParameters(cfParam); // It seems user
* didn't cancel statBar.setStatusText("Filtering with cropping
* filter."); paintNow(); // Collect raw data IDs and initiate filtering
* on the cluster int[] selectedRawDataIDs =
* itemSelector.getSelectedRawDataIDs(); //
* clientForCluster.filterRawDataFiles(selectedRawDataIDs, cfParam); }
*
* if (src == ssZoomScanFilter) { // Ask parameters from user
* ZoomScanFilter zsf = new ZoomScanFilter(); ZoomScanFilterParameters
* zsfParam = zsf.askParameters(this,
* parameterStorage.getZoomScanFilterParameters()); if (zsfParam==null) {
* statBar.setStatusText("Zoom scan filtering cancelled."); return; }
* parameterStorage.setZoomScanFilterParameters(zsfParam); // It seems
* user didn't cancel statBar.setStatusText("Filtering with zoom scan
* filter."); paintNow(); // Collect raw data IDs and initiate filtering
* on the cluster int[] selectedRawDataIDs =
* itemSelector.getSelectedRawDataIDs(); //
* clientForCluster.filterRawDataFiles(selectedRawDataIDs, zsfParam); }
*
* if (src == ssRecursiveThresholdPicker) {
*
* RecursiveThresholdPicker rp = new RecursiveThresholdPicker();
*
* RecursiveThresholdPickerParameters rpParam = rp.askParameters(this,
* mainWin.getParameterStorage().getRecursiveThresholdPickerParameters());
* if (rpParam == null) { statBar.setStatusText("Peak picking
* cancelled."); return; }
* mainWin.getParameterStorage().setRecursiveThresholdPickerParameters(rpParam);
*
* int[] rawDataIDs = itemSelector.getSelectedRawDataIDs();
*
* statBar.setStatusText("Searching for peaks."); paintNow(); // Call
* cluster controller // clientForCluster.findPeaks(rawDataIDs,
* rpParam);
*
* rp = null; rpParam = null; }
*
* if (src == ssLocalPicker) {
*
* LocalPicker lp = new LocalPicker();
*
* LocalPickerParameters lpParam = lp.askParameters(this,
* mainWin.getParameterStorage().getLocalPickerParameters()); if
* (lpParam == null) { statBar.setStatusText("Peak picking cancelled.");
* return; }
* mainWin.getParameterStorage().setLocalPickerParameters(lpParam);
*
* int[] rawDataIDs = itemSelector.getSelectedRawDataIDs();
*
* statBar.setStatusText("Searching for peaks."); paintNow(); // Call
* cluster controller // clientForCluster.findPeaks(rawDataIDs,
* lpParam);
*
* lp = null; lpParam = null; }
*
* if (src == ssCentroidPicker) {
*
* CentroidPicker cp = new CentroidPicker();
*
* CentroidPickerParameters cpParam = cp.askParameters(this,
* mainWin.getParameterStorage().getCentroidPickerParameters()); if
* (cpParam == null) { statBar.setStatusText("Peak picking cancelled.");
* return; }
* mainWin.getParameterStorage().setCentroidPickerParameters(cpParam);
*
* int[] rawDataIDs = itemSelector.getSelectedRawDataIDs();
*
* statBar.setStatusText("Searching for peaks."); paintNow(); // Call
* cluster controller to start peak picking process //
* clientForCluster.findPeaks(rawDataIDs, cpParam);
*
* cp = null; cpParam = null; }
*
* if (src == ssSimpleDeisotoping) {
*
* SimpleDeisotoper sd = new SimpleDeisotoper();
*
* SimpleDeisotoperParameters sdParam = sd.askParameters(this,
* mainWin.getParameterStorage().getSimpleDeisotoperParameters()); if
* (sdParam == null) { statBar.setStatusText("Deisotoping cancelled.");
* return; }
* mainWin.getParameterStorage().setSimpleDeisotoperParameters(sdParam);
*
* Hashtable<Integer, PeakList> peakLists = new Hashtable<Integer,
* PeakList>(); int[] rawDataIDs = itemSelector.getSelectedRawDataIDs();
* for (int i=0; i<rawDataIDs.length; i++) { peakLists.put( new
* Integer(rawDataIDs[i]),
* itemSelector.getRawDataByID(rawDataIDs[i]).getPeakList() ); }
*
* statBar.setStatusText("Deisotoping peak lists."); paintNow(); // Call
* cluster controller to start peak picking process //
* clientForCluster.processPeakLists(peakLists, sdParam);
*
* sd = null; sdParam = null; }
*
* if (src == ssCombinatorialDeisotoping) {
*
* CombinatorialDeisotoper cd = new CombinatorialDeisotoper();
*
* CombinatorialDeisotoperParameters cdParam = cd.askParameters(this,
* mainWin.getParameterStorage().getCombinatorialDeisotoperParameters());
* if (cdParam == null) { statBar.setStatusText("Deisotoping
* cancelled."); return; }
* mainWin.getParameterStorage().setCombinatorialDeisotoperParameters(cdParam);
*
* Hashtable<Integer, PeakList> peakLists = new Hashtable<Integer,
* PeakList>(); int[] rawDataIDs = itemSelector.getSelectedRawDataIDs();
* for (int i=0; i<rawDataIDs.length; i++) { peakLists.put( new
* Integer(rawDataIDs[i]),
* itemSelector.getRawDataByID(rawDataIDs[i]).getPeakList() ); }
*
* statBar.setStatusText("Deisotoping peak lists."); paintNow(); // Call
* cluster controller to start peak picking process //
* clientForCluster.processPeakLists(peakLists, cdParam);
*
* cd = null; cdParam = null; }
*
*
*
* if (src == ssIncompleteIsotopePatternFilter) {
*
* IncompleteIsotopePatternFilter iif = new
* IncompleteIsotopePatternFilter();
*
* IncompleteIsotopePatternFilterParameters iifParam =
* iif.askParameters(this,
* mainWin.getParameterStorage().getIncompleteIsotopePatternFilterParameters());
* if (iifParam == null) { statBar.setStatusText("Peak list filtering
* cancelled."); return; }
* mainWin.getParameterStorage().setIncompleteIsotopePatternFilterParameters(iifParam);
*
* Hashtable<Integer, PeakList> peakLists = new Hashtable<Integer,
* PeakList>(); int[] rawDataIDs = itemSelector.getSelectedRawDataIDs();
* for (int i=0; i<rawDataIDs.length; i++) { peakLists.put( new
* Integer(rawDataIDs[i]),
* itemSelector.getRawDataByID(rawDataIDs[i]).getPeakList() ); }
*
* statBar.setStatusText("Filtering peak lists."); paintNow(); // Call
* cluster controller to start peak picking process //
* clientForCluster.processPeakLists(peakLists, iifParam);
*
*
* iif = null; iifParam = null; }
*
* if (src == tsJoinAligner) { // Make sure that every selected raw data
* file has a peak list Hashtable<Integer, PeakList> peakLists = new
* Hashtable<Integer, PeakList>();
*
* int[] rawDataIDs = itemSelector.getSelectedRawDataIDs(); for (int
* rawDataID : rawDataIDs) { RawDataAtClient rawData =
* itemSelector.getRawDataByID(rawDataID); if (!(rawData.hasPeakData())) {
* displayErrorMessage("Can't align: " + rawData.getNiceName() + " has
* no peak list available."); peakLists = null; return; }
* peakLists.put(new Integer(rawDataID), rawData.getPeakList()); } //
* Show user parameter setup dialog JoinAligner ja = new JoinAligner();
* JoinAlignerParameters jaParam = ja.askParameters(this,
* mainWin.getParameterStorage().getJoinAlignerParameters()); if
* (jaParam==null) { statBar.setStatusText("Alignment cancelled.");
* return; }
* mainWin.getParameterStorage().setJoinAlignerParameters(jaParam);
*
* statBar.setStatusText("Aligning peak lists."); paintNow(); // Call
* cluster controller // clientForCluster.doAlignment(peakLists,
* jaParam);
*
* ja = null; jaParam = null; }
*
* if (src == tsFastAligner) { // Make sure that every selected raw data
* file has a peak list Hashtable<Integer, PeakList> peakLists = new
* Hashtable<Integer, PeakList>();
*
* int[] rawDataIDs = itemSelector.getSelectedRawDataIDs(); for (int
* rawDataID : rawDataIDs) { RawDataAtClient rawData =
* itemSelector.getRawDataByID(rawDataID); if (!(rawData.hasPeakData())) {
* displayErrorMessage("Can't align: " + rawData.getNiceName() + " has
* no peak list available."); peakLists = null; return; }
* peakLists.put(new Integer(rawDataID), rawData.getPeakList()); } //
* Show user parameter setup dialog FastAligner fa = new FastAligner();
* FastAlignerParameters faParam = fa.askParameters(this,
* mainWin.getParameterStorage().getFastAlignerParameters()); if
* (faParam==null) { statBar.setStatusText("Alignment cancelled.");
* return; }
* mainWin.getParameterStorage().setFastAlignerParameters(faParam);
*
* statBar.setStatusText("Aligning peak lists."); paintNow(); // Call
* cluster controller // clientForCluster.doAlignment(peakLists,
* faParam);
*
* fa = null; faParam = null; }
*
* if (src == normLinear) {
*
* LinearNormalizer ln = new LinearNormalizer();
*
* LinearNormalizerParameters lnp = ln.askParameters(this,
* mainWin.getParameterStorage().getLinearNormalizerParameters()); if
* (lnp == null) { statBar.setStatusText("Normalization cancelled.");
* return; }
* mainWin.getParameterStorage().setLinearNormalizerParameters(lnp); //
* If normalization by total raw signal, then must use controller to
* calc total raw signals and finally do normalization if
* (lnp.paramNormalizationType ==
* LinearNormalizerParameters.NORMALIZATIONTYPE_TOTRAWSIGNAL) { //
* Collect raw data IDs from all selected alignment results Vector<AlignmentResult>
* selectedAlignmentResults =
* itemSelector.getSelectedAlignmentResults(); Vector<Integer>
* allRequiredRawDataIDs = new Vector<Integer>(); // Loop all selected
* alignment results for (AlignmentResult ar :selectedAlignmentResults) { //
* Loop all raw data IDs in current alignment results int[]
* tmpRawDataIDs = ar.getRawDataIDs(); for (int tmpRawDataID :
* tmpRawDataIDs) { Integer tmpRawDataIDI = new Integer(tmpRawDataID); //
* If this raw data id is not yet included, then add it if (
* allRequiredRawDataIDs.indexOf(tmpRawDataIDI) == -1 ) {
* allRequiredRawDataIDs.add(tmpRawDataIDI); } } } // Move required raw
* Data IDs from Vector<Integer> to int[] int[] allRequiredRawDataIDsi =
* new int[allRequiredRawDataIDs.size()]; for (int i=0; i<allRequiredRawDataIDs.size();
* i++) { allRequiredRawDataIDsi[i] =
* allRequiredRawDataIDs.get(i).intValue(); } // Ask controller to fetch
* total raw signals for these raw data files //Vector<AlignmentResult>
* selectedAlignmentResults =
* itemSelector.getSelectedAlignmentResults(); //
* clientForCluster.calcTotalRawSignal(allRequiredRawDataIDsi, lnp,
* selectedAlignmentResults); // doLinearNormalizationClientSide() will
* be called by clientForCluster when task completes } else { // Any
* other linear normalization method doesn't need access to raw data, so
* it is possible to call doLinearNormalizationClientSide() immediately
* Vector<AlignmentResult> selectedAlignmentResults =
* itemSelector.getSelectedAlignmentResults();
* doLinearNormalizationClientSide(lnp, selectedAlignmentResults); } }
*
*
* if (src == normStdComp) {
*
* StandardCompoundNormalizer scn = new StandardCompoundNormalizer();
*
* StandardCompoundNormalizerParameters scnp = scn.askParameters(this,
* mainWin.getParameterStorage().getStandardCompoundNormalizerParameters());
* if (scnp==null) { statBar.setStatusText("Normalization cancelled.");
* return; }
* mainWin.getParameterStorage().setStandardCompoundNormalizerParameters(scnp);
*
* statBar.setStatusText("Normalizing selected alignment results.");
* paintNow(); // setBusy(true);
*
* Vector<AlignmentResult> selectedAlignmentResults =
* itemSelector.getSelectedAlignmentResults(); Enumeration<AlignmentResult>
* selectedAlignmentResultEnum = selectedAlignmentResults.elements();
* while (selectedAlignmentResultEnum.hasMoreElements()) {
* AlignmentResult ar = selectedAlignmentResultEnum.nextElement();
* AlignmentResult nar = scn.calcNormalization(this, ar, scnp);
*
* if (nar==null) { if (ar.getNumOfStandardCompounds()==0) {
* displayErrorMessage("Could not normalize " + ar.getNiceName() + ",
* because it does not have any standard compounds defined."); } else {
* displayErrorMessage("Could not normalize " + ar.getNiceName() + ",
* because of an unknown error."); } } else {
* itemSelector.addAlignmentResult(nar);
* addAlignmentResultVisualizerList(nar); } }
*
* statBar.setStatusText("Normalization done."); // setBusy(false); }
*
*
* if (src == tsAlignmentFilter) { // Get all selected alignment results
* Vector<AlignmentResult> alignmentResults =
* itemSelector.getSelectedAlignmentResults(); if
* (alignmentResults==null) { return; }
*
* AlignmentResultFilterByGaps arfbg = new
* AlignmentResultFilterByGaps();
*
* AlignmentResultFilterByGapsParameters arfbgParam=
* arfbg.askParameters(this,
* mainWin.getParameterStorage().getAlignmentResultFilterByGapsParameters());
* if (arfbgParam == null) { statBar.setStatusText("Alignment result
* filtering cancelled."); return; }
* mainWin.getParameterStorage().setAlignmentResultFilterByGapsParameters(arfbgParam);
*
* runAlignmentResultFilteringByGapsClientSide(arfbgParam,
* alignmentResults); }
*
* if (src == tsEmptySlotFiller) { // Get all selected alignment results
* Vector<AlignmentResult> alignmentResults =
* itemSelector.getSelectedAlignmentResults(); if
* (alignmentResults==null) { return; } // Check that only a single
* alignment result was selected if (alignmentResults.size()!=1) {
* displayErrorMessage("Please select only a single alignment result for
* gap filling."); statBar.setStatusText("Please select only a single
* alignment result for gap filling."); return; } AlignmentResult
* alignmentResult = alignmentResults.get(0); // Check that the selected
* alignment result is not an imported version if
* (alignmentResult.isImported()) { }
*
* SimpleGapFiller sgf = new SimpleGapFiller();
*
* SimpleGapFillerParameters sgfParam= sgf.askParameters(this,
* mainWin.getParameterStorage().getSimpleGapFillerParameters()); if
* (sgfParam == null) { statBar.setStatusText("Gap filling cancelled.");
* return; }
* mainWin.getParameterStorage().setSimpleGapFillerParameters(sgfParam);
*
*
* statBar.setStatusText("Filling empty gaps in alignment result."); //
* paintNow(); // clientForCluster.fillGaps(alignmentResult, sgfParam); }
*
* if (src == batDefine) { // Get selected rawDataIDs int[] rawDataIDs =
* itemSelector.getSelectedRawDataIDs();
*
* BatchModeDialog bmd = new BatchModeDialog(mainWin, rawDataIDs); }
*
* if (src == anOpenSRView) { // Add a new visualizer to all selected
* alignment results Vector<AlignmentResult> rv =
* itemSelector.getSelectedAlignmentResults();
*
* for (AlignmentResult ar : rv ) {
* mainWin.addAlignmentResultVisualizerLogratioPlot(ar); } // //
* tileWindows(); }
*
*
* if (src == anOpenSCVView) { // Add a new visualizer to all selected
* alignment results Vector<AlignmentResult> rv =
* itemSelector.getSelectedAlignmentResults();
*
* for (AlignmentResult ar : rv ) {
* mainWin.addAlignmentResultVisualizerCoVarPlot(ar); } //
* tileWindows(); }
*
* if (src == anOpenCDAView) { // Add a new visualizer to all selected
* alignment results // setBusy(true); Vector<AlignmentResult> rv =
* itemSelector.getSelectedAlignmentResults(); for (AlignmentResult ar :
* rv ) { mainWin.addAlignmentResultVisualizerCDAPlot(ar); } //
* setBusy(false); updateMenuAvailability(); // tileWindows(); }
*
* if (src == anOpenSammonsView) { // Add a new visualizer to all
* selected alignment results // setBusy(true); Vector<AlignmentResult>
* rv = itemSelector.getSelectedAlignmentResults(); for (AlignmentResult
* ar : rv ) { // Create new visualizer
* //AlignmentResultVisualizerSammonsPlotView sammonsView = new
* AlignmentResultVisualizerSammonsPlotView(this);
* //sammonsView.askParameters(alignmentResult,
* parameterStorage.getAlignmentResultVisualizerSammonsPlotViewParameters());
* mainWin.addAlignmentResultVisualizerSammonsPlot(ar); } //
* setBusy(false); // tileWindows(); updateMenuAvailability(); }
*
*
* if (src == windowTileWindows) { // tileWindows(); }
*
*
* if (src == hlpAbout) { AboutDialog ad = new AboutDialog();
* ad.showModal(mainWin.getDesktop); }
*
*/
}
/**
* Update menu elements availability according to what is currently selected
* in run selector and on desktop
*/
public void updateMenuAvailability() {
fileClose.setEnabled(false);
filePrint.setEnabled(false);
fileExportPeakList.setEnabled(false);
editCopy.setEnabled(false);
ssMeanFilter.setEnabled(false);
ssSGFilter.setEnabled(false);
ssChromatographicMedianFilter.setEnabled(false);
ssCropFilter.setEnabled(false);
ssZoomScanFilter.setEnabled(false);
ssRecursiveThresholdPicker.setEnabled(false);
ssLocalPicker.setEnabled(false);
ssCentroidPicker.setEnabled(false);
ssSimpleDeisotoping.setEnabled(false);
ssCombinatorialDeisotoping.setEnabled(false);
ssIncompleteIsotopePatternFilter.setEnabled(false);
tsJoinAligner.setEnabled(false);
tsFastAligner.setEnabled(false);
normLinear.setEnabled(false);
normStdComp.setEnabled(false);
batDefine.setEnabled(false);
windowTileWindows.setEnabled(false);
tsEmptySlotFiller.setEnabled(false);
tsAlignmentFilter.setEnabled(false);
anOpenSRView.setEnabled(false);
anOpenSCVView.setEnabled(false);
anOpenCDAView.setEnabled(false);
anOpenSammonsView.setEnabled(false);
fileExportPeakList.setText("Export...");
/*
* if ( (numOfRawDataWithVisibleVisualizer(false)>0) ||
* (numOfResultsWithVisibleVisualizer(false)>0) ) {
* windowTileWindows.setEnabled(true); }
*/
RawDataFile[] actRawData = itemSelector.getSelectedRawData();
if (actRawData != null) {
fileClose.setEnabled(true);
ssMeanFilter.setEnabled(true);
ssSGFilter.setEnabled(true);
ssChromatographicMedianFilter.setEnabled(true);
ssCropFilter.setEnabled(true);
ssZoomScanFilter.setEnabled(true);
ssRecursiveThresholdPicker.setEnabled(true);
ssLocalPicker.setEnabled(true);
ssCentroidPicker.setEnabled(true);
batDefine.setEnabled(true);
/*
* if (actRawData.hasPeakData()) {
* ssSimpleDeisotoping.setEnabled(true); //
* ssCombinatorialDeisotoping.setEnabled(true); DEBUG: Feature //
* not yet ready ssIncompleteIsotopePatternFilter.setEnabled(true);
* fileExportPeakList.setEnabled(true);
* tsJoinAligner.setEnabled(true); tsFastAligner.setEnabled(true); }
*/
JInternalFrame activeWindow = mainWin.getDesktop()
.getSelectedFrame();
if (activeWindow != null) {
if ((activeWindow.getClass() == TICVisualizer.class)
|| (activeWindow.getClass() == TwoDVisualizer.class)
|| (activeWindow.getClass() == SpectrumVisualizer.class)) {
filePrint.setEnabled(true);
editCopy.setEnabled(true);
}
}
}
AlignmentResult actResult = itemSelector.getActiveResult();
if (actResult != null) {
fileClose.setEnabled(true);
normLinear.setEnabled(true);
normStdComp.setEnabled(true);
tsAlignmentFilter.setEnabled(true);
tsEmptySlotFiller.setEnabled(true);
anOpenSRView.setEnabled(true);
anOpenSCVView.setEnabled(true);
anOpenCDAView.setEnabled(true);
anOpenSammonsView.setEnabled(true);
fileExportPeakList.setEnabled(true);
JInternalFrame activeWindow = mainWin.getDesktop()
.getSelectedFrame();
if (activeWindow != null) {
if ((activeWindow.getClass() == AlignmentResultVisualizerLogratioPlotView.class)
|| (activeWindow.getClass() == AlignmentResultVisualizerCoVarPlotView.class)
|| (activeWindow.getClass() == AlignmentResultVisualizerCDAPlotView.class)
|| (activeWindow.getClass() == AlignmentResultVisualizerSammonsPlotView.class)) {
filePrint.setEnabled(true);
editCopy.setEnabled(true);
}
}
}
// If at least one run or result is visible, then tile windows is active
/*
* if ( (numOfRawDataWithVisibleVisualizer(false)>0) ||
* (numOfResultsWithVisibleVisualizer(false)>0) ) {
* windowTileWindows.setEnabled(true); }
*/
}
}
|
package org.fxmisc.wellbehaved.event;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import javafx.beans.property.ObjectProperty;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
/**
* Methods of this class could be added directly to the {@link EventHandler}
* interface. The interface could further be extended with default methods
* <pre>
* {@code
* EventHandler<? super T> orElse(EventHandler<? super T> other);
* EventHandler<? super T> without(EventHandler<?> other);
* }
* </pre>
* The latter may replace the {@link #exclude(EventHandler, EventHandler)}
* static method.
* @param <T>
*/
public final class EventHandlerHelper<T extends Event> {
public static abstract class Builder<T extends Event> {
private static <T extends Event> Builder<T> empty() {
return new Builder<T>() {
@Override
<U extends T> List<EventHandler<? super U>> getHandlers(int additionalCapacity) {
return new ArrayList<>(additionalCapacity);
}
};
}
// private constructor to prevent subclassing by the user
private Builder() {}
public <U extends T> On<T, U> on(EventPattern<? super T, ? extends U> eventMatcher) {
return new On<>(this, eventMatcher);
}
public <U extends T> On<T, U> on(EventType<? extends U> eventType) {
return on(EventPattern.eventTypePattern(eventType));
}
public <U extends T> Builder<U> addHandler(EventHandler<? super U> handler) {
return new CompositeBuilder<>(this, handler);
}
public final EventHandler<T> create() {
List<EventHandler<? super T>> handlers = getHandlers();
return new CompositeEventHandler<>(handlers);
}
List<EventHandler<? super T>> getHandlers() {
return getHandlers(0);
}
abstract <U extends T> List<EventHandler<? super U>> getHandlers(int additionalCapacity);
}
private static class CompositeBuilder<T extends Event> extends Builder<T> {
private final Builder<? super T> previousBuilder;
private final EventHandler<? super T> handler;
private CompositeBuilder(
Builder<? super T> previousBuilder,
EventHandler<? super T> handler) {
this.previousBuilder = previousBuilder;
this.handler = handler;
}
@Override
<U extends T> List<EventHandler<? super U>> getHandlers(int additionalCapacity) {
List<EventHandler<? super U>> handlers = previousBuilder.getHandlers(additionalCapacity + 1);
handlers.add(handler);
return handlers;
}
}
public static class On<T extends Event, U extends T> {
private final Builder<? super T> previousBuilder;
private final EventPattern<? super T, ? extends U> eventMatcher;
private On(
Builder<? super T> previous,
EventPattern<? super T, ? extends U> eventMatcher) {
this.previousBuilder = previous;
this.eventMatcher = eventMatcher;
}
public On<T, U> where(Predicate<? super U> condition) {
return new On<>(previousBuilder, eventMatcher.and(condition));
}
public Builder<T> act(Consumer<? super U> action) {
return previousBuilder.addHandler(t -> {
eventMatcher.match(t).ifPresent(u -> {
action.accept(u);
t.consume();
});
});
}
}
public static <T extends Event, U extends T> On<T, U> on(
EventPattern<? super T, ? extends U> eventMatcher) {
return Builder.<T>empty().on(eventMatcher);
}
public static <T extends Event> On<Event, T> on(
EventType<? extends T> eventType) {
return Builder.empty().on(eventType);
}
public static <T extends Event> Builder<T>
startWith(EventHandler<? super T> handler) {
return Builder.empty().addHandler(handler);
}
static <T extends Event> EventHandler<T> empty() {
return EmptyEventHandler.instance();
}
@SafeVarargs
public static <T extends Event> EventHandler<? super T> chain(EventHandler<? super T>... handlers) {
ArrayList<EventHandler<? super T>> nonEmptyHandlers = new ArrayList<>(handlers.length);
for(EventHandler<? super T> handler: handlers) {
if(handler != empty()) {
nonEmptyHandlers.add(handler);
}
}
if(nonEmptyHandlers.isEmpty()) {
return empty();
} else if(nonEmptyHandlers.size() == 1) {
return nonEmptyHandlers.get(0);
} else {
nonEmptyHandlers.trimToSize();
return new CompositeEventHandler<>(nonEmptyHandlers);
}
}
public static <T extends Event> EventHandler<? super T> exclude(EventHandler<T> handler, EventHandler<?> subHandler) {
if(handler instanceof CompositeEventHandler) {
return ((CompositeEventHandler<T>) handler).without(subHandler);
} else if(handler.equals(subHandler)) {
return empty();
} else {
return handler;
}
}
public static <T extends Event> void install(
ObjectProperty<EventHandler<? super T>> handlerProperty,
EventHandler<? super T> handler) {
EventHandler<? super T> oldHandler = handlerProperty.get();
if(oldHandler != null) {
handlerProperty.set(EventHandlerHelper.chain(handler, oldHandler));
} else {
handlerProperty.set(handler);
}
}
public static <T extends Event> void installAfter(
ObjectProperty<EventHandler<? super T>> handlerProperty,
EventHandler<? super T> handler) {
EventHandler<? super T> oldHandler = handlerProperty.get();
if(oldHandler != null) {
handlerProperty.set(EventHandlerHelper.chain(oldHandler, handler));
} else {
handlerProperty.set(handler);
}
}
public static <T extends Event> void remove(
ObjectProperty<EventHandler<? super T>> handlerProperty,
EventHandler<? super T> handler) {
EventHandler<? super T> oldHandler = handlerProperty.get();
if(oldHandler != null) {
handlerProperty.set(EventHandlerHelper.exclude(oldHandler, handler));
}
}
// prevent instantiation
private EventHandlerHelper() {}
}
final class EmptyEventHandler<T extends Event> implements EventHandler<T> {
private static EmptyEventHandler<?> INSTANCE = new EmptyEventHandler<>();
@SuppressWarnings("unchecked")
static <T extends Event> EmptyEventHandler<T> instance() {
return (EmptyEventHandler<T>) INSTANCE;
}
private EmptyEventHandler() {}
@Override
public void handle(T event) {
// do nothing
}
}
class CompositeEventHandler<T extends Event> implements EventHandler<T> {
private final List<EventHandler<? super T>> handlers;
CompositeEventHandler(List<EventHandler<? super T>> handlers) {
// Since this constructor is package-private, we can be sure that
// the given list of handlers is never mutated, thus there is no need
// to create a copy.
this.handlers = handlers;
}
@Override
public void handle(T event) {
for(EventHandler<? super T> handler: handlers) {
handler.handle(event);
if(event.isConsumed()) {
break;
}
}
}
public EventHandler<? super T> without(EventHandler<?> other) {
if(this.equals(other)) {
return EmptyEventHandler.instance();
} else {
boolean changed = false;
List<EventHandler<? super T>> newHandlers = new ArrayList<>(handlers.size());
for(EventHandler<? super T> handler: handlers) {
EventHandler<? super T> h = EventHandlerHelper.exclude(handler, other);
if(h != handler) {
changed = true;
}
if(h != EmptyEventHandler.instance()) {
newHandlers.add(h);
}
}
if(!changed) {
return this;
} else if(newHandlers.isEmpty()) {
return EmptyEventHandler.instance();
} else if(newHandlers.size() == 1) {
return newHandlers.get(0);
} else {
return new CompositeEventHandler<>(newHandlers);
}
}
}
@Override
public boolean equals(Object other) {
return other instanceof CompositeEventHandler
&& this.handlers.equals(((CompositeEventHandler<?>) other).handlers);
}
@Override
public int hashCode() {
return handlers.hashCode();
}
}
|
package org.exist.xquery.functions.text;
import org.exist.dom.DocumentSet;
import org.exist.dom.NodeSet;
import org.exist.dom.QName;
import org.exist.security.PermissionDeniedException;
import org.exist.util.Occurrences;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionCall;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.FunctionReference;
import org.exist.xquery.value.IntegerValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
import org.exist.xquery.value.ValueSequence;
import java.util.HashMap;
import java.util.Collections;
import java.util.Vector;
/**
* @author wolf
*/
public class IndexTerms extends BasicFunction {
public final static FunctionSignature signature = new FunctionSignature(
new QName("index-terms", TextModule.NAMESPACE_URI, TextModule.PREFIX),
"This function can be used to collect some information on the distribution " +
"of index terms within a set of nodes. The set of nodes is specified in the first " +
"argument $a. The function returns term frequencies for all terms in the index found " +
"in descendants of the nodes in $a. The second argument $b specifies " +
"a start string. Only terms starting with the specified character sequence are returned. " +
"$c is a function reference, which points to a callback function that will be called " +
"for every term occurrence. $d defines the maximum number of terms that should be " +
"reported. The function reference for $c can be created with the util:function " +
"function. It can be an arbitrary user-defined function, but it should take exactly 2 arguments: " +
"1) the current term as found in the index as xs:string, 2) a sequence containing four int " +
"values: a) the overall frequency of the term within the node set, b) the number of distinct " +
"documents in the node set the term occurs in, c) the current position of the term in the whole " +
"list of terms returned, d) the rank of the current term in the whole list of terms returned.",
new SequenceType[]{
new SequenceType(Type.NODE, Cardinality.ZERO_OR_MORE),
new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE),
new SequenceType(Type.FUNCTION_REFERENCE, Cardinality.EXACTLY_ONE),
new SequenceType(Type.INT, Cardinality.EXACTLY_ONE)
},
new SequenceType(Type.ITEM, Cardinality.ZERO_OR_MORE));
public IndexTerms(XQueryContext context) {
super(context, signature);
}
/* (non-Javadoc)
* @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
*/
public Sequence eval(Sequence[] args, Sequence contextSequence)
throws XPathException {
if(args[0].getLength() == 0)
return Sequence.EMPTY_SEQUENCE;
NodeSet nodes = args[0].toNodeSet();
DocumentSet docs = nodes.getDocumentSet();
String start = args[1].getStringValue();
FunctionReference ref = (FunctionReference) args[2].itemAt(0);
int max = ((IntegerValue) args[3].itemAt(0)).getInt();
FunctionCall call = ref.getFunctionCall();
Sequence result = new ValueSequence();
try {
Occurrences occur[] =
context.getBroker().getTextEngine().scanIndexTerms(docs, nodes, start, null);
int len = (occur.length > max ? max : occur.length);
Sequence params[] = new Sequence[2];
ValueSequence data = new ValueSequence();
Vector list = new Vector(len);
for (int j = 0; j < len; j++) {
if (!list.contains(new Integer(occur[j].getOccurrences()))) {
list.add(new Integer(occur[j].getOccurrences()));
}
}
Collections.sort(list);
Collections.reverse(list);
HashMap map = new HashMap(list.size() * 2);
for (int j = 0; j < list.size(); j++) {
map.put((Integer) list.get(j), new Integer(j + 1));
}
for (int j = 0; j < len; j++) {
params[0] = new StringValue(occur[j].getTerm().toString());
data.add(new IntegerValue(occur[j].getOccurrences(), Type.UNSIGNED_INT));
data.add(new IntegerValue(occur[j].getDocuments(), Type.UNSIGNED_INT));
data.add(new IntegerValue(j + 1, Type.UNSIGNED_INT));
data.add(new IntegerValue(((Integer) map.get(new Integer(occur[j].getOccurrences()))).intValue(), Type.UNSIGNED_INT));
params[1] = data;
result.addAll(call.evalFunction(contextSequence, null, params));
data.clear();
}
LOG.debug("Returning: " + result.getLength());
return result;
} catch (PermissionDeniedException e) {
throw new XPathException(getASTNode(), e.getMessage(), e);
}
}
}
|
package org._2585robophiles.frc2015.systems;
import org._2585robophiles.frc2015.Environment;
import org._2585robophiles.frc2015.RobotMap;
import org._2585robophiles.frc2015.input.InputMethod;
import org._2585robophiles.lib2585.MultiMotor;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SensorBase;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.PIDSubsystem;
/**
* This system controls the movement of the robot
*/
public class WheelSystem implements RobotSystem, Runnable {
private RobotDrive drivetrain;
private SpeedController sidewaysMotor;
private InputMethod input;
private AccelerometerSystem accelerometer;
private GyroSystem gyro;
private double previousNormalMovement;
private double currentRampForward;
private double currentRampSideways;
private double rotationValue;
private double forwardDistanceDriven, sidewaysDistanceDriven;
private long lastForwardDistanceUpdate, lastSidewaysDistanceUpdate;
private boolean straightDriveDisabled;
private boolean straightDrivePressed;
private boolean changeSensitivityPressed;
private boolean secondarySensitivity;
private double correctRotate;
private PIDSubsystem forwardDistancePID, sidewaysDistancePID, straightDrivePID;
/* (non-Javadoc)
* @see org._2585robophiles.frc2015.Initializable#init(org._2585robophiles.frc2015.Environment)
*/
@Override
public void init(Environment environment) {
drivetrain = new RobotDrive(RobotMap.FRONT_LEFT_DRIVE, RobotMap.REAR_LEFT_DRIVE, RobotMap.FRONT_RIGHT_DRIVE, RobotMap.REAR_RIGHT_DRIVE);
drivetrain.setInvertedMotor(RobotDrive.MotorType.kFrontRight , true );
drivetrain.setInvertedMotor(RobotDrive.MotorType.kRearRight , true );
sidewaysMotor = new MultiMotor(new SpeedController[]{new Victor(RobotMap.SIDEWAYS_DRIVE), new Victor(RobotMap.SIDEWAYS_DRIVE_2)});
accelerometer = environment.getAccelerometerSystem();
gyro = environment.getGyroSystem();
input = environment.getInput();
straightDriveDisabled = true;
forwardDistancePID = new PIDSubsystem(0.2, 0.03, 0) {
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.Subsystem#initDefaultCommand()
*/
@Override
protected void initDefaultCommand() {
}
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.PIDSubsystem#usePIDOutput(double)
*/
@Override
protected void usePIDOutput(double output) {
drive(output, 0, 0);
}
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.PIDSubsystem#returnPIDInput()
*/
@Override
protected double returnPIDInput() {
return forwardDistanceDriven;
}
};
sidewaysDistancePID = new PIDSubsystem(0.2, 0.03, 0) {
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.Subsystem#initDefaultCommand()
*/
@Override
protected void initDefaultCommand() {
}
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.PIDSubsystem#usePIDOutput(double)
*/
@Override
protected void usePIDOutput(double output) {
drive(0, output, 0);
}
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.PIDSubsystem#returnPIDInput()
*/
@Override
protected double returnPIDInput() {
return sidewaysDistanceDriven;
}
};
straightDrivePID = new PIDSubsystem(0.1, 0.03, 0) {
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.Subsystem#initDefaultCommand()
*/
@Override
protected void initDefaultCommand() {
}
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.PIDSubsystem#usePIDOutput(double)
*/
@Override
protected void usePIDOutput(double output) {
correctRotate = output;
}
/* (non-Javadoc)
* @see edu.wpi.first.wpilibj.command.PIDSubsystem#returnPIDInput()
*/
@Override
protected double returnPIDInput() {
return gyro.angle();
}
};
}
/**
* Drive a certain distance in meters or feet
* @param forwardDistance the distance to drive forward
* @param sidewaysDistance the distance to drive sideways
* @param usingMeters true if using meters false if using feet
* @return if driveDistance is done
*/
public boolean driveDistance(double forwardDistance, double sidewaysDistance, boolean usingMeters){
if(usingMeters){
return driveDistance(forwardDistance, sidewaysDistance);
}else{
return driveDistance(forwardDistance / AccelerometerSystem.METER_TO_FEET, sidewaysDistance / AccelerometerSystem.METER_TO_FEET);
}
}
/**
* Drive the robot
* @param forwardMovement forward back move value
* @param sidewaysMovement left right move value
* @param rotation turn value
* @return if driveDistance is done
*/
public void drive(double forwardMovement, double sidewaysMovement, double rotation){
drivetrain.arcadeDrive(forwardMovement, rotation);
sidewaysMotor.set(sidewaysMovement);// we need to invert the sideways motor
}
/**
* Drives a certain distance using the accelerometer and PID
* @param forwardDistance the distance to drive forward
* @param sidewaysDistance the distance to drive sideways
* @return if distance drive is done
*/
public boolean driveDistance(double forwardMeters , double sidewaysMeters) {
if(forwardMeters != 0){
if(lastForwardDistanceUpdate == 0){
enableForwardDistancePID(forwardMeters);
lastForwardDistanceUpdate = System.currentTimeMillis();
}else if(forwardDistanceDriven == forwardMeters){
disableForwardDistancePID();
forwardDistanceDriven = 0;
lastForwardDistanceUpdate = 0;
}else{
// use the accelerometer to find the forward distance we have driven
forwardDistanceDriven += accelerometer.getSpeedX() * (System.currentTimeMillis() - lastForwardDistanceUpdate) /1000;
lastForwardDistanceUpdate = System.currentTimeMillis();
}
}
if(sidewaysMeters != 0){
if(lastSidewaysDistanceUpdate == 0){
enableSidewaysDistancePID(sidewaysMeters);
lastSidewaysDistanceUpdate = System.currentTimeMillis();
}else if(sidewaysDistanceDriven == sidewaysMeters){
disableSidewaysDistancePID();
sidewaysDistanceDriven = 0;
lastSidewaysDistanceUpdate = 0;
}else{
// use the accelerometer to find the sideways distance we have driven
sidewaysDistanceDriven += accelerometer.getSpeedY() * (System.currentTimeMillis()-lastSidewaysDistanceUpdate) /1000;
lastSidewaysDistanceUpdate = System.currentTimeMillis();
}
}
return forwardDistanceDriven == forwardMeters && sidewaysDistanceDriven == sidewaysMeters;
}
/**
* Drive straight using gyro and PID
* @param forwardMovement the forward movement value
* @param sidewaysMovement the left/right movement value
*/
public void straightDrive(double forwardMovement, double sidewaysMovement){
if(!straightDriving()){
enableStraightDrivePID();
}
drive(forwardMovement, sidewaysMovement, correctRotate);
}
/**
* Enable and set the setpoint of the forward distance drive PID
* @param setpoint forward distance to drive in meters
*/
protected synchronized void enableForwardDistancePID(double setpoint) {
forwardDistancePID.setSetpoint(setpoint);
forwardDistancePID.enable();
}
/**
* Disable forward distance drive PID
*/
protected synchronized void disableForwardDistancePID(){
forwardDistancePID.getPIDController().reset();
forwardDistancePID.disable();
disableSraightDrivePID();
}
/**
* Enable and set the setpoint of the sideways distance drive PID
* @param setpoint sideways distance to drive in meters
*/
protected synchronized void enableSidewaysDistancePID(double setpoint) {
sidewaysDistancePID.setSetpoint(setpoint);
sidewaysDistancePID.enable();
}
/**
* Disable sideways distance drive PID
*/
protected synchronized void disableSidewaysDistancePID(){
sidewaysDistancePID.getPIDController().reset();
sidewaysDistancePID.disable();
disableSraightDrivePID();
}
/**
* Enable straight driving
* @param setpoint target angle
*/
protected synchronized void enableStraightDrivePID(){
straightDrivePID.setSetpoint(gyro.angle());
straightDrivePID.setAbsoluteTolerance(2);// it's OK if we're 2 degrees off
straightDrivePID.enable();
}
/**
* Stop straight driving
* @param setpoint target angle
*/
protected synchronized void disableSraightDrivePID(){
straightDrivePID.getPIDController().reset();
straightDrivePID.disable();
}
/**
* @return whether or not the robot is straight driving
*/
public synchronized boolean straightDriving(){
return straightDrivePID.getPIDController().isEnable();
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
currentRampForward += (input.forwardMovement()-currentRampForward) * RobotMap.FORWARD_RAMPING;
currentRampSideways += (input.sidewaysMovement()-currentRampSideways) * RobotMap.SIDEWAYS_RAMPING;
if(currentRampForward < 0.13 && currentRampForward > -0.13)
currentRampForward = 0.0;
if(currentRampSideways < 0.15 && currentRampSideways > -0.15)
currentRampSideways = 0.0;
rotationValue = input.rotation();
if(rotationValue < 0.15 && rotationValue > -0.15)
rotationValue = 0.0;
else
rotationValue = Math.signum(input.rotation()) * Math.pow(Math.abs(input.rotation()), secondarySensitivity ? RobotMap.SECONDARY_ROTATION_EXPONENT : RobotMap.ROTATION_EXPONENT);
if(rotationValue == 0 && !straightDriveDisabled && !input.stopStraightDrive()){
straightDrive(currentRampForward, currentRampSideways);// straight drive when not turning
}else{
disableSraightDrivePID();
drive(currentRampForward, currentRampSideways, rotationValue);
}
// toggle between straight driving enabled and disabled
if(input.straightDrive() && !straightDrivePressed)
straightDriveDisabled =! straightDriveDisabled;
straightDrivePressed = input.straightDrive();
// toggle sensitivities so people don't die
if(input.changeSensitivity() && !changeSensitivityPressed)
secondarySensitivity =! secondarySensitivity;
changeSensitivityPressed = input.changeSensitivity();
}
/**
* @return the previousNormalMovement
*/
public synchronized double getPreviousNormalMovement() {
return previousNormalMovement;
}
/**
* @param previousNormalMovement the previousNormalMovement to set
*/
protected synchronized void setPreviousNormalMovement(double currentNormalMovement) {
this.previousNormalMovement = currentNormalMovement;
}
/**
* @return the sidewaysMotor
*/
public synchronized SpeedController getSidewaysMotor() {
return sidewaysMotor;
}
/**
* @param sidewaysMotor the sidewaysMotor to set
*/
protected synchronized void setSidewaysMotor(SpeedController sidewaysMotor) {
this.sidewaysMotor = sidewaysMotor;
}
/**
* @return the input
*/
public InputMethod getInput() {
return input;
}
/**
* @param input the input to set
*/
protected synchronized void setInput(InputMethod input) {
this.input = input;
}
/**
* @return the accelerometer
*/
public synchronized AccelerometerSystem getAccelerometer() {
return accelerometer;
}
/**
* @param accelerometer the accelerometer to set
*/
protected synchronized void setAccelerometer(AccelerometerSystem accelerometer) {
this.accelerometer = accelerometer;
}
/**
* @return the forwardDistanceDriven
*/
public synchronized double getForwardDistanceDriven() {
return forwardDistanceDriven;
}
/**
* @return the sidewaysDistanceDriven
*/
public synchronized double getSidewaysDistanceDriven() {
return sidewaysDistanceDriven;
}
/**
* @param forwardDistanceDriven the forwardDistanceDriven to set
*/
protected synchronized void setForwardDistanceDriven(double forwardDistanceDriven) {
this.forwardDistanceDriven = forwardDistanceDriven;
}
/**
* @param sidewaysDistanceDriven the sidewaysDistanceDriven to set
*/
protected synchronized void setSidewaysDistanceDriven(double sidewaysDistanceDriven) {
this.sidewaysDistanceDriven = sidewaysDistanceDriven;
}
/**
* @return the lastForwardDistanceUpdate
*/
public synchronized long getLastForwardDistanceUpdate() {
return lastForwardDistanceUpdate;
}
/**
* @return the lastSidewaysDistanceUpdate
*/
public synchronized long getLastSidewaysDistanceUpdate() {
return lastSidewaysDistanceUpdate;
}
/**
* @param lastForwardDistanceUpdate the lastForwardDistanceUpdate to set
*/
protected synchronized void setLastForwardDistanceUpdate(long lastForwardDistanceUpdate) {
this.lastForwardDistanceUpdate = lastForwardDistanceUpdate;
}
/**
* @param lastSidewaysDistanceUpdate the lastSidewaysDistanceUpdate to set
*/
protected synchronized void setLastSidewaysDistanceUpdate(long lastSidewaysDistanceUpdate) {
this.lastSidewaysDistanceUpdate = lastSidewaysDistanceUpdate;
}
/* (non-Javadoc)
* @see org._2585robophiles.lib2585.Destroyable#destroy()
*/
@Override
public void destroy() {
drivetrain.free();
if(sidewaysMotor instanceof SensorBase){
SensorBase motor = (SensorBase) sidewaysMotor;
motor.free();
}
}
}
|
package org.exist.xslt;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import org.apache.log4j.Logger;
import org.exist.storage.BrokerPool;
/**
* Allows the TransformerFactory that is used for XSLT to be
* chosen through configuration settings in conf.xml
*
* Within eXist this class should be used instead of
* directly calling SAXTransformerFactory.newInstance() directly
*
* @author Adam Retter <adam.retter@devon.gov.uk>
* @author Andrzej Taramina <andrzej@chaeron.com>
*/
public class TransformerFactoryAllocator
{
private final static Logger LOG = Logger.getLogger( TransformerFactoryAllocator.class );
public static final String CONFIGURATION_ELEMENT_NAME = "transformer";
public final static String TRANSFORMER_CLASS_ATTRIBUTE = "class";
public final static String PROPERTY_TRANSFORMER_CLASS = "transformer.class";
public final static String CONFIGURATION_TRANSFORMER_ATTRIBUTE_ELEMENT_NAME = "attribute";
public final static String PROPERTY_TRANSFORMER_ATTRIBUTES = "transformer.attributes";
public final static String TRANSFORMER_CACHING_ATTRIBUTE = "caching";
public final static String PROPERTY_CACHING_ATTRIBUTE = "transformer.caching";
public final static String PROPERTY_BROKER_POOL = "transformer.brokerPool";
//private constructor
private TransformerFactoryAllocator()
{
}
/**
* Get the TransformerFactory defined in conf.xml
* If the class can't be found or the given class doesn't implement
* the required interface, the default factory is returned.
*
* @param pool A database broker pool, used for reading the conf.xml configuration
*
* @return A SAXTransformerFactory, for which newInstance() can then be called
*
*
* Typical usage:
*
* Instead of SAXTransformerFactory.newInstance() use
* TransformerFactoryAllocator.getTransformerFactory(broker).newInstance()
*/
public static SAXTransformerFactory getTransformerFactory( BrokerPool pool )
{
SAXTransformerFactory factory;
//get the transformer class name from conf.xml
String transformerFactoryClassName = (String)pool.getConfiguration().getProperty(PROPERTY_TRANSFORMER_CLASS);
// if( LOG.isDebugEnabled() ) {
// LOG.debug( "transformerFactoryClassName=" + transformerFactoryClassName );
// LOG.debug( "javax.xml.transform.TransformerFactory=" + System.getProperty( "javax.xml.transform.TransformerFactory" ) );
// was a TransformerFactory class specified?
if( transformerFactoryClassName == null ) {
//no, use the system default
factory = (SAXTransformerFactory)TransformerFactory.newInstance();
} else {
//try and load the specified TransformerFactory class
try {
factory = (SAXTransformerFactory)Class.forName( transformerFactoryClassName ).newInstance();
if( LOG.isDebugEnabled() ) {
LOG.debug( "Set transformer factory: " + transformerFactoryClassName );
}
Hashtable attributes = (Hashtable)pool.getConfiguration().getProperty( PROPERTY_TRANSFORMER_ATTRIBUTES );
Enumeration attrNames = attributes.keys();
while( attrNames.hasMoreElements() ) {
String name = (String)attrNames.nextElement();
Object value = attributes.get( name );
try {
factory.setAttribute( name, value );
if( LOG.isDebugEnabled() ) {
LOG.debug( "Set transformer attribute: " + ", name: " + name + ", value: " + value );
}
}
catch( Exception e ) {
LOG.warn( "Unable to set attribute for TransformerFactory: '" + transformerFactoryClassName + "', name: " + name + ", value: " + value + ", exception: " + e );
}
}
if(factory instanceof org.exist.xslt.TransformerFactoryImpl)
factory.setAttribute(PROPERTY_BROKER_POOL, pool);
}
catch( ClassNotFoundException cnfe ) {
if( LOG.isDebugEnabled() ) {
LOG.debug("Cannot find the requested TrAX factory '" + transformerFactoryClassName + "'. Using default TrAX Transformer Factory instead." );
}
//fallback to system default
factory = (SAXTransformerFactory)TransformerFactory.newInstance();
}
catch( ClassCastException cce ) {
if( LOG.isDebugEnabled() ) {
LOG.debug( "The indicated class '" + transformerFactoryClassName + "' is not a TrAX Transformer Factory. Using default TrAX Transformer Factory instead." );
}
//fallback to system default
factory = (SAXTransformerFactory)TransformerFactory.newInstance();
}
catch( Exception e ) {
if( LOG.isDebugEnabled() ) {
LOG.debug( "Error found loading the requested TrAX Transformer Factory '" + transformerFactoryClassName + "'. Using default TrAX Transformer Factory instead: " + e );
}
//fallback to system default
factory = (SAXTransformerFactory)TransformerFactory.newInstance();
}
}
return( factory );
}
}
|
package uk.ac.ebi.spot.goci.curation.service;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import uk.ac.ebi.spot.goci.curation.builder.AssociationBuilder;
import uk.ac.ebi.spot.goci.curation.builder.EfoTraitBuilder;
import uk.ac.ebi.spot.goci.curation.builder.GeneBuilder;
import uk.ac.ebi.spot.goci.curation.builder.LocationBuilder;
import uk.ac.ebi.spot.goci.curation.builder.LocusBuilder;
import uk.ac.ebi.spot.goci.curation.builder.RegionBuilder;
import uk.ac.ebi.spot.goci.curation.builder.RiskAlleleBuilder;
import uk.ac.ebi.spot.goci.curation.builder.SingleNucleotidePolymorphismBuilder;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationStandardMultiForm;
import uk.ac.ebi.spot.goci.curation.model.SnpFormRow;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.EfoTrait;
import uk.ac.ebi.spot.goci.model.Gene;
import uk.ac.ebi.spot.goci.model.Location;
import uk.ac.ebi.spot.goci.model.Locus;
import uk.ac.ebi.spot.goci.model.Region;
import uk.ac.ebi.spot.goci.model.RiskAllele;
import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.GenomicContextRepository;
import uk.ac.ebi.spot.goci.repository.LocusRepository;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
import static org.junit.Assert.assertNull;
@RunWith(MockitoJUnitRunner.class)
public class SingleSnpMultiSnpAssociationServiceTest {
@Mock
private AssociationRepository associationRepository;
@Mock
private LocusRepository locusRepository;
@Mock
private GenomicContextRepository genomicContextRepository;
@Mock
private LociAttributesService lociAttributesService;
private SnpAssociationFormService snpAssociationFormService;
// Entity objects
private static final EfoTrait EFO_01 = new EfoTraitBuilder()
.setId(988L)
.setTrait("atrophic rhinitis")
.setUri("http:
.build();
private static final EfoTrait EFO_02 = new EfoTraitBuilder()
.setId(989L)
.setTrait("HeLa")
.setUri("http:
.build();
private static final Gene GENE_01 = new GeneBuilder().setId(112L).setGeneName("NEGR1").build();
private static final Gene GENE_02 = new GeneBuilder().setId(113L).setGeneName("FRS2").build();
private static final Gene GENE_03 = new GeneBuilder().setId(113L).setGeneName("ELF1").build();
private static final Region REGION_01 = new RegionBuilder().setId(897L).setName("9q33.1").build();
private static final Location LOCATION_01 =
new LocationBuilder().setId(654L).setChromosomeName("1").setChromosomePosition("159001296").build();
private static final SingleNucleotidePolymorphism
PROXY_SNP_01 = new SingleNucleotidePolymorphismBuilder().setId(311L)
.setLastUpdateDate(new Date())
.setRsId("rs6538678")
.build();
private static final SingleNucleotidePolymorphism
PROXY_SNP_02 = new SingleNucleotidePolymorphismBuilder().setId(311L)
.setLastUpdateDate(new Date())
.setRsId("rs7329174")
.build();
private static final SingleNucleotidePolymorphism
PROXY_SNP_03 = new SingleNucleotidePolymorphismBuilder().setId(311L)
.setLastUpdateDate(new Date())
.setRsId("rs1234567")
.build();
private static final SingleNucleotidePolymorphism SNP_01 = new SingleNucleotidePolymorphismBuilder().setId(311L)
.setLastUpdateDate(new Date())
.setRsId("rs579459")
.build();
private static final SingleNucleotidePolymorphism SNP_02 = new SingleNucleotidePolymorphismBuilder().setId(321L)
.setLastUpdateDate(new Date())
.setRsId("rs9533090")
.build();
private static final SingleNucleotidePolymorphism SNP_03 = new SingleNucleotidePolymorphismBuilder().setId(391L)
.setLastUpdateDate(new Date())
.setRsId("rs114205691")
.build();
private static final RiskAllele RISK_ALLELE_01 = new RiskAlleleBuilder().setId(411L)
.setRiskAlleleName("rs579459-?")
.build();
private static final RiskAllele RISK_ALLELE_02 = new RiskAlleleBuilder().setId(412L)
.setRiskAlleleName("rs9533090-?")
.build();
private static final RiskAllele RISK_ALLELE_03 = new RiskAlleleBuilder().setId(413L)
.setRiskAlleleName("rs114205691-?")
.build();
private static final Locus LOCUS_01 =
new LocusBuilder().setId(111L)
.setDescription("Single variant")
.build();
private static final Locus LOCUS_02 =
new LocusBuilder().setId(111L)
.setDescription("2-SNP haplotype")
.setHaplotypeSnpCount(2)
.build();
private static final Association BETA_SINGLE_ASSOCIATION =
new AssociationBuilder().setId((long) 100)
.setBetaDirection("decrease")
.setBetaUnit("mm Hg")
.setBetaNum((float) 1.06)
.setSnpType("novel")
.setMultiSnpHaplotype(false)
.setSnpInteraction(false)
.setSnpApproved(false)
.setPvalueExponent(-8)
.setPvalueMantissa(1)
.setStandardError((float) 6.24)
.setRange("[14.1-38.56]")
.setPvalueDescription("(ferritin)")
.setRiskFrequency(String.valueOf(0.93))
.setEfoTraits(Arrays.asList(EFO_01, EFO_02))
.setDescription("this is a test")
.build();
private static final Association OR_MULTI_ASSOCIATION =
new AssociationBuilder().setId((long) 101)
.setSnpType("novel")
.setMultiSnpHaplotype(true)
.setSnpInteraction(false)
.setSnpApproved(false)
.setPvalueExponent(-8)
.setPvalueMantissa(1)
.setStandardError((float) 6.24)
.setRange("[14.1-38.56]")
.setOrPerCopyNum((float) 1.89)
.setOrPerCopyRecip((float) 0.99)
.setOrPerCopyRecipRange("[1.0-8.0]")
.setPvalueDescription("(ferritin)")
.setRiskFrequency(String.valueOf(0.12))
.setEfoTraits(Arrays.asList(EFO_01, EFO_02))
.setDescription("this is a test")
.build();
@BeforeClass
public static void setUpModelObjects() throws Exception {
// Create the links between all our objects
REGION_01.setLocations(Collections.singletonList(LOCATION_01));
LOCATION_01.setRegion(REGION_01);
// For testing all SNPs can have the same locations
SNP_01.setLocations(Collections.singletonList(LOCATION_01));
SNP_02.setLocations(Collections.singletonList(LOCATION_01));
SNP_03.setLocations(Collections.singletonList(LOCATION_01));
// Set snp risk alleles
SNP_01.setRiskAlleles(Collections.singletonList(RISK_ALLELE_01));
SNP_02.setRiskAlleles(Collections.singletonList(RISK_ALLELE_02));
SNP_03.setRiskAlleles(Collections.singletonList(RISK_ALLELE_03));
// Set risk allele snp
RISK_ALLELE_01.setSnp(SNP_01);
RISK_ALLELE_02.setSnp(SNP_02);
RISK_ALLELE_03.setSnp(SNP_03);
// Set risk allele proxy snp
RISK_ALLELE_01.setProxySnps(Collections.singletonList(PROXY_SNP_01));
RISK_ALLELE_02.setProxySnps(Collections.singletonList(PROXY_SNP_02));
RISK_ALLELE_03.setProxySnps(Collections.singletonList(PROXY_SNP_03));
// Set locus risk allele
LOCUS_01.setStrongestRiskAlleles(Collections.singletonList(RISK_ALLELE_01));
LOCUS_02.setStrongestRiskAlleles(Arrays.asList(RISK_ALLELE_02, RISK_ALLELE_03));
// Set Locus genes
LOCUS_01.setAuthorReportedGenes(Arrays.asList(GENE_01, GENE_02));
LOCUS_02.setAuthorReportedGenes(Collections.singletonList(GENE_03));
// Build association links
BETA_SINGLE_ASSOCIATION.setLoci(Collections.singletonList(LOCUS_01));
OR_MULTI_ASSOCIATION.setLoci(Collections.singletonList(LOCUS_02));
}
@Before
public void setUp() throws Exception {
snpAssociationFormService = new SingleSnpMultiSnpAssociationService(associationRepository,
locusRepository,
genomicContextRepository,
lociAttributesService);
}
@Test
public void testCreateSingleForm() throws Exception {
assertThat(snpAssociationFormService.createForm(BETA_SINGLE_ASSOCIATION)).isInstanceOf(
SnpAssociationStandardMultiForm.class);
SnpAssociationStandardMultiForm form =
(SnpAssociationStandardMultiForm) snpAssociationFormService.createForm(BETA_SINGLE_ASSOCIATION);
// Check values we would expect in form
assertThat(form.getAssociationId()).as("Check form ID").isEqualTo(BETA_SINGLE_ASSOCIATION.getId());
assertThat(form.getBetaDirection()).as("Check form BETA DIRECTION")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getBetaDirection());
assertThat(form.getBetaUnit()).as("Check form BETA UNIT").isEqualTo(BETA_SINGLE_ASSOCIATION.getBetaUnit());
assertThat(form.getBetaNum()).as("Check form BETA NUM").isEqualTo(BETA_SINGLE_ASSOCIATION.getBetaNum());
assertThat(form.getSnpType()).as("Check form SNP TYPE").isEqualTo(BETA_SINGLE_ASSOCIATION.getSnpType());
assertThat(form.getMultiSnpHaplotype()).as("Check form MULTI SNP HAPLOTYPE")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getMultiSnpHaplotype());
assertThat(form.getSnpApproved()).as("Check form SNP APPROVED")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getSnpApproved());
assertThat(form.getPvalueExponent()).as("Check form PVALUE EXPONENT")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getPvalueExponent());
assertThat(form.getPvalueMantissa()).as("Check form PVALUE MANTISSA")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getPvalueMantissa());
assertThat(form.getStandardError()).as("Check form STANDARD ERROR")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getStandardError());
assertThat(form.getRange()).as("Check form RANGE").isEqualTo(BETA_SINGLE_ASSOCIATION.getRange());
assertThat(form.getPvalueDescription()).as("Check form PVALUE DESCRIPTION")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getPvalueDescription());
assertThat(form.getRiskFrequency()).as("Check form RISK FREQUENCY")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getRiskFrequency());
assertThat(form.getDescription()).as("Check form DESCRIPTION")
.isEqualTo(BETA_SINGLE_ASSOCIATION.getDescription());
// Check EFO traits
assertThat(form.getEfoTraits()).extracting("id", "trait", "uri")
.contains(tuple(988L, "atrophic rhinitis", "http:
tuple(989L, "HeLa", "http:
// Check null values
assertNull(form.getOrPerCopyNum());
assertNull(form.getOrPerCopyRecip());
assertNull(form.getOrPerCopyRecipRange());
assertNull(form.getMultiSnpHaplotypeNum());
// Test locus attributes
assertThat(form.getMultiSnpHaplotypeDescr()).as("Check form MULTI HAPLOTYPE DESCRIPTION")
.isEqualTo("Single variant");
assertThat(form.getAuthorReportedGenes()).isInstanceOf(Collection.class);
assertThat(form.getAuthorReportedGenes()).contains("NEGR1", "FRS2");
// Test the row values
Collection<SnpFormRow> rows = form.getSnpFormRows();
assertThat(rows).hasSize(1);
assertThat(rows).extracting("snp", "strongestRiskAllele")
.containsExactly(tuple("rs579459", "rs579459-?"));
assertThat(rows).extracting("proxySnps").isNotEmpty();
List<String> proxyNames = new ArrayList<String>();
for (SnpFormRow row : rows) {
proxyNames.addAll(row.getProxySnps());
}
assertThat(proxyNames).containsOnlyOnce("rs6538678");
}
@Test
public void testCreateMultiForm() throws Exception {
assertThat(snpAssociationFormService.createForm(OR_MULTI_ASSOCIATION)).isInstanceOf(
SnpAssociationStandardMultiForm.class);
SnpAssociationStandardMultiForm form =
(SnpAssociationStandardMultiForm) snpAssociationFormService.createForm(OR_MULTI_ASSOCIATION);
// Check values we would expect in form
assertThat(form.getAssociationId()).as("Check form ID").isEqualTo(OR_MULTI_ASSOCIATION.getId());
assertThat(form.getSnpType()).as("Check form SNP TYPE").isEqualTo(OR_MULTI_ASSOCIATION.getSnpType());
assertThat(form.getMultiSnpHaplotype()).as("Check form MULTI SNP HAPLOTYPE")
.isEqualTo(OR_MULTI_ASSOCIATION.getMultiSnpHaplotype());
assertThat(form.getSnpApproved()).as("Check form SNP APPROVED")
.isEqualTo(OR_MULTI_ASSOCIATION.getSnpApproved());
assertThat(form.getPvalueExponent()).as("Check form PVALUE EXPONENT")
.isEqualTo(OR_MULTI_ASSOCIATION.getPvalueExponent());
assertThat(form.getPvalueMantissa()).as("Check form PVALUE MANTISSA")
.isEqualTo(OR_MULTI_ASSOCIATION.getPvalueMantissa());
assertThat(form.getStandardError()).as("Check form STANDARD ERROR")
.isEqualTo(OR_MULTI_ASSOCIATION.getStandardError());
assertThat(form.getRange()).as("Check form RANGE").isEqualTo(OR_MULTI_ASSOCIATION.getRange());
assertThat(form.getPvalueDescription()).as("Check form PVALUE DESCRIPTION")
.isEqualTo(OR_MULTI_ASSOCIATION.getPvalueDescription());
assertThat(form.getRiskFrequency()).as("Check form RISK FREQUENCY")
.isEqualTo(OR_MULTI_ASSOCIATION.getRiskFrequency());
assertThat(form.getDescription()).as("Check form DESCRIPTION")
.isEqualTo(OR_MULTI_ASSOCIATION.getDescription());
// Check EFO traits
assertThat(form.getEfoTraits()).extracting("id", "trait", "uri")
.contains(tuple(988L, "atrophic rhinitis", "http:
tuple(989L, "HeLa", "http:
// Check null values
assertNull(form.getBetaDirection());
assertNull(form.getBetaNum());
assertNull(form.getBetaUnit());
// Test locus attributes
assertThat(form.getMultiSnpHaplotypeDescr()).as("Check form MULTI HAPLOTYPE DESCRIPTION")
.isEqualTo("2-SNP haplotype");
assertThat(form.getMultiSnpHaplotypeNum()).as("Check form MULTI HAPLOTYPE NUMBER")
.isEqualTo(2);
assertThat(form.getAuthorReportedGenes()).isInstanceOf(Collection.class);
assertThat(form.getAuthorReportedGenes()).containsOnly("ELF1");
// Test the row values
Collection<SnpFormRow> rows = form.getSnpFormRows();
assertThat(rows).hasSize(2);
assertThat(rows).extracting("proxySnps").isNotEmpty();
assertThat(rows).extracting("snp").isNotEmpty();
assertThat(rows).extracting("strongestRiskAllele").isNotEmpty();
assertThat(rows).extracting("snp").containsExactly("rs9533090", "rs114205691");
assertThat(rows).extracting("strongestRiskAllele").containsExactly("rs9533090-?", "rs114205691-?");
List<String> proxyNames = new ArrayList<String>();
for (SnpFormRow row : rows) {
proxyNames.addAll(row.getProxySnps());
}
assertThat(proxyNames).containsExactly("rs7329174", "rs1234567");
}
}
|
package org.jabref.logic.importer.fetcher;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.jabref.logic.importer.FulltextFetcher;
import org.jabref.logic.net.URLDownload;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.DOI;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FulltextFetcher implementation that follows the DOI resolution redirects and scans for a full-text PDF URL.
*/
public class DoiResolution implements FulltextFetcher {
private static final Logger LOGGER = LoggerFactory.getLogger(DoiResolution.class);
@Override
public Optional<URL> findFullText(BibEntry entry) throws IOException {
Objects.requireNonNull(entry);
Optional<DOI> doi = entry.getField(StandardField.DOI).flatMap(DOI::parse);
if (!doi.isPresent()) {
return Optional.empty();
}
String doiLink = doi.get().getURIAsASCIIString();
if (doiLink.isEmpty()) {
return Optional.empty();
}
// follow all redirects and scan for a single pdf link
try {
Connection session = Jsoup.newSession()
// some publishers are quite slow (default is 3s)
.timeout(10000)
.followRedirects(true)
.ignoreHttpErrors(true)
.referrer("https:
.userAgent(URLDownload.USER_AGENT);
Connection connection = session.newRequest().url(doiLink);
Connection.Response response = connection.execute();
Document html = response.parse();
// citation pdf meta tag
Optional<URL> citationMetaTag = citationMetaTag(html);
if (citationMetaTag.isPresent()) {
return checkPdfPresense(citationMetaTag.get(), session);
}
// scan for PDF
Elements hrefElements = html.body().select("a[href]");
List<URL> links = new ArrayList<>();
for (Element element : hrefElements) {
String href = element.attr("abs:href").toLowerCase(Locale.ENGLISH);
String hrefText = element.text().toLowerCase(Locale.ENGLISH);
// Only check if pdf is included in the link or inside the text
// ACM uses tokens without PDF inside the link
// link with "PDF" in title tag
if (element.attr("title").toLowerCase(Locale.ENGLISH).contains("pdf") && new URLDownload(href).isPdf()) {
return Optional.of(new URL(href));
}
if (href.contains("pdf") || hrefText.contains("pdf") && new URLDownload(href).isPdf()) {
links.add(new URL(href));
}
}
// return if only one link was found (high accuracy)
if (links.size() == 1) {
LOGGER.info("Fulltext PDF found @ {}", doiLink);
return checkPdfPresense(links.get(0), session);
}
// return only if one distinct link was found
Optional<URL> distinctLink = findDistinctLinks(links);
if (distinctLink.isEmpty()) {
return Optional.empty();
}
LOGGER.debug("Fulltext PDF link @ {}", distinctLink.get());
return checkPdfPresense(distinctLink.get(), session);
} catch (UnsupportedMimeTypeException type) {
// this might be the PDF already as we follow redirects
if (type.getMimeType().startsWith("application/pdf")) {
return Optional.of(new URL(type.getUrl()));
}
LOGGER.warn("DoiResolution fetcher failed: ", type);
} catch (IOException e) {
LOGGER.warn("DoiResolution fetcher failed: ", e);
}
return Optional.empty();
}
/**
* Uses the given connection to check whether there really is a PDF behind the given link
*
* @return Optional.empty() if there is no PDF found (but HTML)
*/
private Optional<URL> checkPdfPresense(URL url, Connection session) throws IOException {
// Wiley returns wrong content type
if (url.toExternalForm().contains("pdf")) {
// ... too much hacky ...
}
Connection pdfConnection = session.newRequest().url(url);
pdfConnection.method(Connection.Method.HEAD);
Connection.Response pdfResponse = pdfConnection.execute();
String contentType = pdfResponse.header("Content-Type");
if (contentType.startsWith("text/html")) {
return Optional.empty();
} else {
return Optional.of(url);
}
}
private Optional<URL> citationMetaTag(Document html) {
Elements citationPdfUrlElement = html.head().select("meta[name='citation_pdf_url']");
Optional<String> citationPdfUrl = citationPdfUrlElement.stream().map(e -> e.attr("content")).findFirst();
if (citationPdfUrl.isPresent()) {
try {
return Optional.of(new URL(citationPdfUrl.get()));
} catch (MalformedURLException e) {
return Optional.empty();
}
}
return Optional.empty();
}
private Optional<URL> findDistinctLinks(List<URL> urls) {
List<URL> distinctLinks = urls.stream().distinct().collect(Collectors.toList());
if (distinctLinks.isEmpty()) {
return Optional.empty();
}
// equal
if (distinctLinks.size() == 1) {
return Optional.of(distinctLinks.get(0));
}
return Optional.empty();
}
@Override
public TrustLevel getTrustLevel() {
return TrustLevel.SOURCE;
}
}
|
package org.jcodings.specific;
import org.jcodings.CaseFoldMapEncoding;
import org.jcodings.Config;
import org.jcodings.IntHolder;
import org.jcodings.constants.CharacterType;
final public class Windows_1253Encoding extends CaseFoldMapEncoding {
protected Windows_1253Encoding() {
super("Windows-1253", CP1253_CtypeTable, CP1253_ToLowerCaseTable, CP1253_CaseFoldMap, true);
}
@Override
public int caseMap(IntHolder flagP, byte[] bytes, IntHolder pp, int end, byte[] to, int toP, int toEnd) {
int toStart = toP;
int flags = flagP.value;
while (pp.value < end && toP < toEnd) {
int code = bytes[pp.value++] & 0xff;
if (code == 0xF2) {
if ((flags & Config.CASE_UPCASE) != 0) {
flags |= Config.CASE_MODIFIED;
code = 0xD3;
} else if ((flags & Config.CASE_FOLD) != 0) {
flags |= Config.CASE_MODIFIED;
code = 0xF3;
}
} else if (code == 0xB5) {
if ((flags & Config.CASE_UPCASE) != 0) {
flags |= Config.CASE_MODIFIED;
code = 0xCC;
} else if ((flags & Config.CASE_FOLD) != 0) {
flags |= Config.CASE_MODIFIED;
code = 0xEC;
}
} else if (code == 0xC0 || code == 0xE0 || code == 0xB6) {
} else if ((CP1253_CtypeTable[code] & CharacterType.BIT_UPPER) != 0 && (flags & (Config.CASE_DOWNCASE | Config.CASE_FOLD)) != 0) {
flags |= Config.CASE_MODIFIED;
code = LowerCaseTable[code];
} else if (code == 0xC0 || code == 0xE0) {
} else if ((CP1253_CtypeTable[code] & CharacterType.BIT_LOWER) != 0 && (flags & Config.CASE_UPCASE) != 0) {
flags |= Config.CASE_MODIFIED;
if (code == 0xDC)
code = 0xA2;
else if (code >= 0xDD && code <= 0xDF)
code -= 0x25;
else if (code == 0xFC)
code = 0xBC;
else if (code == 0xFD || code == 0xFE)
code -= 0x3F;
else
code -= 0x20;
}
to[toP++] = (byte)code;
if ((flags & Config.CASE_TITLECASE) != 0) {
flags ^= (Config.CASE_UPCASE | Config.CASE_DOWNCASE | Config.CASE_TITLECASE);
}
}
flagP.value = flags;
return toP - toStart;
}
@Override
public int mbcCaseFold(int flag, byte[]bytes, IntHolder pp, int end, byte[]lower) {
int p = pp.value;
int lowerP = 0;
lower[lowerP] = LowerCaseTable[bytes[p] & 0xff];
pp.value++;
return 1;
}
@Override
public boolean isCodeCType(int code, int ctype) {
return code < 256 ? isCodeCTypeInternal(code, ctype) : false;
}
static final short CP1253_CtypeTable[] = {
0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008,
0x4008, 0x420c, 0x4209, 0x4208, 0x4208, 0x4208, 0x4008, 0x4008,
0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008,
0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008,
0x4284, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0,
0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0,
0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0,
0x78b0, 0x78b0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0,
0x41a0, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x74a2,
0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2,
0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2,
0x74a2, 0x74a2, 0x74a2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x51a0,
0x41a0, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x70e2,
0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2,
0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2,
0x70e2, 0x70e2, 0x70e2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x4008,
0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008,
0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008,
0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008,
0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008,
0x0284, 0x01a0, 0x34a2, 0x00a0, 0x0000, 0x0000, 0x00a0, 0x00a0,
0x00a0, 0x00a0, 0x0000, 0x01a0, 0x00a0, 0x01a0, 0x0000, 0x01a0,
0x00a0, 0x00a0, 0x10a0, 0x10a0, 0x00a0, 0x30e2, 0x34a2, 0x01a0,
0x34a2, 0x34a2, 0x34a2, 0x01a0, 0x34a2, 0x10a0, 0x34a2, 0x34a2,
0x30e2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2,
0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2,
0x34a2, 0x34a2, 0x0000, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2,
0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x30e2, 0x30e2, 0x30e2, 0x30e2,
0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2,
0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2,
0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2,
0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x0000
};
static final byte CP1253_ToLowerCaseTable[] = new byte[]{
(byte)'\000', (byte)'\001', (byte)'\002', (byte)'\003', (byte)'\004', (byte)'\005', (byte)'\006', (byte)'\007',
(byte)'\010', (byte)'\011', (byte)'\012', (byte)'\013', (byte)'\014', (byte)'\015', (byte)'\016', (byte)'\017',
(byte)'\020', (byte)'\021', (byte)'\022', (byte)'\023', (byte)'\024', (byte)'\025', (byte)'\026', (byte)'\027',
(byte)'\030', (byte)'\031', (byte)'\032', (byte)'\033', (byte)'\034', (byte)'\035', (byte)'\036', (byte)'\037',
(byte)'\040', (byte)'\041', (byte)'\042', (byte)'\043', (byte)'\044', (byte)'\045', (byte)'\046', (byte)'\047',
(byte)'\050', (byte)'\051', (byte)'\052', (byte)'\053', (byte)'\054', (byte)'\055', (byte)'\056', (byte)'\057',
(byte)'\060', (byte)'\061', (byte)'\062', (byte)'\063', (byte)'\064', (byte)'\065', (byte)'\066', (byte)'\067',
(byte)'\070', (byte)'\071', (byte)'\072', (byte)'\073', (byte)'\074', (byte)'\075', (byte)'\076', (byte)'\077',
(byte)'\100', (byte)'\141', (byte)'\142', (byte)'\143', (byte)'\144', (byte)'\145', (byte)'\146', (byte)'\147',
(byte)'\150', (byte)'\151', (byte)'\152', (byte)'\153', (byte)'\154', (byte)'\155', (byte)'\156', (byte)'\157',
(byte)'\160', (byte)'\161', (byte)'\162', (byte)'\163', (byte)'\164', (byte)'\165', (byte)'\166', (byte)'\167',
(byte)'\170', (byte)'\171', (byte)'\172', (byte)'\133', (byte)'\134', (byte)'\135', (byte)'\136', (byte)'\137',
(byte)'\140', (byte)'\141', (byte)'\142', (byte)'\143', (byte)'\144', (byte)'\145', (byte)'\146', (byte)'\147',
(byte)'\150', (byte)'\151', (byte)'\152', (byte)'\153', (byte)'\154', (byte)'\155', (byte)'\156', (byte)'\157',
(byte)'\160', (byte)'\161', (byte)'\162', (byte)'\163', (byte)'\164', (byte)'\165', (byte)'\166', (byte)'\167',
(byte)'\170', (byte)'\171', (byte)'\172', (byte)'\173', (byte)'\174', (byte)'\175', (byte)'\176', (byte)'\177',
(byte)'\200', (byte)'\201', (byte)'\202', (byte)'\203', (byte)'\204', (byte)'\205', (byte)'\206', (byte)'\207',
(byte)'\210', (byte)'\211', (byte)'\212', (byte)'\213', (byte)'\214', (byte)'\215', (byte)'\216', (byte)'\217',
(byte)'\220', (byte)'\221', (byte)'\222', (byte)'\223', (byte)'\224', (byte)'\225', (byte)'\226', (byte)'\227',
(byte)'\230', (byte)'\231', (byte)'\232', (byte)'\233', (byte)'\234', (byte)'\235', (byte)'\236', (byte)'\237',
(byte)'\240', (byte)'\241', (byte)'\334', (byte)'\243', (byte)'\244', (byte)'\245', (byte)'\246', (byte)'\247',
(byte)'\250', (byte)'\251', (byte)'\252', (byte)'\253', (byte)'\254', (byte)'\255', (byte)'\256', (byte)'\257',
(byte)'\260', (byte)'\261', (byte)'\262', (byte)'\263', (byte)'\264', (byte)'\354', (byte)'\334', (byte)'\267',
(byte)'\335', (byte)'\336', (byte)'\337', (byte)'\273', (byte)'\374', (byte)'\275', (byte)'\375', (byte)'\376',
(byte)'\300', (byte)'\341', (byte)'\342', (byte)'\343', (byte)'\344', (byte)'\345', (byte)'\346', (byte)'\347',
(byte)'\350', (byte)'\351', (byte)'\352', (byte)'\353', (byte)'\354', (byte)'\355', (byte)'\356', (byte)'\357',
(byte)'\360', (byte)'\361', (byte)'\322', (byte)'\363', (byte)'\364', (byte)'\365', (byte)'\366', (byte)'\367',
(byte)'\370', (byte)'\371', (byte)'\372', (byte)'\373', (byte)'\334', (byte)'\335', (byte)'\336', (byte)'\337',
(byte)'\340', (byte)'\341', (byte)'\342', (byte)'\343', (byte)'\344', (byte)'\345', (byte)'\346', (byte)'\347',
(byte)'\350', (byte)'\351', (byte)'\352', (byte)'\353', (byte)'\354', (byte)'\355', (byte)'\356', (byte)'\357',
(byte)'\360', (byte)'\361', (byte)'\362', (byte)'\363', (byte)'\364', (byte)'\365', (byte)'\366', (byte)'\367',
(byte)'\370', (byte)'\371', (byte)'\372', (byte)'\373', (byte)'\374', (byte)'\375', (byte)'\376', (byte)'\377'
};
static final int CP1253_CaseFoldMap[][] = {
{ 0xb6, 0xdc },
{ 0xb8, 0xdd },
{ 0xb9, 0xde },
{ 0xba, 0xdf },
{ 0xbc, 0xfc },
{ 0xbe, 0xfd },
{ 0xbf, 0xfe },
{ 0xc1, 0xe1 },
{ 0xc2, 0xe2 },
{ 0xc3, 0xe3 },
{ 0xc4, 0xe4 },
{ 0xc5, 0xe5 },
{ 0xc6, 0xe6 },
{ 0xc7, 0xe7 },
{ 0xc8, 0xe8 },
{ 0xc9, 0xe9 },
{ 0xca, 0xea },
{ 0xcb, 0xeb },
{ 0xcc, 0xec },
{ 0xcd, 0xed },
{ 0xce, 0xee },
{ 0xcf, 0xef },
{ 0xd0, 0xf0 },
{ 0xd1, 0xf1 },
{ 0xd2, 0xf2 },
{ 0xd3, 0xf3 },
{ 0xd4, 0xf4 },
{ 0xd5, 0xf5 },
{ 0xd6, 0xf6 },
{ 0xd7, 0xf7 },
{ 0xd8, 0xf8 },
{ 0xd9, 0xf9 },
{ 0xda, 0xfa },
{ 0xdb, 0xfb }
};
public static final Windows_1253Encoding INSTANCE = new Windows_1253Encoding();
}
|
package org.innovateuk.ifs.thread.attachment.security;
import org.innovateuk.ifs.BaseServiceSecurityTest;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.file.service.FileAndContents;
import org.innovateuk.ifs.project.finance.security.AttachmentPermissionsRules;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.project.security.ProjectLookupStrategy;
import org.innovateuk.ifs.threads.attachments.security.AttachmentLookupStrategy;
import org.innovateuk.ifs.threads.attachments.service.ProjectFinanceAttachmentService;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.threads.attachment.resource.AttachmentResource;
import org.innovateuk.threads.resource.QueryResource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.HttpServletRequest;
import static org.innovateuk.ifs.project.builder.ProjectResourceBuilder.newProjectResource;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.*;
public class ProjectFinanceAttachmentServiceSecurityTest extends BaseServiceSecurityTest<ProjectFinanceAttachmentService> {
private AttachmentPermissionsRules attachmentPermissionsRules;
private AttachmentLookupStrategy attachmentLookupStrategy;
private ProjectLookupStrategy projectLookupStrategy;
@Override
protected Class<? extends ProjectFinanceAttachmentService> getClassUnderTest() {
return TestProjectFinanceAttachmentService.class;
}
@Before
public void lookupPermissionRules() {
attachmentPermissionsRules = getMockPermissionRulesBean(AttachmentPermissionsRules.class);
attachmentLookupStrategy = getMockPermissionEntityLookupStrategiesBean(AttachmentLookupStrategy.class);
projectLookupStrategy = getMockPermissionEntityLookupStrategiesBean(ProjectLookupStrategy.class);
}
@Test
public void test_upload() throws Exception {
final QueryResource queryResource = new QueryResource(null, null, null, null, null, false, null);
when(projectLookupStrategy.getProjectResource(77L)).thenReturn(newProjectResource().withId(77L).build());
assertAccessDenied(
() -> classUnderTest.upload("application.pdf", "3234", "filename.pdf", 77L, null),
() -> {
verify(attachmentPermissionsRules).projectFinanceCanUploadAttachments(isA(ProjectResource.class), isA(UserResource.class));
verify(attachmentPermissionsRules).projectPartnersCanUploadAttachments(isA(ProjectResource.class), isA(UserResource.class));
verifyNoMoreInteractions(attachmentPermissionsRules);
});
}
@Test
public void test_findOne() throws Exception {
setLoggedInUser(null);
assertAccessDenied(() -> classUnderTest.findOne(1L), () -> {
verify(attachmentPermissionsRules).projectFinanceUsersCanFetchAnyAttachment(isA(AttachmentResource.class), isNull(UserResource.class));
verify(attachmentPermissionsRules).financeContactUsersCanOnlyFetchAnAttachmentIfUploaderOrIfRelatedToItsQuery(isA(AttachmentResource.class), isNull(UserResource.class));
verifyNoMoreInteractions(attachmentPermissionsRules);
});
}
@Test
public void test_downloadAttachment() throws Exception {
setLoggedInUser(null);
when(attachmentLookupStrategy.findById(3L))
.thenReturn(new AttachmentResource(3L, "file", "application/pdf", 3456));
assertAccessDenied(() -> classUnderTest.attachmentFileAndContents(3L), () -> {
verify(attachmentPermissionsRules).projectFinanceUsersCanDownloadAnyAttachment(isA(AttachmentResource.class), isNull(UserResource.class));
verify(attachmentPermissionsRules).financeContactUsersCanOnlyDownloadAnAttachmentIfRelatedToItsQuery(isA(AttachmentResource.class), isNull(UserResource.class));
verifyNoMoreInteractions(attachmentPermissionsRules);
});
}
@Test
public void test_deleteAttachment() throws Exception {
setLoggedInUser(null);
when(attachmentLookupStrategy.findById(3L))
.thenReturn(new AttachmentResource(3L, "file", "application/pdf", 3456));
assertAccessDenied(() -> classUnderTest.delete(3L), () -> {
verify(attachmentPermissionsRules).onlyTheUploaderOfAnAttachmentCanDeleteItIfStillOrphan(isA(AttachmentResource.class), isNull(UserResource.class));
verifyNoMoreInteractions(attachmentPermissionsRules);
});
}
public static class TestProjectFinanceAttachmentService implements ProjectFinanceAttachmentService {
@Override
public ServiceResult<AttachmentResource> upload(String contentType, String contentLength, String originalFilename,
Long projectId, HttpServletRequest request) {
return ServiceResult.serviceSuccess(new AttachmentResource(33L, "name",
"application/pdf", 2345));
}
@Override
public ServiceResult<AttachmentResource> findOne(Long attachmentId) {
return ServiceResult.serviceSuccess(new AttachmentResource(33L, "name",
"application/pdf", 2345));
}
@Override
public ServiceResult<FileAndContents> attachmentFileAndContents(Long attachmentId) {
return null;
}
@Override
public ServiceResult<Void> delete(Long attachmentId) {
return ServiceResult.serviceSuccess();
}
}
}
|
package org.jmeterplugins.repository;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DependencyResolver {
private static final Logger log = LoggingManager.getLoggerForClass();
private static final Pattern libNameParser = Pattern.compile("([^=<>]+)([=<>]+[0-9.]+)?");
public static final String JAVA_CLASS_PATH = "java.class.path";
protected final Set<Plugin> deletions = new HashSet<>();
protected final Set<Plugin> additions = new HashSet<>();
protected final Map<String, String> libAdditions = new HashMap<>();
protected final Set<String> libDeletions = new HashSet<>();
protected final Map<Plugin, Boolean> allPlugins;
public DependencyResolver(Map<Plugin, Boolean> allPlugins) {
this.allPlugins = allPlugins;
resolveFlags();
resolveUpgrades();
resolveDeleteByDependency();
resolveInstallByDependency();
resolveDeleteLibs();
resolveInstallLibs();
}
// TODO: return iterators to make values read-only
public Set<Plugin> getDeletions() {
return deletions;
}
public Set<Plugin> getAdditions() {
return additions;
}
public Map<String, String> getLibAdditions() {
return libAdditions;
}
public Set<String> getLibDeletions() {
return libDeletions;
}
private Plugin getPluginByID(String id) {
for (Plugin plugin : allPlugins.keySet()) {
if (plugin.getID().equals(id)) {
return plugin;
}
}
throw new RuntimeException("Plugin not found by ID: " + id);
}
private Set<Plugin> getDependants(Plugin plugin) {
Set<Plugin> res = new HashSet<>();
for (Plugin pAll : allPlugins.keySet()) {
for (String depID : pAll.getDepends()) {
if (depID.equals(plugin.getID())) {
res.add(pAll);
}
}
}
return res;
}
private void resolveFlags() {
for (Map.Entry<Plugin, Boolean> entry : allPlugins.entrySet()) {
if (entry.getKey().isInstalled()) {
if (!entry.getValue()) {
deletions.add(entry.getKey());
}
} else if (entry.getValue()) {
additions.add(entry.getKey());
}
}
}
private void resolveUpgrades() {
// detect upgrades
for (Map.Entry<Plugin, Boolean> entry : allPlugins.entrySet()) {
Plugin plugin = entry.getKey();
if (entry.getValue() && plugin.isInstalled() && !plugin.getInstalledVersion().equals(plugin.getCandidateVersion())) {
log.debug("Upgrade: " + plugin);
deletions.add(plugin);
additions.add(plugin);
}
}
}
private void resolveDeleteByDependency() {
// delete by depend
boolean hasModifications = true;
while (hasModifications) {
log.debug("Check uninstall dependencies");
hasModifications = false;
for (Plugin plugin : deletions) {
if (!additions.contains(plugin)) {
for (Plugin dep : getDependants(plugin)) {
if (!deletions.contains(dep) && dep.isInstalled()) {
log.debug("Add to deletions: " + dep);
deletions.add(dep);
hasModifications = true;
}
if (additions.contains(dep)) {
log.debug("Remove from additions: " + dep);
additions.remove(dep);
hasModifications = true;
}
}
}
if (hasModifications) {
break; // prevent ConcurrentModificationException
}
}
}
}
private void resolveInstallByDependency() {
// resolve dependencies
boolean hasModifications = true;
while (hasModifications) {
log.debug("Check install dependencies: " + additions);
hasModifications = false;
for (Plugin plugin : additions) {
for (String pluginID : plugin.getDepends()) {
Plugin depend = getPluginByID(pluginID);
if (!depend.isInstalled() || deletions.contains(depend)) {
if (!additions.contains(depend)) {
log.debug("Add to install: " + depend);
additions.add(depend);
hasModifications = true;
}
}
}
if (hasModifications) {
break; // prevent ConcurrentModificationException
}
}
}
}
private void resolveInstallLibs() {
for (Plugin plugin : additions) {
Map<String, String> libs = plugin.getLibs(plugin.getCandidateVersion());
for (String lib : libs.keySet()) {
if (Plugin.getLibInstallPath(getLibName(lib)) == null) {
libAdditions.put(lib, libs.get(lib));
}
}
}
resolveLibsVersionsConflicts();
}
private void resolveDeleteLibs() {
for (Plugin plugin : deletions) {
if (additions.contains(plugin)) { // skip upgrades
continue;
}
Map<String, String> libs = plugin.getLibs(plugin.getInstalledVersion());
for (String lib : libs.keySet()) {
String name = getLibName(lib);
if (Plugin.getLibInstallPath(name) != null) {
libDeletions.add(name);
} else {
log.warn("Did not find library to uninstall it: " + lib);
}
}
}
for (Plugin plugin : allPlugins.keySet()) {
if (additions.contains(plugin) || (plugin.isInstalled() && !deletions.contains(plugin))) {
String ver = additions.contains(plugin) ? plugin.getCandidateVersion() : plugin.getInstalledVersion();
//log.debug("Affects " + plugin + " v" + ver);
Map<String, String> libs = plugin.getLibs(ver);
for (String lib : libs.keySet()) {
String name = getLibName(lib);
if (libDeletions.contains(name)) {
log.debug("Won't delete lib " + lib + " since it is used by " + plugin);
libDeletions.remove(name);
}
}
}
}
}
private String getLibName(String fullLibName) {
Matcher m = libNameParser.matcher(fullLibName);
if (!m.find()) {
throw new IllegalArgumentException("Cannot parse str: " + fullLibName);
}
return m.group(1);
}
private void resolveLibsVersionsConflicts() {
Map<String, List<Library>> libsToResolve = new HashMap<>();
for (String key : libAdditions.keySet()) {
Matcher m = libNameParser.matcher(key);
if (!m.find()) {
throw new IllegalArgumentException("Cannot parse str: " + key);
}
if (m.groupCount() == 2 && m.group(2) != null && !m.group(2).isEmpty()) {
String name = m.group(1);
String condition = m.group(2).substring(0, 2);
verifyConditionFormat(condition);
String version = m.group(2).substring(2);
if (libsToResolve.containsKey(name)) {
libsToResolve.get(name).add(new Library(name, condition, version, libAdditions.get(key)));
} else {
List<Library> libs = new ArrayList<>();
libs.add(new Library(name, condition, version, libAdditions.get(key)));
libsToResolve.put(name, libs);
}
}
}
for (String key : libsToResolve.keySet()) {
List<Library> libs = libsToResolve.get(key);
Collections.sort(libs, Library.versionComparator);
for (Library lib : libs) {
libAdditions.remove(lib.getFullName());
}
final Library libToInstall = libs.get(libs.size() - 1);
// override lib
libAdditions.put(libToInstall.getName(), libToInstall.getLink());
}
}
protected void verifyConditionFormat(String condition) {
if (!(condition.equals(">=") || condition.equals("=="))) {
throw new IllegalArgumentException("Expected conditions are ['>=', '=='], but was: " + condition);
}
}
}
|
package ca.ualberta.CMPUT301W15T06.test;
import ca.ualberta.CMPUT301W15T06.AppSingleton;
import ca.ualberta.CMPUT301W15T06.Claim;
import ca.ualberta.CMPUT301W15T06.ClaimantClaimListActivity;
import ca.ualberta.CMPUT301W15T06.ClaimantClaimListController;
import ca.ualberta.CMPUT301W15T06.ClaimantEditDestinationActivity;
import ca.ualberta.CMPUT301W15T06.ClaimantItemListActivity;
import ca.ualberta.CMPUT301W15T06.MainActivity;
import ca.ualberta.CMPUT301W15T06.R;
import ca.ualberta.CMPUT301W15T06.ShowLocationActivity;
import ca.ualberta.CMPUT301W15T06.User;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.app.Instrumentation.ActivityMonitor;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.test.ActivityInstrumentationTestCase2;
import android.test.ViewAsserts;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ListView;
@SuppressLint("CutPasteId")
public class US01_07_01_Test<Final> extends
ActivityInstrumentationTestCase2<MainActivity> {
Button ApproverButton;
Button ClaimantButton;
Button UserButton;
Instrumentation instrumentation;
MainActivity activity;
EditText textInput;
Intent intent;
TextView input_name;
TextView input_start;
TextView input_end;
ListView listView;
Menu menu;
View View1;
EditText claimant_name;
EditText claimant_starting_date;
EditText claimant_ending_date;
Button FinishButton;
ClaimantClaimListController cclc;
User u;
public US01_07_01_Test() {
super(MainActivity.class);
}
//set up
protected void setUp() throws Exception {
super.setUp();
instrumentation = getInstrumentation();
activity = getActivity();
setActivityInitialTouchMode(false);
ApproverButton = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.approverButton);
ClaimantButton = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimantButton);
UserButton = (Button) activity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.userButton);
intent = new Intent(getInstrumentation().getTargetContext(), MainActivity.class);
u = new User("t");
cclc = new ClaimantClaimListController(u);
}
public void testUS010701() {
//User click "Change User"
activity.runOnUiThread(new Runnable(){
@Override
public void run() {
/*
* Test for US 01.02.01 Basic Flow 2
*/
// click button to start another activity
assertTrue(UserButton.performClick());
/*
* Test for US 01.02.01 Basic Flow 3
*/
//test opening a dialog
// access the alert dialog using the getDialog() method created in the activity
AlertDialog d = (AlertDialog) activity.getDialog();
}
});
//click "Claimant" button and create next activity
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(ClaimantClaimListActivity.class.getName(), null, false);
//open current activity
MainActivity myActivity = getActivity();
final Button button = (Button) myActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimantButton);
myActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// click button and open next activity.
button.performClick();
}
});
ClaimantClaimListActivity nextActivity = (ClaimantClaimListActivity) getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 10000);
// next activity is opened and captured.
assertNotNull(nextActivity);
/*
* Test Case for US01.02.01 Basic Flow 7
*/
// view which is expected to be present on the screen
final View decorView1 = nextActivity.getWindow().getDecorView();
listView = (ListView) nextActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimListView);
// check if it is on screen
ViewAsserts.assertOnScreen(decorView1, listView);
// check whether the Button object's width and height attributes match the expected values
final ViewGroup.LayoutParams layoutParams11 = listView.getLayoutParams();
/*assertNotNull(layoutParams);*/
assertEquals(layoutParams11.width, WindowManager.LayoutParams.MATCH_PARENT);
assertEquals(layoutParams11.height, WindowManager.LayoutParams.WRAP_CONTENT);
final ListView claimList = (ListView) nextActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.claimListView);
//get next activity
nextActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// click the list open next activity.
ActivityMonitor am = getInstrumentation().addMonitor(ClaimantItemListActivity.class.getName(), null, false);
claimList.getChildAt(0).performClick();
ClaimantItemListActivity thirdActivity = (ClaimantItemListActivity) getInstrumentation().waitForMonitorWithTimeout(am, 10000);
assertNotNull(thirdActivity);
/*
* Test for US 01.07.01 Basic Flow 1
*/
ListView ilv = (ListView) thirdActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.itemListView);
// check if it is on screen
ViewAsserts.assertOnScreen(decorView1, ilv);
// Click the menu option;
getInstrumentation().invokeMenuActionSync(thirdActivity,ca.ualberta.CMPUT301W15T06.R.id.detail, 1);
//open the forth activity
Activity forthActivity = getInstrumentation().waitForMonitorWithTimeout(am, 10000);
assertNotNull(forthActivity);
/*
* Test for US 01.07.01 Basic Flow 2
*/
//test 'Add a Destination' button layout
Button addDestination = (Button) forthActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.addDestinationButton);
final View dv = forthActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(dv, addDestination);
final ViewGroup.LayoutParams lp =addDestination.getLayoutParams();
assertNotNull(lp);
assertEquals(lp.width, WindowManager.LayoutParams.WRAP_CONTENT);
assertEquals(lp.height, WindowManager.LayoutParams.WRAP_CONTENT);
assertEquals("Incorrect label of the button", "Add a destination", addDestination.getText());
Claim claim = new Claim();
int count1 = claim.getDestinationList().size();
//test click "Add a Destination" button
// open next activity.
final Button desButton = (Button) thirdActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.addDestinationButton);
forthActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
ActivityMonitor activityMonitor1 = getInstrumentation().addMonitor(ClaimantEditDestinationActivity.class.getName(), null, false);
// click button and open next activity.
desButton.performClick();
// next activity is opened and captured.
ClaimantEditDestinationActivity fifthActivity = (ClaimantEditDestinationActivity) getInstrumentation().waitForMonitorWithTimeout(activityMonitor1, 1000);
assertNotNull(fifthActivity);
/*
* Test for US 01.07.01 Basic Flow 3
*/
//test interface
EditText claimant_des = ((EditText) fifthActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.DestinationEditText));
EditText claimant_reason = ((EditText) fifthActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.ReasonEditText));
final View dv1 = fifthActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(dv1, claimant_des);
assertTrue(View.GONE == claimant_des.getVisibility());
ViewAsserts.assertOnScreen(dv1, claimant_reason);
assertTrue(View.GONE == claimant_reason.getVisibility());
/*
* Test for US 01.07.01 Basic Flow 4
*/
//fill blank
String claimantDes = "a";
String claimantReason = "b";
claimant_des.setText(claimantDes);
claimant_reason.setText(claimantReason);
//finish the activity and go back
fifthActivity.finish();
}
});
/*
* Test for US 01.07.01 Basic Flow 5
*/
int count2 = claim.getDestinationList().size();
assertEquals(count1,count2-1);
final ListView detailListView = (ListView) forthActivity.findViewById(ca.ualberta.CMPUT301W15T06.R.id.detailListView);
forthActivity.runOnUiThread(new Runnable() {
//test add button works
@Override
public void run() {
/*
* test US01.07.01 Basic Flow 6
*/
ListView geoArray = (ListView) detailListView.findViewById(ca.ualberta.CMPUT301W15T06.R.array.dest_dialog_array);
assertNotNull(geoArray);
geoArray.getChildAt(0).performClick();
/*
* test US01.07.01 Basic Flow 7
*/
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(ShowLocationActivity.class.getName(), null, false);
/*
* test US01.07.01 Basic Flow 8
*/
ShowLocationActivity aaa = (ShowLocationActivity) getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 10000);
assertNotNull(aaa);
/*
* test US01.07.01 Basic Flow 9
*/
ImageView image=(ImageView)aaa.findViewById(R.drawable.worldmap);
assertNotNull(image);
TextView tv=(TextView)aaa.findViewById(R.id.llTextView);
assertNotNull(tv);
/*
* test US01.07.01 Basic Flow 10
*/
boolean clickMap = image.performClick();
assertTrue(clickMap);
/*
* test US01.07.01 Basic Flow 11
*/
Location location=AppSingleton.getInstance().getLocation();
tv.setText("Lat: " + location.getLatitude()
+ "\nLong: " + location.getLongitude());
}
});
}
});
}
}
|
package org.mtransit.android.commons;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.mtransit.android.commons.data.Route;
import org.mtransit.android.commons.data.RouteTripStop;
import org.mtransit.android.commons.provider.AgencyProviderContract;
import org.mtransit.android.commons.task.MTAsyncTask;
import android.content.Context;
import android.database.Cursor;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.text.TextUtils;
public class LocationUtils implements MTLog.Loggable {
private static final String TAG = LocationUtils.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
public static final long UPDATE_INTERVAL_IN_MS = TimeUnit.SECONDS.toMillis(5);
public static final long FASTEST_INTERVAL_IN_MS = TimeUnit.SECONDS.toMillis(1);
public static final long PREFER_ACCURACY_OVER_TIME_IN_MS = TimeUnit.SECONDS.toMillis(30);
public static final int SIGNIFICANT_ACCURACY_IN_METERS = 200; // 200 meters
public static final int SIGNIFICANT_DISTANCE_MOVED_IN_METERS = 5; // 5 meters
public static final int LOCATION_CHANGED_ALLOW_REFRESH_IN_METERS = 10;
public static final int LOCATION_CHANGED_NOTIFY_USER_IN_METERS = 100;
public static final double MIN_AROUND_DIFF = 0.01;
public static final double INC_AROUND_DIFF = 0.01;
public static final float FEET_PER_M = 3.2808399f;
public static final float FEET_PER_MILE = 5280;
public static final float METER_PER_KM = 1000f;
public static final int MIN_NEARBY_LIST = 10;
public static final int MAX_NEARBY_LIST = 20;
public static final int MAX_POI_NEARBY_POIS_LIST = 10;
public static final int MIN_NEARBY_LIST_COVERAGE_IN_METERS = 100;
public static final int MIN_POI_NEARBY_POIS_LIST_COVERAGE_IN_METERS = 100;
public static AroundDiff getNewDefaultAroundDiff() {
return new AroundDiff(LocationUtils.MIN_AROUND_DIFF, LocationUtils.INC_AROUND_DIFF);
}
private LocationUtils() {
}
public static String locationToString(Location location) {
if (location == null) {
return null;
}
return String.format("%s > %s,%s (%s) %s seconds ago", location.getProvider(), location.getLatitude(), location.getLongitude(), location.getAccuracy(),
TimeUtils.millisToSec(TimeUtils.currentTimeMillis() - location.getTime()));
}
public static Location getNewLocation(double lat, double lng) {
return getNewLocation(lat, lng, null);
}
public static Location getNewLocation(double lat, double lng, Float optAccuracy) {
Location newLocation = new Location("MT");
newLocation.setLatitude(lat);
newLocation.setLongitude(lng);
if (optAccuracy != null) {
newLocation.setAccuracy(optAccuracy);
}
return newLocation;
}
public static float bearTo(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
float[] results = new float[2];
Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
return results[1];
}
public static float distanceToInMeters(Location start, Location end) {
if (start == null || end == null) {
return -1f;
}
return distanceToInMeters(start.getLatitude(), start.getLongitude(), end.getLatitude(), end.getLongitude());
}
public static float distanceToInMeters(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
float[] results = new float[2];
Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
return results[0];
}
public static boolean isMoreRelevant(String tag, Location currentLocation, Location newLocation) {
return isMoreRelevant(tag, currentLocation, newLocation, SIGNIFICANT_ACCURACY_IN_METERS, SIGNIFICANT_DISTANCE_MOVED_IN_METERS,
PREFER_ACCURACY_OVER_TIME_IN_MS);
}
public static boolean isMoreRelevant(String tag, Location currentLocation, Location newLocation, int significantAccuracyInMeters,
int significantDistanceMovedInMeters, long preferAccuracyOverTimeInMS) {
if (newLocation == null) {
return false;
}
if (currentLocation == null) {
return true;
}
if (areTheSame(currentLocation, newLocation)) {
return false;
}
long timeDelta = newLocation.getTime() - currentLocation.getTime();
boolean isSignificantlyNewer = timeDelta > preferAccuracyOverTimeInMS;
boolean isSignificantlyOlder = timeDelta < -preferAccuracyOverTimeInMS;
boolean isNewer = timeDelta > 0;
if (isSignificantlyNewer) {
return true;
} else if (isSignificantlyOlder) {
return false;
}
int accuracyDelta = (int) (newLocation.getAccuracy() - currentLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > significantAccuracyInMeters;
boolean isSignificantlyMoreAccurate = isMoreAccurate && accuracyDelta < -significantAccuracyInMeters;
if (isSignificantlyMoreAccurate) {
return true;
}
int distanceTo = (int) distanceToInMeters(currentLocation, newLocation);
if (distanceTo < significantDistanceMovedInMeters) {
return false;
}
boolean isFromSameProvider = isSameProvider(newLocation, currentLocation);
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
private static boolean isSameProvider(Location loc1, Location loc2) {
if (loc1.getProvider() == null) {
return loc2.getProvider() == null;
}
return loc1.getProvider().equals(loc2.getProvider());
}
public static Address getLocationAddress(Context context, Location location) {
try {
if (Geocoder.isPresent()) {
Geocoder geocoder = new Geocoder(context);
int maxResults = 1;
java.util.List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), maxResults);
if (addresses == null || addresses.size() == 0) {
return null; // no address found
}
return addresses.get(0);
}
} catch (IOException ioe) {
if (MTLog.isLoggable(android.util.Log.DEBUG)) {
MTLog.w(TAG, ioe, "getLocationAddress() > Can't find the address of the current location!");
} else {
MTLog.w(TAG, "getLocationAddress() > Can't find the address of the current location!");
}
}
return null;
}
public static String getLocationString(Context context, String initialString, Address locationAddress, Float accuracy) {
StringBuilder sb = new StringBuilder();
if (context == null) {
return sb.toString();
}
boolean hasInitialString = !TextUtils.isEmpty(initialString);
if (hasInitialString) {
sb.append(initialString);
}
if (hasInitialString) {
sb.append(" (");
}
if (locationAddress != null) {
if (locationAddress.getMaxAddressLineIndex() > 0) {
sb.append(locationAddress.getAddressLine(0));
} else if (locationAddress.getThoroughfare() != null) {
sb.append(locationAddress.getThoroughfare());
} else if (locationAddress.getLocality() != null) {
sb.append(locationAddress.getLocality());
} else {
sb.append(context.getString(R.string.unknown_address));
}
} else {
sb.append(context.getString(R.string.unknown_address));
}
if (accuracy != null && accuracy > 0.0f) {
sb.append(" ± ").append(getDistanceStringUsingPref(context, accuracy, accuracy));
}
if (hasInitialString) {
sb.append(")");
}
return sb.toString();
}
public static double truncAround(String loc) {
return Double.parseDouble(truncAround(Double.parseDouble(loc)));
}
private static final String AROUND_TRUNC = "%.4g";
public static String truncAround(double loc) {
return String.format(Locale.US, AROUND_TRUNC, loc);
}
public static String getDistanceStringUsingPref(Context context, float distanceInMeters, float accuracyInMeters) {
String distanceUnit = PreferenceUtils.getPrefDefault(context, PreferenceUtils.PREFS_UNITS, PreferenceUtils.PREFS_UNITS_DEFAULT);
return getDistanceString(distanceInMeters, accuracyInMeters, distanceUnit);
}
private static String getDistanceString(float distanceInMeters, float accuracyInMeters, String distanceUnit) {
if (distanceUnit.equals(PreferenceUtils.PREFS_UNITS_IMPERIAL)) {
float distanceInSmall = distanceInMeters * FEET_PER_M;
float accuracyInSmall = accuracyInMeters * FEET_PER_M;
return getDistance(distanceInSmall, accuracyInSmall, FEET_PER_MILE, 10, "ft", "mi");
} else { // use Metric (default)
return getDistance(distanceInMeters, accuracyInMeters, METER_PER_KM, 1, "m", "km");
}
}
private static String getDistance(float distance, float accuracy, float smallPerBig, int threshold, String smallUnit, String bigUnit) {
StringBuilder sb = new StringBuilder();
if (accuracy > distance) {
if (accuracy > (smallPerBig / threshold)) {
float accuracyInBigUnit = accuracy / smallPerBig;
float niceAccuracyInBigUnit = Integer.valueOf(Math.round(accuracyInBigUnit * 10)).floatValue() / 10;
sb.append("< ").append(niceAccuracyInBigUnit).append(" ").append(bigUnit);
} else {
int niceAccuracyInSmallUnit = Math.round(accuracy);
sb.append("< ").append(getSimplerDistance(niceAccuracyInSmallUnit, accuracy)).append(" ").append(smallUnit);
}
} else {
if (distance > (smallPerBig / threshold)) {
float distanceInBigUnit = distance / smallPerBig;
float niceDistanceInBigUnit = Integer.valueOf(Math.round(distanceInBigUnit * 10)).floatValue() / 10;
sb.append(niceDistanceInBigUnit).append(" ").append(bigUnit);
} else {
int niceDistanceInSmallUnit = Math.round(distance);
sb.append(getSimplerDistance(niceDistanceInSmallUnit, accuracy)).append(" ").append(smallUnit);
}
}
return sb.toString();
}
public static int getSimplerDistance(int distance, float accuracyF) {
int accuracy = Math.round(accuracyF);
int simplerDistance = Math.round(distance / 10f) * 10;
if (Math.abs(simplerDistance - distance) < accuracy) {
return simplerDistance;
} else {
return distance; // accuracy too good, have to keep real data
}
}
private static final float MAX_DISTANCE_ON_EARTH_IN_METERS = 40075017f / 2f;
public static float getAroundCoveredDistanceInMeters(double lat, double lng, double aroundDiff) {
Area area = getArea(lat, lng, aroundDiff);
float distanceToSouth = area.minLat > MIN_LAT ? distanceToInMeters(lat, lng, area.minLat, lng) : MAX_DISTANCE_ON_EARTH_IN_METERS;
float distanceToNorth = area.maxLat < MAX_LAT ? distanceToInMeters(lat, lng, area.maxLat, lng) : MAX_DISTANCE_ON_EARTH_IN_METERS;
float distanceToWest = area.minLng > MIN_LNG ? distanceToInMeters(lat, lng, lat, area.minLng) : MAX_DISTANCE_ON_EARTH_IN_METERS;
float distanceToEast = area.maxLng < MAX_LNG ? distanceToInMeters(lat, lng, lat, area.maxLng) : MAX_DISTANCE_ON_EARTH_IN_METERS;
float[] distances = new float[] { distanceToNorth, distanceToSouth, distanceToWest, distanceToEast };
Arrays.sort(distances);
return distances[0]; // return the closest
}
public static Area getArea(double lat, double lng, double aroundDiff) {
// latitude
double latTrunc = Math.abs(lat);
double latBefore = Math.signum(lat) * Double.parseDouble(truncAround(latTrunc - aroundDiff));
double latAfter = Math.signum(lat) * Double.parseDouble(truncAround(latTrunc + aroundDiff));
// longitude
double lngTrunc = Math.abs(lng);
double lngBefore = Math.signum(lng) * Double.parseDouble(truncAround(lngTrunc - aroundDiff));
double lngAfter = Math.signum(lng) * Double.parseDouble(truncAround(lngTrunc + aroundDiff));
double minLat = Math.min(latBefore, latAfter);
if (minLat < MIN_LAT) {
minLat = MIN_LAT;
}
double maxLat = Math.max(latBefore, latAfter);
if (maxLat > MAX_LAT) {
maxLat = MAX_LAT;
}
double minLng = Math.min(lngBefore, lngAfter);
if (minLng < MIN_LNG) {
minLng = MIN_LNG;
}
double maxLng = Math.max(lngBefore, lngAfter);
if (maxLng > MAX_LNG) {
maxLng = MAX_LNG;
}
return new Area(minLat, maxLat, minLng, maxLng);
}
public static final double MAX_LAT = 90.0f;
public static final double MIN_LAT = -90.0f;
public static final double MAX_LNG = 180.0f;
public static final double MIN_LNG = -180.0f;
public static final Area THE_WORLD = new Area(MIN_LAT, MAX_LAT, MIN_LNG, MAX_LNG);
public static String genAroundWhere(String lat, String lng, String latTableColumn, String lngTableColumn, double aroundDiff) {
StringBuilder qb = new StringBuilder();
Area area = getArea(truncAround(lat), truncAround(lng), aroundDiff);
qb.append(SqlUtils.getBetween(latTableColumn, area.minLat, area.maxLat));
qb.append(SqlUtils.AND);
qb.append(SqlUtils.getBetween(lngTableColumn, area.minLng, area.maxLng));
return qb.toString();
}
public static String genAroundWhere(double lat, double lng, String latTableColumn, String lngTableColumn, double aroundDiff) {
return genAroundWhere(String.valueOf(lat), String.valueOf(lng), latTableColumn, lngTableColumn, aroundDiff);
}
public static String genAroundWhere(Location location, String latTableColumn, String lngTableColumn, double aroundDiff) {
return genAroundWhere(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), latTableColumn, lngTableColumn, aroundDiff);
}
public static void updateDistance(HashMap<?, ? extends LocationPOI> pois, Location location) {
if (location == null) {
return;
}
updateDistance(pois, location.getLatitude(), location.getLongitude());
}
public static void updateDistance(HashMap<?, ? extends LocationPOI> pois, double lat, double lng) {
if (pois == null) {
return;
}
for (LocationPOI poi : pois.values()) {
if (!poi.hasLocation()) {
continue;
}
poi.setDistance(distanceToInMeters(lat, lng, poi.getLat(), poi.getLng()));
}
}
public static void updateDistanceWithString(Context context, Collection<? extends LocationPOI> pois, Location currentLocation, MTAsyncTask<?, ?, ?> task) {
if (pois == null || currentLocation == null) {
return;
}
String distanceUnit = PreferenceUtils.getPrefDefault(context, PreferenceUtils.PREFS_UNITS, PreferenceUtils.PREFS_UNITS_DEFAULT);
float accuracyInMeters = currentLocation.getAccuracy();
for (LocationPOI poi : pois) {
if (!poi.hasLocation()) {
continue;
}
float newDistance = distanceToInMeters(currentLocation.getLatitude(), currentLocation.getLongitude(), poi.getLat(), poi.getLng());
if (poi.getDistance() > 1 && newDistance == poi.getDistance() && poi.getDistanceString() != null) {
continue;
}
poi.setDistance(newDistance);
poi.setDistanceString(getDistanceString(poi.getDistance(), accuracyInMeters, distanceUnit));
if (task != null && task.isCancelled()) {
break;
}
}
}
public static void updateDistance(ArrayList<? extends LocationPOI> pois, Location location) {
if (location == null) {
return;
}
updateDistance(pois, location.getLatitude(), location.getLongitude());
}
public static void updateDistance(ArrayList<? extends LocationPOI> pois, double lat, double lng) {
if (pois == null) {
return;
}
for (LocationPOI poi : pois) {
if (!poi.hasLocation()) {
continue;
}
poi.setDistance(distanceToInMeters(lat, lng, poi.getLat(), poi.getLng()));
}
}
public static void updateDistanceWithString(Context context, LocationPOI poi, Location currentLocation) {
if (poi == null || currentLocation == null) {
return;
}
String distanceUnit = PreferenceUtils.getPrefDefault(context, PreferenceUtils.PREFS_UNITS, PreferenceUtils.PREFS_UNITS_DEFAULT);
float accuracyInMeters = currentLocation.getAccuracy();
if (!poi.hasLocation()) {
return;
}
float newDistance = distanceToInMeters(currentLocation.getLatitude(), currentLocation.getLongitude(), poi.getLat(), poi.getLng());
if (poi.getDistance() > 1 && newDistance == poi.getDistance() && poi.getDistanceString() != null) {
return;
}
poi.setDistance(newDistance);
poi.setDistanceString(getDistanceString(poi.getDistance(), accuracyInMeters, distanceUnit));
}
public static boolean areAlmostTheSame(Location loc1, Location loc2, int distanceInMeters) {
if (loc1 == null || loc2 == null) {
return false;
}
return distanceToInMeters(loc1, loc2) < distanceInMeters;
}
public static boolean areTheSame(Location loc1, Location loc2) {
if (loc1 == null) {
return loc2 == null;
}
if (loc2 == null) {
return false;
}
return areTheSame(loc1.getLatitude(), loc1.getLongitude(), loc2.getLatitude(), loc2.getLongitude());
}
public static boolean areTheSame(Location loc1, double lat2, double lng2) {
if (loc1 == null) {
return false;
}
return areTheSame(loc1.getLatitude(), loc1.getLongitude(), lat2, lng2);
}
public static boolean areTheSame(double lat1, double lng1, double lat2, double lng2) {
return lat1 == lat2 && lng1 == lng2;
}
public static void removeTooFar(ArrayList<? extends LocationPOI> pois, float maxDistanceInMeters) {
if (pois != null) {
ListIterator<? extends LocationPOI> it = pois.listIterator();
while (it.hasNext()) {
LocationPOI poi = it.next();
if (poi.getDistance() > maxDistanceInMeters) {
it.remove();
}
}
}
}
public static void removeTooMuchWhenNotInCoverage(ArrayList<? extends LocationPOI> pois, float minCoverageInMeters, int maxSize) {
if (pois != null) {
CollectionUtils.sort(pois, POI_DISTANCE_COMPARATOR); // sort required
int nbKeptInList = 0;
ListIterator<? extends LocationPOI> it = pois.listIterator();
while (it.hasNext()) {
LocationPOI poi = it.next();
if (poi.getDistance() > minCoverageInMeters && nbKeptInList >= maxSize) {
it.remove();
} else {
nbKeptInList++;
}
}
}
}
public static boolean searchComplete(double lat, double lng, double aroundDiff) {
Area area = getArea(lat, lng, aroundDiff);
return searchComplete(area);
}
public static boolean searchComplete(Area area) {
if (area.minLat > MIN_LAT) {
return false; // more places to explore in the south
}
if (area.maxLat < MAX_LAT) {
return false; // more places to explore in the north
}
if (area.minLng > MIN_LNG) {
return false; // more places to explore to the west
}
if (area.maxLng < MAX_LNG) {
return false; // more places to explore to the east
}
return true; // planet search completed!
}
public static void incAroundDiff(AroundDiff ad) {
ad.aroundDiff += ad.incAroundDiff;
ad.incAroundDiff *= 2; // warning, might return huge chunk of data if far away (all POIs or none)
}
public static boolean isInside(double lat, double lng, Area area) {
if (area == null) {
return false;
}
return isInside(lat, lng, area.minLat, area.maxLat, area.minLng, area.maxLng);
}
public static boolean isInside(double lat, double lng, double minLat, double maxLat, double minLng, double maxLng) {
return lat >= minLat && lat <= maxLat && lng >= minLng && lng <= maxLng;
}
private static boolean areCompletelyOverlapping(Area area1, Area area2) {
// MTLog.v(TAG, "areCompletelyOverlapping(%s,%s)", area1, area2);
if (area1.minLat >= area2.minLat && area1.maxLat <= area2.maxLat) {
if (area2.minLng >= area1.minLng && area2.maxLng <= area1.maxLng) {
return true; // area 1 wider than area 2 but area 2 higher than area 1
}
}
if (area2.minLat >= area1.minLat && area2.maxLat <= area1.maxLat) {
if (area1.minLng >= area2.minLng && area1.maxLng <= area2.maxLng) {
return true; // area 2 wider than area 1 but area 1 higher than area 2
}
}
return false;
}
public static class AroundDiff {
public double aroundDiff = LocationUtils.MIN_AROUND_DIFF;
public double incAroundDiff = LocationUtils.INC_AROUND_DIFF;
public AroundDiff() {
}
public AroundDiff(double aroundDiff, double incAroundDiff) {
this.aroundDiff = aroundDiff;
this.incAroundDiff = incAroundDiff;
}
@Override
public String toString() {
return new StringBuilder(AroundDiff.class.getSimpleName()).append('[')
.append(this.aroundDiff)
.append(',')
.append(this.incAroundDiff)
.append(']').toString();
}
}
public static class Area {
public double minLat;
public double maxLat;
public double minLng;
public double maxLng;
public Area(double minLat, double maxLat, double minLng, double maxLng) {
this.minLat = minLat;
this.maxLat = maxLat;
this.minLng = minLng;
this.maxLng = maxLng;
}
@Override
public String toString() {
return new StringBuilder(Area.class.getSimpleName()).append('[')
.append(this.minLat)
.append(',')
.append(this.maxLat)
.append(',')
.append(this.minLng)
.append(',')
.append(this.maxLng)
.append(']').toString();
}
public boolean isEntirelyInside(Area otherArea) {
if (otherArea == null) {
return false;
}
if (!isInside(this.minLat, this.minLng, otherArea)) {
return false; // min lat, min lng
}
if (!isInside(this.minLat, this.maxLng, otherArea)) {
return false; // min lat, max lng
}
if (!isInside(this.maxLat, this.minLng, otherArea)) {
return false; // max lat, min lng
}
if (!isInside(this.maxLat, this.maxLng, otherArea)) {
return false; // max lat, max lng
}
return true;
}
public static boolean areOverlapping(Area area1, Area area2) {
if (area1 == null || area2 == null) {
return false; // no data to compare
}
// AREA1 (at least partially) INSIDE AREA2
if (isInside(area1.minLat, area1.minLng, area2)) {
return true; // min lat, min lng
}
if (isInside(area1.minLat, area1.maxLng, area2)) {
return true; // min lat, max lng
}
if (isInside(area1.maxLat, area1.minLng, area2)) {
return true; // max lat, min lng
}
if (isInside(area1.maxLat, area1.maxLng, area2)) {
return true; // max lat, max lng
}
// AREA2 (at least partially) INSIDE AREA1
if (isInside(area2.minLat, area2.minLng, area1)) {
return true; // min lat, min lng
}
if (isInside(area2.minLat, area2.maxLng, area1)) {
return true; // min lat, max lng
}
if (isInside(area2.maxLat, area2.minLng, area1)) {
return true; // max lat, min lng
}
if (isInside(area2.maxLat, area2.maxLng, area1)) {
return true; // max lat, max lng
}
// OVERLAPPING
return areCompletelyOverlapping(area1, area2);
}
public static Area fromCursor(Cursor cursor) {
if (cursor == null) {
return null;
}
try {
double minLat = cursor.getDouble(cursor.getColumnIndexOrThrow(AgencyProviderContract.AREA_MIN_LAT));
double maxLat = cursor.getDouble(cursor.getColumnIndexOrThrow(AgencyProviderContract.AREA_MAX_LAT));
double minLng = cursor.getDouble(cursor.getColumnIndexOrThrow(AgencyProviderContract.AREA_MIN_LNG));
double maxLng = cursor.getDouble(cursor.getColumnIndexOrThrow(AgencyProviderContract.AREA_MAX_LNG));
return new Area(minLat, maxLat, minLng, maxLng);
} catch (Exception e) {
MTLog.w(TAG, e, "Error while reading cursor!");
return null;
}
}
}
public static final POIDistanceComparator POI_DISTANCE_COMPARATOR = new POIDistanceComparator();
public static class POIDistanceComparator implements Comparator<LocationPOI> {
@Override
public int compare(LocationPOI lhs, LocationPOI rhs) {
if (lhs instanceof RouteTripStop && rhs instanceof RouteTripStop) {
RouteTripStop alhs = (RouteTripStop) lhs;
RouteTripStop arhs = (RouteTripStop) rhs;
if (alhs.getStop().getId() == arhs.getStop().getId()) {
String lShortName = alhs.getRoute().getShortName();
String rShortName = arhs.getRoute().getShortName();
if (!TextUtils.isEmpty(lShortName) || !TextUtils.isEmpty(rShortName)) {
return Route.SHORT_NAME_COMPATOR.compare(alhs.getRoute(), arhs.getRoute());
}
}
}
float d1 = lhs.getDistance();
float d2 = rhs.getDistance();
if (d1 > d2) {
return ComparatorUtils.AFTER;
} else if (d1 < d2) {
return ComparatorUtils.BEFORE;
} else {
return ComparatorUtils.SAME;
}
}
}
public static interface LocationPOI {
public Double getLat();
public Double getLng();
public boolean hasLocation();
public void setDistanceString(CharSequence distanceString);
public CharSequence getDistanceString();
public void setDistance(float distance);
public float getDistance();
}
}
|
package org.innovateuk.ifs.dashboard.populator;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.service.ApplicationRestService;
import org.innovateuk.ifs.application.service.CompetitionService;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionStatus;
import org.innovateuk.ifs.dashboard.viewmodel.ApplicantDashboardViewModel;
import org.innovateuk.ifs.project.ProjectService;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.user.resource.ProcessRoleResource;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.innovateuk.ifs.user.service.ProcessRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleToMap;
/**
* Populator for the applicant dashboard, it populates an {@link org.innovateuk.ifs.dashboard.viewmodel.ApplicantDashboardViewModel}
*/
@Service
public class ApplicantDashboardPopulator {
private EnumSet<ApplicationState> inProgress = EnumSet.of(ApplicationState.CREATED, ApplicationState.OPEN);
private EnumSet<ApplicationState> submitted = EnumSet.of(ApplicationState.SUBMITTED, ApplicationState.INELIGIBLE);
private EnumSet<ApplicationState> finished = EnumSet.of(ApplicationState.APPROVED, ApplicationState.REJECTED, ApplicationState.INELIGIBLE_INFORMED);
private EnumSet<CompetitionStatus> fundingNotYetCompete = EnumSet.of(CompetitionStatus.OPEN, CompetitionStatus.IN_ASSESSMENT, CompetitionStatus.FUNDERS_PANEL);
private EnumSet<CompetitionStatus> fundingComplete = EnumSet.of(CompetitionStatus.ASSESSOR_FEEDBACK, CompetitionStatus.PROJECT_SETUP);
private EnumSet<CompetitionStatus> open = EnumSet.of(CompetitionStatus.OPEN);
@Autowired
private ApplicationRestService applicationRestService;
@Autowired
private ProcessRoleService processRoleService;
@Autowired
private ProjectService projectService;
@Autowired
private CompetitionService competitionService;
public ApplicantDashboardViewModel populate(UserResource user) {
List<ApplicationResource> allApplications = applicationRestService
.getApplicationsByUserId(user.getId())
.getSuccessObjectOrThrowException();
Map<Long, CompetitionResource> competitionApplicationMap = createCompetitionApplicationMap(allApplications);
Map<Long, ApplicationState> applicationStatusMap = createApplicationStateMap(allApplications);
List<ApplicationResource> inProgress = simpleFilter(allApplications, this::applicationInProgress);
Map<Long, Integer> applicationProgress =
simpleToMap(inProgress, ApplicationResource::getId, a -> a.getCompletion().intValue());
List<ApplicationResource> finished = simpleFilter(allApplications, this::applicationFinished);
List<ProjectResource> projectsInSetup = projectService.findByUser(user.getId()).getSuccessObjectOrThrowException();
List<Long> applicationsAssigned = getAssignedApplications(inProgress, user);
return new ApplicantDashboardViewModel(applicationProgress, inProgress,
applicationsAssigned, finished,
projectsInSetup, competitionApplicationMap, applicationStatusMap);
}
private List<Long> getAssignedApplications(List<ApplicationResource> inProgress, UserResource user) {
return inProgress.stream().filter(applicationResource -> {
ProcessRoleResource role = processRoleService.findProcessRole(user.getId(), applicationResource.getId());
if (!UserRoleType.LEADAPPLICANT.getName().equals(role.getRoleName())) {
int count = applicationRestService
.getAssignedQuestionsCount(applicationResource.getId(), role.getId())
.getSuccessObjectOrThrowException();
return count != 0;
} else {
return false;
}
}
).mapToLong(ApplicationResource::getId).boxed().collect(toList());
}
private Map<Long, ApplicationState> createApplicationStateMap(List<ApplicationResource> resources) {
return simpleToMap(resources, ApplicationResource::getId, ApplicationResource::getApplicationState);
}
private Map<Long, CompetitionResource> createCompetitionApplicationMap(List<ApplicationResource> resources) {
Map<Long, CompetitionResource> competitions = getCompetitions(resources);
return resources.stream()
.collect(toMap(
ApplicationResource::getId,
application -> competitions.get(application.getCompetition()), (p1, p2) -> p1)
);
}
private Map<Long, CompetitionResource> getCompetitions(List<ApplicationResource> resources) {
return resources.stream()
.map(ApplicationResource::getCompetition)
.distinct()
.map(compId -> competitionService.getById(compId))
.collect(toMap(
CompetitionResource::getId,
identity()
));
}
private boolean applicationInProgress(ApplicationResource a) {
return (applicationStateInProgress(a) && competitionOpen(a))
|| (applicationStateSubmitted(a) && competitionFundingNotYetComplete(a));
}
private boolean applicationFinished(ApplicationResource a) {
return (applicationStateFinished(a))
|| (applicationStateInProgress(a) && competitionClosed(a))
|| (applicationStateSubmitted(a) && competitionFundingComplete(a));
}
private boolean applicationStateInProgress(ApplicationResource a) {
return inProgress.contains(a.getApplicationState());
}
private boolean competitionOpen(ApplicationResource a) {
return open.contains(a.getCompetitionStatus());
}
private boolean competitionClosed(ApplicationResource a) {
return !competitionOpen(a);
}
private boolean applicationStateSubmitted(ApplicationResource a) {
return submitted.contains(a.getApplicationState());
}
private boolean applicationStateFinished(ApplicationResource a) {
return finished.contains(a.getApplicationState());
}
private boolean competitionFundingNotYetComplete(ApplicationResource a) {
return fundingNotYetCompete.contains(a.getCompetitionStatus());
}
private boolean competitionFundingComplete(ApplicationResource a) {
return fundingComplete.contains(a.getCompetitionStatus());
}
}
|
package org.bouncycastle.asn1;
import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
class DefiniteLengthInputStream
extends LimitedInputStream
{
private int _length;
DefiniteLengthInputStream(
InputStream in,
int length)
{
super(in);
if (length < 0)
{
throw new IllegalArgumentException("negative lengths not allowed");
}
this._length = length;
}
public int read()
throws IOException
{
if (_length > 0)
{
int b = _in.read();
if (b < 0)
{
throw new EOFException();
}
--_length;
return b;
}
setParentEofDetect(true);
return -1;
}
public int read(byte[] buf, int off, int len)
throws IOException
{
if (_length > 0)
{
int toRead = Math.min(len, _length);
int numRead = _in.read(buf, off, toRead);
if (numRead < 0)
throw new EOFException();
_length -= numRead;
return numRead;
}
setParentEofDetect(true);
return -1;
}
byte[] toByteArray()
throws IOException
{
byte[] bytes = new byte[_length];
if (_length > 0)
{
int pos = 0;
do
{
int read = _in.read(bytes, pos, _length - pos);
if (read < 0)
{
throw new EOFException();
}
pos += read;
}
while (pos < _length);
_length = 0;
}
setParentEofDetect(true);
return bytes;
}
}
|
package org.junit.experimental.interceptor;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
public class TestWatchman implements StatementInterceptor {
public Statement intercept(final Statement base,
final FrameworkMethod method) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
starting(method);
try {
base.evaluate();
succeeded(method);
} catch (Throwable t) {
failed(t, method);
throw t;
} finally {
finished(method);
}
}
};
}
public void succeeded(FrameworkMethod method) {
}
// TODO (Apr 28, 2009 10:50:47 PM): is this right? Is
// FrameworkMethod too powerful?
public void failed(Throwable e, FrameworkMethod method) {
}
public void starting(FrameworkMethod method) throws Exception {
}
public void finished(FrameworkMethod method) {
}
}
|
package org.inheritsource.service.common.domain;
import java.util.Date;
import java.util.Set;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("ActivityInstancePendingItem")
public class ActivityInstancePendingItem extends ActivityInstanceItem {
private static final long serialVersionUID = 6551923994738613262L;
Set<UserInfo> candidates;
UserInfo assignedUser;
public ActivityInstancePendingItem() {
}
public Set<UserInfo> getCandidates() {
return candidates;
}
public void setCandidates(Set<UserInfo> candidates) {
this.candidates = candidates;
}
public UserInfo getAssignedUser() {
return assignedUser;
}
public void setAssignedUser(UserInfo assignedUser) {
this.assignedUser = assignedUser;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((assignedUser == null) ? 0 : assignedUser.hashCode());
result = prime * result
+ ((candidates == null) ? 0 : candidates.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ActivityInstancePendingItem other = (ActivityInstancePendingItem) obj;
if (assignedUser == null) {
if (other.assignedUser != null)
return false;
} else if (!assignedUser.equals(other.assignedUser))
return false;
if (candidates == null) {
if (other.candidates != null)
return false;
} else if (!candidates.equals(other.candidates))
return false;
return true;
}
@Override
public String toString() {
return "ActivityInstancePendingItem [candidates=" + candidates
+ ", assignedUser=" + assignedUser
+ " " + super.toString() + "]";
}
}
|
package org.minimalj.frontend.impl.json;
import java.util.ArrayList;
import java.util.Arrays;
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 java.util.UUID;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.minimalj.application.Application;
import org.minimalj.application.Application.AuthenticatonMode;
import org.minimalj.backend.Backend;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.Frontend.IContent;
import org.minimalj.frontend.action.Action;
import org.minimalj.frontend.action.ActionGroup;
import org.minimalj.frontend.impl.json.JsonComponent.JsonPropertyListener;
import org.minimalj.frontend.impl.util.PageAccess;
import org.minimalj.frontend.impl.util.PageList;
import org.minimalj.frontend.impl.util.PageStore;
import org.minimalj.frontend.page.ExpiredPage;
import org.minimalj.frontend.page.IDialog;
import org.minimalj.frontend.page.Page;
import org.minimalj.frontend.page.PageManager;
import org.minimalj.frontend.page.Routing;
import org.minimalj.security.Authentication;
import org.minimalj.security.Authorization;
import org.minimalj.security.RememberMeAuthentication;
import org.minimalj.security.Subject;
import org.minimalj.util.StringUtils;
import org.minimalj.util.resources.Resources;
public class JsonPageManager implements PageManager {
private static final Logger logger = Logger.getLogger(JsonPageManager.class.getName());
private final String sessionId;
private final Authentication authentication;
private long lastUsed = System.currentTimeMillis();
private Subject subject;
private Runnable onLogin;
private boolean initializing;
private final Map<String, JsonComponent> componentById = new HashMap<>(100);
private List<Object> navigation;
private final PageList visiblePageAndDetailsList = new PageList();
private final Set<String> horizontalPageIds = new HashSet<>();
// this makes this class not thread safe. Caller of handle have to synchronize.
private JsonOutput output;
private final JsonPropertyListener propertyListener = new JsonSessionPropertyChangeListener();
private final PageStore pageStore = new PageStore();
private final JsonPush push;
public JsonPageManager() {
this(null);
}
public JsonPageManager(JsonPush push) {
sessionId = UUID.randomUUID().toString();
authentication = Backend.getInstance().getAuthentication();
this.push = push;
}
public String getSessionId() {
return sessionId;
}
public long getLastUsed() {
return lastUsed;
}
private void updateNavigation() {
componentById.clear();
navigation = createNavigation();
output.add("navigation", navigation);
output.add("hasSearchPages", Application.getInstance().hasSearch());
}
public String handle(String inputString) {
JsonInput input = new JsonInput(inputString);
JsonOutput output = handle(input);
return output.toString();
}
private Thread thread;
public JsonOutput handle(JsonInput input) {
lastUsed = System.currentTimeMillis();
Long retry = (Long) input.getObject("retry");
if (retry == null || thread == null) {
retry = 0L;
thread = new Thread(new Runnable() {
public void run() {
try {
JsonFrontend.setSession(JsonPageManager.this);
Subject.setCurrent(subject);
handle_(input);
} catch (ComponentUnknowException x) {
logger.log(Level.WARNING, x.getMessage(), x);
output = new JsonOutput();
show(visiblePageAndDetailsList.getPageIds(), true);
} catch (Exception x) {
output.add("error", x.getClass().getSimpleName() + ":\n" + x.getMessage());
logger.log(Level.SEVERE, x.getMessage(), x);
} finally {
subject = Subject.getCurrent();
Subject.setCurrent(null);
JsonFrontend.setSession(null);
}
}
});
thread.start();
}
try {
thread.join(2000);
} catch (InterruptedException t) {
}
if (!thread.isAlive()) {
output.add("session", sessionId);
return output;
} else {
JsonOutput output = new JsonOutput();
output.add("wait", ++retry);
return output;
}
}
private static class ComponentUnknowException extends Exception {
private static final long serialVersionUID = 1L;
}
private JsonComponent getComponentById(Object id) throws ComponentUnknowException {
JsonComponent result = componentById.get(id);
if (result == null) {
throw new ComponentUnknowException();
}
return result;
}
private JsonOutput handle_(JsonInput input) throws ComponentUnknowException {
JsonFrontend.setUseInputTypes(Boolean.TRUE.equals(input.getObject("inputTypes")));
output = new JsonOutput();
Object initialize = input.getObject(JsonInput.INITIALIZE);
initializing = initialize != null;
if (initializing) {
if (initialize instanceof List) {
List<String> pageIds = (List<String>) initialize;
if (!pageIds.isEmpty() && pageStore.valid(pageIds)) {
onLogin = () -> show(pageIds, false);
} else {
onLogin = () -> show(Application.getInstance().createDefaultPage());
}
}
Subject subject = null;
if (authentication instanceof RememberMeAuthentication) {
RememberMeAuthentication rememberMeAuthentication = (RememberMeAuthentication) authentication;
String token = (String) input.getObject("rememberMeToken");
if (token != null) {
subject = rememberMeAuthentication.remember(token);
}
}
login(subject);
}
if (input.containsObject("closePage")) {
String pageId = (String) input.getObject("closePage");
visiblePageAndDetailsList.removeAllFrom(pageId);
}
Map<String, Object> changedValues = input.get(JsonInput.CHANGED_VALUE);
for (Map.Entry<String, Object> entry : changedValues.entrySet()) {
String componentId = entry.getKey();
Object newValue = entry.getValue(); // most of the time a String,
// but not for password
JsonComponent component = getComponentById(componentId);
((JsonInputComponent<?>) component).changedValue(newValue);
output.add("source", componentId);
}
String actionId = (String) input.getObject(JsonInput.ACTIVATED_ACTION);
if (actionId != null) {
JsonAction action = (JsonAction) getComponentById(actionId);
action.run();
}
Map<String, Object> tableAction = input.get(JsonInput.TABLE_ACTION);
if (tableAction != null && !tableAction.isEmpty()) {
JsonTable<?> table = (JsonTable<?>) getComponentById(tableAction.get("table"));
int row = ((Long) tableAction.get("row")).intValue();
table.action(row);
}
Map<String, Object> tableSortAction = input.get("tableSortAction");
if (tableSortAction != null && !tableSortAction.isEmpty()) {
JsonTable<?> table = (JsonTable<?>) getComponentById(tableSortAction.get("table"));
int column = ((Long) tableSortAction.get("column")).intValue();
table.sort(column);
}
Map<String, Object> tableSelection = input.get("tableSelection");
if (tableSelection != null && !tableSelection.isEmpty()) {
JsonTable<?> table = (JsonTable<?>) getComponentById(tableSelection.get("table"));
List<Number> rows = ((List<Number>) tableSelection.get("rows"));
table.selection(rows);
}
String tableExtendContent = (String) input.getObject("tableExtendContent");
if (tableExtendContent != null) {
JsonTable<?> table = (JsonTable<?>) getComponentById(tableExtendContent);
output.add("tableId", tableExtendContent);
output.add("tableExtendContent", table.extendContent());
output.add("extendable", table.isExtendable());
}
String search = (String) input.getObject("search");
if (search != null && Application.getInstance().hasSearch()) {
Application.getInstance().search(search);
}
String loadSuggestions = (String) input.getObject("loadSuggestions");
if (loadSuggestions != null) {
JsonTextField textField = (JsonTextField) getComponentById(loadSuggestions);
String searchText = (String) input.getObject("searchText");
List<String> suggestions = textField.getSuggestions().search(searchText);
suggestions = suggestions != null && suggestions.size() > 50 ? suggestions.subList(0, 50) : suggestions;
output.add("suggestions", suggestions);
output.add("loadSuggestions", loadSuggestions);
}
String openLookupDialog = (String) input.getObject("openLookupDialog");
if (openLookupDialog != null) {
JsonLookup lookup = (JsonLookup) getComponentById(openLookupDialog);
lookup.showLookupDialog();
}
if (input.containsObject("logout")) {
if (Subject.getCurrent() != null) {
Backend.getInstance().getAuthentication().getLogoutAction().run();
}
if (Application.getInstance().getAuthenticatonMode() == AuthenticatonMode.REQUIRED) {
Backend.getInstance().getAuthentication().showLogin();
}
}
if (input.containsObject("login")) {
Backend.getInstance().getAuthentication().getLoginAction().run();
}
List<String> pageIds = (List<String>) input.getObject("showPages");
if (pageIds != null) {
if (pageStore.valid(pageIds)) {
show(pageIds, true);
} else {
Page page = new ExpiredPage();
String pageId = pageStore.put(page);
output.add("showPages", List.of(createJson(page, pageId, null)));
}
}
register(output);
return output;
}
@Override
public void show(Page page) {
show(page, null);
updateTitle(page);
}
@Override
public void showDetail(Page mainPage, Page detail, boolean horizontalDetailLayout) {
int pageIndex = visiblePageAndDetailsList.indexOf(detail);
String pageId;
if (pageIndex < 0) {
String mainPageId = visiblePageAndDetailsList.getId(mainPage);
pageId = show(detail, mainPageId);
} else {
pageId = visiblePageAndDetailsList.getId(pageIndex);
output.add("pageId", pageId);
output.add("title", detail.getTitle());
}
if (horizontalDetailLayout) {
horizontalPageIds.add(pageId);
} else {
horizontalPageIds.remove(pageId);
}
output.add("horizontalDetailLayout", Boolean.valueOf(horizontalDetailLayout));
}
private String show(Page page, String masterPageId) {
if (!Authorization.hasAccess(Subject.getCurrent(), page)) {
if (authentication == null) {
throw new IllegalStateException("Page " + page.getClass().getSimpleName() + " is annotated with @Role but authentication is not configured.");
}
onLogin = () -> show(page, masterPageId);
authentication.showLogin();
return null;
}
if (masterPageId == null) {
visiblePageAndDetailsList.clear();
componentById.clear();
// navigation is not part of the output. Needs special registration
register(navigation);
} else {
visiblePageAndDetailsList.removeAllAfter(masterPageId);
}
String pageId = pageStore.put(page);
output.add("showPage", createJson(page, pageId, masterPageId));
visiblePageAndDetailsList.put(pageId, page);
return pageId;
}
private void show(List<String> pageIds, boolean loginNotAuthorized) {
if (!pageStore.valid(pageIds)) {
Frontend.show(Application.getInstance().createDefaultPage());
return;
}
List<JsonComponent> jsonList = new ArrayList<>();
visiblePageAndDetailsList.clear();
String previousId = null;
Page firstPage = null;
boolean authorized = true;
for (String pageId : pageIds) {
Page page = pageStore.get(pageId);
if (Authorization.hasAccess(Subject.getCurrent(), page)) {
visiblePageAndDetailsList.put(pageId, page);
jsonList.add(createJson(page, pageId, previousId));
if (previousId == null) {
firstPage = page;
}
previousId = pageId;
} else {
authorized = false;
}
}
if (authorized) {
output.add("horizontalDetailLayout", pageIds.size() > 0 && horizontalPageIds.contains(pageIds.get(pageIds.size() - 1)));
output.add("showPages", jsonList);
updateTitle(firstPage != null ? firstPage : null);
} else if (loginNotAuthorized) {
onLogin = () -> show(pageIds, false);
authentication.showLogin();
} else {
show(Application.getInstance().createDefaultPage());
}
}
@Override
public void login(Subject subject) {
this.subject = subject;
Subject.setCurrent(subject);
if (Application.getInstance().getAuthenticatonMode() != AuthenticatonMode.NOT_AVAILABLE) {
output.add("canLogin", subject == null);
output.add("canLogout", subject != null);
}
updateNavigation();
if (subject == null && initializing && Application.getInstance().getAuthenticatonMode().showLoginAtStart()) {
Backend.getInstance().getAuthentication().showLogin();
} else if (onLogin != null) {
try {
onLogin.run();
} finally {
onLogin = null;
}
} else {
Frontend.show(Application.getInstance().createDefaultPage());
}
}
private void updateTitle(Page page) {
String title = page != null ? page.getTitle() : null;
if (StringUtils.isEmpty(title)) {
title = Application.getInstance().getName();
}
if (StringUtils.isEmpty(title)) {
title = "Minimal-J";
}
output.add("title", title);
}
private JsonComponent createJson(Page page, String pageId, String masterPageId) {
JsonComponent json = new JsonComponent("page");
json.put("masterPageId", masterPageId);
json.put("pageId", pageId);
json.put("title", page.getTitle());
json.put("pageClass", page.getClass().getSimpleName());
String route = Routing.getRouteSafe(page);
if (route != null) {
json.put("route", route);
}
JsonComponent content = (JsonComponent) PageAccess.getContent(page);
json.put("content", content);
List<Object> actionMenu = createActionMenu(page);
json.put("actionMenu", actionMenu);
return json;
}
@Override
public void hideDetail(Page page) {
if (isDetailShown(page)) {
output.add("hidePage", visiblePageAndDetailsList.getId(page));
visiblePageAndDetailsList.removeAllFrom(page);
}
}
@Override
public boolean isDetailShown(Page page) {
return visiblePageAndDetailsList.contains(page);
}
@Override
public IDialog showDialog(String title, IContent content, Action saveAction, Action closeAction, Action... actions) {
JsonDialog dialog = new JsonDialog(title, content, saveAction, closeAction, actions);
openDialog(dialog);
return dialog;
}
public Optional<IDialog> showLogin(IContent content, Action loginAction, Action... additionalActions) {
Action[] actions;
if (Application.getInstance().getAuthenticatonMode() != AuthenticatonMode.REQUIRED) {
SkipLoginAction skipLoginAction = new SkipLoginAction();
actions = new org.minimalj.frontend.action.Action[] {skipLoginAction, loginAction};
} else {
actions = new org.minimalj.frontend.action.Action[] {loginAction};
}
Page page = new Page() {
@Override
public IContent getContent() {
return new JsonLoginContent(content, loginAction, actions);
}
@Override
public String getTitle() {
return Resources.getString("Login.title");
}
};
show(page);
return Optional.empty();
}
private class SkipLoginAction extends Action {
@Override
public void run() {
Frontend.getInstance().login(null);
}
}
@Override
public void showMessage(String text) {
output.add("message", text);
}
@Override
public void showError(String text) {
output.add("error", text);
}
private List<Object> createNavigation() {
List<Action> navigationActions = Application.getInstance().getNavigation();
List<Object> navigationItems = createActions(navigationActions);
return navigationItems;
}
private List<Object> createActionMenu(Page page) {
List<Action> actions = PageAccess.getActions(page);
if (actions != null && actions.size() > 0) {
return createActions(actions);
}
return null;
}
static List<Object> createActions(List<Action> actions) {
List<Object> items = new ArrayList<>();
for (Action action : actions) {
items.add(createAction(action));
}
return items;
}
static List<Object> createActions(Action[] actions) {
return createActions(Arrays.asList(actions));
}
static JsonComponent createAction(Action action) {
JsonComponent item;
if (action instanceof ActionGroup) {
ActionGroup actionGroup = (ActionGroup) action;
item = new JsonAction.JsonActionGroup();
item.put("items", createActions(actionGroup.getItems()));
} else {
item = new JsonAction(action);
}
item.put("name", action.getName());
return item;
}
public void register(Object o) {
travers(o, c -> {
if (c instanceof JsonComponent) {
JsonComponent component = (JsonComponent) c;
String id = component.getId();
if (id != null) {
componentById.put(component.getId(), component);
}
component.setPropertyListener(propertyListener);
}
});
}
public void unregister(Object o) {
travers(o, c -> {
if (c instanceof JsonComponent) {
JsonComponent component = (JsonComponent) c;
componentById.remove(component.getId());
}
});
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void travers(Object o, Consumer<Object> c) {
if (o instanceof JsonComponent) {
c.accept((JsonComponent) o);
}
if (o instanceof Map) {
((Map) o).values().forEach(v -> travers(v, c));
}
if (o instanceof Collection) {
((Collection) o).forEach(v -> travers(v, c));
}
if (o instanceof JsonOutput) {
((JsonOutput) o).forEach(v -> travers(v, c));
}
}
public void openDialog(JsonDialog jsonDialog) {
output.add("dialog", jsonDialog);
}
public void closeDialog(JsonDialog dialog) {
unregister(dialog);
output.addElement("closeDialog", dialog.getId());
}
public void replaceContent(JsonSwitch jsonSwitch, JsonComponent content) {
boolean switchIsRegistred = componentById.containsKey(jsonSwitch.getId());
if (switchIsRegistred) {
if (JsonFrontend.getClientSession() != null) {
replaceContent(output, jsonSwitch, content);
} else {
JsonOutput output = new JsonOutput();
replaceContent(output, jsonSwitch, content);
push.push(output.toString());
}
}
}
private void replaceContent(JsonOutput output, JsonSwitch jsonSwitch, JsonComponent content) {
if (!jsonSwitch.isEmpty()) {
jsonSwitch.values().forEach(this::unregister);
output.removeContent(jsonSwitch.getId());
}
if (content != null) {
output.addContent(jsonSwitch.getId(), content);
}
}
public void addContent(String elementId, JsonComponent content) {
output.addContent(elementId, content);
}
public void show(String url) {
output.add("showUrl", url);
}
public void setRememberMeCookie(String rememberMeCookie) {
output.add("rememberMeToken", rememberMeCookie != null ? rememberMeCookie : "");
}
private class JsonSessionPropertyChangeListener implements JsonPropertyListener {
@Override
public void propertyChange(JsonComponent component, String property, Object value) {
if (JsonFrontend.getClientSession() != null) {
output.propertyChange(component.getId(), property, value);
} else if (component instanceof JsonText) {
JsonOutput output = new JsonOutput();
output.propertyChange(component.getId(), property, value);
push.push(output.toString());
}
}
}
}
|
package org.pentaho.di.trans.steps.xmljoin;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.pentaho.di.core.BlockingRowSet;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
/**
* Converts input rows to one or more XML files.
*
* @author Matt
* @since 14-jan-2006
*/
public class XMLJoin extends BaseStep implements StepInterface
{
private static Class<?> PKG = XMLJoinMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private XMLJoinMeta meta;
private XMLJoinData data;
private Transformer serializer;
public XMLJoin(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(XMLJoinMeta)smi;
data=(XMLJoinData)sdi;
XPath xpath = XPathFactory.newInstance().newXPath();
//if first row we do some initializing and process the first row of the target XML Step
if (first)
{
first=false;
int target_field_id = -1;
XMLJoinMeta meta = (XMLJoinMeta) smi;
//Get the two input row sets
data.TargetRowSet = findInputRowSet(meta.getTargetXMLstep());
data.SourceRowSet = findInputRowSet(meta.getSourceXMLstep());
//get the first line from the target row set
Object[] rTarget = getRowFrom(data.TargetRowSet);
//get target xml
meta.getTargetXMLstep();
String[] target_field_names = data.TargetRowSet.getRowMeta().getFieldNames();
for(int i=0; i< target_field_names.length; i++){
if(meta.getTargetXMLfield().equals(target_field_names[i])){
target_field_id = i;
}
}
//Throw exception if target field has not been found
if(target_field_id == -1) throw new KettleException(BaseMessages.getString(PKG, "XMLJoin.Exception.FieldNotFound", meta.getTargetXMLfield())); //$NON-NLS-1$
data.outputRowMeta = data.TargetRowSet.getRowMeta().clone();
meta.getFields(data.outputRowMeta, getStepname(), new RowMetaInterface[] { data.TargetRowSet.getRowMeta() }, null, this);
data.outputRowData = rTarget.clone();
//get the target xml structure and create a DOM
String strTarget = (String)rTarget[target_field_id];
// parse the XML as a W3C Document
InputSource inputSource = new InputSource(new StringReader(strTarget));
data.XPathStatement = meta.getTargetXPath();
try{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
data.targetDOM = builder.parse(inputSource);
if(! meta.isComplexJoin()){
data.targetNode = (Node) xpath.evaluate(data.XPathStatement, data.targetDOM, XPathConstants.NODE);
if(data.targetNode == null){
throw new KettleXMLException("XPath statement returned no result [" + data.XPathStatement +"]"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
catch(Exception e){
throw new KettleXMLException(e);
}
}
Object[] rJoinSource = getRowFrom(data.SourceRowSet); // This also waits for a row to be finished.
// no more input to be expected... create the output row
if (rJoinSource==null) // no more input to be expected...
{
//create string from xml tree
try{
String strOmitXMLHeader;
if(meta.isOmitXMLHeader()){
strOmitXMLHeader = "yes"; //$NON-NLS-1$
}
else{
strOmitXMLHeader = "no"; //$NON-NLS-1$
}
serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, strOmitXMLHeader);
serializer.setOutputProperty(OutputKeys.INDENT, "no"); //$NON-NLS-1$
StringWriter sw = new StringWriter();
StreamResult resultXML = new StreamResult(sw);
DOMSource source = new DOMSource(data.targetDOM);
serializer.transform(source, resultXML);
int outputIndex = data.outputRowMeta.size()-1;
//send the row to the next steps...
putRow(data.outputRowMeta, RowDataUtil.addValueData(data.outputRowData, outputIndex, sw.toString()));
// finishing up
setOutputDone();
return false;
} catch (Exception e) {
throw new KettleException(e);
}
}
if (data.iSourceXMLField == -1){
//assume failure
//get the column of the join xml set
//get target xml
String[] source_field_names = data.SourceRowSet.getRowMeta().getFieldNames();
for(int i=0; i< source_field_names.length; i++){
if(meta.getSourceXMLfield().equals(source_field_names[i])){
data.iSourceXMLField = i;
}
}
//Throw exception if source xml field has not been found
if(data.iSourceXMLField == -1) throw new KettleException(BaseMessages.getString(PKG, "XMLJoin.Exception.FieldNotFound", meta.getSourceXMLfield())); //$NON-NLS-1$
}
if(meta.isComplexJoin() && data.iCompareFieldID == -1){
//get the column of the compare value
String[] source_field_names = data.SourceRowSet.getRowMeta().getFieldNames();
for(int i=0; i< source_field_names.length; i++){
if(meta.getJoinCompareField().equals(source_field_names[i])){
data.iCompareFieldID= i;
}
}
//Throw exception if source xml field has not been found
if(data.iCompareFieldID == -1) throw new KettleException(BaseMessages.getString(PKG, "XMLJoin.Exception.FieldNotFound", meta.getJoinCompareField())); //$NON-NLS-1$
}
//get XML tags to join
Document joinDocument;
if (rJoinSource != null){
String strJoinXML = (String) rJoinSource[data.iSourceXMLField];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder builder = factory.newDocumentBuilder();
joinDocument = builder.parse(new InputSource(new StringReader(strJoinXML)));
}
catch(Exception e){
throw new KettleException(e);
}
Node node = data.targetDOM.importNode(joinDocument.getDocumentElement(), true);
if(meta.isComplexJoin()){
String strCompareValue = rJoinSource[data.iCompareFieldID].toString();
String strXPathStatement = data.XPathStatement.replace("?", strCompareValue); //$NON-NLS-1$
try{
data.targetNode = (Node) xpath.evaluate(strXPathStatement, data.targetDOM, XPathConstants.NODE);
if(data.targetNode == null){
throw new KettleXMLException("XPath statement returned no reuslt [" + strXPathStatement +"]"); //$NON-NLS-1$ //$NON-NLS-2$
}else{
data.targetNode.appendChild(node);
}
} catch (Exception e) {
throw new KettleException(e);
}
}else{
data.targetNode.appendChild(node);
}
}
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(XMLJoinMeta)smi;
data=(XMLJoinData)sdi;
if(!super.init(smi, sdi))
return false;
try {
if(meta.isOmitNullValues()) {
setSerializer(TransformerFactory.newInstance().newTransformer(new StreamSource(XMLJoin.class.getClassLoader().getResourceAsStream("org/pentaho/di/trans/steps/xmljoin/RemoveNulls.xsl")))); //$NON-NLS-1$
} else {
setSerializer(TransformerFactory.newInstance().newTransformer());
}
if(meta.getEncoding()!=null) {
getSerializer().setOutputProperty(OutputKeys.ENCODING, meta.getEncoding());
}
if(meta.isOmitXMLHeader()) {
getSerializer().setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
}
// See if a main step is supplied: in that case move the corresponding rowset to position 0
for (int i=0;i<getInputRowSets().size();i++)
{
BlockingRowSet rs = (BlockingRowSet) getInputRowSets().get(i);
if (rs.getOriginStepName().equalsIgnoreCase(meta.getTargetXMLstep()))
{
// swap this one and position 0...
// That means, the main stream is always stream 0 --> easy!
BlockingRowSet zero = (BlockingRowSet)getInputRowSets().get(0);
getInputRowSets().set(0, rs);
getInputRowSets().set(i, zero);
}
}
} catch (Exception e) {
return false;
}
return true;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(XMLJoinMeta)smi;
data=(XMLJoinData)sdi;
super.dispose(smi, sdi);
}
private void setSerializer(Transformer serializer) {
this.serializer = serializer;
}
private Transformer getSerializer() {
return serializer;
}
}
|
package org.jtalks.jcommune.web.controller;
import org.jtalks.jcommune.model.entity.PrivateMessage;
import org.jtalks.jcommune.service.PrivateMessageService;
import org.jtalks.jcommune.service.exceptions.NotFoundException;
import org.jtalks.jcommune.web.dto.PrivateMessageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
/**
* MVC controller for Private Messaging. Handles request for inbox, outbox and new private messages.
*
* @author Pavel Vervenko
*/
@Controller
public class PrivateMessageController {
private final PrivateMessageService pmService;
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Requires {@link PrivateMessageService} for manipulations with messages.
*
* @param pmService the PrivateMessageService instance
*/
@Autowired
public PrivateMessageController(PrivateMessageService pmService) {
this.pmService = pmService;
}
/**
* Render the PM inbox page with the list of incoming messages for the /inbox URI.
*
* @return ModelAndView with added list of inbox messages
*/
@RequestMapping(value = "/pm/inbox", method = RequestMethod.GET)
public ModelAndView displayInboxPage() {
return new ModelAndView("pm/inbox", "pmList", pmService.getInboxForCurrentUser());
}
/**
* Render the PM outbox page with the list of sent messages for the /outbox URI.
*
* @return ModelAndView with added list of outbox messages
*/
@RequestMapping(value = "/pm/outbox", method = RequestMethod.GET)
public ModelAndView displayOutboxPage() {
return new ModelAndView("pm/outbox", "pmList", pmService.getOutboxForCurrentUser());
}
/**
* Render the page with a form for creation new Private Message with empty binded {@link PrivateMessageDto}.
*
* @return ModelAndView with the form
*/
@RequestMapping(value = "/pm/new", method = RequestMethod.GET)
public ModelAndView displayNewPMPage() {
return new ModelAndView("pm/newPm", "privateMessageDto", new PrivateMessageDto());
}
/**
* Save the PrivateMessage for the filled in PrivateMessageDto.
*
* @param pmDto {@link PrivateMessageDto} populated in form
* @param result result of {@link PrivateMessageDto} validation
* @return redirect to /inbox on success or back to "/new_pm" on validation errors
*/
@RequestMapping(value = "/pm/new", method = RequestMethod.POST)
public ModelAndView submitNewPm(@Valid @ModelAttribute PrivateMessageDto pmDto, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView("pm/newPm");
}
try {
pmService.sendMessage(pmDto.getTitle(), pmDto.getBody(), pmDto.getRecipient());
} catch (NotFoundException nfe) {
logger.info("User not found: {} ", pmDto.getRecipient());
result.rejectValue("recipient", "label.worg_recipient");
return new ModelAndView("pm/newPm");
}
return new ModelAndView("redirect:/pm/outbox.html");
}
@RequestMapping(value="/pm/{pmId}", method = RequestMethod.GET)
public void show(@PathVariable("pmId") Long pmId) throws NotFoundException {
PrivateMessage pm = pmService.get(pmId);
pmService.markAsReaded(pm);
}
}
|
/*
* @author <a href="mailto:novotny@gridsphere.org">Jason Novotny</a>
* @version $Id$
*/
package org.gridsphere.portlets.core.login;
import org.gridsphere.layout.PortletPageFactory;
import org.gridsphere.portlet.impl.PortletURLImpl;
import org.gridsphere.portlet.impl.SportletProperties;
import org.gridsphere.portlet.service.PortletServiceException;
import org.gridsphere.provider.event.jsr.ActionFormEvent;
import org.gridsphere.provider.event.jsr.RenderFormEvent;
import org.gridsphere.provider.portlet.jsr.ActionPortlet;
import org.gridsphere.provider.portletui.beans.HiddenFieldBean;
import org.gridsphere.provider.portletui.beans.PasswordBean;
import org.gridsphere.provider.portletui.beans.TextFieldBean;
import org.gridsphere.services.core.filter.PortalFilter;
import org.gridsphere.services.core.filter.PortalFilterService;
import org.gridsphere.services.core.mail.MailMessage;
import org.gridsphere.services.core.mail.MailService;
import org.gridsphere.services.core.portal.PortalConfigService;
import org.gridsphere.services.core.request.Request;
import org.gridsphere.services.core.request.RequestService;
import org.gridsphere.services.core.security.auth.AuthModuleService;
import org.gridsphere.services.core.security.auth.AuthenticationException;
import org.gridsphere.services.core.security.auth.AuthorizationException;
import org.gridsphere.services.core.security.auth.modules.LoginAuthModule;
import org.gridsphere.services.core.security.auth.modules.LateUserRetrievalAuthModule;
import org.gridsphere.services.core.security.auth.modules.impl.UserDescriptor;
import org.gridsphere.services.core.security.auth.modules.impl.AuthenticationParameters;
import org.gridsphere.services.core.security.password.PasswordEditor;
import org.gridsphere.services.core.security.password.PasswordManagerService;
import org.gridsphere.services.core.user.User;
import org.gridsphere.services.core.user.UserManagerService;
import javax.portlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.*;
public class LoginPortlet extends ActionPortlet {
private static String FORGOT_PASSWORD_LABEL = "forgotpassword";
private static long REQUEST_LIFETIME = 1000 * 60 * 60 * 24 * 3; // 3 days
public static final String LOGIN_ERROR_FLAG = "LOGIN_FAILED";
public static final Integer LOGIN_ERROR_UNKNOWN = new Integer(-1);
public static final String DO_VIEW_USER_EDIT_LOGIN = "login/createaccount.jsp"; //edit user
public static final String DO_FORGOT_PASSWORD = "login/forgotpassword.jsp";
public static final String DO_NEW_PASSWORD = "login/newpassword.jsp";
private UserManagerService userManagerService = null;
private PortalConfigService portalConfigService = null;
private RequestService requestService = null;
private MailService mailService = null;
private AuthModuleService authModuleService = null;
private PasswordManagerService passwordManagerService = null;
private String newpasswordURL = null;
private String redirectURL = null;
public void init(PortletConfig config) throws PortletException {
super.init(config);
userManagerService = (UserManagerService) createPortletService(UserManagerService.class);
requestService = (RequestService) createPortletService(RequestService.class);
mailService = (MailService) createPortletService(MailService.class);
portalConfigService = (PortalConfigService) createPortletService(PortalConfigService.class);
authModuleService = (AuthModuleService) createPortletService(AuthModuleService.class);
passwordManagerService = (PasswordManagerService) createPortletService(PasswordManagerService.class);
DEFAULT_VIEW_PAGE = "doViewUser";
}
public void doViewUser(RenderFormEvent event) throws PortletException {
log.debug("in LoginPortlet: doViewUser");
PortletRequest request = event.getRenderRequest();
RenderResponse response = event.getRenderResponse();
if (newpasswordURL == null) {
PortletURL url = response.createActionURL();
((PortletURLImpl) url).setAction("newpassword");
((PortletURLImpl) url).setLayout("login");
((PortletURLImpl) url).setEncoding(false);
newpasswordURL = url.toString();
}
if (redirectURL == null) {
PortletURL url = response.createRenderURL();
((PortletURLImpl) url).setLayout(PortletPageFactory.USER_PAGE);
((PortletURLImpl) url).setEncoding(false);
redirectURL = url.toString();
}
PasswordBean pass = event.getPasswordBean("password");
pass.setValue("");
// Check certificates
String x509supported = portalConfigService.getProperty(PortalConfigService.SUPPORT_X509_AUTH);
if ((x509supported != null) && (x509supported.equalsIgnoreCase("true"))) {
X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
if (certs != null && certs.length > 0) {
request.setAttribute("certificate", certs[0].getSubjectDN().toString());
}
}
String remUser = portalConfigService.getProperty(PortalConfigService.REMEMBER_USER);
if ((remUser != null) && (remUser.equalsIgnoreCase("TRUE"))) {
request.setAttribute("remUser", "true");
}
Boolean useSecureLogin = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.USE_HTTPS_LOGIN));
request.setAttribute("useSecureLogin", useSecureLogin.toString());
boolean canUserCreateAccount = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.CAN_USER_CREATE_ACCOUNT)).booleanValue();
if (canUserCreateAccount) request.setAttribute("canUserCreateAcct", "true");
boolean dispUser = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.SEND_USER_FORGET_PASSWORD)).booleanValue();
if (dispUser) request.setAttribute("dispPass", "true");
String errorMsg = (String) request.getPortletSession(true).getAttribute(LOGIN_ERROR_FLAG);
if (errorMsg != null) {
createErrorMessage(event, errorMsg);
request.getPortletSession(true).removeAttribute(LOGIN_ERROR_FLAG);
}
Boolean useUserName = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.USE_USERNAME_FOR_LOGIN));
if (useUserName) request.setAttribute("useUserName", "true");
setNextState(request, "login/login.jsp");
}
public void gs_login(ActionFormEvent event) throws PortletException {
log.debug("in LoginPortlet: gs_login");
PortletRequest req = event.getActionRequest();
try {
login(event);
} catch (AuthorizationException err) {
log.debug(err.getMessage());
req.getPortletSession(true).setAttribute(LOGIN_ERROR_FLAG, err.getMessage());
} catch (AuthenticationException err) {
log.debug(err.getMessage());
req.getPortletSession(true).setAttribute(LOGIN_ERROR_FLAG, err.getMessage());
}
setNextState(req, DEFAULT_VIEW_PAGE);
}
public void notifyUser(ActionFormEvent evt) {
PortletRequest req = evt.getActionRequest();
User user;
TextFieldBean emailTF = evt.getTextFieldBean("emailTF");
if (emailTF.getValue().equals("")) {
createErrorMessage(evt, this.getLocalizedText(req, "LOGIN_NO_EMAIL"));
return;
} else {
user = userManagerService.getUserByEmail(emailTF.getValue());
}
if (user == null) {
createErrorMessage(evt, this.getLocalizedText(req, "LOGIN_NOEXIST"));
return;
}
// create a request
Request request = requestService.createRequest(FORGOT_PASSWORD_LABEL);
long now = Calendar.getInstance().getTime().getTime();
request.setLifetime(new Date(now + REQUEST_LIFETIME));
request.setUserID(user.getID());
requestService.saveRequest(request);
MailMessage mailToUser = new MailMessage();
mailToUser.setEmailAddress(emailTF.getValue());
String subjectHeader = portalConfigService.getProperty("LOGIN_FORGOT_SUBJECT");
if (subjectHeader == null) subjectHeader = getLocalizedText(req, "MAIL_SUBJECT_HEADER");
mailToUser.setSubject(subjectHeader);
StringBuffer body = new StringBuffer();
String forgotMail = portalConfigService.getProperty("LOGIN_FORGOT_BODY");
if (forgotMail == null) forgotMail = getLocalizedText(req, "LOGIN_FORGOT_MAIL");
body.append(forgotMail).append("\n\n");
body.append(getLocalizedText(req, "USERNAME")).append(" :").append(user.getUserName()).append("\n\n");
body.append(newpasswordURL).append("&reqid=").append(request.getOid());
mailToUser.setBody(body.toString());
mailToUser.setSender(portalConfigService.getProperty(PortalConfigService.MAIL_FROM));
try {
mailService.sendMail(mailToUser);
createSuccessMessage(evt, this.getLocalizedText(req, "LOGIN_SUCCESS_MAIL"));
} catch (PortletServiceException e) {
log.error("Unable to send mail message!", e);
createErrorMessage(evt, this.getLocalizedText(req, "LOGIN_FAILURE_MAIL"));
setNextState(req, DEFAULT_VIEW_PAGE);
}
}
/**
* Handles login requests
*
* @param event a <code>GridSphereEvent</code>
* @throws org.gridsphere.services.core.security.auth.AuthenticationException
* if auth fails
* @throws org.gridsphere.services.core.security.auth.AuthorizationException
* if authz fails
*/
protected void login(ActionFormEvent event) throws AuthenticationException, AuthorizationException {
ActionRequest req = event.getActionRequest();
ActionResponse res = event.getActionResponse();
User user = login(req);
Long now = Calendar.getInstance().getTime().getTime();
user.setLastLoginTime(now);
Integer numLogins = user.getNumLogins();
if (numLogins == null) numLogins = 0;
numLogins++;
user.setNumLogins(numLogins);
user.setAttribute(PortalConfigService.LOGIN_NUMTRIES, "0");
userManagerService.saveUser(user);
req.setAttribute(SportletProperties.PORTLET_USER, user);
req.getPortletSession(true).setAttribute(SportletProperties.PORTLET_USER, user.getID(), PortletSession.APPLICATION_SCOPE);
String query = event.getAction().getParameter("queryString");
if (query != null) {
//redirectURL.setParameter("cid", query);
}
//req.setAttribute(SportletProperties.LAYOUT_PAGE, PortletPageFactory.USER_PAGE);
String realuri = null;
Boolean useSecureRedirect = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.USE_HTTPS_REDIRECT));
if (useSecureRedirect.booleanValue()) {
if(redirectURL.startsWith("https")){
realuri = redirectURL;
}else{
realuri = "https" + redirectURL.substring("http".length());
String port = portalConfigService.getProperty(PortalConfigService.PORTAL_PORT);
String securePort = portalConfigService.getProperty(PortalConfigService.PORTAL_SECURE_PORT);
if(null != port && !"".equals(port) && null != securePort && !"".equals(securePort)){
realuri = realuri.replaceAll(port,securePort);
}
}
} else {
realuri = redirectURL;
}
//after login redirect (GPF-463 feature) to URI from session
String redirectURI = (String) ((HttpServletRequest)req).getSession().getAttribute(SportletProperties.PORTAL_REDIRECT_PATH);
if(null != redirectURI){
realuri = realuri.substring(0,realuri.indexOf('/',8))+redirectURI;
}
//mark request as successfull login in order to invoke doAfterLogin (GPF-457 fix)
req.setAttribute(SportletProperties.PORTAL_FILTER_EVENT, SportletProperties.PORTAL_FILTER_EVENT_AFTER_LOGIN);
log.debug("in login redirecting to portal: " + realuri.toString());
try {
if (req.getParameter("ajax") != null) {
//res.setContentType("text/html");
//res.getWriter().print(realuri.toString());
} else {
res.sendRedirect(realuri.toString());
}
} catch (IOException e) {
log.error("Unable to perform a redirect!", e);
}
}
public User login(PortletRequest req)
throws AuthenticationException, AuthorizationException {
boolean lateUserRetrieval = false;
boolean hasLateUserRetrievalAuthModules = false;
String loginName = req.getParameter("username");
String loginPassword = req.getParameter("password");
String certificate = null;
X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
if (certs != null && certs.length > 0) {
certificate = certificateTransform(certs[0].getSubjectDN().toString());
}
User user = null;
// if using client certificate, then don't use login modules
if (certificate == null) {
if ((loginName == null) || (loginPassword == null)) {
throw new AuthorizationException(getLocalizedText(req, "LOGIN_AUTH_BLANK"));
}
// first get user
Boolean useUserName = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.USE_USERNAME_FOR_LOGIN));
if (useUserName) {
user = userManagerService.getUserByUserName(loginName);
} else {
user = userManagerService.getUserByEmail(loginName);
}
// check if there are late user retrieval modules in case user is not obtained from the active login module
List<LoginAuthModule> modules = authModuleService.getActiveAuthModules();
Iterator modulesIterator = modules.iterator();
while (modulesIterator.hasNext()) {
if (modulesIterator.next() instanceof LateUserRetrievalAuthModule) {
hasLateUserRetrievalAuthModules = true;
break;
}
}
if (null == user && hasLateUserRetrievalAuthModules)
lateUserRetrieval = true;
} else {
log.debug("Using certificate for login :" + certificate);
List userList = userManagerService.getUsersByAttribute("certificate", certificate, null);
if (!userList.isEmpty()) {
user = (User) userList.get(0);
}
}
int numTriesInt = 1;
if (!lateUserRetrieval) {
if (user == null) throw new AuthorizationException(getLocalizedText(req, "LOGIN_AUTH_NOUSER"));
// tried one to many times using same name
int defaultNumTries = Integer.valueOf(portalConfigService.getProperty(PortalConfigService.LOGIN_NUMTRIES)).intValue();
String numTries = (String) user.getAttribute(PortalConfigService.LOGIN_NUMTRIES);
if (numTries != null)
numTriesInt = Integer.valueOf(numTries).intValue();
System.err.println("num tries = " + numTriesInt);
if ((defaultNumTries != -1) && (numTriesInt >= defaultNumTries)) {
disableAccount(req);
throw new AuthorizationException(getLocalizedText(req, "LOGIN_TOOMANY_ATTEMPTS"));
}
String accountStatus = (String) user.getAttribute(User.DISABLED);
if ((accountStatus != null) && ("TRUE".equalsIgnoreCase(accountStatus)))
throw new AuthorizationException(getLocalizedText(req, "LOGIN_AUTH_DISABLED"));
}
// If authorized via certificates no other authorization needed
if (certificate != null) return user;
// second invoke the appropriate auth module
List<LoginAuthModule> modules = authModuleService.getActiveAuthModules();
Collections.sort(modules);
AuthenticationException authEx = null;
Map parametersMap = new HashMap();
if(hasLateUserRetrievalAuthModules){
Enumeration parametersNamesEnumeration = req.getParameterNames();
while (parametersNamesEnumeration.hasMoreElements()) {
String parameterName = (String) parametersNamesEnumeration.nextElement();
parametersMap.put(parameterName, req.getParameter(parameterName));
}
}
Iterator it = modules.iterator();
if (lateUserRetrieval)
log.debug("in login: Use late user retrieval modules only");
log.debug("in login: Active modules are: ");
boolean success = false;
while (it.hasNext()) {
success = false;
LoginAuthModule mod = (LoginAuthModule) it.next();
//in case of late user retrieval use LateUserRetrievalAuthModule modules only
if (lateUserRetrieval && !(mod instanceof LateUserRetrievalAuthModule)) {
log.debug(mod.getModuleName() + " (NOT late user retrieval module)");
continue;
}
log.debug(mod.getModuleName());
try {
if (mod instanceof LateUserRetrievalAuthModule) {
UserDescriptor userDescriptor = ((LateUserRetrievalAuthModule) mod).checkAuthentication(new AuthenticationParameters(loginName, loginPassword, parametersMap, req));
//TODO: substitute with localized messages
if(null == userDescriptor)
throw new AuthenticationException("Late user retrieval module did not return user descriptor");
//TODO: substitute with localized messages
if(null == userDescriptor.getUserName() && null == userDescriptor.getEmailAddress() && null == userDescriptor.getID())
throw new AuthenticationException("Late user retrieval module did not return user descriptor containing login name or email or id");
User tmpUser = null;
//obtain user by user name or email or id
if(null != userDescriptor.getUserName())
tmpUser = userManagerService.getUserByUserName(userDescriptor.getUserName());
else if(null != userDescriptor.getEmailAddress())
tmpUser = userManagerService.getUserByEmail(userDescriptor.getEmailAddress());
else if(null != userDescriptor.getID()) {
List users = userManagerService.getUsers();
for (int i = 0; i < users.size(); i++) {
User user1 = (User) users.get(i);
if(user1.getID().equals(userDescriptor.getID())){
tmpUser = user1;
break;
}
}
}
//TODO: substitute with localized messages
if(null == tmpUser)
throw new AuthenticationException("User descriptor returned by late user retrieval is invalid");
//check if user descriptor matches user object
//TODO: substitute with localized messages
if(null != userDescriptor.getID() && !tmpUser.getID().equals(userDescriptor.getID()))
throw new AuthenticationException("ID in auth module and GridSphere doesn't match");
//TODO: substitute with localized messages
if(null != userDescriptor.getEmailAddress() && !tmpUser.getEmailAddress().equals(userDescriptor.getEmailAddress()))
throw new AuthenticationException("User email in auth module and GridSphere doesn't match");
//TODO: substitute with localized messages
if(null != userDescriptor.getUserName() && !tmpUser.getUserName().equals(userDescriptor.getUserName()))
throw new AuthenticationException("User name in auth module and GridSphere doesn't match");
user = tmpUser;
} else {
mod.checkAuthentication(user, loginPassword);
}
success = true;
} catch (AuthenticationException e) {
//TODO: shouldn't we accumulate authentication error messages from all modules - not from the last only ?
String errMsg = mod.getModuleError(e.getMessage(), req.getLocale());
if (errMsg != null) {
authEx = new AuthenticationException(errMsg);
} else {
authEx = e;
}
} catch (Exception e){
log.error("",e);
}
if (success) break;
}
if (!lateUserRetrieval && !success) {
numTriesInt++;
user.setAttribute(PortalConfigService.LOGIN_NUMTRIES, String.valueOf(numTriesInt));
userManagerService.saveUser(user);
}
if (!success)
throw authEx;
return user;
}
/**
* Transform certificate subject from :
* CN=Engbert Heupers, O=sara, O=users, O=dutchgrid
* to :
* /O=dutchgrid/O=users/O=sara/CN=Engbert Heupers
*
* @param certificate string
* @return certificate string
*/
private String certificateTransform(String certificate) {
String ls[] = certificate.split(", ");
StringBuffer res = new StringBuffer();
for (int i = ls.length - 1; i >= 0; i
res.append("/");
res.append(ls[i]);
}
return res.toString();
}
protected String getLocalizedText(HttpServletRequest req, String key) {
Locale locale = req.getLocale();
ResourceBundle bundle = ResourceBundle.getBundle("gridsphere.resources.Portlet", locale);
return bundle.getString(key);
}
public void disableAccount(PortletRequest req) {
//PortletRequest req = event.getRenderRequest();
String loginName = req.getParameter("username");
User user = userManagerService.getUserByUserName(loginName);
if (user != null) {
user.setAttribute(User.DISABLED, "true");
userManagerService.saveUser(user);
MailMessage mailToUser = new MailMessage();
StringBuffer body = new StringBuffer();
body.append(getLocalizedText(req, "LOGIN_DISABLED_MSG1")).append(" ").append(getLocalizedText(req, "LOGIN_DISABLED_MSG2")).append("\n\n");
mailToUser.setBody(body.toString());
mailToUser.setSubject(getLocalizedText(req, "LOGIN_DISABLED_SUBJECT"));
mailToUser.setEmailAddress(user.getEmailAddress());
MailMessage mailToAdmin = new MailMessage();
StringBuffer body2 = new StringBuffer();
body2.append(getLocalizedText(req, "LOGIN_DISABLED_ADMIN_MSG")).append(" ").append(user.getUserName());
mailToAdmin.setBody(body2.toString());
mailToAdmin.setSubject(getLocalizedText(req, "LOGIN_DISABLED_SUBJECT") + " " + user.getUserName());
String portalAdminEmail = portalConfigService.getProperty(PortalConfigService.PORTAL_ADMIN_EMAIL);
mailToAdmin.setEmailAddress(portalAdminEmail);
try {
mailService.sendMail(mailToUser);
mailService.sendMail(mailToAdmin);
} catch (PortletServiceException e) {
log.error("Unable to send mail message!", e);
//createErrorMessage(event, this.getLocalizedText(req, "LOGIN_FAILURE_MAIL"));
}
}
}
public void displayForgotPassword(RenderFormEvent event) {
boolean sendMail = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.SEND_USER_FORGET_PASSWORD)).booleanValue();
if (sendMail) {
PortletRequest req = event.getRenderRequest();
setNextState(req, DO_FORGOT_PASSWORD);
}
}
public void newpassword(ActionFormEvent evt) {
PortletRequest req = evt.getActionRequest();
String id = req.getParameter("reqid");
Request request = requestService.getRequest(id, FORGOT_PASSWORD_LABEL);
if (request != null) {
HiddenFieldBean reqid = evt.getHiddenFieldBean("reqid");
reqid.setValue(id);
setNextState(req, DO_NEW_PASSWORD);
} else {
setNextState(req, DEFAULT_VIEW_PAGE);
}
}
public void doSavePass(ActionFormEvent event) {
PortletRequest req = event.getActionRequest();
HiddenFieldBean reqid = event.getHiddenFieldBean("reqid");
String id = reqid.getValue();
Request request = requestService.getRequest(id, FORGOT_PASSWORD_LABEL);
if (request != null) {
String uid = request.getUserID();
User user = userManagerService.getUser(uid);
passwordManagerService.editPassword(user);
String passwordValue = event.getPasswordBean("password").getValue();
String confirmPasswordValue = event.getPasswordBean("confirmPassword").getValue();
if (passwordValue == null) {
createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_NOTSET"));
setNextState(req, DO_NEW_PASSWORD);
return;
}
// Otherwise, password must match confirmation
if (!passwordValue.equals(confirmPasswordValue)) {
createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_MISMATCH"));
setNextState(req, DO_NEW_PASSWORD);
// If they do match, then validate password with our service
} else {
if (passwordValue.length() == 0) {
createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_BLANK"));
setNextState(req, DO_NEW_PASSWORD);
} else if (passwordValue.length() < 5) {
System.err.println("length < 5 password= " + passwordValue);
createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_TOOSHORT"));
setNextState(req, DO_NEW_PASSWORD);
} else {
// save password
//System.err.println("saving password= " + passwordValue);
PasswordEditor editPasswd = passwordManagerService.editPassword(user);
editPasswd.setValue(passwordValue);
editPasswd.setDateLastModified(Calendar.getInstance().getTime());
passwordManagerService.savePassword(editPasswd);
createSuccessMessage(event, this.getLocalizedText(req, "USER_PASSWORD_SUCCESS"));
requestService.deleteRequest(request);
}
}
}
}
}
|
package org.minimalj.frontend.impl.swing;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.prefs.BackingStoreException;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
import org.minimalj.application.Application;
// for: java.util.prefs Could not open/create prefs root node Software\JavaSoft\Prefs
public class SwingFavorites implements PreferenceChangeListener {
private final Consumer<LinkedHashMap<String, String>> changeListener;
private Preferences preferences;
public SwingFavorites(Consumer<LinkedHashMap<String, String>> changeListener) {
Objects.nonNull(changeListener);
setUser(null);
this.changeListener = changeListener;
}
public void setUser(String user) {
if (preferences != null) {
preferences.removePreferenceChangeListener(this);
}
if (user != null) {
preferences = Preferences.userNodeForPackage(Application.getInstance().getClass()).node("favoritesByUser").node(user);
} else {
preferences = Preferences.userNodeForPackage(Application.getInstance().getClass()).node("favorites");
}
preferences.addPreferenceChangeListener(this);
if (changeListener != null) {
changeListener.accept(getFavorites());
}
}
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
changeListener.accept(getFavorites());
}
public LinkedHashMap<String, String> getFavorites() {
try {
String[] keys = preferences.keys();
Arrays.sort(keys);
LinkedHashMap<String, String> favorites = new LinkedHashMap<>();
for (String key : keys) {
try {
String route = key.substring(key.indexOf("@") + 1);
favorites.put(route, preferences.get(key, "Page"));
} catch (Exception e) {
e.printStackTrace();
}
}
return favorites;
} catch (BackingStoreException e) {
// do nothing, favorites not available
return new LinkedHashMap<>();
}
}
public boolean isFavorite(String route) {
return findKey(route) != null;
}
private String findKey(String route) {
route = "@" + route;
String[] keys;
try {
keys = preferences.keys();
for (String key : keys) {
if (key.endsWith(route)) {
return key;
}
}
} catch (BackingStoreException e) {
// do nothing, favorites not available
}
return null;
}
private void addFavorite(String route, String title) {
LocalDateTime time = LocalDateTime.now();
String timeString = time.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
String key = timeString + "@" + route;
preferences.put(key, title);
}
private void removeFavorite(String route) {
route = "@" + route;
String[] keys;
try {
keys = preferences.keys();
for (String key : keys) {
if (key.endsWith(route)) {
preferences.remove(key);
}
}
} catch (BackingStoreException e) {
// do nothing, favorites not available
}
}
public void toggleFavorite(String route, String title) {
String key = findKey(route);
if (key != null) {
removeFavorite(route);
} else {
addFavorite(route, title);
}
}
}
|
package com.psddev.dari.db;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.PaginatedResult;
/**
* Caches the results of read operations.
*
* <p>For example, given:</p>
*
* <blockquote><pre>{@literal
CachingDatabase caching = new CachingDatabase();
caching.setDelegate(Database.Static.getDefault());
PaginatedResult<Article> result = Query.from(Article.class).using(caching).select(0, 5);
* }</pre></blockquote>
*
* <p>These are some of the queries that won't trigger additional
* reads in the delegate database:</p>
*
* <ul>
* <li>{@code Query.from(Article.class).using(caching).count()}</li>
* <li>{@code Query.from(Article.class).using(caching).where("_id = ?", result.getItems().get(0));}</li>
* </ul>
*
* <p>All methods are thread-safe.</p>
*/
public class CachingDatabase extends ForwardingDatabase {
private static final Object MISSING = new Object();
private final ConcurrentMap<UUID, Object> objectCache = new ConcurrentHashMap<UUID, Object>();
private final ConcurrentMap<UUID, Object> referenceCache = new ConcurrentHashMap<UUID, Object>();
private final ConcurrentMap<Query<?>, List<?>> readAllCache = new ConcurrentHashMap<Query<?>, List<?>>();
private final ConcurrentMap<Query<?>, Long> readCountCache = new ConcurrentHashMap<Query<?>, Long>();
private final ConcurrentMap<Query<?>, Object> readFirstCache = new ConcurrentHashMap<Query<?>, Object>();
private final ConcurrentMap<Query<?>, Map<Range, PaginatedResult<?>>> readPartialCache = new ConcurrentHashMap<Query<?>, Map<Range, PaginatedResult<?>>>();
private static class Range {
public final long offset;
public final int limit;
public Range(long offset, int limit) {
this.offset = offset;
this.limit = limit;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Range) {
Range otherRange = (Range) other;
return offset == otherRange.offset &&
limit == otherRange.limit;
} else {
return false;
}
}
@Override
public int hashCode() {
return ObjectUtils.hashCode(offset, limit);
}
}
/**
* Returns the map of all objects cached so far.
*
* @return Never {@code null}. Mutable. Thread-safe.
*/
public Map<UUID, Object> getObjectCache() {
return objectCache;
}
/**
* Returns the map of all object references cached so far.
*
* @return Never {@code null}. Mutable. Thread-safe.
*/
public Map<UUID, Object> getReferenceCache() {
return referenceCache;
}
private boolean isCacheDisabled(Query<?> query) {
if (query.isCache()) {
return query.as(QueryOptions.class).isDisabled();
} else {
return true;
}
}
private List<Object> findIdOnlyQueryValues(Query<?> query) {
if (query.getSorters().isEmpty()) {
Predicate predicate = query.getPredicate();
if (predicate instanceof ComparisonPredicate) {
ComparisonPredicate comparison = (ComparisonPredicate) predicate;
if (Query.ID_KEY.equals(comparison.getKey()) &&
PredicateParser.EQUALS_ANY_OPERATOR.equals(comparison.getOperator()) &&
comparison.findValueQuery() == null) {
return comparison.getValues();
}
}
}
return null;
}
private Object findCachedObject(UUID id, Query<?> query) {
Object object = objectCache.get(id);
if (object == null && query.isReferenceOnly()) {
object = referenceCache != null ? referenceCache.get(id) : null;
}
if (object != null) {
Class<?> objectClass = query.getObjectClass();
if (objectClass != null && !objectClass.isInstance(object)) {
object = null;
}
}
return object;
}
private void cacheObject(Object object) {
State state = ((Recordable) object).getState();
UUID id = state.getId();
if (state.isReferenceOnly()) {
referenceCache.put(id, object);
} else if (!state.isResolveToReferenceOnly()) {
objectCache.put(id, object);
}
}
@Override
@SuppressWarnings("unchecked")
public <T> List<T> readAll(Query<T> query) {
if (isCacheDisabled(query)) {
return super.readAll(query);
}
List<Object> all = new ArrayList<Object>();
List<Object> values = findIdOnlyQueryValues(query);
if (values != null) {
List<Object> newValues = null;
for (Object value : values) {
UUID valueId = ObjectUtils.to(UUID.class, value);
if (valueId != null) {
Object object = findCachedObject(valueId, query);
if (object != null) {
all.add(object);
continue;
}
}
if (newValues == null) {
newValues = new ArrayList<Object>();
}
newValues.add(value);
}
if (newValues == null) {
return (List<T>) all;
} else {
query = query.clone();
query.setPredicate(PredicateParser.Static.parse("_id = ?", newValues));
}
}
List<?> list = readAllCache.get(query);
if (list == null) {
list = super.readAll(query);
readAllCache.put(query, list);
for (Object item : list) {
cacheObject(item);
}
}
all.addAll(list);
return (List<T>) all;
}
@Override
public long readCount(Query<?> query) {
if (isCacheDisabled(query)) {
return super.readCount(query);
}
Long count = readCountCache.get(query);
if (count == null) {
COUNT: {
if (readAllCache != null) {
List<?> list = readAllCache.get(query);
if (list != null) {
count = (long) list.size();
break COUNT;
}
}
if (readPartialCache != null) {
Map<Range, PaginatedResult<?>> subCache = readPartialCache.get(query);
if (subCache != null && !subCache.isEmpty()) {
count = subCache.values().iterator().next().getCount();
break COUNT;
}
}
count = super.readCount(query);
}
readCountCache.put(query, count);
}
return count;
}
@Override
@SuppressWarnings("unchecked")
public <T> T readFirst(Query<T> query) {
if (isCacheDisabled(query)) {
return super.readFirst(query);
}
List<Object> values = findIdOnlyQueryValues(query);
if (values != null) {
for (Object value : values) {
UUID valueId = ObjectUtils.to(UUID.class, value);
if (valueId != null) {
Object object = findCachedObject(valueId, query);
if (object != null) {
return (T) object;
}
}
}
}
Object first = readFirstCache.get(query);
if (first == null) {
first = super.readFirst(query);
if (first == null) {
first = MISSING;
} else {
cacheObject(first);
}
readFirstCache.put(query, first);
}
return first != MISSING ? (T) first : null;
}
@Override
@SuppressWarnings("unchecked")
public <T> PaginatedResult<T> readPartial(Query<T> query, long offset, int limit) {
if (isCacheDisabled(query)) {
return super.readPartial(query, offset, limit);
}
Map<Range, PaginatedResult<?>> subCache = readPartialCache.get(query);
if (subCache == null) {
Map<Range, PaginatedResult<?>> newSubCache = new ConcurrentHashMap<Range, PaginatedResult<?>>();
subCache = readPartialCache.putIfAbsent(query, newSubCache);
if (subCache == null) {
subCache = newSubCache;
}
}
Range range = new Range(offset, limit);
PaginatedResult<?> result = subCache.get(range);
if (result == null) {
result = super.readPartial(query, offset, limit);
subCache.put(range, result);
for (Object item : result.getItems()) {
cacheObject(item);
}
}
return (PaginatedResult<T>) result;
}
/**
* {@link Query} options for {@link CachingDatabase}.
*
* @deprecated Use {@link Query#isCache}, {@link Query#noCache}, or
* {@link Query#setCache} instead.
*/
@Deprecated
@Modification.FieldInternalNamePrefix("caching.")
public static class QueryOptions extends Modification<Query<?>> {
private boolean disabled;
/**
* Returns {@code true} if the caching should be disabled when
* running the query.
*
* @deprecated Use {@link Query#isCache} instead.
*/
@Deprecated
public boolean isDisabled() {
Boolean old = ObjectUtils.to(Boolean.class, getOriginalObject().getOptions().get(IS_DISABLED_QUERY_OPTION));
return old != null ? old : disabled;
}
/**
* Sets whether the caching should be disabled when running
* the query.
*
* @deprecated Use {@link Query#noCache} or {@link Query#setCache}
* instead.
*/
@Deprecated
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
}
/** @deprecated Use {@link QueryOptions} instead. */
@Deprecated
public static final String IS_DISABLED_QUERY_OPTION = "caching.isDisabled";
@Deprecated
@Override
public <T> List<T> readList(Query<T> query) {
return readAll(query);
}
}
|
/*
* $Id$
* $URL$
*/
package org.subethamail.web.action.auth;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.servlet.http.Cookie;
import lombok.extern.java.Log;
import org.apache.commons.codec.binary.Base64;
import org.subethamail.core.auth.SubEthaPrincipal;
import org.subethamail.web.Backend;
import org.subethamail.web.action.SubEthaAction;
import org.subethamail.web.security.SubEthaLogin;
@Log
abstract public class AuthAction extends SubEthaAction
{
/** Name of autologin cookie */
protected static final String AUTO_LOGIN_COOKIE_KEY = "subetha.auth";
/** The j2ee security role for administrative users */
public final static String SITE_ADMIN_ROLE = "siteAdmin";
/**
* Actually perform the login logic by calling into the JAAS stack.
*
* @throws LoginException if it didn't work.
*/
public void login(String who, String password) throws LoginException
{
SubEthaLogin rl = Backend.instance().getLogin();
rl.logout(this.getCtx().getRequest());
log.log(Level.FINE,"Successful authentication for: {0}", who);
if (!rl.login(who, password, this.getCtx().getRequest()))
throw new FailedLoginException("Bad username or password");
}
/**
* @return true if the user has been authenticated.
*/
public boolean isLoggedIn()
{
return this.getPrincipal() != null;
}
/**
* @return whether or not the user is the most powerful kind of administrator
*/
public boolean isSiteAdmin()
{
return this.getCtx().getRequest().isUserInRole(SITE_ADMIN_ROLE);
}
/**
* @return the email of the currently logged-in user, or null if not logged in.
*/
public String getAuthName()
{
if (this.isLoggedIn())
return getPrincipal().getEmail();
else
return null;
}
/**
* Logs the user out.
*/
protected void logout()
{
Backend.instance().getLogin().logout(this.getCtx().getRequest());
}
/**
* Stops auto-login from working by clearing the cookie credentials.
*/
protected void stopAutoLogin()
{
this.setCookie(AUTO_LOGIN_COOKIE_KEY, "", 0);
}
protected void setAutoLogin(String name, String password) throws Exception
{
this.setCookie(AUTO_LOGIN_COOKIE_KEY, this.encryptAutoLogin(name, password), Integer.MAX_VALUE);
}
/**
* Tries to execute an autologin. Not guaranteed to work, in which case nothing happens.
* Side effects might include the user being logged in, or an invalid autlogin cookie
* being deleted.
*/
protected void tryAutoLogin() throws Exception
{
Cookie cook = this.getCookie(AUTO_LOGIN_COOKIE_KEY);
if (cook != null)
{
String[] nameAndPass = this.decryptAutoLogin(cook.getValue());
if (nameAndPass != null)
{
try
{
this.login(nameAndPass[0], nameAndPass[1]);
}
catch (LoginException ex)
{
this.stopAutoLogin();
}
}
}
}
/**
* The cookie string is "name/password" but with both parts URLEncoded first.
*
* @return a value suitable for a cookie.
*/
protected String encryptAutoLogin(String name, String password) throws Exception
{
List<String> pair = new ArrayList<String>(2);
pair.add(name);
pair.add(password);
byte[] cipherText = Backend.instance().getEncryptor().encryptList(pair);
return new String(Base64.encodeBase64(cipherText));
}
/**
* @param cookieText was encrypted with encryptAutoLogin()
* @return the cookie translated into username (index 0) and password (index 1),
* or null if anything at all went wrong.
*/
protected String[] decryptAutoLogin(String cookieText)
{
try
{
byte[] cipherText = Base64.decodeBase64(cookieText.getBytes());
List<String> pair = Backend.instance().getEncryptor().decryptList(cipherText);
return new String[] { pair.get(0), pair.get(1) };
}
catch (Exception ex)
{
log.log(Level.FINE,"Error decrypting autologin cookie: ", ex);
// Delete the damn thing
this.stopAutoLogin();
return null;
}
}
/**
* helper method to consolidate {@link Principal} acquisition
* @return the current {@link Principal}
*/
protected SubEthaPrincipal getPrincipal()
{
SubEthaPrincipal p = (SubEthaPrincipal)this.getCtx().getRequest().getUserPrincipal();
return p;
}
}
|
package org.ndexbio.model.object.network;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.ndexbio.model.object.NdexExternalObject;
import org.ndexbio.model.object.NdexPropertyValuePair;
import org.ndexbio.model.object.PropertiedObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkSummary extends NdexExternalObject implements PropertiedObject {
private String _description;
private int _edgeCount;
private VisibilityType _visibility;
private String _name;
private int _nodeCount;
private String _owner;
private UUID ownerUUID;
private boolean isReadOnly;
private String _version;
private String _URI;
private Set<Long> subnetworkIds;
private List<NdexPropertyValuePair> _properties;
private String errorMessage;
private boolean isValid;
private List<String> warnings;
private boolean isShowcase;
// private boolean isIndexed;
private boolean isCompleted;
private String doi;
private boolean isCertified;
private NetworkIndexLevel indexLevel;
private boolean hasLayout;
private boolean hasSample;
// private boolean cxFileSize;
public NetworkSummary () {
super();
_edgeCount = 0;
_nodeCount = 0;
_properties = new ArrayList<> (10);
this.subnetworkIds = new HashSet<>();
isReadOnly = false;
warnings = new LinkedList<>();
indexLevel=NetworkIndexLevel.NONE;
}
public String getDescription()
{
return _description;
}
public void setDescription(String description)
{
_description = description;
}
public int getEdgeCount()
{
return _edgeCount;
}
public void setEdgeCount(int edgeCount)
{
_edgeCount = edgeCount;
}
public String getVersion() {
return _version;
}
public void setVersion(String version) {
this._version = version;
}
public VisibilityType getVisibility() {
return _visibility;
}
public void setVisibility(VisibilityType visibility) {
this._visibility = visibility;
}
public boolean getIsReadOnly()
{
return isReadOnly;
}
public void setIsReadOnly(boolean isReadOnly)
{
this.isReadOnly = isReadOnly;
}
public String getName()
{
return _name;
}
public void setName(String name)
{
_name = name;
}
public int getNodeCount()
{
return _nodeCount;
}
public void setNodeCount(int nodeCount)
{
_nodeCount = nodeCount;
}
@Override
public List<NdexPropertyValuePair> getProperties() {
return _properties;
}
@Override
public void setProperties(List<NdexPropertyValuePair> properties) {
_properties = properties;
}
public String getOwner() {
return _owner;
}
public void setOwner(String owner) {
this._owner = owner;
}
public String getURI() {
return _URI;
}
public void setURI(String URI) {
this._URI = URI;
}
public Set<Long> getSubnetworkIds() {
return subnetworkIds;
}
public void setSubnetworkIds(Set<Long> subnetworkIds) {
this.subnetworkIds = subnetworkIds;
}
public UUID getOwnerUUID() {
return ownerUUID;
}
public void setOwnerUUID(UUID ownerUUID) {
this.ownerUUID = ownerUUID;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public boolean getIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
public List<String> getWarnings() {
return warnings;
}
public void setWarnings(List<String> warnings) {
this.warnings = warnings;
}
public boolean getIsShowcase() {
return isShowcase;
}
public void setIsShowcase(boolean displayInHomePage) {
this.isShowcase = displayInHomePage;
}
/*
public boolean isIndexed() {
return isIndexed;
}
public void setIndexed(boolean isIndexed) {
this.isIndexed = isIndexed;
}
*/
public boolean isCompleted() {
return isCompleted;
}
public void setCompleted(boolean isCompleted) {
this.isCompleted = isCompleted;
}
public String getDoi() {
return doi;
}
public void setDoi(String doi) {
this.doi = doi;
}
public boolean getIsCertified() {
return isCertified;
}
public void setIsCertified(boolean certified) {
this.isCertified = certified;
}
public NetworkIndexLevel getIndexLevel() {
return indexLevel;
}
public void setIndexLevel(NetworkIndexLevel solrIndexLevel) {
this.indexLevel = solrIndexLevel;
}
public boolean getHasLayout() {
return hasLayout;
}
public void setHasLayout(boolean hasLayout) {
this.hasLayout = hasLayout;
}
public boolean getHasSample() {
return hasSample;
}
public void setHasSample(boolean hasSample) {
this.hasSample = hasSample;
}
}
|
package io.subutai.core.localpeer.impl.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import io.subutai.common.command.CommandException;
import io.subutai.common.command.CommandResult;
import io.subutai.common.command.CommandUtil;
import io.subutai.common.command.RequestBuilder;
import io.subutai.common.environment.RhP2pIp;
import io.subutai.common.host.ContainerHostInfo;
import io.subutai.common.host.ContainerHostState;
import io.subutai.common.host.HostId;
import io.subutai.common.host.HostInfo;
import io.subutai.common.host.HostInterface;
import io.subutai.common.host.HostInterfaces;
import io.subutai.common.host.InstanceType;
import io.subutai.common.host.NullHostInterface;
import io.subutai.common.host.ResourceHostInfo;
import io.subutai.common.network.JournalCtlLevel;
import io.subutai.common.network.NetworkResource;
import io.subutai.common.network.P2pLogs;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.ContainerSize;
import io.subutai.common.peer.EnvironmentId;
import io.subutai.common.peer.HostNotFoundException;
import io.subutai.common.peer.ResourceHost;
import io.subutai.common.peer.ResourceHostException;
import io.subutai.common.protocol.Disposable;
import io.subutai.common.protocol.P2PConnections;
import io.subutai.common.protocol.P2pIps;
import io.subutai.common.protocol.Tunnel;
import io.subutai.common.protocol.Tunnels;
import io.subutai.common.quota.ContainerQuota;
import io.subutai.common.security.objects.PermissionObject;
import io.subutai.common.settings.Common;
import io.subutai.common.util.P2PUtil;
import io.subutai.common.util.ServiceLocator;
import io.subutai.core.hostregistry.api.HostDisconnectedException;
import io.subutai.core.hostregistry.api.HostRegistry;
import io.subutai.core.localpeer.impl.ResourceHostCommands;
import io.subutai.core.lxc.quota.api.QuotaManager;
import io.subutai.core.network.api.NetworkManager;
import io.subutai.core.network.api.NetworkManagerException;
import io.subutai.core.registration.api.RegistrationManager;
/**
* Resource host implementation.
*/
@Entity
@Table( name = "r_host" )
@Access( AccessType.FIELD )
public class ResourceHostEntity extends AbstractSubutaiHost implements ResourceHost, Disposable
{
private static final Logger LOG = LoggerFactory.getLogger( ResourceHostEntity.class );
private static final Pattern LXC_STATE_PATTERN = Pattern.compile( "(RUNNING|STOPPED|FROZEN)" );
private static final String PRECONDITION_CONTAINER_IS_NULL_MSG = "Container host is null";
private static final String CONTAINER_EXCEPTION_MSG_FORMAT = "Container with name %s does not exist";
private static final Pattern CLONE_OUTPUT_PATTERN = Pattern.compile( "with ID (.*) successfully cloned" );
@OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER,
targetEntity = ContainerHostEntity.class, orphanRemoval = true )
private Set<ContainerHost> containersHosts = Sets.newHashSet();
@Column( name = "instance" )
@Enumerated( EnumType.STRING )
private InstanceType instanceType;
@OneToMany( mappedBy = "host", fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity =
HostInterfaceEntity.class, orphanRemoval = true )
@JsonIgnore
protected Set<HostInterface> netInterfaces = new HashSet<>();
@Transient
protected CommandUtil commandUtil = new CommandUtil();
@Transient
protected ResourceHostCommands resourceHostCommands = new ResourceHostCommands();
@Transient
protected int numberOfCpuCores = -1;
protected ResourceHostEntity()
{
init();
}
@Override
public void init()
{
super.init();
}
public ResourceHostEntity( final String peerId, final ResourceHostInfo resourceHostInfo )
{
super( peerId, resourceHostInfo );
this.instanceType = resourceHostInfo.getInstanceType();
setSavedHostInterfaces( resourceHostInfo.getHostInterfaces() );
init();
}
@Override
public Set<HostInterface> getSavedHostInterfaces()
{
return netInterfaces;
}
protected void setSavedHostInterfaces( HostInterfaces hostInterfaces )
{
Preconditions.checkNotNull( hostInterfaces );
this.netInterfaces.clear();
for ( HostInterface iface : hostInterfaces.getAll() )
{
HostInterfaceEntity netInterface = new HostInterfaceEntity( iface );
netInterface.setHost( this );
this.netInterfaces.add( netInterface );
}
}
@Override
public InstanceType getInstanceType()
{
return instanceType;
}
@Override
public Set<ContainerHostInfo> getContainers()
{
try
{
return getHostRegistry().getResourceHostInfoById( getId() ).getContainers();
}
catch ( HostDisconnectedException e )
{
LOG.warn( "Error in getContainers", e );
}
return Sets.newHashSet();
}
public void dispose()
{
}
//this method must be executed sequentially since other parallel executions can setup the same tunnel
public synchronized void setupTunnels( P2pIps p2pIps, NetworkResource networkResource ) throws ResourceHostException
{
Preconditions.checkNotNull( p2pIps, "Invalid peer ips set" );
Preconditions.checkNotNull( networkResource, "Invalid networkResource" );
Tunnels tunnels = getTunnels();
//setup tunnel to each local and remote RH
for ( RhP2pIp rhP2pIp : p2pIps.getP2pIps() )
{
//skip self
if ( getId().equalsIgnoreCase( rhP2pIp.getRhId() ) )
{
continue;
}
//skip if own IP
boolean ownIp = !( getHostInterfaces().findByIp( rhP2pIp.getP2pIp() ) instanceof NullHostInterface );
if ( ownIp )
{
continue;
}
//check p2p connections in case heartbeat hasn't arrived yet with new p2p interface
P2PConnections p2PConnections = getP2PConnections();
//skip if exists
if ( p2PConnections.findByIp( rhP2pIp.getP2pIp() ) != null )
{
continue;
}
//see if tunnel exists
Tunnel tunnel = tunnels.findByIp( rhP2pIp.getP2pIp() );
//create new tunnel
if ( tunnel == null )
{
String tunnelName = P2PUtil.generateTunnelName( tunnels );
if ( tunnelName == null )
{
throw new ResourceHostException( "Free tunnel name not found" );
}
Tunnel newTunnel = new Tunnel( tunnelName, rhP2pIp.getP2pIp(), networkResource.getVlan(),
networkResource.getVni() );
createTunnel( newTunnel );
//add to avoid duplication in the next iteration
tunnels.addTunnel( newTunnel );
}
}
}
protected NetworkManager getNetworkManager()
{
return ServiceLocator.getServiceNoCache( NetworkManager.class );
}
protected RegistrationManager getRegistrationManager()
{
return ServiceLocator.getServiceNoCache( RegistrationManager.class );
}
protected QuotaManager getQuotaManager()
{
return ServiceLocator.getServiceNoCache( QuotaManager.class );
}
protected HostRegistry getHostRegistry()
{
return ServiceLocator.getServiceNoCache( HostRegistry.class );
}
@Override
public ContainerHostState getContainerHostState( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, PRECONDITION_CONTAINER_IS_NULL_MSG );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( CONTAINER_EXCEPTION_MSG_FORMAT, containerHost.getHostname() ), e );
}
CommandResult result;
try
{
result = commandUtil
.execute( resourceHostCommands.getListContainerInfoCommand( containerHost.getHostname() ), this );
}
catch ( CommandException e )
{
LOG.error( e.getMessage(), e );
throw new ResourceHostException(
String.format( "Error fetching container %s state: %s", containerHost.getHostname(),
e.getMessage() ), e );
}
String stdOut = result.getStdOut();
String[] outputLines = stdOut.split( System.lineSeparator() );
if ( outputLines.length == 3 )
{
Matcher m = LXC_STATE_PATTERN.matcher( outputLines[2] );
if ( m.find() )
{
return ContainerHostState.valueOf( m.group( 1 ) );
}
}
return ContainerHostState.UNKNOWN;
}
public Set<ContainerHost> getContainerHosts()
{
synchronized ( containersHosts )
{
return containersHosts == null ? Sets.<ContainerHost>newHashSet() :
Sets.newConcurrentHashSet( containersHosts );
}
}
public void startContainerHost( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, PRECONDITION_CONTAINER_IS_NULL_MSG );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( CONTAINER_EXCEPTION_MSG_FORMAT, containerHost.getHostname() ), e );
}
try
{
commandUtil.execute( resourceHostCommands.getStartContainerCommand( containerHost.getHostname() ), this );
}
catch ( CommandException e )
{
throw new ResourceHostException(
String.format( "Error on starting container %s: %s", containerHost.getHostname(), e.getMessage() ),
e );
}
waitContainerStart( containerHost );
}
private void waitContainerStart( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, PRECONDITION_CONTAINER_IS_NULL_MSG );
//wait container connection
long ts = System.currentTimeMillis();
while ( System.currentTimeMillis() - ts < Common.WAIT_CONTAINER_CONNECTION_SEC * 1000 && !containerHost
.isConnected() )
{
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
throw new ResourceHostException( e );
}
}
if ( !ContainerHostState.RUNNING.equals( getContainerHostState( containerHost ) ) )
{
throw new ResourceHostException(
String.format( "Error starting container %s", containerHost.getHostname() ) );
}
}
public void stopContainerHost( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, PRECONDITION_CONTAINER_IS_NULL_MSG );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( CONTAINER_EXCEPTION_MSG_FORMAT, containerHost.getHostname() ), e );
}
try
{
commandUtil.execute( resourceHostCommands.getStopContainerCommand( containerHost.getHostname() ), this );
}
catch ( CommandException e )
{
throw new ResourceHostException(
String.format( "Error stopping container %s: %s", containerHost.getHostname(), e.getMessage() ),
e );
}
}
@Override
public void destroyContainerHost( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, PRECONDITION_CONTAINER_IS_NULL_MSG );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( CONTAINER_EXCEPTION_MSG_FORMAT, containerHost.getHostname() ), e );
}
try
{
commandUtil.execute( resourceHostCommands.getDestroyContainerCommand( containerHost.getHostname() ), this );
}
catch ( CommandException e )
{
throw new ResourceHostException(
String.format( "Error destroying container %s: %s", containerHost.getHostname(), e.getMessage() ),
e );
}
removeContainerHost( containerHost );
}
@Override
public void setContainerQuota( final ContainerHost containerHost, final ContainerSize containerSize )
throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, PRECONDITION_CONTAINER_IS_NULL_MSG );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( CONTAINER_EXCEPTION_MSG_FORMAT, containerHost.getHostname() ), e );
}
ContainerQuota quota = getQuotaManager().getDefaultContainerQuota( containerSize );
try
{
commandUtil.execute( resourceHostCommands.getSetQuotaCommand( containerHost.getHostname(), quota ), this );
}
catch ( CommandException e )
{
throw new ResourceHostException( String.format( "Error setting quota %s to container %s: %s", containerSize,
containerHost.getHostname(), e.getMessage() ), e );
}
}
@Override
public ContainerHost getContainerHostByName( final String hostname ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ), "Invalid hostname" );
for ( ContainerHost containerHost : getContainerHosts() )
{
if ( containerHost.getHostname().equalsIgnoreCase( hostname ) )
{
return containerHost;
}
}
throw new HostNotFoundException( String.format( "Container host not found by hostname %s", hostname ) );
}
public void removeContainerHost( final ContainerHost containerHost )
{
Preconditions.checkNotNull( containerHost, PRECONDITION_CONTAINER_IS_NULL_MSG );
if ( getContainerHosts().contains( containerHost ) )
{
synchronized ( containersHosts )
{
containersHosts.remove( containerHost );
}
( ( ContainerHostEntity ) containerHost ).setParent( null );
}
}
public ContainerHost getContainerHostById( final String id ) throws HostNotFoundException
{
Preconditions.checkNotNull( id, "Invalid container id" );
for ( ContainerHost containerHost : getContainerHosts() )
{
if ( containerHost.getId().equals( id ) )
{
return containerHost;
}
}
throw new HostNotFoundException( String.format( "Container host not found by id %s", id ) );
}
@Override
public Set<ContainerHost> getContainerHostsByEnvironmentId( final String environmentId )
{
Set<ContainerHost> result = new HashSet<>();
for ( ContainerHost containerHost : getContainerHosts() )
{
if ( environmentId.equals( containerHost.getEnvironmentId().getId() ) )
{
result.add( containerHost );
}
}
return result;
}
@Override
public Set<ContainerHost> getContainerHostsByOwnerId( final String ownerId )
{
Set<ContainerHost> result = new HashSet<>();
for ( ContainerHost containerHost : getContainerHosts() )
{
if ( ownerId.equals( containerHost.getOwnerId() ) )
{
result.add( containerHost );
}
}
return result;
}
@Override
public Set<ContainerHost> getContainerHostsByPeerId( final String peerId )
{
Set<ContainerHost> result = new HashSet<>();
for ( ContainerHost containerHost : getContainerHosts() )
{
if ( peerId.equals( containerHost.getInitiatorPeerId() ) )
{
result.add( containerHost );
}
}
return result;
}
@Override
public void addContainerHost( ContainerHost host )
{
Preconditions.checkNotNull( host, "Invalid container host" );
ContainerHostEntity containerHostEntity = ( ContainerHostEntity ) host;
containerHostEntity.setParent( this );
synchronized ( containersHosts )
{
containersHosts.add( host );
}
}
@Override
public void cleanup( final EnvironmentId environmentId, final int vlan ) throws ResourceHostException
{
try
{
commandUtil.execute( resourceHostCommands.getCleanupEnvironmentCommand( vlan ), this );
}
catch ( CommandException e )
{
throw new ResourceHostException(
String.format( "Could not cleanup resource host %s: %s", hostname, e.getMessage() ) );
}
Set<ContainerHost> containerHosts = getContainerHostsByEnvironmentId( environmentId.getId() );
if ( containerHosts.size() > 0 )
{
for ( ContainerHost containerHost : containerHosts )
{
removeContainerHost( containerHost );
}
}
}
@Override
public int getNumberOfCpuCores() throws ResourceHostException
{
if ( numberOfCpuCores == -1 )
{
try
{
CommandResult commandResult =
commandUtil.execute( resourceHostCommands.getFetchCpuCoresNumberCommand(), this );
numberOfCpuCores = Integer.parseInt( commandResult.getStdOut().trim() );
}
catch ( Exception e )
{
throw new ResourceHostException( String.format( "Error fetching # of cpu cores: %s", e.getMessage() ),
e );
}
}
return numberOfCpuCores;
}
@Override
public P2PConnections getP2PConnections() throws ResourceHostException
{
try
{
return getNetworkManager().getP2PConnections( this );
}
catch ( NetworkManagerException e )
{
throw new ResourceHostException( String.format( "Failed to get P2P connections: %s", e.getMessage() ), e );
}
}
@Override
public void joinP2PSwarm( final String p2pIp, final String interfaceName, final String p2pHash,
final String secretKey, final long secretKeyTtlSec ) throws ResourceHostException
{
try
{
if ( getP2PConnections().findByHash( p2pHash ) != null )
{
getNetworkManager().resetSwarmSecretKey( this, p2pHash, secretKey, secretKeyTtlSec );
}
else
{
getNetworkManager().joinP2PSwarm( this, interfaceName, p2pIp, p2pHash, secretKey, secretKeyTtlSec );
}
}
catch ( NetworkManagerException e )
{
throw new ResourceHostException( String.format( "Failed to join P2P swarm: %s", e.getMessage() ), e );
}
}
@Override
public void resetSwarmSecretKey( final String p2pHash, final String newSecretKey, final long ttlSeconds )
throws ResourceHostException
{
try
{
if ( getP2PConnections().findByHash( p2pHash ) != null )
{
getNetworkManager().resetSwarmSecretKey( this, p2pHash, newSecretKey, ttlSeconds );
}
}
catch ( NetworkManagerException e )
{
throw new ResourceHostException(
String.format( "Failed to reset P2P connection secret key: %s", e.getMessage() ), e );
}
}
@Override
public Tunnels getTunnels() throws ResourceHostException
{
try
{
return getNetworkManager().getTunnels( this );
}
catch ( NetworkManagerException e )
{
throw new ResourceHostException( String.format( "Failed to get tunnels: %s", e.getMessage() ), e );
}
}
@Override
public void createTunnel( final Tunnel tunnel ) throws ResourceHostException
{
try
{
getNetworkManager().createTunnel( this, tunnel.getTunnelName(), tunnel.getTunnelIp(), tunnel.getVlan(),
tunnel.getVni() );
}
catch ( NetworkManagerException e )
{
throw new ResourceHostException( String.format( "Failed to create tunnel: %s", e.getMessage() ), e );
}
}
@Override
public void importTemplate( final String templateName ) throws ResourceHostException
{
try
{
commandUtil.execute( resourceHostCommands.getImportTemplateCommand( templateName ), this );
}
catch ( Exception e )
{
throw new ResourceHostException(
String.format( "Error importing template %s: %s", templateName, e.getMessage() ), e );
}
}
@Override
public String cloneContainer( final String templateName, final String hostname, final String ip, final int vlan,
final String environmentId ) throws ResourceHostException
{
try
{
//generate registration token for container for 30 min
String token = getRegistrationManager().generateContainerTTLToken( 30 * 60 * 1000L ).getToken();
CommandResult result = commandUtil.execute( resourceHostCommands
.getCloneContainerCommand( templateName, hostname, ip, vlan, environmentId, token ), this );
//parse ID from output
StringTokenizer st = new StringTokenizer( result.getStdOut(), System.lineSeparator() );
String containerId = null;
while ( st.hasMoreTokens() )
{
final String nextToken = st.nextToken();
Matcher m = CLONE_OUTPUT_PATTERN.matcher( nextToken );
if ( m.find() && m.groupCount() == 1 )
{
containerId = m.group( 1 );
break;
}
}
if ( Strings.isNullOrEmpty( containerId ) )
{
LOG.error( "Container ID not found in output of subutai clone command" );
throw new CommandException( "Container ID not found in output of subutai clone command" );
}
return containerId;
}
catch ( Exception e )
{
throw new ResourceHostException(
String.format( "Error cloning container %s: %s", hostname, e.getMessage() ), e );
}
}
@Override
public boolean updateHostInfo( final HostInfo hostInfo )
{
super.updateHostInfo( hostInfo );
setSavedHostInterfaces( hostInfo.getHostInterfaces() );
ResourceHostInfo resourceHostInfo = ( ResourceHostInfo ) hostInfo;
for ( ContainerHostInfo info : resourceHostInfo.getContainers() )
{
ContainerHostEntity containerHost;
try
{
containerHost = ( ContainerHostEntity ) getContainerHostByName( info.getHostname() );
containerHost.updateHostInfo( info );
}
catch ( HostNotFoundException e )
{
if ( Common.MANAGEMENT_HOSTNAME.equals( info.getHostname() ) )
{
containerHost = new ContainerHostEntity( peerId, info.getId(), info.getHostname(), info.getArch(),
info.getHostInterfaces(), info.getContainerName(), Common.MANAGEMENT_HOSTNAME,
info.getArch().name(), Common.MANAGEMENT_HOSTNAME, null, null, ContainerSize.SMALL );
addContainerHost( containerHost );
}
else
{
LOG.warn( String.format( "Found not registered container host: %s %s", info.getId(),
info.getHostname() ) );
}
}
}
//remove containers that are missing in heartbeat
for ( ContainerHost containerHost : getContainerHosts() )
{
boolean found = false;
for ( ContainerHostInfo info : resourceHostInfo.getContainers() )
{
if ( info.getId().equals( containerHost.getId() ) )
{
found = true;
break;
}
}
if ( !found )
{
removeContainerHost( containerHost );
}
}
return true;
}
@Override
public String getRhVersion() throws ResourceHostException
{
try
{
return commandUtil.execute( new RequestBuilder( "subutai -v" ), this ).getStdOut();
}
catch ( CommandException e )
{
throw new ResourceHostException( String.format( "Error obtaining RH version: %s", e.getMessage() ), e );
}
}
@Override
public String getP2pVersion() throws ResourceHostException
{
try
{
//todo use "subutai" binding when implemented
return commandUtil.execute( new RequestBuilder( "/apps/subutai/current/bin/p2p version" ), this )
.getStdOut();
}
catch ( CommandException e )
{
throw new ResourceHostException( String.format( "Error obtaining P2P version: %s", e.getMessage() ), e );
}
}
public P2pLogs getP2pLogs( JournalCtlLevel logLevel, Date from, Date till ) throws ResourceHostException
{
P2pLogs p2pLogs = new P2pLogs();
try
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
CommandResult result = execute( new RequestBuilder(
String.format( "journalctl -u *p2p* --since \"%s\" --until " + "\"%s\"",
simpleDateFormat.format( from ), simpleDateFormat.format( till ) ) ) );
StringTokenizer st = new StringTokenizer( result.getStdOut(), System.lineSeparator() );
while ( st.hasMoreTokens() )
{
String logLine = st.nextToken();
if ( logLevel == JournalCtlLevel.ALL && !Strings.isNullOrEmpty( logLine ) )
{
p2pLogs.addLog( logLine );
}
else if ( logLine.contains( String.format( "[%s]", logLevel.name() ) ) )
{
p2pLogs.addLog( logLine );
}
}
}
catch ( CommandException e )
{
throw new ResourceHostException( String.format( "Error obtaining P2P logs: %s", e.getMessage() ), e );
}
return p2pLogs;
}
@Override
public boolean isConnected()
{
return getPeer().isConnected( new HostId( getId() ) );
}
@Override
public String getLinkId()
{
return String.format( "%s|%s", getClassPath(), getUniqueIdentifier() );
}
@Override
public String getUniqueIdentifier()
{
return getId();
}
@Override
public String getClassPath()
{
return this.getClass().getSimpleName();
}
@Override
public String getContext()
{
return PermissionObject.ResourceManagement.getName();
}
@Override
public String getKeyId()
{
return getId();
}
}
|
package org.orbeon.oxf.processor.generator;
import org.apache.log4j.Logger;
import org.dom4j.Element;
import org.orbeon.oxf.cache.*;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.pipeline.api.XMLReceiver;
import org.orbeon.oxf.processor.*;
import org.orbeon.oxf.resources.ResourceManagerWrapper;
import org.orbeon.oxf.resources.URLFactory;
import org.orbeon.oxf.resources.handler.OXFHandler;
import org.orbeon.oxf.resources.handler.SystemHandler;
import org.orbeon.oxf.util.*;
import org.orbeon.oxf.xml.SAXStore;
import org.orbeon.oxf.xml.TransformerUtils;
import org.orbeon.oxf.xml.XMLUtils;
import org.orbeon.oxf.xml.XPathUtils;
import org.orbeon.oxf.xml.dom4j.Dom4jUtils;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.w3c.tidy.Tidy;
import org.xml.sax.*;
import scala.Option;
import javax.xml.transform.dom.DOMSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class URLGenerator extends ProcessorImpl {
private static Logger logger = Logger.getLogger(URLGenerator.class);
public static IndentedLogger indentedLogger = new IndentedLogger(logger, "oxf:url-generator");
public static final boolean DEFAULT_VALIDATING = false;
public static final boolean DEFAULT_HANDLE_XINCLUDE = false;
public static final boolean DEFAULT_EXTERNAL_ENTITIES = false;
public static final boolean DEFAULT_HANDLE_LEXICAL = true;
private static final boolean DEFAULT_FORCE_CONTENT_TYPE = false;
private static final boolean DEFAULT_FORCE_ENCODING = false;
private static final boolean DEFAULT_IGNORE_CONNECTION_ENCODING = false;
private static final boolean DEFAULT_CACHE_USE_LOCAL_CACHE = true;
private static final boolean DEFAULT_ENABLE_CONDITIONAL_GET = false;
private static final boolean DEFAULT_PREEMPTIVE_AUTHENTICATION = true;
public static final String URL_NAMESPACE_URI = "http:
public static final String VALIDATING_PROPERTY = "validating";
public static final String HANDLE_XINCLUDE_PROPERTY = "handle-xinclude";
public static final String HANDLE_LEXICAL_PROPERTY = "handle-lexical";
private ConfigURIReferences localConfigURIReferences;
public URLGenerator() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_CONFIG, URL_NAMESPACE_URI));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA));
}
public URLGenerator(String url) {
init(URLFactory.createURL(url), DEFAULT_HANDLE_XINCLUDE);
}
public URLGenerator(String url, boolean handleXInclude) {
init(URLFactory.createURL(url), handleXInclude);
}
public URLGenerator(URL url) {
init(url, DEFAULT_HANDLE_XINCLUDE);
}
public URLGenerator(URL url, boolean handleXInclude) {
init(url, handleXInclude);
}
private void init(URL url, boolean handleXInclude) {
this.localConfigURIReferences = new ConfigURIReferences(new Config(url, handleXInclude));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA));
}
public URLGenerator(URL url, String contentType, boolean forceContentType) {
this.localConfigURIReferences = new ConfigURIReferences(new Config(url, contentType, forceContentType));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA));
}
public URLGenerator(URL url, String contentType, boolean forceContentType, String encoding, boolean forceEncoding,
boolean ignoreConnectionEncoding, XMLUtils.ParserConfiguration parserConfiguration, boolean handleLexical,
String mode, Map<String, String[]> headerNameValues, String forwardHeaders, boolean cacheUseLocalCache,
boolean enableConditionalGET) {
this.localConfigURIReferences = new ConfigURIReferences(new Config(url, contentType, forceContentType, encoding,
forceEncoding, ignoreConnectionEncoding, parserConfiguration, handleLexical, mode,
headerNameValues, forwardHeaders,
cacheUseLocalCache, enableConditionalGET, null, null, DEFAULT_PREEMPTIVE_AUTHENTICATION, null, new TidyConfig(null)));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA));
}
private static class Config {
private URL url;
private String contentType = ProcessorUtils.DEFAULT_CONTENT_TYPE;
private boolean forceContentType = DEFAULT_FORCE_CONTENT_TYPE;
private String encoding;
private boolean forceEncoding = DEFAULT_FORCE_ENCODING;
private boolean ignoreConnectionEncoding = DEFAULT_IGNORE_CONNECTION_ENCODING;
private Map<String, String[]> headerNameValues;
private String forwardHeaders;
private XMLUtils.ParserConfiguration parserConfiguration = null;
private boolean handleLexical = DEFAULT_HANDLE_LEXICAL;
private String mode;
private boolean cacheUseLocalCache = DEFAULT_CACHE_USE_LOCAL_CACHE;
private boolean enableConditionalGET = DEFAULT_ENABLE_CONDITIONAL_GET;
private String username;
private String password;
private String domain;
private boolean preemptiveAuthentication = DEFAULT_PREEMPTIVE_AUTHENTICATION;
private TidyConfig tidyConfig;
public Config(URL url) {
this.url = url;
this.parserConfiguration = XMLUtils.ParserConfiguration.PLAIN;
this.tidyConfig = new TidyConfig(null);
}
public Config(URL url, boolean handleXInclude) {
this.url = url;
this.parserConfiguration = new XMLUtils.ParserConfiguration(DEFAULT_VALIDATING, handleXInclude, DEFAULT_EXTERNAL_ENTITIES);
this.tidyConfig = new TidyConfig(null);
}
public Config(URL url, String contentType, boolean forceContentType) {
this(url);
this.forceContentType = true;
this.contentType = contentType;
this.forceContentType = forceContentType;
this.tidyConfig = new TidyConfig(null);
}
public Config(URL url, String contentType, boolean forceContentType, String encoding, boolean forceEncoding,
boolean ignoreConnectionEncoding, XMLUtils.ParserConfiguration parserConfiguration,
boolean handleLexical, String mode, Map<String, String[]> headerNameValues, String forwardHeaders,
boolean cacheUseLocalCache, boolean enableConditionalGET, String username, String password,
boolean preemptiveAuthentication, String domain, TidyConfig tidyConfig) {
this.url = url;
this.contentType = contentType;
this.forceContentType = forceContentType;
this.encoding = encoding;
this.forceEncoding = forceEncoding;
this.ignoreConnectionEncoding = ignoreConnectionEncoding;
this.headerNameValues = headerNameValues;
this.forwardHeaders = forwardHeaders;
this.parserConfiguration = parserConfiguration;
this.handleLexical = handleLexical;
this.mode = mode;
// Local cache required for conditional GET
this.cacheUseLocalCache = cacheUseLocalCache || enableConditionalGET;
// NOTE: Hard to handle this if XInclude is enabled as we would need to conditional-GET all dependencies,
// and then cache all individually-included documents. Or, store the non-XInclude-processed document in
// cache. Either way, it's complicated. So we disable conditional GET if XInclude is enabled for now. This
// could be easier if we had a real HTTP client document cache.
this.enableConditionalGET = enableConditionalGET && ! parserConfiguration.handleXInclude;
// Authentication
this.username = username;
this.password = password;
this.domain = domain;
this.preemptiveAuthentication = preemptiveAuthentication;
this.tidyConfig = tidyConfig;
}
public URL getURL() {
return url;
}
public String getContentType() {
return contentType;
}
public boolean isForceContentType() {
return forceContentType;
}
public String getEncoding() {
return encoding;
}
public boolean isForceEncoding() {
return forceEncoding;
}
public boolean isIgnoreConnectionEncoding() {
return ignoreConnectionEncoding;
}
public TidyConfig getTidyConfig() {
return tidyConfig;
}
public XMLUtils.ParserConfiguration getParserConfiguration() {
return parserConfiguration;
}
public boolean isHandleLexical() {
return handleLexical;
}
public String getMode() {
return mode;
}
public Map<String, String[]> getHeaderNameValues() {
return headerNameValues;
}
public String getForwardHeaders() {
return forwardHeaders;
}
public boolean isCacheUseLocalCache() {
return cacheUseLocalCache;
}
public boolean isEnableConditionalGET() {
return enableConditionalGET;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getDomain() {
return domain;
}
public boolean isPreemptiveAuthentication() {
return preemptiveAuthentication;
}
@Override
public String toString() {
return "[" + getURL().toExternalForm() + "|" + getContentType() + "|" + getEncoding() + "|" + parserConfiguration.getKey() + "|" + isHandleLexical() + "|" + isForceContentType()
+ "|" + isForceEncoding() + "|" + isIgnoreConnectionEncoding() + "|" + getUsername() + "|" + getPassword() + "|" + isPreemptiveAuthentication() + "|" + getDomain()
+ "|" + tidyConfig + "]";
}
}
private static class ConfigURIReferences {
public ConfigURIReferences(Config config) {
this.config = config;
}
public Config config;
public List<URIProcessorOutputImpl.URIReference> uriReferences;
}
@Override
public ProcessorOutput createOutput(final String name) {
final ProcessorOutput output = new ProcessorOutputImpl(URLGenerator.this, name) {
public void readImpl(PipelineContext pipelineContext, XMLReceiver xmlReceiver) {
makeSureStateIsSet(pipelineContext);
// Read config input into a URL, cache if possible
final ConfigURIReferences configURIReferences = URLGenerator.this.localConfigURIReferences != null ? localConfigURIReferences :
readCacheInputAsObject(pipelineContext, getInputByName(INPUT_CONFIG), new CacheableInputReader<ConfigURIReferences>() {
public ConfigURIReferences read(PipelineContext context, ProcessorInput input) {
final Element configElement = readInputAsDOM4J(context, input).getRootElement();
// Processor location data
final LocationData locationData = URLGenerator.this.getLocationData();
// Shortcut if the url is direct child of config
{
final String url = configElement.getTextTrim();
if (url != null && !url.equals("")) {
// Legacy, don't even care about handling relative URLs
return new ConfigURIReferences(new Config(URLFactory.createURL(url)));
}
}
// We have the /config/url syntax
final String url = XPathUtils.selectStringValueNormalize(configElement, "/config/url");
if (url == null) {
throw new ValidationException("URL generator found null URL for config:\n" + Dom4jUtils.domToString(configElement), locationData);
}
// Get content-type
final String contentType = XPathUtils.selectStringValueNormalize(configElement, "/config/content-type");
final boolean forceContentType = ProcessorUtils.selectBooleanValue(configElement, "/config/force-content-type", DEFAULT_FORCE_CONTENT_TYPE);
if (forceContentType && (contentType == null || contentType.equals("")))
throw new ValidationException("The force-content-type element requires a content-type element.", locationData);
// Get encoding
final String encoding = XPathUtils.selectStringValueNormalize(configElement, "/config/encoding");
final boolean forceEncoding = ProcessorUtils.selectBooleanValue(configElement, "/config/force-encoding", DEFAULT_FORCE_ENCODING);
final boolean ignoreConnectionEncoding = ProcessorUtils.selectBooleanValue(configElement, "/config/ignore-connection-encoding", DEFAULT_IGNORE_CONNECTION_ENCODING);
if (forceEncoding && (encoding == null || encoding.equals("")))
throw new ValidationException("The force-encoding element requires an encoding element.", locationData);
// Get headers
Map<String, String[]> headerNameValues = null;
for (Object o: configElement.selectNodes("/config/header")) {
final Element currentHeaderElement = (Element) o;
final String currentHeaderName = currentHeaderElement.element("name").getStringValue();
final String currentHeaderValue = currentHeaderElement.element("value").getStringValue();
if (headerNameValues == null) {
// Lazily create collections
headerNameValues = new LinkedHashMap<String, String[]>();
}
headerNameValues.put(currentHeaderName, new String[]{currentHeaderValue});
}
final String forwardHeaders; {
// Get from configuration first, otherwise use global default
final org.dom4j.Node configForwardHeaders = XPathUtils.selectSingleNode(configElement, "/config/forward-headers");
forwardHeaders = configForwardHeaders != null ? XPathUtils.selectStringValue(configForwardHeaders, ".") : Connection.getForwardHeaders();
}
// Validation setting: local, then properties, then hard-coded default
final boolean defaultValidating = getPropertySet().getBoolean(VALIDATING_PROPERTY, DEFAULT_VALIDATING);
final boolean validating = ProcessorUtils.selectBooleanValue(configElement, "/config/validating", defaultValidating);
// XInclude handling
final boolean defaultHandleXInclude = getPropertySet().getBoolean(HANDLE_XINCLUDE_PROPERTY, DEFAULT_HANDLE_XINCLUDE);
final boolean handleXInclude = ProcessorUtils.selectBooleanValue(configElement, "/config/handle-xinclude", defaultHandleXInclude);
// External entities
final boolean externalEntities = ProcessorUtils.selectBooleanValue(configElement, "/config/external-entities", DEFAULT_EXTERNAL_ENTITIES);
final boolean defaultHandleLexical = getPropertySet().getBoolean(HANDLE_LEXICAL_PROPERTY, DEFAULT_HANDLE_LEXICAL);
final boolean handleLexical = ProcessorUtils.selectBooleanValue(configElement, "/config/handle-lexical", defaultHandleLexical);
// Output mode
final String mode = XPathUtils.selectStringValueNormalize(configElement, "/config/mode");
// Cache control
final boolean cacheUseLocalCache = ProcessorUtils.selectBooleanValue(configElement, "/config/cache-control/use-local-cache", DEFAULT_CACHE_USE_LOCAL_CACHE);
final boolean enableConditionalGET = ProcessorUtils.selectBooleanValue(configElement, "/config/cache-control/conditional-get", DEFAULT_ENABLE_CONDITIONAL_GET);
// Authentication
final org.dom4j.Node configAuthentication = XPathUtils.selectSingleNode(configElement, "/config/authentication");
final String username = configAuthentication == null ? null : XPathUtils.selectStringValue(configAuthentication, "username");
final String password = configAuthentication == null ? null : XPathUtils.selectStringValue(configAuthentication, "password");
final boolean preemptiveAuthentication = ProcessorUtils.selectBooleanValue(configElement, "/config/authentication/preemptive", DEFAULT_PREEMPTIVE_AUTHENTICATION);
final String domain = configAuthentication == null ? null : XPathUtils.selectStringValue(configAuthentication, "domain");
// Get Tidy config (will only apply if content-type is text/html)
final TidyConfig tidyConfig = new TidyConfig(XPathUtils.selectSingleNode(configElement, "/config/tidy-options"));
// Create configuration object
// Use location data if present so that relative URLs can be supported
// NOTE: We check whether there is a protocol, because we have
// some Java location data which are NOT to be interpreted as
// base URIs
final URL fullURL = (locationData != null && locationData.getSystemID() != null && NetUtils.urlHasProtocol(locationData.getSystemID()))
? URLFactory.createURL(locationData.getSystemID(), url)
: URLFactory.createURL(url);
// Create configuration
final Config config = new Config(fullURL, contentType, forceContentType, encoding, forceEncoding,
ignoreConnectionEncoding, new XMLUtils.ParserConfiguration(validating, handleXInclude, externalEntities), handleLexical, mode,
headerNameValues, forwardHeaders,
cacheUseLocalCache, enableConditionalGET,
username, password, preemptiveAuthentication, domain,
tidyConfig);
if (logger.isDebugEnabled())
logger.debug("Read configuration: " + config.toString());
return new ConfigURIReferences(config);
}
});
try {
// Never accept a null URL
if (configURIReferences.config.getURL() == null)
throw new OXFException("Missing configuration.");
// We use the same validity as for the output
final boolean isUseLocalCache = configURIReferences.config.isCacheUseLocalCache();
final CacheKey localCacheKey;
final Object localCacheValidity;
if (isUseLocalCache) {
localCacheKey = new InternalCacheKey(URLGenerator.this, "urlDocument", configURIReferences.config.toString());
localCacheValidity = getValidityImpl(pipelineContext);
} else {
localCacheKey = null;
localCacheValidity = null;
}
// Decide whether to use read from the special oxf: handler or the generic URL handler
final URLGeneratorState state = (URLGenerator.URLGeneratorState) URLGenerator.this.getState(pipelineContext);
if (state.getDocument() != null) {
// Document was found when retrieving validity in conditional get
// NOTE: This only happens if isCacheUseLocalCache() == true
// NOTE: Document was re-added to cache in getValidityImpl()
state.getDocument().replay(xmlReceiver);
} else {
final Object cachedResource = (localCacheKey == null) ? null : ObjectCache.instance().findValid(localCacheKey, localCacheValidity);
if (cachedResource != null) {
// Just replay the cached resource
((SAXStore) cachedResource).replay(xmlReceiver);
} else {
final ResourceHandler handler = state.ensureMainResourceHandler(pipelineContext, configURIReferences.config);
try {
// We need to read the resource
// Find content-type to use. If the config says to force the
// content-type, we use the content-type provided by the user.
// Otherwise, we give the priority to the content-type provided by
// the connection, then the content-type provided by the user, then
// we use the default content-type (XML). The user will have to
// provide a content-type for example to read HTML documents with
// the file: protocol.
String contentType;
if (configURIReferences.config.isForceContentType()) {
contentType = configURIReferences.config.getContentType();
} else {
contentType = handler.getResourceMediaType();
if (contentType == null)
contentType = configURIReferences.config.getContentType();
if (contentType == null)
contentType = ProcessorUtils.DEFAULT_CONTENT_TYPE;
}
// Get and cache validity as the handler is open, as validity is likely to be used later
// again for caching reasons
final Long validity = (Long) getHandlerValidity(pipelineContext, configURIReferences.config, configURIReferences.config.getURL(), handler);
// Create store for caching if necessary
final XMLReceiver output = isUseLocalCache ? new SAXStore(xmlReceiver) : xmlReceiver;
// Handle mode
String mode = configURIReferences.config.getMode();
if (mode == null) {
// Mode is inferred from content-type
if (ProcessorUtils.HTML_CONTENT_TYPE.equals(contentType))
mode = "html";
else if (XMLUtils.isXMLMediatype(contentType))
mode = "xml";
else if (XMLUtils.isTextOrJSONContentType(contentType))
mode = "text";
else
mode = "binary";
}
// Read resource
if (mode.equals("html")) {
// HTML mode
handler.readHTML(output);
configURIReferences.uriReferences = null;
} else if (mode.equals("xml")) {
// XML mode
final URIProcessorOutputImpl.URIReferences uriReferences = new URIProcessorOutputImpl.URIReferences();
handler.readXML(pipelineContext, output, uriReferences);
configURIReferences.uriReferences = uriReferences.getReferences();
} else if (mode.equals("text")) {
// Text mode
handler.readText(output, contentType, validity);
configURIReferences.uriReferences = null;
} else {
// Binary mode
handler.readBinary(output, contentType, validity);
configURIReferences.uriReferences = null;
}
// Cache the resource if requested but only if there is not a failure status code. It
// seems reasonable to follow the semantic of the web and to never cache unsuccessful
// responses.
if (isUseLocalCache && ! handler.isFailureStatusCode()) {
// Make sure SAXStore loses its reference on its output so that we don't clutter the cache
((SAXStore) output).setXMLReceiver(null);
// Add to cache
ObjectCache.instance().add(localCacheKey, localCacheValidity, output);
}
} finally {
handler.destroy();
}
}
}
} catch (SAXParseException spe) {
throw new ValidationException(spe.getMessage(), new LocationData(spe));
} catch (ValidationException e) {
final LocationData locationData = e.getLocationData();
// The system id may not be set
if (locationData == null || locationData.getSystemID() == null)
throw ValidationException.wrapException(e, new LocationData(configURIReferences.config.getURL().toExternalForm(), -1, -1));
else
throw e;
} catch (OXFException e) {
throw e;
} catch (Exception e) {
throw new ValidationException(e, new LocationData(configURIReferences.config.getURL().toExternalForm(), -1, -1));
}
}
@Override
public OutputCacheKey getKeyImpl(PipelineContext pipelineContext) {
makeSureStateIsSet(pipelineContext);
final ConfigURIReferences configURIReferences = getConfigURIReferences(pipelineContext);
if (configURIReferences == null) {
return null;
}
final int keyCount = 1 + ((localConfigURIReferences == null) ? 1 : 0)
+ ((configURIReferences.uriReferences != null) ? configURIReferences.uriReferences.size() : 0);
final CacheKey[] outputKeys = new CacheKey[keyCount];
// Handle config if read as input
int keyIndex = 0;
if (localConfigURIReferences == null) {
KeyValidity configKeyValidity = getInputKeyValidity(pipelineContext, INPUT_CONFIG);
if (configKeyValidity == null) {
return null;
}
outputKeys[keyIndex++] = configKeyValidity.key;
}
// Handle main document and config
outputKeys[keyIndex++] = new SimpleOutputCacheKey(getProcessorClass(), name, configURIReferences.config.toString());
// Handle dependencies if any
if (configURIReferences.uriReferences != null) {
for (URIProcessorOutputImpl.URIReference uriReference : configURIReferences.uriReferences) {
outputKeys[keyIndex++] = new InternalCacheKey(URLGenerator.this, "urlReference", URLFactory.createURL(uriReference.context, uriReference.spec).toExternalForm());
}
}
return new CompoundOutputCacheKey(getProcessorClass(), name, outputKeys);
}
@Override
public Object getValidityImpl(PipelineContext pipelineContext) {
makeSureStateIsSet(pipelineContext);
ConfigURIReferences configURIReferences = getConfigURIReferences(pipelineContext);
if (configURIReferences == null)
return null;
List<Object> validities = new ArrayList<Object>();
// Handle config if read as input
if (localConfigURIReferences == null) {
KeyValidity configKeyValidity = getInputKeyValidity(pipelineContext, INPUT_CONFIG);
if (configKeyValidity == null)
return null;
validities.add(configKeyValidity.validity);
}
// Handle main document and config
final URLGeneratorState state = (URLGenerator.URLGeneratorState) URLGenerator.this.getState(pipelineContext);
final ResourceHandler resourceHandler = state.ensureMainResourceHandler(pipelineContext, configURIReferences.config);
validities.add(getHandlerValidity(pipelineContext, configURIReferences.config, configURIReferences.config.getURL(), resourceHandler));
// Handle dependencies if any
if (configURIReferences.uriReferences != null) {
for (URIProcessorOutputImpl.URIReference uriReference: configURIReferences.uriReferences) {
validities.add(getHandlerValidity(pipelineContext, configURIReferences.config, URLFactory.createURL(uriReference.context, uriReference.spec), null));
}
}
return validities;
}
private Long getHandlerValidity(PipelineContext pipelineContext, Config config, URL url, ResourceHandler handler) {
final URLGeneratorState state = (URLGenerator.URLGeneratorState) URLGenerator.this.getState(pipelineContext);
final String urlString = url.toExternalForm();
if (state.isLastModifiedSet(urlString)) {
// Found value in state cache
return state.getLastModified(urlString);
} else {
// Get value and cache it in state
try {
final Long validity;
if (handler == null) {
// Include dependency
// Create handler right here
handler = OXFHandler.PROTOCOL.equals(url.getProtocol())
? new OXFResourceHandler(new Config(url)) // Should use full config so that headers are forwarded?
: new URLResourceHandler(pipelineContext, new Config(url));// Should use full config so that headers are forwarded?
try {
// FIXME: this can potentially be very slow with some URLs like HTTP URLs. We try to
// optimized this by keeping the URLConnection for the main document, but dependencies may
// cause multiple requests to the same URL.
validity = handler.getValidity();
} finally {
// Destroy handler
handler.destroy();
}
} else {
// Main handler
// Try to see what we have in cache
final CacheEntry cacheEntry;
if (config.isEnableConditionalGET()) {
// NOTE: This *could* be transparently handled by HttpClient cache if configured properly:
// Although, this would only cache the bytes, and probably not provide us with a
// readily-parsed SAXStore.
final CacheKey localCacheKey = new InternalCacheKey(URLGenerator.this, "urlDocument", config.toString());
cacheEntry = ObjectCache.instance().findAny(localCacheKey);
} else {
cacheEntry = null;
}
if (cacheEntry != null) {
// Found some entry in cache for the key
final long lastModified = findLastModified(cacheEntry.validity);
// This returns the validity and, possibly, stores the document in the state
validity = handler.getConditional(lastModified);
if (handler.getConnectionStatusCode() == 304) {
// The server responded that the resource hasn't changed
// Update the entry in cache
ObjectCache.instance().add(cacheEntry.key, lastModified, cacheEntry.cacheable);
// Remember the document for the rest of this request
state.setDocument((SAXStore) cacheEntry.cacheable);
}
} else {
validity = handler.getValidity();
}
}
state.setLastModified(urlString, validity);
return validity;
} catch (Exception e) {
// If the file no longer exists, for example, we don't want to throw, just to invalidate
// An exception will be thrown if necessary when the document is actually read
return null;
}
}
}
private ConfigURIReferences getConfigURIReferences(PipelineContext context) {
// Check if config is external
if (localConfigURIReferences != null)
return localConfigURIReferences;
// Make sure the config input is cacheable
final KeyValidity keyValidity = getInputKeyValidity(context, INPUT_CONFIG);
if (keyValidity == null) {
return null;
}
// Try to find resource manager key in cache
final ConfigURIReferences config = (ConfigURIReferences) ObjectCache.instance().findValid(keyValidity.key, keyValidity.validity);
if (logger.isDebugEnabled()) {
if (config != null)
logger.debug("Config found: " + config.toString());
else
logger.debug("Config not found");
}
return config;
}
};
addOutput(name, output);
return output;
}
private interface ResourceHandler {
Long getValidity() throws IOException;
Long getConditional(Long lastModified) throws IOException;
String getResourceMediaType() throws IOException;
String getConnectionEncoding() throws IOException;
int getConnectionStatusCode() throws IOException;
boolean isFailureStatusCode() throws IOException;
void destroy() throws IOException;
void readHTML(XMLReceiver xmlReceiver) throws IOException;
void readText(ContentHandler output, String contentType, Long lastModified) throws IOException;
void readXML(PipelineContext pipelineContext, XMLReceiver xmlReceiver, URIProcessorOutputImpl.URIReferences uriReferences) throws IOException;
void readBinary(ContentHandler output, String contentType, Long lastModified) throws IOException;
}
private static class OXFResourceHandler implements ResourceHandler {
private Config config;
private String resourceManagerKey;
private InputStream inputStream;
public OXFResourceHandler(Config config) {
this.config = config;
}
public String getResourceMediaType() throws IOException {
// We generally don't know the "connection" content-type
return null;
}
public String getConnectionEncoding() throws IOException {
// We generally don't know the "connection" encoding
// NOTE: We could know, if the underlying protocol was for example HTTP. But we may
// want to abstract that anyway, so that the behavior is consistent whatever the sandbox
return null;
}
public int getConnectionStatusCode() throws IOException {
return -1;
}
public boolean isFailureStatusCode() throws IOException {
return false;
}
public Long getValidity() throws IOException {
getKey();
if (logger.isDebugEnabled())
logger.debug("OXF Protocol: Using ResourceManager for key " + getKey());
long result = ResourceManagerWrapper.instance().lastModified(getKey(), false);
// Zero and negative values often have a special meaning, make sure to normalize here
return (result <= 0) ? null : result;
}
public Long getConditional(Long lastModified) throws IOException {
return getValidity();
}
public void destroy() throws IOException {
if (inputStream != null) {
inputStream.close();
}
}
private String getExternalEncoding() throws IOException {
if (config.isForceEncoding())
return config.getEncoding();
String connectionEncoding = getConnectionEncoding();
if (!config.isIgnoreConnectionEncoding() && connectionEncoding != null)
return connectionEncoding;
String userEncoding = config.getEncoding();
if (userEncoding != null)
return userEncoding;
return null;
}
public void readHTML(XMLReceiver xmlReceiver) throws IOException {
inputStream = ResourceManagerWrapper.instance().getContentAsStream(getKey());
URLResourceHandler.readHTML(inputStream, config.getTidyConfig(), getExternalEncoding(), xmlReceiver);
}
public void readText(ContentHandler output, String contentType, Long lastModified) throws IOException {
inputStream = ResourceManagerWrapper.instance().getContentAsStream(getKey());
ProcessorUtils.readText(inputStream, getExternalEncoding(), output, contentType, lastModified, getConnectionStatusCode());
}
public void readXML(PipelineContext pipelineContext, XMLReceiver xmlReceiver, URIProcessorOutputImpl.URIReferences uriReferences) throws IOException {
final XMLUtils.ParserConfiguration parserConfiguration = new XMLUtils.ParserConfiguration(config.getParserConfiguration(), uriReferences);
if (getExternalEncoding() != null) {
// The encoding is set externally, either forced by the user, or set by the connection
inputStream = ResourceManagerWrapper.instance().getContentAsStream(getKey());
XMLUtils.readerToSAX(new InputStreamReader(inputStream, getExternalEncoding()), config.getURL().toExternalForm(),
xmlReceiver, parserConfiguration, config.isHandleLexical());
} else {
// Regular case, the resource manager does the job and autodetects the encoding
ResourceManagerWrapper.instance().getContentAsSAX(getKey(),
xmlReceiver, parserConfiguration, config.isHandleLexical());
}
}
public void readBinary(ContentHandler output, String contentType, Long lastModified) throws IOException {
inputStream = ResourceManagerWrapper.instance().getContentAsStream(getKey());
ProcessorUtils.readBinary(inputStream, output, contentType, lastModified, getConnectionStatusCode());
}
private String getKey() {
if (resourceManagerKey == null)
resourceManagerKey = config.getURL().getFile();
return resourceManagerKey;
}
}
private static class URLResourceHandler implements ResourceHandler {
private PipelineContext pipelineContext;
private Config config;
private ConnectionResult connectionResult;
private InputStream inputStream;
public URLResourceHandler(PipelineContext pipelineContext, Config config) {
this.pipelineContext = pipelineContext;
this.config = config;
}
public String getResourceMediaType() throws IOException {
// Return null for file protocol, as it returns incorrect content types
if ("file".equals(config.getURL().getProtocol()))
return null;
// Otherwise, try URLConnection
openConnection();
return connectionResult.getResponseMediaType();
}
public String getConnectionEncoding() throws IOException {
// Return null for file protocol, as it returns incorrect content types
if ("file".equals(config.getURL().getProtocol()))
return null;
// Otherwise, try URLConnection
openConnection();
return NetUtils.getContentTypeCharset(connectionResult.getResponseContentType());
}
public int getConnectionStatusCode() throws IOException {
// Return -1 for file protocol, as it returns nothing significant
if ("file".equals(config.getURL().getProtocol()))
return -1;
// Otherwise, try URLConnection
openConnection();
return connectionResult.statusCode;
}
public Long getValidity() throws IOException {
openConnection();
return isFailureStatusCode() ? null : connectionResult.getLastModified();
}
public Long getConditional(Long lastModified) throws IOException {
openConnection(lastModified);
return getValidity();
}
public void destroy() throws IOException {
// Make sure the connection is closed because when
// getting the last modified date, the stream is
// actually opened. When using the file: protocol, the
// file can be locked on disk.
if (inputStream != null) {
inputStream.close();
}
// Just in case - although URLResourceHandler should be gc'ed quickly
pipelineContext = null;
config = null;
connectionResult = null;
inputStream = null;
}
private void openConnection() throws IOException {
openConnection(null);
}
private void openConnection(Long lastModified) throws IOException {
if (connectionResult == null) {
// TODO: pass logging callback
final Map<String, String[]> newHeaders;
if (lastModified != null) {
// A conditional GET is requested
newHeaders = new HashMap<String, String[]>();
if (config.getHeaderNameValues() != null)
newHeaders.putAll(config.getHeaderNameValues());
newHeaders.put("If-Modified-Since", new String[] { DateUtils.RFC1123Date().print(lastModified) });
} else {
// Regular GET
newHeaders = config.getHeaderNameValues();
}
final Connection.Credentials credentials = config.getUsername() == null ?
null :
new Connection.Credentials(config.getUsername(), config.getPassword(), config.isPreemptiveAuthentication() ? "true" : "false", config.getDomain());
final URL url = config.getURL();
final scala.collection.immutable.Map<String, String[]> headers =
Connection.jBuildConnectionHeaders(url.getProtocol(), credentials, newHeaders, config.getForwardHeaders(), indentedLogger);
connectionResult =
Connection.jApply("GET", url, credentials, null, headers, true, false, indentedLogger).connect(true);
inputStream =
connectionResult.getResponseInputStream(); // empty stream if conditional GET succeeded
}
}
private String getExternalEncoding() throws IOException {
if (config.isForceEncoding())
return config.getEncoding();
String connectionEncoding = getConnectionEncoding();
if (!config.isIgnoreConnectionEncoding() && connectionEncoding != null)
return connectionEncoding;
String userEncoding = config.getEncoding();
if (userEncoding != null)
return userEncoding;
return null;
}
public void readHTML(XMLReceiver xmlReceiver) throws IOException {
openConnection();
checkStatusCode();
readHTML(inputStream, config.getTidyConfig(), getExternalEncoding(), xmlReceiver);
}
public void readText(ContentHandler output, String contentType, Long lastModified) throws IOException {
openConnection();
ProcessorUtils.readText(inputStream, getExternalEncoding(), output, contentType, lastModified, getConnectionStatusCode());
}
public void readBinary(ContentHandler output, String contentType, Long lastModified) throws IOException {
openConnection();
ProcessorUtils.readBinary(inputStream, output, contentType, lastModified, getConnectionStatusCode());
}
public void readXML(PipelineContext pipelineContext, XMLReceiver xmlReceiver, URIProcessorOutputImpl.URIReferences uriReferences) throws IOException {
openConnection();
checkStatusCode();
final XMLUtils.ParserConfiguration parserConfiguration = new XMLUtils.ParserConfiguration(config.getParserConfiguration(), uriReferences);
try {
final XMLReader reader = XMLUtils.newXMLReader(parserConfiguration);
reader.setContentHandler(xmlReceiver);
// TODO: lexical handler?
final InputSource inputSource;
if (getExternalEncoding() != null) {
// The encoding is set externally, either force by the user, or set by the connection
inputSource = new InputSource(new InputStreamReader(inputStream, getExternalEncoding()));
} else {
// This is the regular case where the XML parser autodetects the encoding
inputSource = new InputSource(inputStream);
}
inputSource.setSystemId(config.getURL().toExternalForm());
reader.parse(inputSource);
} catch (SAXException e) {
throw new OXFException(e);
}
}
public boolean isFailureStatusCode() throws IOException {
// NOTE: We accept -1 internally to indicate we don't have an actual status code
final int statusCode = getConnectionStatusCode();
return statusCode > 0 && ! NetUtils.isSuccessCode(statusCode);
}
private void checkStatusCode() throws IOException {
if (isFailureStatusCode())
throw new HttpStatusCodeException(getConnectionStatusCode(), Option.<String>apply(config.getURL().toExternalForm()), Option.<Throwable>apply(null));
}
public static void readHTML(InputStream is, TidyConfig tidyConfig, String encoding, XMLReceiver output) {
Tidy tidy = new Tidy();
// tidy.setOnlyErrors(false);
tidy.setShowWarnings(tidyConfig.isShowWarnings());
tidy.setQuiet(tidyConfig.isQuiet());
// Set encoding
// If the encoding is null, we get a default
tidy.setInputEncoding(TidyConfig.getTidyEncoding(encoding));
// Parse and output to SAXResult
TransformerUtils.sourceToSAX(new DOMSource(tidy.parseDOM(is, null)), output);
}
}
/**
* This resource handler reads from System.in...
*/
private static class SystemResourceHandler implements ResourceHandler {
private Config config;
public SystemResourceHandler(Config config) {
this.config = config;
}
public String getResourceMediaType() throws IOException {
// We generally don't know the "connection" content-type
return null;
}
public String getConnectionEncoding() throws IOException {
// We generally don't know the "connection" encoding
// NOTE: We could know, if the underlying protocol was for example HTTP. But we may
// want to abstract that anyway, so that the behavior is consistent whatever the sandbox
return null;
}
public int getConnectionStatusCode() throws IOException {
return -1;
}
public boolean isFailureStatusCode() throws IOException {
return false;
}
public Long getValidity() throws IOException {
return null;
}
public Long getConditional(Long lastModified) throws IOException {
return getValidity();
}
public void destroy() throws IOException {
}
private String getExternalEncoding() throws IOException {
if (config.isForceEncoding())
return config.getEncoding();
String connectionEncoding = getConnectionEncoding();
if (!config.isIgnoreConnectionEncoding() && connectionEncoding != null)
return connectionEncoding;
String userEncoding = config.getEncoding();
if (userEncoding != null)
return userEncoding;
return java.nio.charset.Charset.defaultCharset().name();
}
public void readHTML(XMLReceiver xmlReceiver) throws IOException {
URLResourceHandler.readHTML(System.in, config.getTidyConfig(), getExternalEncoding(), xmlReceiver);
}
public void readText(ContentHandler output, String contentType, Long lastModified) throws IOException {
ProcessorUtils.readText(System.in, getExternalEncoding(), output, contentType, lastModified, getConnectionStatusCode());
}
public void readXML(PipelineContext pipelineContext, XMLReceiver xmlReceiver, URIProcessorOutputImpl.URIReferences uriReferences) throws IOException {
final XMLUtils.ParserConfiguration parserConfiguration = new XMLUtils.ParserConfiguration(config.getParserConfiguration(), uriReferences);
if (getExternalEncoding() != null) {
// The encoding is set externally, either forced by the user, or set by the connection
XMLUtils.readerToSAX(new InputStreamReader(System.in, getExternalEncoding()), config.getURL().toExternalForm(),
xmlReceiver, parserConfiguration, config.isHandleLexical());
} else {
// Regular case, the resource manager does the job and autodetects the encoding
ResourceManagerWrapper.instance().getContentAsSAX(getKey(),
xmlReceiver, parserConfiguration, config.isHandleLexical());
}
}
public void readBinary(ContentHandler output, String contentType, Long lastModified) throws IOException {
ProcessorUtils.readBinary(System.in, output, contentType, lastModified, getConnectionStatusCode());
}
private String getKey() {
return "system:in";
}
}
// The idea of URLGeneratorState is that, during a pipeline execution with a given PipelineContext, there is typically:
// o a call to getValidity()
// o followed by a call to read()
// In order to avoid dereferencing the URL twice, the handler is stored in the state so it can be accessed by read().
private static class URLGeneratorState {
private ResourceHandler mainResourceHandler;
private Map<String, Object> map;
private SAXStore document;
public void setLastModified(String urlString, Long lastModified) {
if (map == null)
map = new HashMap<String, Object>();
map.put(urlString, lastModified == null ? "" : lastModified);
}
public boolean isLastModifiedSet(String urlString) {
return map != null && map.get(urlString) != null;
}
public Long getLastModified(String urlString) {
final Object result = map.get(urlString);
return (result instanceof String) ? null : (Long) result;
}
public ResourceHandler ensureMainResourceHandler(PipelineContext pipelineContext, Config config) {
if (mainResourceHandler == null) {
// Create and remember handler
mainResourceHandler = OXFHandler.PROTOCOL.equals(config.getURL().getProtocol()) ? new OXFResourceHandler(config)
: SystemHandler.PROTOCOL.equals(config.getURL().getProtocol()) ? new SystemResourceHandler(config)
: new URLResourceHandler(pipelineContext, config);
// Make sure it is destroyed when the pipeline ends at the latest
pipelineContext.addContextListener(new PipelineContext.ContextListener() {
public void contextDestroyed(boolean success) {
try {
mainResourceHandler.destroy();
} catch (IOException e) {
logger.error("Exception caught while destroying ResourceHandler", e);
}
}
});
}
return mainResourceHandler;
}
public void setDocument(SAXStore document) {
this.document = document;
}
public SAXStore getDocument() {
return document;
}
}
private void makeSureStateIsSet(PipelineContext pipelineContext) {
if (!hasState(pipelineContext))
setState(pipelineContext, new URLGeneratorState());
}
@Override
public void reset(PipelineContext pipelineContext) {
setState(pipelineContext, new URLGeneratorState());
}
}
|
package com.kentender.nifi.nifi_opcua_bundle;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.nifi.annotation.behavior.ReadsAttribute;
import org.apache.nifi.annotation.behavior.ReadsAttributes;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.io.OutputStreamCallback;
import org.apache.nifi.processor.util.StandardValidators;
import org.opcfoundation.ua.builtintypes.ExpandedNodeId;
import org.opcfoundation.ua.builtintypes.NodeId;
import org.opcfoundation.ua.builtintypes.UnsignedInteger;
import org.opcfoundation.ua.core.Identifiers;
import com.kentender.nifi.nifi_opcua_services.OPCUAService;
@Tags({"OPC", "OPCUA", "UA"})
@CapabilityDescription("Retrieves the namespace from an OPC UA server")
@SeeAlso({})
@ReadsAttributes({@ReadsAttribute(attribute="", description="")})
@WritesAttributes({@WritesAttribute(attribute="", description="")})
public class GetNodeIds extends AbstractProcessor {
private static String starting_node = null;
private static String print_indentation = "No";
private static String remove_opc_string = "No";
private static Integer max_recursiveDepth;
private static Integer max_reference_per_node;
public static final PropertyDescriptor OPCUA_SERVICE = new PropertyDescriptor.Builder()
.name("OPC UA Service")
.description("Specifies the OPC UA Service that can be used to access data")
.required(true)
.identifiesControllerService(OPCUAService.class)
.build();
public static final PropertyDescriptor STARTING_NODE = new PropertyDescriptor
.Builder().name("Starting Nodes")
.description("From what node should Nifi begin browsing the node tree. Default is the root node. Seperate multiple nodes with a comma (,)")
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor RECURSIVE_DEPTH = new PropertyDescriptor
.Builder().name("Recursive Depth")
.description("Maximum depth from the starting node to read, Default is 0")
.required(true)
.addValidator(StandardValidators.INTEGER_VALIDATOR)
.build();
public static final PropertyDescriptor PRINT_INDENTATION = new PropertyDescriptor
.Builder().name("Print Indentation")
.description("Should Nifi add indentation to the output text")
.required(true)
.allowableValues("No", "Yes")
.defaultValue("No")
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor REMOVE_OPC_STRING = new PropertyDescriptor
.Builder().name("Remove OPC String")
.description("Should remove OPCfoundation string from the list")
.required(true)
.allowableValues("No", "Yes")
.defaultValue("No")
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor MAX_REFERENCE_PER_NODE = new PropertyDescriptor
.Builder().name("Max References Per Node")
.description("The number of Reference Descriptions to pull per node query.")
.required(true)
.addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR)
.build();
public static final Relationship SUCCESS = new Relationship.Builder()
.name("Success")
.description("Successful OPC read")
.build();
public static final Relationship FAILURE = new Relationship.Builder()
.name("Failure")
.description("Failed OPC read")
.build();
private List<PropertyDescriptor> descriptors;
private Set<Relationship> relationships;
@Override
protected void init(final ProcessorInitializationContext context) {
final List<PropertyDescriptor> descriptors = new ArrayList<PropertyDescriptor>();
descriptors.add(OPCUA_SERVICE);
descriptors.add(RECURSIVE_DEPTH);
descriptors.add(STARTING_NODE);
descriptors.add(PRINT_INDENTATION);
descriptors.add(REMOVE_OPC_STRING);
descriptors.add(MAX_REFERENCE_PER_NODE);
this.descriptors = Collections.unmodifiableList(descriptors);
final Set<Relationship> relationships = new HashSet<Relationship>();
relationships.add(SUCCESS);
relationships.add(FAILURE);
this.relationships = Collections.unmodifiableSet(relationships);
}
@Override
public Set<Relationship> getRelationships() {
return this.relationships;
}
@Override
public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return descriptors;
}
@OnScheduled
public void onScheduled(final ProcessContext context) {
print_indentation = context.getProperty(PRINT_INDENTATION).getValue();
max_recursiveDepth = Integer.valueOf(context.getProperty(RECURSIVE_DEPTH).getValue());
starting_node = context.getProperty(STARTING_NODE).getValue();
remove_opc_string = context.getProperty(REMOVE_OPC_STRING).getValue();
max_reference_per_node = Integer.valueOf(context.getProperty(MAX_REFERENCE_PER_NODE).getValue());
}
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
final ComponentLog logger = getLogger();
StringBuilder stringBuilder = new StringBuilder();
// Submit to getValue
final OPCUAService opcUAService = context.getProperty(OPCUA_SERVICE)
.asControllerService(OPCUAService.class);
if(opcUAService.updateSession()){
logger.debug("Session current");
}else {
logger.debug("Session update failed");
}
// Set the starting node and parse the node tree
if ( starting_node == null) {
logger.debug("Parse the root node " + new ExpandedNodeId(Identifiers.RootFolder));
List<ExpandedNodeId> ids = new ArrayList<>();
ids.add(new ExpandedNodeId((Identifiers.RootFolder)));
stringBuilder.append(opcUAService.getNameSpace(print_indentation, max_recursiveDepth, ids,new UnsignedInteger(max_reference_per_node)));
} else {
logger.debug("Parse the result list for node " + new ExpandedNodeId(NodeId.parseNodeId(starting_node)));
List<ExpandedNodeId> ids = new ArrayList<>();
String[] splits = NodeId.parseNodeId(starting_node).toString().split(",");
for(String split : splits) {
ids.add(new ExpandedNodeId(NodeId.parseNodeId(split)));
}
stringBuilder.append(opcUAService.getNameSpace(print_indentation, max_recursiveDepth, ids,new UnsignedInteger(max_reference_per_node)));
}
// Write the results back out to a flow file
FlowFile flowFile = session.create();
if ( flowFile != null ) {
try{
flowFile = session.write(flowFile, new OutputStreamCallback() {
public void process(OutputStream out) throws IOException {
switch (remove_opc_string) {
case "Yes":{
String str = stringBuilder.toString();
String parts[] = str.split("\\r?\\n");
String outString = "";
for (int i = 0; i < parts.length; i++){
if (parts[i].startsWith("nsu")){
continue;
}
outString = outString + parts[i] + System.getProperty("line.separator");;
}
outString.trim();
out.write(outString.getBytes());
break;
}
case "No":{
out.write(stringBuilder.toString().getBytes());
break;
}
}
}
});
// Transfer data to flow file
session.transfer(flowFile, SUCCESS);
}catch (ProcessException ex) {
logger.error("Unable to process", ex);
session.transfer(flowFile, FAILURE);
}
}else{
logger.error("Flowfile is null");
session.transfer(flowFile, FAILURE);
}
}
}
|
// $Id: ParticipantGmsImpl.java,v 1.24 2007/03/13 16:23:47 belaban Exp $
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.util.Promise;
import java.util.Vector;
import java.util.Iterator;
import java.util.Collection;
import java.util.LinkedHashSet;
public class ParticipantGmsImpl extends GmsImpl {
private final Vector suspected_mbrs=new Vector(11);
private final Promise leave_promise=new Promise();
public ParticipantGmsImpl(GMS g) {
super(g);
}
public void init() throws Exception {
super.init();
suspected_mbrs.removeAllElements();
leave_promise.reset();
}
public void join(Address mbr) {
wrongMethod("join");
}
/**
* Loop: determine coord. If coord is me --> handleLeave().
* Else send handleLeave() to coord until success
*/
public void leave(Address mbr) {
Address coord;
int max_tries=3;
Object result;
leave_promise.reset();
if(mbr.equals(gms.local_addr))
leaving=true;
while((coord=gms.determineCoordinator()) != null && max_tries
if(gms.local_addr.equals(coord)) { // I'm the coordinator
gms.becomeCoordinator();
// gms.getImpl().handleLeave(mbr, false); // regular leave
gms.getImpl().leave(mbr); // regular leave
return;
}
if(log.isDebugEnabled()) log.debug("sending LEAVE request to " + coord + " (local_addr=" + gms.local_addr + ")");
sendLeaveMessage(coord, mbr);
result=leave_promise.getResult(gms.leave_timeout);
if(result != null)
break;
}
gms.becomeClient();
}
/** In case we get a different JOIN_RSP from a previous JOIN_REQ sent by us (as a client), we simply apply the
* new view if it is greater than ours
*
* @param join_rsp
*/
public void handleJoinResponse(JoinRsp join_rsp) {
View v=join_rsp.getView();
ViewId tmp_vid=v != null? v.getVid() : null;
if(tmp_vid != null && gms.view_id != null && tmp_vid.compareTo(gms.view_id) > 0) {
gms.installView(v);
}
}
public void handleLeaveResponse() {
if(leave_promise == null) {
if(log.isErrorEnabled()) log.error("leave_promise is null");
return;
}
leave_promise.setResult(Boolean.TRUE); // unblocks thread waiting in leave()
}
public void suspect(Address mbr) {
Collection emptyVector=new LinkedHashSet(0);
Collection suspected=new LinkedHashSet(1);
suspected.add(mbr);
handleMembershipChange(emptyVector, emptyVector, suspected);
}
/** Removes previously suspected member from list of currently suspected members */
public void unsuspect(Address mbr) {
if(mbr != null)
suspected_mbrs.remove(mbr);
}
public void handleMembershipChange(Collection newMembers, Collection leavingMembers, Collection suspectedMembers) {
if(suspectedMembers == null || suspectedMembers.isEmpty())
return;
for(Iterator i=suspectedMembers.iterator(); i.hasNext();) {
Address mbr=(Address)i.next();
if(!suspected_mbrs.contains(mbr))
suspected_mbrs.addElement(mbr);
}
if(log.isDebugEnabled())
log.debug("suspected members=" + suspectedMembers + ", suspected_mbrs=" + suspected_mbrs);
if(wouldIBeCoordinator()) {
if(log.isDebugEnabled())
log.debug("members are " + gms.members + ", coord=" + gms.local_addr + ": I'm the new coord !");
suspected_mbrs.removeAllElements();
gms.becomeCoordinator();
for(Iterator i=suspectedMembers.iterator(); i.hasNext();) {
Address mbr=(Address)i.next();
gms.getViewHandler().add(new GMS.Request(GMS.Request.SUSPECT, mbr, true, null));
gms.ack_collector.suspect(mbr);
}
}
}
/**
* If we are leaving, we have to wait for the view change (last msg in the current view) that
* excludes us before we can leave.
* @param new_view The view to be installed
* @param digest If view is a MergeView, digest contains the seqno digest of all members and has to
* be set by GMS
*/
public void handleViewChange(View new_view, Digest digest) {
Vector mbrs=new_view.getMembers();
if(log.isDebugEnabled()) log.debug("view=" + new_view);
suspected_mbrs.removeAllElements();
if(leaving && !mbrs.contains(gms.local_addr)) { // received a view in which I'm not member: ignore
return;
}
gms.installView(new_view, digest);
}
/* public void handleSuspect(Address mbr) {
if(mbr == null) return;
if(!suspected_mbrs.contains(mbr))
suspected_mbrs.addElement(mbr);
if(log.isDebugEnabled()) log.debug("suspected mbr=" + mbr + ", suspected_mbrs=" + suspected_mbrs);
if(wouldIBeCoordinator()) {
if(log.isDebugEnabled()) log.debug("suspected mbr=" + mbr + "), members are " +
gms.members + ", coord=" + gms.local_addr + ": I'm the new coord !");
suspected_mbrs.removeAllElements();
gms.becomeCoordinator();
// gms.getImpl().suspect(mbr);
gms.getViewHandler().add(new GMS.Request(GMS.Request.SUSPECT, mbr, true, null));
gms.ack_collector.suspect(mbr);
}
}*/
public void handleMergeRequest(Address sender, ViewId merge_id) {
// only coords handle this method; reject it if we're not coord
sendMergeRejectedResponse(sender, merge_id);
}
/**
* Determines whether this member is the new coordinator given a list of suspected members. This is
* computed as follows: the list of currently suspected members (suspected_mbrs) is removed from the current
* membership. If the first member of the resulting list is equals to the local_addr, then it is true,
* otherwise false. Example: own address is B, current membership is {A, B, C, D}, suspected members are {A,
* D}. The resulting list is {B, C}. The first member of {B, C} is B, which is equal to the
* local_addr. Therefore, true is returned.
*/
boolean wouldIBeCoordinator() {
Address new_coord;
Vector mbrs=gms.members.getMembers(); // getMembers() returns a *copy* of the membership vector
mbrs.removeAll(suspected_mbrs);
if(mbrs.size() < 1) return false;
new_coord=(Address)mbrs.elementAt(0);
return gms.local_addr.equals(new_coord);
}
void sendLeaveMessage(Address coord, Address mbr) {
Message msg=new Message(coord, null, null);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.LEAVE_REQ, mbr);
msg.putHeader(gms.getName(), hdr);
gms.getDownProtocol().down(new Event(Event.MSG, msg));
}
}
|
package org.opendaylight.bgpcep.pcep.tunnel.provider;
import static java.util.Objects.requireNonNull;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.FluentFuture;
import java.util.Dictionary;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.checkerframework.checker.lock.qual.GuardedBy;
import org.opendaylight.bgpcep.programming.spi.InstructionScheduler;
import org.opendaylight.bgpcep.topology.DefaultTopologyReference;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.tunnel.pcep.programming.rev181109.TopologyTunnelPcepProgrammingService;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class PCEPTunnelClusterSingletonService implements ClusterSingletonService, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(PCEPTunnelClusterSingletonService.class);
private final PCEPTunnelTopologyProvider ttp;
private final TunnelProgramming tp;
private final ServiceGroupIdentifier sgi;
private final TopologyId tunnelTopologyId;
private final TunnelProviderDependencies dependencies;
@GuardedBy("this")
private ServiceRegistration<?> serviceRegistration;
@GuardedBy("this")
private ClusterSingletonServiceRegistration pcepTunnelCssReg;
@GuardedBy("this")
private ObjectRegistration<TunnelProgramming> reg;
public PCEPTunnelClusterSingletonService(
final TunnelProviderDependencies dependencies,
final InstanceIdentifier<Topology> pcepTopology,
final TopologyId tunnelTopologyId
) {
this.dependencies = requireNonNull(dependencies);
this.tunnelTopologyId = requireNonNull(tunnelTopologyId);
final TopologyId pcepTopologyId = pcepTopology.firstKeyOf(Topology.class).getTopologyId();
final InstructionScheduler scheduler;
ServiceTracker<InstructionScheduler, ?> tracker = null;
try {
tracker = new ServiceTracker<>(dependencies.getBundleContext(),
dependencies.getBundleContext().createFilter(String.format("(&(%s=%s)%s)", Constants.OBJECTCLASS,
InstructionScheduler.class.getName(), "(" + InstructionScheduler.class.getName()
+ "=" + pcepTopologyId.getValue() + ")")), null);
tracker.open();
scheduler = (InstructionScheduler) tracker.waitForService(
TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES));
Preconditions.checkState(scheduler != null, "InstructionScheduler service not found");
} catch (InvalidSyntaxException | InterruptedException e) {
throw new IllegalStateException("Error retrieving InstructionScheduler service", e);
} finally {
if (tracker != null) {
tracker.close();
}
}
final InstanceIdentifier<Topology> tunnelTopology = InstanceIdentifier.builder(NetworkTopology.class)
.child(Topology.class, new TopologyKey(tunnelTopologyId)).build();
ttp = new PCEPTunnelTopologyProvider(dependencies.getDataBroker(), pcepTopology, pcepTopologyId,
tunnelTopology, tunnelTopologyId);
sgi = scheduler.getIdentifier();
tp = new TunnelProgramming(scheduler, dependencies);
serviceRegistration = dependencies.getBundleContext()
.registerService(DefaultTopologyReference.class.getName(), ttp, props(tunnelTopologyId));
LOG.info("PCEP Tunnel Cluster Singleton service {} registered", getIdentifier().getName());
pcepTunnelCssReg = dependencies.getCssp().registerClusterSingletonService(this);
}
private static Dictionary<String, String> props(final TopologyId tunnelTopologyId) {
return FrameworkUtil.asDictionary(Map.of(
PCEPTunnelTopologyProvider.class.getName(), tunnelTopologyId.getValue()));
}
@Override
public synchronized void instantiateServiceInstance() {
LOG.info("Instantiate PCEP Tunnel Topology Provider Singleton Service {}", getIdentifier().getName());
final InstanceIdentifier<Topology> topology = InstanceIdentifier
.builder(NetworkTopology.class).child(Topology.class, new TopologyKey(tunnelTopologyId)).build();
reg = dependencies.getRpcProviderRegistry()
.registerRpcImplementation(TopologyTunnelPcepProgrammingService.class, tp, Set.of(topology));
ttp.init();
}
@Override
public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
LOG.info("Close Service Instance PCEP Tunnel Topology Provider Singleton Service {}",
getIdentifier().getName());
reg.close();
tp.close();
ttp.close();
return CommitInfo.emptyFluentFuture();
}
@Override
public ServiceGroupIdentifier getIdentifier() {
return sgi;
}
@Override
@SuppressWarnings("checkstyle:IllegalCatch")
public synchronized void close() {
LOG.info("Close PCEP Tunnel Topology Provider Singleton Service {}", getIdentifier().getName());
if (pcepTunnelCssReg != null) {
try {
pcepTunnelCssReg.close();
} catch (final Exception e) {
LOG.debug("Failed to close PCEP Tunnel Topology service {}", sgi.getName(), e);
}
pcepTunnelCssReg = null;
}
if (serviceRegistration != null) {
serviceRegistration.unregister();
serviceRegistration = null;
}
}
}
|
package org.myrobotlab.document.transformer;
import org.myrobotlab.document.transformer.StageConfiguration;
import java.util.List;
import org.myrobotlab.document.Document;
/**
* This stage will rename the field on a document.
* @author kwatters
*
*/
public class RenameField extends AbstractStage {
private String oldName = "fielda";
private String newName = "fieldb";
@Override
public void startStage(StageConfiguration config) {
// TODO Auto-generated method stub
if (config != null) {
oldName = config.getProperty("oldName");
newName = config.getProperty("newName");
}
}
@Override
public List<Document> processDocument(Document doc) {
if (!doc.hasField(oldName)) {
return null;
}
for (Object o : doc.getField(oldName)) {
doc.addToField(newName, o);
}
doc.removeField(oldName);
return null;
}
@Override
public void stopStage() {
// TODO Auto-generated method stub
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
}
|
package org.pathwaycommons.cypath2.internal;
import org.biopax.paxtools.trove.TProvider;
import org.biopax.paxtools.util.BPCollections;
import org.cytoscape.task.NodeViewTaskFactory;
import org.cytoscape.task.hide.UnHideAllEdgesTaskFactory;
import org.cytoscape.util.swing.OpenBrowser;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.session.CyNetworkNaming;
import org.cytoscape.work.swing.DialogTaskManager;
import org.cytoscape.work.undo.UndoSupport;
import org.cytoscape.application.swing.CyAction;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.subnetwork.CyRootNetworkManager;
import org.cytoscape.property.CyProperty;
import org.cytoscape.io.read.CyNetworkReaderManager;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.cytoscape.service.util.AbstractCyActivator;
import cpath.client.CPathClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static org.cytoscape.work.ServiceProperties.*;
public final class CyActivator extends AbstractCyActivator {
private static final Logger LOGGER = LoggerFactory.getLogger(CyActivator.class);
public CyActivator() {
super();
LOGGER.info("Creating CyPathwayCommons bundle activator...");
}
public void start(BundleContext bc) {
LOGGER.info("Starting CyPathwayCommons app...");
//set a system property for Paxtools to use memory-efficient collections
try {
Class.forName("org.biopax.paxtools.trove.TProvider");
System.setProperty("paxtools.CollectionProvider", "org.biopax.paxtools.trove.TProvider");
BPCollections.I.setProvider(new TProvider());
LOGGER.info("Set: paxtools.CollectionProvider=org.biopax.paxtools.trove.TProvider");
} catch (ClassNotFoundException e1) {
LOGGER.error("org.biopax.paxtools.trove.TProvider is not found on the classpath; so " +
"Paxtools will use default biopax collections (HashSet, HashMap).");
} catch (Throwable t) {
LOGGER.error("static{} initializer failed; " + t);
}
CySwingApplication cySwingApplication = getService(bc,CySwingApplication.class);
DialogTaskManager taskManager = getService(bc,DialogTaskManager.class);
OpenBrowser openBrowser = getService(bc,OpenBrowser.class);
CyNetworkManager cyNetworkManager = getService(bc,CyNetworkManager.class);
CyApplicationManager cyApplicationManager = getService(bc,CyApplicationManager.class);
CyNetworkViewManager cyNetworkViewManager = getService(bc,CyNetworkViewManager.class);
CyNetworkReaderManager cyNetworkReaderManager = getService(bc,CyNetworkReaderManager.class);
CyNetworkNaming cyNetworkNaming = getService(bc,CyNetworkNaming.class);
CyNetworkFactory cyNetworkFactory = getService(bc,CyNetworkFactory.class);
CyLayoutAlgorithmManager cyLayoutAlgorithmManager = getService(bc,CyLayoutAlgorithmManager.class);
UndoSupport undoSupport = getService(bc,UndoSupport.class);
VisualMappingManager visualMappingManager = getService(bc,VisualMappingManager.class);
CyProperty<Properties> cyProperties = getService(bc, CyProperty.class, "(cyPropertyName=cytoscape3.props)");
CyRootNetworkManager cyRootNetworkManager = getService(bc, CyRootNetworkManager.class);
UnHideAllEdgesTaskFactory unHideAllEdgesTaskFactory = getService(bc, UnHideAllEdgesTaskFactory.class);
// keep all the service references in one place -
CyPC.cyServices = new CyServices(cySwingApplication, taskManager, openBrowser,
cyNetworkManager, cyApplicationManager, cyNetworkViewManager, cyNetworkReaderManager,
cyNetworkNaming, cyNetworkFactory, cyLayoutAlgorithmManager, undoSupport, visualMappingManager,
cyProperties, cyRootNetworkManager, unHideAllEdgesTaskFactory);
// Create/init a cpath2 client instance
String cPath2Url = cyProperties.getProperties().getProperty(CyPC.PROP_CPATH2_SERVER_URL);
if(cPath2Url != null && !cPath2Url.isEmpty())
CyPC.client = CPathClient.newInstance(cPath2Url);
else {
//the default cpath2 URL unless -DcPath2Url=<someURL> jvm option used
CyPC.client = CPathClient.newInstance();
}
cyProperties.getProperties().setProperty(CyPC.PROP_CPATH2_SERVER_URL, CyPC.client.getEndPointURL());
// get the app description from the resource file
final Properties props = new Properties();
try {
props.load(getClass().getResourceAsStream("/cypath2.properties"));
} catch (IOException e) { throw new RuntimeException(e);}
final String description = props.getProperty("cypath2.description");
// Create and initialize (build the GUI) new CyPC instance
CyPC app = new CyPC("Pathway Commons 2 (BioPAX L3)", description);
app.init();
// Create a new menu/toolbar item (CyAction) that opens the CyPathwayCommons GUI
Map<String,String> showTheDialogActionProps = new HashMap<String, String>();
showTheDialogActionProps.put(ID,"showCyPathwayCommonsDialogAction");
showTheDialogActionProps.put(TITLE,"Search/Import Network...");
showTheDialogActionProps.put(PREFERRED_MENU, APPS_MENU + ".CyPathwayCommons");
showTheDialogActionProps.put(MENU_GRAVITY,"2.0");
showTheDialogActionProps.put(SMALL_ICON_URL,getClass().getResource("pc2_small.png").toString());
showTheDialogActionProps.put(IN_TOOL_BAR,"false");
showTheDialogActionProps.put(IN_MENU_BAR,"true");
showTheDialogActionProps.put(TOOLTIP,"Networks From PC2");
ShowTheDialogAction showTheDialogAction =
new ShowTheDialogAction(showTheDialogActionProps, app.getQueryBuilderGUI());
// register the service
registerService(bc, showTheDialogAction, CyAction.class, new Properties());
// Create "About..." menu item and action
Map<String,String> showAboutDialogActionProps = new HashMap<String, String>();
showAboutDialogActionProps.put(ID,"showCyPathwayCommonsAboutDialogAction");
showAboutDialogActionProps.put(TITLE,"About...");
showAboutDialogActionProps.put(PREFERRED_MENU, APPS_MENU + ".CyPathwayCommons");
showAboutDialogActionProps.put(MENU_GRAVITY,"1.0");
showAboutDialogActionProps.put(SMALL_ICON_URL,getClass().getResource("pc2_small.png").toString());
showAboutDialogActionProps.put(IN_TOOL_BAR,"false");
showAboutDialogActionProps.put(IN_MENU_BAR,"true");
ShowAboutDialogAction showAboutDialogAction =
new ShowAboutDialogAction(showAboutDialogActionProps, "CyPathwayCommons", description);
// register the service
registerService(bc, showAboutDialogAction, CyAction.class, new Properties());
// create a context menu (using a task factory, for this uses tunables and can be used by Cy3 scripts, headless too)
final NodeViewTaskFactory expandNodeContextMenuFactory = new ExpandNetworkContextMenuFactory();
final Properties nodeProp = new Properties();
nodeProp.setProperty("preferredTaskManager", "menu");
nodeProp.setProperty(PREFERRED_MENU, NODE_APPS_MENU);
nodeProp.setProperty(MENU_GRAVITY, "13.0");
nodeProp.setProperty(TITLE, "CyPathwayCommons: Extend Network...");
registerService(bc, expandNodeContextMenuFactory, NodeViewTaskFactory.class, nodeProp);
// Node selection listener (only for networks imported from BioPAX) and eastern cytopanel (results panel).
//TODO move BioPaxCytoPanelComponent to the biopax core app.
final BioPaxCytoPanelComponent cytoPanelComponent = new BioPaxCytoPanelComponent();
registerAllServices(bc, cytoPanelComponent, new Properties());
// Register: WebServiceClient, WebServiceGUIClient, SearchWebServiceClient,..
registerAllServices(bc, app, new Properties());
}
}
|
package org.waterforpeople.mapping.helper;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary;
import org.waterforpeople.mapping.dao.AccessPointDao;
import org.waterforpeople.mapping.dao.AccessPointScoreDetailDao;
import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.domain.AccessPoint;
import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType;
import org.waterforpeople.mapping.domain.AccessPointMappingHistory;
import org.waterforpeople.mapping.domain.AccessPointScoreDetail;
import org.waterforpeople.mapping.domain.GeoCoordinates;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.SurveyAttributeMapping;
import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.gallatinsystems.common.util.StringUtil;
import com.gallatinsystems.framework.analytics.summarization.DataSummarizationRequest;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.framework.domain.DataChangeRecord;
import com.gallatinsystems.gis.location.GeoLocationServiceGeonamesImpl;
import com.gallatinsystems.gis.location.GeoPlace;
import com.gallatinsystems.gis.map.domain.OGRFeature;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.domain.Question;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
public class AccessPointHelper {
private static String photo_url_root;
private static final String GEO_TYPE = "GEO";
private static final String PHOTO_TYPE = "IMAGE";
private SurveyAttributeMappingDao mappingDao;
static {
Properties props = System.getProperties();
photo_url_root = props.getProperty("photo_url_root");
}
private static Logger logger = Logger.getLogger(AccessPointHelper.class
.getName());
public AccessPointHelper() {
mappingDao = new SurveyAttributeMappingDao();
}
public AccessPoint getAccessPoint(Long id) {
BaseDAO<AccessPoint> apDAO = new BaseDAO<AccessPoint>(AccessPoint.class);
return apDAO.getByKey(id);
}
public AccessPoint getAccessPoint(Long id, Boolean needScoreDetail) {
BaseDAO<AccessPoint> apDAO = new BaseDAO<AccessPoint>(AccessPoint.class);
AccessPointScoreDetailDao apddao = new AccessPointScoreDetailDao();
AccessPoint ap = apDAO.getByKey(id);
List<AccessPointScoreDetail> apScoreSummaryList = apddao
.listByAccessPointId(id);
if (apScoreSummaryList != null && !apScoreSummaryList.isEmpty())
ap.setApScoreDetailList(apScoreSummaryList);
return ap;
}
public void processSurveyInstance(String surveyInstanceId) {
// Get the survey and QuestionAnswerStore
// Get the surveyDefinition
SurveyInstanceDAO sid = new SurveyInstanceDAO();
List<QuestionAnswerStore> questionAnswerList = sid
.listQuestionAnswerStore(Long.parseLong(surveyInstanceId), null);
Collection<AccessPoint> apList = null;
if (questionAnswerList != null && questionAnswerList.size() > 0) {
try {
apList = parseAccessPoint(new Long(questionAnswerList.get(0)
.getSurveyId()), questionAnswerList,
AccessPoint.AccessPointType.WATER_POINT);
} catch (Exception ex) {
logger.log(Level.SEVERE, "problem parsing access point." + ex);
}
if (apList != null) {
for (AccessPoint ap : apList) {
try {
saveAccessPoint(ap);
} catch (Exception ex) {
logger.log(
Level.SEVERE,
"Inside processSurveyInstance could not save AP for SurveyInstanceId: "
+ surveyInstanceId + ":"
+ ap.toString() + " ex: " + ex
+ " exMessage: " + ex.getMessage());
}
}
}
}
}
private Collection<AccessPoint> parseAccessPoint(Long surveyId,
List<QuestionAnswerStore> questionAnswerList,
AccessPoint.AccessPointType accessPointType) {
Collection<AccessPoint> apList = null;
List<SurveyAttributeMapping> mappings = mappingDao
.listMappingsBySurvey(surveyId);
if (mappings != null) {
apList = parseAccessPoint(surveyId, questionAnswerList, mappings);
} else {
logger.log(Level.SEVERE, "NO mappings for survey " + surveyId);
}
return apList;
}
/**
* uses the saved mappings for the survey definition to parse values in the
* questionAnswerStore into attributes of an AccessPoint object
*
* TODO: figure out way around known limitation of only having 1 GEO
* response per survey
*
* @param questionAnswerList
* @param mappings
* @return
*/
private Collection<AccessPoint> parseAccessPoint(Long surveyId,
List<QuestionAnswerStore> questionAnswerList,
List<SurveyAttributeMapping> mappings) {
HashMap<String, AccessPoint> apMap = new HashMap<String, AccessPoint>();
List<AccessPointMappingHistory> apmhList = new ArrayList<AccessPointMappingHistory>();
List<Question> questionList = new QuestionDao()
.listQuestionsBySurvey(surveyId);
if (questionAnswerList != null) {
for (QuestionAnswerStore qas : questionAnswerList) {
SurveyAttributeMapping mapping = getMappingForQuestion(
mappings, qas.getQuestionID());
if (mapping != null) {
List<String> types = mapping.getApTypes();
if (types == null || types.size() == 0) {
// default the list to be access point if nothing is
// specified (for backward compatibility)
types.add(AccessPointType.WATER_POINT.toString());
} else {
if (types.contains(AccessPointType.PUBLIC_INSTITUTION
.toString())
&& (types.contains(AccessPointType.HEALTH_POSTS
.toString()) || types
.contains(AccessPointType.SCHOOL
.toString()))) {
types.remove(AccessPointType.PUBLIC_INSTITUTION
.toString());
}
}
for (String type : types) {
AccessPointMappingHistory apmh = new AccessPointMappingHistory();
apmh.setSource(this.getClass().getName());
apmh.setSurveyId(surveyId);
apmh.setSurveyInstanceId(qas.getSurveyInstanceId());
apmh.setQuestionId(Long.parseLong(qas.getQuestionID()));
apmh.addAccessPointType(type);
try {
AccessPoint ap = apMap.get(type);
if (ap == null) {
ap = new AccessPoint();
ap.setPointType(AccessPointType.valueOf(type));
// if(AccessPointType.PUBLIC_INSTITUTION.toString().equals(type)){
// //get the pointType value from the survey to
// properly set it
apMap.put(type, ap);
}
ap.setCollectionDate(qas.getCollectionDate());
setAccessPointField(ap, qas, mapping, apmh);
} catch (NoSuchFieldException e) {
logger.log(
Level.SEVERE,
"Could not map field to access point: "
+ mapping.getAttributeName()
+ ". Check the surveyAttribueMapping for surveyId "
+ surveyId);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE,
"Could not set field to access point: "
+ mapping.getAttributeName()
+ ". Illegal access.");
}
for (Question q : questionList) {
if (q.getKey().getId() == Long.parseLong(qas
.getQuestionID())) {
apmh.setQuestionText(q.getText());
break;
}
}
apmhList.add(apmh);
}
}
// if (apmhList.size() > 0) {
// BaseDAO<AccessPointMappingHistory> apmhDao = new
// BaseDAO<AccessPointMappingHistory>(
// AccessPointMappingHistory.class);
// apmhDao.save(apmhList);
}
}
return apMap.values();
}
public static void setAccessPointField(AccessPoint ap,
QuestionAnswerStore qas, SurveyAttributeMapping mapping,
AccessPointMappingHistory apmh) throws SecurityException,
NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
apmh.setResponseAnswerType(qas.getType());
QuestionDao qDao = new QuestionDao();
Question q = qDao.getByKey(Long.parseLong(qas.getQuestionID()));
if (!qas.getType().equals(q.getType().toString())){
qas.setType(q.getType().toString());
logger.log(Level.INFO,"Remapping question type value because QAS version is incorrect");
}
//FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK, NAME, STRENGTH
if (GEO_TYPE.equals(q.getType())) {
GeoCoordinates geoC = new GeoCoordinates().extractGeoCoordinate(qas
.getValue());
ap.setLatitude(geoC.getLatitude());
ap.setLongitude(geoC.getLongitude());
ap.setAltitude(geoC.getAltitude());
if (ap.getCommunityCode() == null && geoC.getCode() != null) {
ap.setCommunityCode(geoC.getCode());
}
apmh.setSurveyResponse(geoC.getLatitude() + "|"
+ geoC.getLongitude() + "|" + geoC.getAltitude());
apmh.setQuestionAnswerType("GEO");
apmh.setAccessPointValue(ap.getLatitude() + "|" + ap.getLongitude()
+ "|" + ap.getAltitude());
apmh.setAccessPointField("Latitude,Longitude,Altitude");
} else {
apmh.setSurveyResponse(qas.getValue());
// if it's a value or OTHER type
Field f = ap.getClass()
.getDeclaredField(mapping.getAttributeName());
if (!f.isAccessible()) {
f.setAccessible(true);
}
apmh.setAccessPointField(f.getName());
// TODO: Hack. In the QAS the type is PHOTO, but we were looking for
// image this is why we were getting /sdcard I think.
if (PHOTO_TYPE.equals(q.getType())
|| qas.getType().equals("PHOTO")) {
String newURL = null;
String[] photoParts = qas.getValue().split("/");
if (qas.getValue().startsWith("/sdcard")) {
newURL = photo_url_root + photoParts[2];
} else if (qas.getValue().startsWith("/mnt")) {
newURL = photo_url_root + photoParts[3];
}
f.set(ap, newURL);
apmh.setQuestionAnswerType("PHOTO");
apmh.setAccessPointValue(ap.getPhotoURL());
} else if (mapping.getAttributeName().equals("pointType")) {
if (qas.getValue().contains("Health")) {
f.set(ap, AccessPointType.HEALTH_POSTS);
} else {
qas.setValue(qas.getValue().replace(" ", "_"));
f.set(ap, AccessPointType.valueOf(qas.getValue()
.toUpperCase()));
}
} else {
String stringVal = qas.getValue();
if (stringVal != null && stringVal.trim().length() > 0) {
if (f.getType() == String.class) {
f.set(ap, qas.getValue());
apmh.setQuestionAnswerType("String");
apmh.setAccessPointValue(f.get(ap).toString());
} else if (f.getType() == AccessPoint.Status.class) {
String val = qas.getValue();
f.set(ap, encodeStatus(val, ap.getPointType()));
apmh.setQuestionAnswerType("STATUS");
apmh.setAccessPointValue(f.get(ap).toString());
} else if (f.getType() == Double.class) {
try {
Double val = Double.parseDouble(stringVal.trim());
f.set(ap, val);
apmh.setQuestionAnswerType("DOUBLE");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as double", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as double");
}
} else if (f.getType() == Long.class) {
try {
String temp = stringVal.trim();
if (temp.contains(".")) {
temp = temp.substring(0, temp.indexOf("."));
}
Long val = Long.parseLong(temp);
f.set(ap, val);
logger.info("Setting "
+ f.getName()
+ " to "
+ val
+ " for ap: "
+ (ap.getKey() != null ? ap.getKey()
.getId() : "UNSET"));
apmh.setQuestionAnswerType("LONG");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as long", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as long");
}
} else if (f.getType() == Boolean.class) {
try {
Boolean val = null;
if (stringVal.toLowerCase().contains("yes")) {
val = true;
} else if (stringVal.toLowerCase().contains("no")) {
val = false;
} else {
if (stringVal == null || stringVal.equals("")) {
val = null;
}
val = Boolean.parseBoolean(stringVal.trim());
}
f.set(ap, val);
apmh.setQuestionAnswerType("BOOLEAN");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as boolean", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as boolean");
}
}
}
}
}
}
/**
* reads value of field from AccessPoint via reflection
*
* @param ap
* @param field
* @return
*/
public static String getAccessPointFieldAsString(AccessPoint ap,
String field) {
try {
Field f = ap.getClass().getDeclaredField(field);
if (!f.isAccessible()) {
f.setAccessible(true);
}
Object val = f.get(ap);
if (val != null) {
return val.toString();
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not extract field value: " + field,
e);
}
return null;
}
private SurveyAttributeMapping getMappingForQuestion(
List<SurveyAttributeMapping> mappings, String questionId) {
if (mappings != null) {
for (SurveyAttributeMapping mapping : mappings) {
if (mapping.getSurveyQuestionId().equals(questionId)) {
return mapping;
}
}
}
return null;
}
/**
* generates a unique code based on the lat/lon passed in. Current algorithm
* returns the concatenation of the integer portion of 1000 times absolute
*
* value of lat and lon in base 36
*
* @param lat
* @param lon
* @return
*/
private String generateCode(double lat, double lon) {
Long code = Long.parseLong((int) ((Math.abs(lat) * 10000d)) + ""
+ (int) ((Math.abs(lon) * 10000d)));
return Long.toString(code, 36);
}
/**
* saves an access point and fires off a summarization message
*
* @param ap
* @return
*/
public AccessPoint saveAccessPoint(AccessPoint ap) {
AccessPointDao apDao = new AccessPointDao();
AccessPoint apCurrent = null;
if (ap != null) {
if (ap.getPointType() != null && ap.getLatitude() != null
&& ap.getLongitude() != null) {
apCurrent = apDao.findAccessPoint(ap.getPointType(),
ap.getLatitude(), ap.getLongitude(),
ap.getCollectionDate());
if (apCurrent != null) {
// if (!apCurrent.getKey().equals(ap.getKey())) {
ap.setKey(apCurrent.getKey());
}
if (ap.getAccessPointCode() == null) {
ap.setAccessPointCode(generateCode(ap.getLatitude(),
ap.getLongitude()));
logger.log(
Level.INFO,
"No APCode set in ap so setting to: "
+ ap.getAccessPointCode());
}
if (ap.getCommunityCode() == null) {
if (ap.getAccessPointCode() != null)
ap.setCommunityCode(ap.getAccessPointCode());
logger.log(
Level.INFO,
"No Community Code set in ap so setting to: "
+ ap.getAccessPointCode());
}
if (ap.getKey() != null) {
String oldValues = null;
if (ap != null && ap.getKey() != null && apCurrent == null) {
apCurrent = apDao.getByKey(ap.getKey());
}
if (apCurrent != null) {
oldValues = formChangeRecordString(apCurrent);
if (apCurrent != null) {
ap.setKey(apCurrent.getKey());
apCurrent = ap;
logger.log(Level.INFO,
"Found existing point and updating it."
+ apCurrent.getKey().getId());
}
// TODO: Hack since the fileUrl keeps getting set to
// incorrect value
// Changing from apCurrent to ap
ap = apDao.save(ap);
String newValues = formChangeRecordString(ap);
if (oldValues != null) {
DataChangeRecord change = new DataChangeRecord(
AccessPointStatusSummary.class.getName(),
"n/a", oldValues, newValues);
Queue queue = QueueFactory.getQueue("dataUpdate");
queue.add(url("/app_worker/dataupdate")
.param(DataSummarizationRequest.OBJECT_KEY,
ap.getKey().getId() + "")
.param(DataSummarizationRequest.OBJECT_TYPE,
"AccessPointSummaryChange")
.param(DataSummarizationRequest.VALUE_KEY,
change.packString()));
}
}
} else {
logger.log(Level.INFO,
"Did not find existing point" + ap.toString());
if (ap.getGeocells() == null
|| ap.getGeocells().size() == 0) {
if (ap.getLatitude() != null
&& ap.getLongitude() != null
&& ap.getLongitude() < 180
&& ap.getLatitude() < 180) {
try {
ap.setGeocells(GeocellManager
.generateGeoCell(new Point(ap
.getLatitude(), ap
.getLongitude())));
} catch (Exception ex) {
logger.log(Level.INFO,
"Could not generate GeoCell for AP: "
+ ap.getKey().getId()
+ " error: " + ex);
}
}
}
try {
ap = apDao.save(ap);
} catch (Exception ex) {
logger.log(Level.INFO, "Could not save point");
}
if (ap.getKey() != null) {
Queue summQueue = QueueFactory
.getQueue("dataSummarization");
summQueue.add(url("/app_worker/datasummarization")
.param("objectKey", ap.getKey().getId() + "")
.param("type", "AccessPoint"));
} else {
logger.log(
Level.SEVERE,
"After saving could not get key"
+ ap.toString());
}
}
}
}
if (ap != null) {
return ap;
} else
return null;
}
private String formChangeRecordString(AccessPoint ap) {
String changeString = null;
if (ap != null) {
changeString = (ap.getCountryCode() != null ? ap.getCountryCode()
: "")
+ "|"
+ (ap.getCommunityCode() != null ? ap.getCommunityCode()
: "")
+ "|"
+ (ap.getPointType() != null ? ap.getPointType().toString()
: "")
+ "|"
+ (ap.getPointStatus() != null ? ap.getPointStatus()
.toString() : "")
+ "|"
+ StringUtil.getYearString(ap.getCollectionDate());
}
return changeString;
}
public List<AccessPoint> listAccessPoint(String cursorString) {
AccessPointDao apDao = new AccessPointDao();
return apDao.list(cursorString);
}
public static AccessPoint.Status encodeStatus(String statusVal,
AccessPoint.AccessPointType pointType) {
AccessPoint.Status status = null;
statusVal = statusVal.toLowerCase().trim();
if (pointType.equals(AccessPointType.WATER_POINT)) {
if ("functioning but with problems".equals(statusVal)
|| "working but with problems".equals(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS;
} else if ("broken down system".equals(statusVal)
|| "broken down".equals(statusVal)
|| statusVal.contains("broken")) {
status = AccessPoint.Status.BROKEN_DOWN;
} else if ("no improved system".equals(statusVal)
|| "not a protected waterpoint".equals(statusVal)) {
status = AccessPoint.Status.NO_IMPROVED_SYSTEM;
} else if ("functioning and meets government standards"
.equals(statusVal)
|| "working and protected".equals(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_HIGH;
} else if ("high".equalsIgnoreCase(statusVal)
|| "functioning".equals(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_HIGH;
} else if ("ok".equalsIgnoreCase(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_OK;
} else {
status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS;
}
} else if (pointType.equals(AccessPointType.SANITATION_POINT)) {
if ("latrine full".equals(statusVal))
status = AccessPoint.Status.LATRINE_FULL;
else if ("Latrine used but technical problems evident"
.toLowerCase().trim().equals(statusVal))
status = AccessPoint.Status.LATRINE_USED_TECH_PROBLEMS;
else if ("Latrine not being used due to structural/technical problems"
.toLowerCase().equals(statusVal))
status = AccessPoint.Status.LATRINE_NOT_USED_TECH_STRUCT_PROBLEMS;
else if ("Do not Know".toLowerCase().equals(statusVal))
status = AccessPoint.Status.LATRINE_DO_NOT_KNOW;
else if ("Functional".toLowerCase().equals(statusVal))
status = AccessPoint.Status.LATRINE_FUNCTIONAL;
} else {
if ("functioning but with problems".equals(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS;
} else if ("broken down system".equals(statusVal)) {
status = AccessPoint.Status.BROKEN_DOWN;
} else if ("no improved system".equals(statusVal))
status = AccessPoint.Status.NO_IMPROVED_SYSTEM;
else if ("functioning and meets government standards"
.equals(statusVal))
status = AccessPoint.Status.FUNCTIONING_HIGH;
else if ("high".equalsIgnoreCase(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_HIGH;
} else if ("ok".equalsIgnoreCase(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_OK;
} else {
status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS;
}
}
return status;
}
private void copyNonKeyValues(AccessPoint source, AccessPoint target) {
if (source != null && target != null) {
Field[] fields = AccessPoint.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
try {
if (isCopyable(fields[i].getName())) {
fields[i].setAccessible(true);
fields[i].set(target, fields[i].get(source));
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't set the field: "
+ fields[i].getName());
}
}
}
}
private boolean isCopyable(String name) {
if ("key".equals(name)) {
return false;
} else if ("serialVersionUID".equals(name)) {
return false;
} else if ("jdoFieldFlags".equals(name)) {
return false;
} else if ("jdoPersistenceCapableSuperclass".equals(name)) {
return false;
} else if ("jdoFieldTypes".equals(name)) {
return false;
} else if ("jdoFieldNames".equals(name)) {
return false;
} else if ("jdoInheritedFieldCount".equals(name)) {
return false;
}
return true;
}
public AccessPoint setGeoDetails(AccessPoint point) {
if (point.getLatitude() != null && point.getLongitude() != null) {
GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
GeoPlace geoPlace = gs.manualLookup(point.getLatitude().toString(),
point.getLongitude().toString(),
OGRFeature.FeatureType.SUB_COUNTRY_OTHER);
if (geoPlace != null) {
point.setCountryCode(geoPlace.getCountryCode());
point.setSub1(geoPlace.getSub1());
point.setSub2(geoPlace.getSub2());
point.setSub3(geoPlace.getSub3());
point.setSub4(geoPlace.getSub4());
point.setSub5(geoPlace.getSub5());
point.setSub6(geoPlace.getSub6());
} else if (geoPlace == null && point.getCountryCode() == null) {
GeoPlace geoPlaceCountry = gs.manualLookup(point.getLatitude()
.toString(), point.getLongitude().toString(),
OGRFeature.FeatureType.COUNTRY);
if (geoPlaceCountry != null) {
point.setCountryCode(geoPlaceCountry.getCountryCode());
}
}
}
return point;
}
public static AccessPoint scoreAccessPoint(AccessPoint ap) {
// Is there an improved water system no=0, yes=1
// Provide enough drinking water for community everyday of year no=0,
// yes=1, don't know=0,
// Water system been down in 30 days: No=1,yes=0
// Are there current problems: no=1,yes=0
// meet govt quantity standards:no=0,yes=1
// Is there a tarriff or fee no=0,yes=1
AccessPointScoreDetail apss = new AccessPointScoreDetail();
logger.log(Level.INFO,
"About to compute score for: " + ap.getCommunityCode());
Integer score = 0;
if (ap.isImprovedWaterPointFlag() != null
&& ap.isImprovedWaterPointFlag()) {
score++;
apss.addScoreComputationItem("Plus 1 for Improved Water System = true: ");
if (ap.getProvideAdequateQuantity() != null
&& ap.getProvideAdequateQuantity().equals(true)) {
score++;
apss.addScoreComputationItem("Plus 1 for Provide Adequate Quantity = true: ");
} else {
apss.addScoreComputationItem("Plus 0 for Provide Adequate Quantity = false or null: ");
}
if (ap.getHasSystemBeenDown1DayFlag() != null
&& !ap.getHasSystemBeenDown1DayFlag().equals(true)) {
score++;
apss.addScoreComputationItem("Plus 1 for Has System Been Down 1 Day Flag = false: ");
} else {
apss.addScoreComputationItem("Plus 0 for Has System Been Down 1 Day Flag = true or null: ");
}
if (ap.getCurrentProblem() == null) {
score++;
apss.addScoreComputationItem("Plus 1 for Get Current Problem = null");
} else {
apss.addScoreComputationItem("Plus 0 for Get Current Problem != null value: "
+ ap.getCurrentProblem());
}
if (ap.isCollectTariffFlag() != null && ap.isCollectTariffFlag()) {
score++;
apss.addScoreComputationItem("Plus 1 for Collect Tariff Flag = true ");
} else {
apss.addScoreComputationItem("Plus 0 for Collect Tariff Flag = false or null: ");
}
} else {
apss.addScoreComputationItem("Plus 0 for Improved Water System = false or null: ");
}
apss.setScore(score);
ap.setScore(score);
ap.setScoreComputationDate(new Date());
apss.setComputationDate(ap.getScoreComputationDate());
logger.log(Level.INFO,
"AP Collected in 2011 so scoring: " + ap.getCommunityCode()
+ "/" + ap.getCollectionDate() + " score: " + score);
if (score == 0) {
ap.setPointStatus(AccessPoint.Status.NO_IMPROVED_SYSTEM);
apss.setStatus(AccessPoint.Status.NO_IMPROVED_SYSTEM.toString());
} else if (score >= 1 && score <= 2) {
ap.setPointStatus(AccessPoint.Status.BROKEN_DOWN);
apss.setStatus(AccessPoint.Status.BROKEN_DOWN.toString());
} else if (score >= 3 && score <= 4) {
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS);
apss.setStatus(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS
.toString());
} else if (score >= 5) {
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
apss.setStatus(AccessPoint.Status.FUNCTIONING_HIGH.toString());
} else {
ap.setPointStatus(AccessPoint.Status.OTHER);
apss.setStatus(AccessPoint.Status.OTHER.toString());
}
ap.setApScoreDetail(apss);
return ap;
}
}
|
package org.royaldev.royalcommands.spawninfo;
import com.google.common.base.Splitter;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
import com.google.common.io.OutputSupplier;
import com.google.common.primitives.Primitives;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import java.io.BufferedInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
@SuppressWarnings("UnusedDeclaration, JavadocReference")
public class NbtFactory {
// Convert between NBT id and the equivalent class in java
private static final BiMap<Integer, Class<?>> NBT_CLASS = HashBiMap.create();
private static final BiMap<Integer, NbtType> NBT_ENUM = HashBiMap.create();
/**
* Whether or not to enable stream compression.
*
* @author Kristian
*/
public enum StreamOptions {
NO_COMPRESSION,
GZIP_COMPRESSION,
}
private enum NbtType {
TAG_END(0, Void.class),
TAG_BYTE(1, byte.class),
TAG_SHORT(2, short.class),
TAG_INT(3, int.class),
TAG_LONG(4, long.class),
TAG_FLOAT(5, float.class),
TAG_DOUBLE(6, double.class),
TAG_BYTE_ARRAY(7, byte[].class),
TAG_INT_ARRAY(11, int[].class),
TAG_STRING(8, String.class),
TAG_LIST(9, List.class),
TAG_COMPOUND(10, Map.class);
// Unique NBT id
public final int id;
private NbtType(int id, Class<?> type) {
this.id = id;
NBT_CLASS.put(id, type);
NBT_ENUM.put(id, this);
}
private String getFieldName() {
if (this == TAG_COMPOUND) return "map";
else if (this == TAG_LIST) return "list";
else return "data";
}
}
// The NBT base class
private Class<?> BASE_CLASS;
private Method NBT_CREATE_TAG;
private Method NBT_GET_TYPE;
private Field NBT_LIST_TYPE;
private final Field[] DATA_FIELD = new Field[12];
// CraftItemStack
private Class<?> CRAFT_STACK;
private Field CRAFT_HANDLE;
private Field STACK_TAG;
// Loading/saving compounds
private Method LOAD_COMPOUND;
private Method SAVE_COMPOUND;
// Shared instance
private static NbtFactory INSTANCE;
/**
* Represents a root NBT compound.
* <p/>
* All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following:
* <ul>
* <li>Primitive types</li>
* <li>{@link java.lang.String String}</li>
* <li>{@link NbtList}</li>
* <li>{@link NbtCompound}</li>
* </ul>
* <p/>
* See also:
* <ul>
* <li>{@link NbtFactory#createCompound()}</li>
* <li>{@link NbtFactory#fromCompound(Object)}</li>
* </ul>
*
* @author Kristian
*/
public final class NbtCompound extends ConvertedMap {
private NbtCompound(Object handle) {
super(handle, getDataMap(handle));
}
// Simplifiying access to each value
public Byte getByte(String key, Byte defaultValue) {
return containsKey(key) ? (Byte) get(key) : defaultValue;
}
public Short getShort(String key, Short defaultValue) {
return containsKey(key) ? (Short) get(key) : defaultValue;
}
public Integer getInteger(String key, Integer defaultValue) {
return containsKey(key) ? (Integer) get(key) : defaultValue;
}
public Long getLong(String key, Long defaultValue) {
return containsKey(key) ? (Long) get(key) : defaultValue;
}
public Float getFloat(String key, Float defaultValue) {
return containsKey(key) ? (Float) get(key) : defaultValue;
}
public Double getDouble(String key, Double defaultValue) {
return containsKey(key) ? (Double) get(key) : defaultValue;
}
public String getString(String key, String defaultValue) {
return containsKey(key) ? (String) get(key) : defaultValue;
}
public byte[] getByteArray(String key, byte[] defaultValue) {
return containsKey(key) ? (byte[]) get(key) : defaultValue;
}
public int[] getIntegerArray(String key, int[] defaultValue) {
return containsKey(key) ? (int[]) get(key) : defaultValue;
}
/**
* Retrieve the list by the given name.
*
* @param key - the name of the list.
* @param createNew - whether or not to create a new list if its missing.
* @return An existing list, a new list or NULL.
*/
public NbtList getList(String key, boolean createNew) {
NbtList list = (NbtList) get(key);
if (list == null) put(key, list = createList());
return list;
}
/**
* Retrieve the map by the given name.
*
* @param key - the name of the map.
* @param createNew - whether or not to create a new map if its missing.
* @return An existing map, a new map or NULL.
*/
public NbtCompound getMap(String key, boolean createNew) {
return getMap(Arrays.asList(key), createNew);
}
// Done
/**
* Set the value of an entry at a given location.
* <p/>
* Every element of the path (except the end) are assumed to be compounds, and will
* be created if they are missing.
*
* @param path - the path to the entry.
* @param value - the new value of this entry.
* @return This compound, for chaining.
*/
public NbtCompound putPath(String path, Object value) {
List<String> entries = getPathElements(path);
Map<String, Object> map = getMap(entries.subList(0, entries.size() - 1), true);
map.put(entries.get(entries.size() - 1), value);
return this;
}
/**
* Retrieve the value of a given entry in the tree.
* <p/>
* Every element of the path (except the end) are assumed to be compounds. The
* retrieval operation will be cancelled if any of them are missing.
*
* @param path - path to the entry.
* @return The value, or NULL if not found.
*/
@SuppressWarnings("unchecked")
public <T> T getPath(String path) {
List<String> entries = getPathElements(path);
NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false);
if (map != null) return (T) map.get(entries.get(entries.size() - 1));
return null;
}
/**
* Save the content of a NBT compound to a stream.
* <p/>
* Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file.
*
* @param stream - the output stream.
* @param option - whether or not to compress the output.
* @throws IOException If anything went wrong.
*/
public void saveTo(OutputSupplier<? extends OutputStream> stream, StreamOptions option) throws IOException {
saveStream(this, stream, option);
}
/**
* Retrieve a map from a given path.
*
* @param path - path of compounds to look up.
* @param createNew - whether or not to create new compounds on the way.
* @return The map at this location.
*/
private NbtCompound getMap(Iterable<String> path, boolean createNew) {
NbtCompound current = this;
for (String entry : path) {
NbtCompound child = (NbtCompound) current.get(entry);
if (child == null) {
if (!createNew) throw new IllegalArgumentException("Cannot find " + entry + " in " + path);
current.put(entry, child = createCompound());
}
current = child;
}
return current;
}
/**
* Split the path into separate elements.
*
* @param path - the path to split.
* @return The elements.
*/
private List<String> getPathElements(String path) {
return Lists.newArrayList(Splitter.on(".").omitEmptyStrings().split(path));
}
}
/**
* Represents a root NBT list.
* See also:
* <ul>
* <li>{@link NbtFactory#createNbtList()}</li>
* <li>{@link NbtFactory#fromList(Object)}</li>
* </ul>
*
* @author Kristian
*/
public final class NbtList extends ConvertedList {
private NbtList(Object handle) {
super(handle, getDataList(handle));
}
}
/**
* Represents an object that provides a view of a native NMS class.
*
* @author Kristian
*/
public static interface Wrapper {
/**
* Retrieve the underlying native NBT tag.
*
* @return The underlying NBT.
*/
public Object getHandle();
}
/**
* Retrieve or construct a shared NBT factory.
*
* @return The factory.
*/
private static NbtFactory get() {
if (INSTANCE == null) INSTANCE = new NbtFactory();
return INSTANCE;
}
/**
* Construct an instance of the NBT factory by deducing the class of NBTBase.
*/
private NbtFactory() {
if (BASE_CLASS == null) {
try {
// Keep in mind that I do use hard-coded field names - but it's okay as long as we're dealing
// with CraftBukkit or its derivatives. This does not work in MCPC+ however.
ClassLoader loader = NbtFactory.class.getClassLoader();
String packageName = getPackageName();
Class<?> offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer");
// Prepare NBT
Class<?> compoundClass = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType();
BASE_CLASS = compoundClass.getSuperclass();
NBT_GET_TYPE = getMethod(0, Modifier.STATIC, BASE_CLASS, "getTypeId");
NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, BASE_CLASS, "createTag", byte.class);
// Prepare CraftItemStack
CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack");
CRAFT_HANDLE = getField(null, CRAFT_STACK, "handle");
STACK_TAG = getField(null, CRAFT_HANDLE.getType(), "tag");
// Loading/saving
Class<?> streamTools = loader.loadClass(BASE_CLASS.getPackage().getName() + ".NBTCompressedStreamTools");
LOAD_COMPOUND = getMethod(Modifier.STATIC, 0, streamTools, null, DataInput.class);
SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, streamTools, null, BASE_CLASS, DataOutput.class);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to find offline player.", e);
}
}
}
private String getPackageName() {
Server server = Bukkit.getServer();
String name = server != null ? server.getClass().getPackage().getName() : null;
if (name != null && name.contains("craftbukkit")) return name;
else return "org.bukkit.craftbukkit.v1_7_R1"; // Fallback
}
@SuppressWarnings("unchecked")
private Map<String, Object> getDataMap(Object handle) {
return (Map<String, Object>) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle);
}
@SuppressWarnings("unchecked")
private List<Object> getDataList(Object handle) {
return (List<Object>) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle);
}
/**
* Construct a new NBT list of an unspecified type.
*
* @return The NBT list.
*/
public static NbtList createList(Object... content) {
return createList(Arrays.asList(content));
}
/**
* Construct a new NBT list of an unspecified type.
*
* @return The NBT list.
*/
public static NbtList createList(Iterable<?> iterable) {
NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null));
// Add the content as well
for (Object obj : iterable) list.add(obj);
return list;
}
/**
* Construct a new NBT compound.
* <p/>
* Use {@link NbtCompound#asMap()} to modify it.
*
* @return The NBT compound.
*/
public static NbtCompound createCompound() {
return get().new NbtCompound(INSTANCE.createNbtTag(NbtType.TAG_COMPOUND, null));
}
/**
* Construct a new NBT wrapper from a list.
*
* @param nmsList - the NBT list.
* @return The wrapper.
*/
public static NbtList fromList(Object nmsList) {
return get().new NbtList(nmsList);
}
/**
* Load the content of a file from a stream.
* <p/>
* Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file.
*
* @param stream - the stream supplier.
* @param option - whether or not to decompress the input stream.
* @return The decoded NBT compound.
* @throws IOException If anything went wrong.
*/
public static NbtCompound fromStream(InputSupplier<? extends InputStream> stream, StreamOptions option) throws IOException {
InputStream input = null;
DataInputStream data = null;
try {
input = stream.getInput();
data = new DataInputStream(new BufferedInputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPInputStream(input) : input));
return fromCompound(invokeMethod(get().LOAD_COMPOUND, null, data));
} finally {
if (data != null) Closeables.closeQuietly(data);
if (input != null) Closeables.closeQuietly(input);
}
}
/**
* Save the content of a NBT compound to a stream.
* <p/>
* Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file.
*
* @param source - the NBT compound to save.
* @param stream - the stream.
* @param option - whether or not to compress the output.
* @throws IOException If anything went wrong.
*/
public static void saveStream(NbtCompound source, OutputSupplier<? extends OutputStream> stream, StreamOptions option) throws IOException {
OutputStream output = null;
DataOutputStream data = null;
try {
output = stream.getOutput();
data = new DataOutputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output);
invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data);
} finally {
if (data != null) Closeables.closeQuietly(data);
if (output != null) Closeables.closeQuietly(output);
}
}
/**
* Construct a new NBT wrapper from a compound.
*
* @param nmsCompound - the NBT compund.
* @return The wrapper.
*/
public static NbtCompound fromCompound(Object nmsCompound) {
return get().new NbtCompound(nmsCompound);
}
public static void setItemTag(ItemStack stack, NbtCompound compound) {
checkItemStack(stack);
Object nms = getFieldValue(get().CRAFT_HANDLE, stack);
// Now update the tag compound
if (compound == null) setFieldValue(get().STACK_TAG, nms, null);
else setFieldValue(get().STACK_TAG, nms, compound.getHandle());
}
/**
* Construct a wrapper for an NBT tag stored (in memory) in an item stack. This is where
* auxiliary data such as enchanting, name and lore is stored. It does not include items
* material, damage value or count.
* <p/>
* The item stack must be a wrapper for a CraftItemStack.
*
* @param stack - the item stack.
* @return A wrapper for its NBT tag.
*/
public static NbtCompound fromItemTag(ItemStack stack) {
checkItemStack(stack);
Object nms = getFieldValue(get().CRAFT_HANDLE, stack);
Object tag = getFieldValue(get().STACK_TAG, nms);
// Create the tag if it doesn't exist
if (tag == null) {
NbtCompound compound = createCompound();
setItemTag(stack, compound);
return compound;
}
return fromCompound(tag);
}
/**
* Retrieve a CraftItemStack version of the stack.
*
* @param stack - the stack to convert.
* @return The CraftItemStack version.
*/
public static ItemStack getCraftItemStack(ItemStack stack) {
// Any need to convert?
if (stack == null || get().CRAFT_STACK.isAssignableFrom(stack.getClass())) return stack;
try {
// Call the private constructor
Constructor<?> caller = INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class);
caller.setAccessible(true);
return (ItemStack) caller.newInstance(stack);
} catch (Exception e) {
throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack.");
}
}
/**
* Ensure that the given stack can store arbitrary NBT information.
*
* @param stack - the stack to check.
*/
private static void checkItemStack(ItemStack stack) {
if (stack == null) throw new IllegalArgumentException("Stack cannot be NULL.");
if (!get().CRAFT_STACK.isAssignableFrom(stack.getClass()))
throw new IllegalArgumentException("Stack must be a CraftItemStack.");
if (stack.getType() == Material.AIR)
throw new IllegalArgumentException("ItemStacks representing air cannot store NMS information.");
}
/**
* Convert wrapped List and Map objects into their respective NBT counterparts.
*
* @param name - the name of the NBT element to create.
* @param value - the value of the element to create. Can be a List or a Map.
* @return The NBT element.
*/
private Object unwrapValue(Object value) {
if (value == null) return null;
if (value instanceof Wrapper) return ((Wrapper) value).getHandle();
else if (value instanceof List) throw new IllegalArgumentException("Can only insert a WrappedList.");
else if (value instanceof Map) throw new IllegalArgumentException("Can only insert a WrappedCompound.");
else return createNbtTag(getPrimitiveType(value), value);
}
/**
* Convert a given NBT element to a primitive wrapper or List/Map equivalent.
* <p/>
* All changes to any mutable objects will be reflected in the underlying NBT element(s).
*
* @param nms - the NBT element.
* @return The wrapper equivalent.
*/
private Object wrapNative(Object nms) {
if (nms == null) return null;
if (BASE_CLASS.isAssignableFrom(nms.getClass())) {
final NbtType type = getNbtType(nms);
// Handle the different types
switch (type) {
case TAG_COMPOUND:
return new NbtCompound(nms);
case TAG_LIST:
return new NbtList(nms);
default:
return getFieldValue(getDataField(type, nms), nms);
}
}
throw new IllegalArgumentException("Unexpected type: " + nms);
}
/**
* Construct a new NMS NBT tag initialized with the given value.
*
* @param type - the NBT type.
* @param value - the value, or NULL to keep the original value.
* @return The created tag.
*/
private Object createNbtTag(NbtType type, Object value) {
Object tag = invokeMethod(NBT_CREATE_TAG, null, (byte) type.id);
if (value != null) setFieldValue(getDataField(type, tag), tag, value);
return tag;
}
/**
* Retrieve the field where the NBT class stores its value.
*
* @param type - the NBT type.
* @param nms - the NBT class instance.
* @return The corresponding field.
*/
private Field getDataField(NbtType type, Object nms) {
if (DATA_FIELD[type.id] == null) DATA_FIELD[type.id] = getField(nms, null, type.getFieldName());
return DATA_FIELD[type.id];
}
/**
* Retrieve the NBT type from a given NMS NBT tag.
*
* @param nms - the native NBT tag.
* @return The corresponding type.
*/
private NbtType getNbtType(Object nms) {
int type = (Byte) invokeMethod(NBT_GET_TYPE, nms);
return NBT_ENUM.get(type);
}
/**
* Retrieve the nearest NBT type for a given primitive type.
*
* @param primitive - the primitive type.
* @return The corresponding type.
*/
private NbtType getPrimitiveType(Object primitive) {
NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass())));
if (type == null)
throw new IllegalArgumentException(String.format("Illegal type: %s (%s)", primitive.getClass(), primitive));
return type;
}
/**
* Invoke a method on the given target instance using the provided parameters.
*
* @param method - the method to invoke.
* @param target - the target.
* @param params - the parameters to supply.
* @return The result of the method.
*/
private static Object invokeMethod(Method method, Object target, Object... params) {
try {
return method.invoke(target, params);
} catch (Exception e) {
throw new RuntimeException("Unable to invoke method " + method + " for " + target, e);
}
}
private static void setFieldValue(Field field, Object target, Object value) {
try {
field.set(target, value);
} catch (Exception e) {
throw new RuntimeException("Unable to set " + field + " for " + target, e);
}
}
private static Object getFieldValue(Field field, Object target) {
try {
return field.get(target);
} catch (Exception e) {
throw new RuntimeException("Unable to retrieve " + field + " for " + target, e);
}
}
private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz, String methodName, Class<?>... params) {
for (Method method : clazz.getDeclaredMethods()) {
// Limitation: Doesn't handle overloads
if ((method.getModifiers() & requireMod) == requireMod &&
(method.getModifiers() & bannedMod) == 0 &&
(methodName == null || method.getName().equals(methodName)) &&
Arrays.equals(method.getParameterTypes(), params)) {
method.setAccessible(true);
return method;
}
}
// Search in every superclass
if (clazz.getSuperclass() != null)
return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params);
throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
}
private static Field getField(Object instance, Class<?> clazz, String fieldName) {
if (clazz == null) clazz = instance.getClass();
// Ignore access rules
for (Field field : clazz.getDeclaredFields()) {
if (field.getName().equals(fieldName)) {
field.setAccessible(true);
return field;
}
}
// Recursively fild the correct field
if (clazz.getSuperclass() != null) return getField(instance, clazz.getSuperclass(), fieldName);
throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance);
}
/**
* Represents a class for caching wrappers.
*
* @author Kristian
*/
private final class CachedNativeWrapper {
// Don't recreate wrapper objects
private final ConcurrentMap<Object, Object> cache = new MapMaker().weakKeys().makeMap();
public Object wrap(Object value) {
Object current = cache.get(value);
if (current == null) {
current = wrapNative(value);
// Only cache composite objects
if (current instanceof ConvertedMap || current instanceof ConvertedList) cache.put(value, current);
}
return current;
}
}
/**
* Represents a map that wraps another map and automatically
* converts entries of its type and another exposed type.
*
* @author Kristian
*/
private class ConvertedMap extends AbstractMap<String, Object> implements Wrapper {
private final Object handle;
private final Map<String, Object> original;
private final CachedNativeWrapper cache = new CachedNativeWrapper();
public ConvertedMap(Object handle, Map<String, Object> original) {
this.handle = handle;
this.original = original;
}
// For converting back and forth
protected Object wrapOutgoing(Object value) {
return cache.wrap(value);
}
protected Object unwrapIncoming(Object wrapped) {
return unwrapValue(wrapped);
}
// Modification
@Override
public Object put(String key, Object value) {
return wrapOutgoing(original.put(key, unwrapIncoming(value)));
}
// Performance
@Override
public Object get(Object key) {
return wrapOutgoing(original.get(key));
}
@Override
public Object remove(Object key) {
return wrapOutgoing(original.remove(key));
}
@Override
public boolean containsKey(Object key) {
return original.containsKey(key);
}
@SuppressWarnings("NullableProblems")
@Override
public Set<Entry<String, Object>> entrySet() {
return new AbstractSet<Entry<String, Object>>() {
@Override
public boolean add(Entry<String, Object> e) {
String key = e.getKey();
Object value = e.getValue();
original.put(key, unwrapIncoming(value));
return true;
}
@Override
public int size() {
return original.size();
}
@Override
public Iterator<Entry<String, Object>> iterator() {
return ConvertedMap.this.iterator();
}
};
}
private Iterator<Entry<String, Object>> iterator() {
final Iterator<Entry<String, Object>> proxy = original.entrySet().iterator();
return new Iterator<Entry<String, Object>>() {
@Override
public boolean hasNext() {
return proxy.hasNext();
}
@Override
public Entry<String, Object> next() {
Entry<String, Object> entry = proxy.next();
return new SimpleEntry<String, Object>(entry.getKey(), wrapOutgoing(entry.getValue()));
}
@Override
public void remove() {
proxy.remove();
}
};
}
@Override
public Object getHandle() {
return handle;
}
}
/**
* Represents a list that wraps another list and converts elements
* of its type and another exposed type.
*
* @author Kristian
*/
private class ConvertedList extends AbstractList<Object> implements Wrapper {
private final Object handle;
private final List<Object> original;
private final CachedNativeWrapper cache = new CachedNativeWrapper();
public ConvertedList(Object handle, List<Object> original) {
if (NBT_LIST_TYPE == null) NBT_LIST_TYPE = getField(handle, null, "type");
this.handle = handle;
this.original = original;
}
protected Object wrapOutgoing(Object value) {
return cache.wrap(value);
}
protected Object unwrapIncoming(Object wrapped) {
return unwrapValue(wrapped);
}
@Override
public Object get(int index) {
return wrapOutgoing(original.get(index));
}
@Override
public int size() {
return original.size();
}
@Override
public Object set(int index, Object element) {
return wrapOutgoing(original.set(index, unwrapIncoming(element)));
}
@Override
public void add(int index, Object element) {
Object nbt = unwrapIncoming(element);
// Set the list type if it's the first element
if (size() == 0) setFieldValue(NBT_LIST_TYPE, handle, (byte) getNbtType(nbt).id);
original.add(index, nbt);
}
@Override
public Object remove(int index) {
return wrapOutgoing(original.remove(index));
}
@Override
public boolean remove(Object o) {
return original.remove(unwrapIncoming(o));
}
@Override
public Object getHandle() {
return handle;
}
}
}
|
package org.opencms.ade.contenteditor;
import org.opencms.acacia.shared.CmsAttributeConfiguration;
import org.opencms.acacia.shared.CmsEntity;
import org.opencms.acacia.shared.CmsEntityAttribute;
import org.opencms.acacia.shared.CmsEntityHtml;
import org.opencms.acacia.shared.CmsType;
import org.opencms.acacia.shared.CmsValidationResult;
import org.opencms.ade.containerpage.CmsContainerpageService;
import org.opencms.ade.containerpage.CmsElementUtil;
import org.opencms.ade.containerpage.shared.CmsCntPageData;
import org.opencms.ade.containerpage.shared.CmsContainer;
import org.opencms.ade.containerpage.shared.CmsContainerElement;
import org.opencms.ade.contenteditor.shared.CmsContentDefinition;
import org.opencms.ade.contenteditor.shared.CmsEditorConstants;
import org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.collectors.A_CmsResourceCollector;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.CmsRpcException;
import org.opencms.gwt.shared.CmsModelResourceInfo;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.json.JSONObject;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.search.CmsSearchManager;
import org.opencms.search.galleries.CmsGallerySearch;
import org.opencms.search.galleries.CmsGallerySearchResult;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsDialog;
import org.opencms.workplace.editors.CmsEditor;
import org.opencms.workplace.editors.CmsXmlContentEditor;
import org.opencms.workplace.explorer.CmsNewResourceXmlContent;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.CmsXmlEntityResolver;
import org.opencms.xml.CmsXmlException;
import org.opencms.xml.CmsXmlUtils;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.containerpage.CmsADESessionCache;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentErrorHandler;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.I_CmsXmlContentEditorChangeHandler;
import org.opencms.xml.types.I_CmsXmlContentValue;
import org.opencms.xml.types.I_CmsXmlSchemaType;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.dom4j.Element;
import com.google.common.collect.Sets;
/**
* Service to provide entity persistence within OpenCms. <p>
*/
public class CmsContentService extends CmsGwtService implements I_CmsContentService {
/** The logger for this class. */
protected static final Log LOG = CmsLog.getLog(CmsContentService.class);
/** The type name prefix. */
static final String TYPE_NAME_PREFIX = "http://opencms.org/types/";
/** The serial version id. */
private static final long serialVersionUID = 7873052619331296648L;
/** The session cache. */
private CmsADESessionCache m_sessionCache;
/** The current users workplace locale. */
private Locale m_workplaceLocale;
/**
* Returns the entity attribute name representing the given content value.<p>
*
* @param contentValue the content value
*
* @return the attribute name
*/
public static String getAttributeName(I_CmsXmlContentValue contentValue) {
return getTypeUri(contentValue.getContentDefinition()) + "/" + contentValue.getName();
}
/**
* Returns the entity attribute name to use for this element.<p>
*
* @param elementName the element name
* @param parentType the parent type
*
* @return the attribute name
*/
public static String getAttributeName(String elementName, String parentType) {
return parentType + "/" + elementName;
}
/**
* Returns the entity id to the given content value.<p>
*
* @param contentValue the content value
*
* @return the entity id
*/
public static String getEntityId(I_CmsXmlContentValue contentValue) {
String result = CmsContentDefinition.uuidToEntityId(
contentValue.getDocument().getFile().getStructureId(),
contentValue.getLocale().toString());
String valuePath = contentValue.getPath();
if (valuePath.contains("/")) {
result += "/" + valuePath.substring(0, valuePath.lastIndexOf("/"));
}
if (contentValue.isChoiceOption()) {
result += "/"
+ CmsType.CHOICE_ATTRIBUTE_NAME
+ "_"
+ contentValue.getName()
+ "["
+ contentValue.getXmlIndex()
+ "]";
}
return result;
}
/**
* Returns the RDF annotations required for in line editing.<p>
*
* @param parentValue the parent XML content value
* @param childNames the child attribute names separated by '|'
*
* @return the RDFA
*/
public static String getRdfaAttributes(I_CmsXmlContentValue parentValue, String childNames) {
StringBuffer result = new StringBuffer();
result.append("about=\"");
result.append(
CmsContentDefinition.uuidToEntityId(
parentValue.getDocument().getFile().getStructureId(),
parentValue.getLocale().toString()));
result.append("/").append(parentValue.getPath());
result.append("\" ");
String[] children = childNames.split("\\|");
result.append("property=\"");
for (int i = 0; i < children.length; i++) {
I_CmsXmlSchemaType schemaType = parentValue.getContentDefinition().getSchemaType(
parentValue.getName() + "/" + children[i]);
if (schemaType != null) {
if (i > 0) {
result.append(" ");
}
result.append(getTypeUri(schemaType.getContentDefinition())).append("/").append(children[i]);
}
}
result.append("\"");
return result.toString();
}
/**
* Returns the RDF annotations required for in line editing.<p>
*
* @param document the parent XML document
* @param contentLocale the content locale
* @param childName the child attribute name
*
* @return the RDFA
*/
public static String getRdfaAttributes(I_CmsXmlDocument document, Locale contentLocale, String childName) {
I_CmsXmlSchemaType schemaType = document.getContentDefinition().getSchemaType(childName);
StringBuffer result = new StringBuffer();
if (schemaType != null) {
result.append("about=\"");
result.append(
CmsContentDefinition.uuidToEntityId(document.getFile().getStructureId(), contentLocale.toString()));
result.append("\" property=\"");
result.append(getTypeUri(schemaType.getContentDefinition())).append("/").append(childName);
result.append("\"");
}
return result.toString();
}
/**
* Returns the type URI.<p>
*
* @param xmlContentDefinition the type content definition
*
* @return the type URI
*/
public static String getTypeUri(CmsXmlContentDefinition xmlContentDefinition) {
return xmlContentDefinition.getSchemaLocation() + "/" + xmlContentDefinition.getTypeName();
}
/**
* Fetches the initial content definition.<p>
*
* @param request the current request
*
* @return the initial content definition
*
* @throws CmsRpcException if something goes wrong
*/
public static CmsContentDefinition prefetch(HttpServletRequest request) throws CmsRpcException {
CmsContentService srv = new CmsContentService();
srv.setCms(CmsFlexController.getCmsObject(request));
srv.setRequest(request);
CmsContentDefinition result = null;
try {
result = srv.prefetch();
} finally {
srv.clearThreadStorage();
}
return result;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#callEditorChangeHandlers(java.lang.String, org.opencms.acacia.shared.CmsEntity, java.util.Collection, java.util.Collection)
*/
public CmsContentDefinition callEditorChangeHandlers(
String entityId,
CmsEntity editedLocaleEntity,
Collection<String> skipPaths,
Collection<String> changedScopes) throws CmsRpcException {
CmsContentDefinition result = null;
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(editedLocaleEntity.getId());
if (structureId != null) {
CmsObject cms = getCmsObject();
CmsResource resource = null;
Locale locale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
try {
resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
ensureLock(resource);
CmsFile file = cms.readFile(resource);
CmsXmlContent content = getContentDocument(file, true).clone();
checkAutoCorrection(cms, content);
synchronizeLocaleIndependentForEntity(file, content, skipPaths, editedLocaleEntity);
for (I_CmsXmlContentEditorChangeHandler handler : content.getContentDefinition().getContentHandler().getEditorChangeHandlers()) {
Set<String> handlerScopes = evaluateScope(handler.getScope(), content.getContentDefinition());
if (!Collections.disjoint(changedScopes, handlerScopes)) {
handler.handleChange(cms, content, locale, changedScopes);
}
}
result = readContentDefinition(file, content, entityId, locale, false);
} catch (Exception e) {
error(e);
}
}
return result;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#cancelEdit(org.opencms.util.CmsUUID, boolean)
*/
public void cancelEdit(CmsUUID structureId, boolean delete) throws CmsRpcException {
try {
getSessionCache().uncacheXmlContent(structureId);
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
if (delete) {
ensureLock(resource);
getCmsObject().deleteResource(
getCmsObject().getSitePath(resource),
CmsResource.DELETE_PRESERVE_SIBLINGS);
}
tryUnlock(resource);
} catch (Throwable t) {
error(t);
}
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#copyLocale(java.util.Collection, org.opencms.acacia.shared.CmsEntity)
*/
public void copyLocale(Collection<String> locales, CmsEntity sourceLocale) throws CmsRpcException {
try {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(sourceLocale.getId());
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getSessionCache().getCacheXmlContent(structureId);
synchronizeLocaleIndependentForEntity(file, content, Collections.<String> emptyList(), sourceLocale);
Locale sourceContentLocale = CmsLocaleManager.getLocale(
CmsContentDefinition.getLocaleFromId(sourceLocale.getId()));
for (String loc : locales) {
Locale targetLocale = CmsLocaleManager.getLocale(loc);
if (content.hasLocale(targetLocale)) {
content.removeLocale(targetLocale);
}
content.copyLocale(sourceContentLocale, targetLocale);
}
} catch (Throwable t) {
error(t);
}
}
/**
* @see org.opencms.gwt.CmsGwtService#getCmsObject()
*/
@Override
public CmsObject getCmsObject() {
CmsObject result = super.getCmsObject();
// disable link invalidation in the editor
result.getRequestContext().setRequestTime(CmsResource.DATE_RELEASED_EXPIRED_IGNORE);
return result;
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#loadContentDefinition(java.lang.String)
*/
public CmsContentDefinition loadContentDefinition(String entityId) throws CmsRpcException {
throw new CmsRpcException(new UnsupportedOperationException());
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#loadDefinition(java.lang.String, org.opencms.acacia.shared.CmsEntity, java.util.Collection)
*/
public CmsContentDefinition loadDefinition(
String entityId,
CmsEntity editedLocaleEntity,
Collection<String> skipPaths) throws CmsRpcException {
CmsContentDefinition definition = null;
try {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(entityId);
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getContentDocument(file, true);
if (editedLocaleEntity != null) {
synchronizeLocaleIndependentForEntity(file, content, skipPaths, editedLocaleEntity);
}
definition = readContentDefinition(
file,
content,
CmsContentDefinition.uuidToEntityId(structureId, contentLocale.toString()),
contentLocale,
false);
} catch (Exception e) {
error(e);
}
return definition;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#loadInitialDefinition(java.lang.String, java.lang.String, org.opencms.util.CmsUUID, java.lang.String, java.lang.String, java.lang.String)
*/
public CmsContentDefinition loadInitialDefinition(
String entityId,
String newLink,
CmsUUID modelFileId,
String editContext,
String mode,
String postCreateHandler) throws CmsRpcException {
CmsContentDefinition result = null;
getCmsObject().getRequestContext().setAttribute(CmsXmlContentEditor.ATTRIBUTE_EDITCONTEXT, editContext);
try {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(entityId);
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(newLink)) {
result = readContentDefnitionForNew(
newLink,
resource,
modelFileId,
contentLocale,
mode,
postCreateHandler);
} else {
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getContentDocument(file, false);
result = readContentDefinition(
file,
content,
CmsContentDefinition.uuidToEntityId(structureId, contentLocale.toString()),
contentLocale,
false);
}
} catch (Throwable t) {
error(t);
}
return result;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#loadNewDefinition(java.lang.String, org.opencms.acacia.shared.CmsEntity, java.util.Collection)
*/
public CmsContentDefinition loadNewDefinition(
String entityId,
CmsEntity editedLocaleEntity,
Collection<String> skipPaths) throws CmsRpcException {
CmsContentDefinition definition = null;
try {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(entityId);
CmsResource resource = getCmsObject().readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getContentDocument(file, true);
synchronizeLocaleIndependentForEntity(file, content, skipPaths, editedLocaleEntity);
definition = readContentDefinition(
file,
content,
CmsContentDefinition.uuidToEntityId(structureId, contentLocale.toString()),
contentLocale,
true);
} catch (Exception e) {
error(e);
}
return definition;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#prefetch()
*/
public CmsContentDefinition prefetch() throws CmsRpcException {
String paramResource = getRequest().getParameter(CmsDialog.PARAM_RESOURCE);
String paramDirectEdit = getRequest().getParameter(CmsEditor.PARAM_DIRECTEDIT);
boolean isDirectEdit = false;
if (paramDirectEdit != null) {
isDirectEdit = Boolean.parseBoolean(paramDirectEdit);
}
String paramNewLink = getRequest().getParameter(CmsXmlContentEditor.PARAM_NEWLINK);
boolean createNew = false;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(paramNewLink)) {
createNew = true;
paramNewLink = decodeNewLink(paramNewLink);
}
String paramLocale = getRequest().getParameter(CmsEditor.PARAM_ELEMENTLANGUAGE);
Locale locale = null;
CmsObject cms = getCmsObject();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(paramResource)) {
try {
CmsResource resource = cms.readResource(paramResource, CmsResourceFilter.IGNORE_EXPIRATION);
if (CmsResourceTypeXmlContent.isXmlContent(resource)) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(paramLocale)) {
locale = CmsLocaleManager.getLocale(paramLocale);
}
CmsContentDefinition result;
if (createNew) {
if (locale == null) {
locale = OpenCms.getLocaleManager().getDefaultLocale(cms, paramResource);
}
CmsUUID modelFileId = null;
String paramModelFile = getRequest().getParameter(CmsNewResourceXmlContent.PARAM_MODELFILE);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(paramModelFile)) {
modelFileId = cms.readResource(paramModelFile).getStructureId();
}
String mode = getRequest().getParameter(CmsEditorConstants.PARAM_MODE);
String postCreateHandler = getRequest().getParameter(
CmsEditorConstants.PARAM_POST_CREATE_HANDLER);
result = readContentDefnitionForNew(
paramNewLink,
resource,
modelFileId,
locale,
mode,
postCreateHandler);
} else {
CmsFile file = cms.readFile(resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file);
getSessionCache().setCacheXmlContent(resource.getStructureId(), content);
if (locale == null) {
locale = getBestAvailableLocale(resource, content);
}
result = readContentDefinition(file, content, null, locale, false);
}
result.setDirectEdit(isDirectEdit);
return result;
}
} catch (Throwable e) {
error(e);
}
}
return null;
}
/**
* @see org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService#saveAndDeleteEntities(org.opencms.acacia.shared.CmsEntity, java.util.List, java.util.Collection, java.lang.String, boolean)
*/
public CmsValidationResult saveAndDeleteEntities(
CmsEntity lastEditedEntity,
List<String> deletedEntities,
Collection<String> skipPaths,
String lastEditedLocale,
boolean clearOnSuccess) throws CmsRpcException {
CmsUUID structureId = null;
if (lastEditedEntity != null) {
structureId = CmsContentDefinition.entityIdToUuid(lastEditedEntity.getId());
}
if ((structureId == null) && !deletedEntities.isEmpty()) {
structureId = CmsContentDefinition.entityIdToUuid(deletedEntities.get(0));
}
if (structureId != null) {
CmsObject cms = getCmsObject();
CmsResource resource = null;
try {
resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
ensureLock(resource);
CmsFile file = cms.readFile(resource);
CmsXmlContent content = getContentDocument(file, true);
checkAutoCorrection(cms, content);
if (lastEditedEntity != null) {
synchronizeLocaleIndependentForEntity(file, content, skipPaths, lastEditedEntity);
}
for (String deleteId : deletedEntities) {
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(deleteId));
if (content.hasLocale(contentLocale)) {
content.removeLocale(contentLocale);
}
}
CmsValidationResult validationResult = validateContent(cms, structureId, content);
if (validationResult.hasErrors()) {
return validationResult;
}
writeContent(cms, file, content, getFileEncoding(cms, file));
// update offline indices
OpenCms.getSearchManager().updateOfflineIndexes(2 * CmsSearchManager.DEFAULT_OFFLINE_UPDATE_FREQNENCY);
if (clearOnSuccess) {
tryUnlock(resource);
getSessionCache().uncacheXmlContent(structureId);
}
} catch (Exception e) {
if (resource != null) {
tryUnlock(resource);
getSessionCache().uncacheXmlContent(structureId);
}
error(e);
}
}
return null;
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#saveEntities(java.util.List)
*/
public CmsValidationResult saveEntities(List<CmsEntity> entities) {
throw new UnsupportedOperationException();
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#saveEntity(org.opencms.acacia.shared.CmsEntity)
*/
public CmsValidationResult saveEntity(CmsEntity entity) {
throw new UnsupportedOperationException();
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#updateEntityHtml(org.opencms.acacia.shared.CmsEntity, java.lang.String, java.lang.String)
*/
public CmsEntityHtml updateEntityHtml(CmsEntity entity, String contextUri, String htmlContextInfo)
throws Exception {
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(entity.getId());
if (structureId != null) {
CmsObject cms = getCmsObject();
try {
CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = cms.readFile(resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file);
String entityId = entity.getId();
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
if (content.hasLocale(contentLocale)) {
content.removeLocale(contentLocale);
}
content.addLocale(cms, contentLocale);
addEntityAttributes(cms, content, "", entity, contentLocale);
CmsValidationResult validationResult = validateContent(cms, structureId, content);
String htmlContent = null;
if (!validationResult.hasErrors()) {
file.setContents(content.marshal());
JSONObject contextInfo = new JSONObject(htmlContextInfo);
String containerName = contextInfo.getString(CmsCntPageData.JSONKEY_NAME);
String containerType = contextInfo.getString(CmsCntPageData.JSONKEY_TYPE);
int containerWidth = contextInfo.getInt(CmsCntPageData.JSONKEY_WIDTH);
int maxElements = contextInfo.getInt(CmsCntPageData.JSONKEY_MAXELEMENTS);
boolean detailView = contextInfo.getBoolean(CmsCntPageData.JSONKEY_DETAILVIEW);
CmsContainer container = new CmsContainer(
containerName,
containerType,
null,
containerWidth,
maxElements,
detailView,
true,
Collections.<CmsContainerElement> emptyList(),
null,
null);
CmsUUID detailContentId = null;
if (contextInfo.has(CmsCntPageData.JSONKEY_DETAIL_ELEMENT_ID)) {
detailContentId = new CmsUUID(contextInfo.getString(CmsCntPageData.JSONKEY_DETAIL_ELEMENT_ID));
}
CmsElementUtil elementUtil = new CmsElementUtil(
cms,
contextUri,
detailContentId,
getThreadLocalRequest(),
getThreadLocalResponse(),
contentLocale);
htmlContent = elementUtil.getContentByContainer(
file,
contextInfo.getString(CmsCntPageData.JSONKEY_ELEMENT_ID),
container,
true);
}
return new CmsEntityHtml(htmlContent, validationResult);
} catch (Exception e) {
error(e);
}
}
return null;
}
/**
* @see org.opencms.acacia.shared.rpc.I_CmsContentService#validateEntities(java.util.List)
*/
public CmsValidationResult validateEntities(List<CmsEntity> changedEntities) throws CmsRpcException {
CmsUUID structureId = null;
if (changedEntities.isEmpty()) {
return new CmsValidationResult(null, null);
}
structureId = CmsContentDefinition.entityIdToUuid(changedEntities.get(0).getId());
if (structureId != null) {
CmsObject cms = getCmsObject();
Set<String> setFieldNames = Sets.newHashSet();
try {
CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = cms.readFile(resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file);
for (CmsEntity entity : changedEntities) {
String entityId = entity.getId();
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
if (content.hasLocale(contentLocale)) {
content.removeLocale(contentLocale);
}
content.addLocale(cms, contentLocale);
setFieldNames.addAll(addEntityAttributes(cms, content, "", entity, contentLocale));
}
return validateContent(cms, structureId, content, setFieldNames);
} catch (Exception e) {
error(e);
}
}
return new CmsValidationResult(null, null);
}
/**
* Decodes the newlink request parameter if possible.<p>
*
* @param newLink the parameter to decode
*
* @return the decoded value
*/
protected String decodeNewLink(String newLink) {
String result = newLink;
if (result == null) {
return null;
}
try {
result = CmsEncoder.decode(result);
try {
result = CmsEncoder.decode(result);
} catch (Throwable e) {
LOG.info(e.getLocalizedMessage(), e);
}
} catch (Throwable e) {
LOG.info(e.getLocalizedMessage(), e);
}
return result;
}
/**
* Returns the element name to the given element.<p>
*
* @param attributeName the attribute name
*
* @return the element name
*/
protected String getElementName(String attributeName) {
if (attributeName.contains("/")) {
return attributeName.substring(attributeName.lastIndexOf("/") + 1);
}
return attributeName;
}
/**
* Helper method to determine the encoding of the given file in the VFS,
* which must be set using the "content-encoding" property.<p>
*
* @param cms the CmsObject
* @param file the file which is to be checked
* @return the encoding for the file
*/
protected String getFileEncoding(CmsObject cms, CmsResource file) {
String result;
try {
result = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue(
OpenCms.getSystemInfo().getDefaultEncoding());
} catch (CmsException e) {
result = OpenCms.getSystemInfo().getDefaultEncoding();
}
return CmsEncoder.lookupEncoding(result, OpenCms.getSystemInfo().getDefaultEncoding());
}
/**
* Parses the element into an entity.<p>
*
* @param content the entity content
* @param element the current element
* @param locale the content locale
* @param entityId the entity id
* @param parentPath the parent path
* @param typeName the entity type name
* @param visitor the content type visitor
* @param includeInvisible include invisible attributes
*
* @return the entity
*/
protected CmsEntity readEntity(
CmsXmlContent content,
Element element,
Locale locale,
String entityId,
String parentPath,
String typeName,
CmsContentTypeVisitor visitor,
boolean includeInvisible) {
String newEntityId = entityId + (CmsStringUtil.isNotEmptyOrWhitespaceOnly(parentPath) ? "/" + parentPath : "");
CmsEntity newEntity = new CmsEntity(newEntityId, typeName);
CmsEntity result = newEntity;
List<Element> elements = element.elements();
CmsType type = visitor.getTypes().get(typeName);
boolean isChoice = type.isChoice();
String choiceTypeName = null;
// just needed for choice attributes
Map<String, Integer> attributeCounter = null;
if (isChoice) {
choiceTypeName = type.getAttributeTypeName(CmsType.CHOICE_ATTRIBUTE_NAME);
type = visitor.getTypes().get(type.getAttributeTypeName(CmsType.CHOICE_ATTRIBUTE_NAME));
attributeCounter = new HashMap<String, Integer>();
}
int counter = 0;
CmsObject cms = getCmsObject();
String previousName = null;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(parentPath)) {
parentPath += "/";
}
for (Element child : elements) {
String attributeName = getAttributeName(child.getName(), typeName);
String subTypeName = type.getAttributeTypeName(attributeName);
if (visitor.getTypes().get(subTypeName) == null) {
// in case there is no type configured for this element, the schema may have changed, skip the element
continue;
}
if (!includeInvisible && !visitor.getAttributeConfigurations().get(attributeName).isVisible()) {
// skip attributes marked as invisible, there content should not be transfered to the client
continue;
}
if (isChoice && (attributeCounter != null)) {
if (!attributeName.equals(previousName)) {
if (attributeCounter.get(attributeName) != null) {
counter = attributeCounter.get(attributeName).intValue();
} else {
counter = 0;
}
previousName = attributeName;
}
attributeCounter.put(attributeName, Integer.valueOf(counter + 1));
} else if (!attributeName.equals(previousName)) {
// reset the attribute counter for every attribute name
counter = 0;
previousName = attributeName;
}
if (isChoice) {
result = new CmsEntity(
newEntityId + "/" + CmsType.CHOICE_ATTRIBUTE_NAME + "_" + child.getName() + "[" + counter + "]",
choiceTypeName);
newEntity.addAttributeValue(CmsType.CHOICE_ATTRIBUTE_NAME, result);
}
String path = parentPath + child.getName();
if (visitor.getTypes().get(subTypeName).isSimpleType()) {
I_CmsXmlContentValue value = content.getValue(path, locale, counter);
result.addAttributeValue(attributeName, value.getStringValue(cms));
} else {
CmsEntity subEntity = readEntity(
content,
child,
locale,
entityId,
path + "[" + (counter + 1) + "]",
subTypeName,
visitor,
includeInvisible);
result.addAttributeValue(attributeName, subEntity);
}
counter++;
}
return newEntity;
}
/**
* Reads the types from the given content definition and adds the to the map of already registered
* types if necessary.<p>
*
* @param xmlContentDefinition the XML content definition
* @param locale the messages locale
*
* @return the types of the given content definition
*/
protected Map<String, CmsType> readTypes(CmsXmlContentDefinition xmlContentDefinition, Locale locale) {
CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(getCmsObject(), null, locale);
visitor.visitTypes(xmlContentDefinition, locale);
return visitor.getTypes();
}
/**
* Synchronizes the locale independent fields.<p>
*
* @param file the content file
* @param content the XML content
* @param skipPaths the paths to skip during locale synchronization
* @param entities the edited entities
* @param lastEdited the last edited locale
*
* @throws CmsXmlException if something goes wrong
*/
protected void synchronizeLocaleIndependentFields(
CmsFile file,
CmsXmlContent content,
Collection<String> skipPaths,
Collection<CmsEntity> entities,
Locale lastEdited) throws CmsXmlException {
CmsEntity lastEditedEntity = null;
for (CmsEntity entity : entities) {
if (lastEdited.equals(CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entity.getId())))) {
lastEditedEntity = entity;
} else {
synchronizeLocaleIndependentForEntity(file, content, skipPaths, entity);
}
}
if (lastEditedEntity != null) {
// prepare the last edited last, to sync locale independent fields
synchronizeLocaleIndependentForEntity(file, content, skipPaths, lastEditedEntity);
}
}
/**
* Transfers values marked as invisible from the original entity to the target entity.<p>
*
* @param original the original entity
* @param target the target entiy
* @param visitor the type visitor holding the content type configuration
*/
protected void transferInvisibleValues(CmsEntity original, CmsEntity target, CmsContentTypeVisitor visitor) {
List<String> invisibleAttributes = new ArrayList<String>();
for (Entry<String, CmsAttributeConfiguration> configEntry : visitor.getAttributeConfigurations().entrySet()) {
if (!configEntry.getValue().isVisible()) {
invisibleAttributes.add(configEntry.getKey());
}
}
CmsContentDefinition.transferValues(
original,
target,
invisibleAttributes,
visitor.getTypes(),
visitor.getAttributeConfigurations(),
true);
}
/**
* Adds the attribute values of the entity to the given XML content.<p>
*
* @param cms the current cms context
* @param content the XML content
* @param parentPath the parent path
* @param entity the entity
* @param contentLocale the content locale
*
* @return the set of xpaths of simple fields in the XML content which were set by this method
*/
private Set<String> addEntityAttributes(
CmsObject cms,
CmsXmlContent content,
String parentPath,
CmsEntity entity,
Locale contentLocale) {
Set<String> fieldsSet = Sets.newHashSet();
addEntityAttributes(cms, content, parentPath, entity, contentLocale, fieldsSet);
return fieldsSet;
}
/**
* Adds the attribute values of the entity to the given XML content.<p>
*
* @param cms the current cms context
* @param content the XML content
* @param parentPath the parent path
* @param entity the entity
* @param contentLocale the content locale
* @param fieldsSet set to store which fields were set in the XML content
*/
private void addEntityAttributes(
CmsObject cms,
CmsXmlContent content,
String parentPath,
CmsEntity entity,
Locale contentLocale,
Set<String> fieldsSet) {
for (CmsEntityAttribute attribute : entity.getAttributes()) {
if (CmsType.CHOICE_ATTRIBUTE_NAME.equals(attribute.getAttributeName())) {
List<CmsEntity> choiceEntities = attribute.getComplexValues();
for (int i = 0; i < choiceEntities.size(); i++) {
List<CmsEntityAttribute> choiceAttributes = choiceEntities.get(i).getAttributes();
// each choice entity may only have a single attribute with a single value
assert (choiceAttributes.size() == 1)
&& choiceAttributes.get(
0).isSingleValue() : "each choice entity may only have a single attribute with a single value";
CmsEntityAttribute choiceAttribute = choiceAttributes.get(0);
String elementPath = parentPath + getElementName(choiceAttribute.getAttributeName());
if (choiceAttribute.isSimpleValue()) {
String value = choiceAttribute.getSimpleValue();
I_CmsXmlContentValue field = content.getValue(elementPath, contentLocale, i);
if (field == null) {
field = content.addValue(cms, elementPath, contentLocale, i);
}
field.setStringValue(cms, value);
fieldsSet.add(field.getPath());
} else {
CmsEntity child = choiceAttribute.getComplexValue();
I_CmsXmlContentValue field = content.getValue(elementPath, contentLocale, i);
if (field == null) {
field = content.addValue(cms, elementPath, contentLocale, i);
}
addEntityAttributes(cms, content, field.getPath() + "/", child, contentLocale, fieldsSet);
}
}
} else {
String elementPath = parentPath + getElementName(attribute.getAttributeName());
if (attribute.isSimpleValue()) {
List<String> values = attribute.getSimpleValues();
for (int i = 0; i < values.size(); i++) {
String value = values.get(i);
I_CmsXmlContentValue field = content.getValue(elementPath, contentLocale, i);
if (field == null) {
field = content.addValue(cms, elementPath, contentLocale, i);
}
field.setStringValue(cms, value);
fieldsSet.add(field.getPath());
}
} else {
List<CmsEntity> entities = attribute.getComplexValues();
for (int i = 0; i < entities.size(); i++) {
CmsEntity child = entities.get(i);
I_CmsXmlContentValue field = content.getValue(elementPath, contentLocale, i);
if (field == null) {
field = content.addValue(cms, elementPath, contentLocale, i);
}
addEntityAttributes(cms, content, field.getPath() + "/", child, contentLocale, fieldsSet);
}
}
}
}
}
/**
* Check if automatic content correction is required. Returns <code>true</code> if the content was changed.<p>
*
* @param cms the cms context
* @param content the content to check
*
* @return <code>true</code> if the content was changed
* @throws CmsXmlException if the automatic content correction failed
*/
private boolean checkAutoCorrection(CmsObject cms, CmsXmlContent content) throws CmsXmlException {
boolean performedAutoCorrection = false;
try {
content.validateXmlStructure(new CmsXmlEntityResolver(cms));
} catch (CmsXmlException eXml) {
// validation failed
content.setAutoCorrectionEnabled(true);
content.correctXmlStructure(cms);
performedAutoCorrection = true;
}
return performedAutoCorrection;
}
/**
* Evaluates any wildcards in the given scope and returns all allowed permutations of it.<p>
*
* a path like Paragraph* /Image should result in Paragraph[0]/Image, Paragraph[1]/Image and Paragraph[2]/Image
* in case max occurrence for Paragraph is 3
*
* @param scope the scope
* @param definition the content definition
*
* @return the evaluate scope permutations
*/
private Set<String> evaluateScope(String scope, CmsXmlContentDefinition definition) {
Set<String> evaluatedScopes = new HashSet<String>();
if (scope.contains("*")) {
// evaluate wildcards to get all allowed permutations of the scope
// a path like Paragraph*/Image should result in Paragraph[0]/Image, Paragraph[1]/Image and Paragraph[2]/Image
// in case max occurrence for Paragraph is 3
String[] pathElements = scope.split("/");
String parentPath = "";
for (int i = 0; i < pathElements.length; i++) {
String elementName = pathElements[i];
boolean hasWildCard = elementName.endsWith("*");
if (hasWildCard) {
elementName = elementName.substring(0, elementName.length() - 1);
parentPath = CmsStringUtil.joinPaths(parentPath, elementName);
I_CmsXmlSchemaType type = definition.getSchemaType(parentPath);
Set<String> tempScopes = new HashSet<String>();
if (type.getMaxOccurs() == Integer.MAX_VALUE) {
throw new IllegalStateException(
"Can not use fields with unbounded maxOccurs in scopes for editor change handler.");
}
for (int j = 0; j < type.getMaxOccurs(); j++) {
if (evaluatedScopes.isEmpty()) {
tempScopes.add(elementName + "[" + (j + 1) + "]");
} else {
for (String evScope : evaluatedScopes) {
tempScopes.add(CmsStringUtil.joinPaths(evScope, elementName + "[" + (j + 1) + "]"));
}
}
}
evaluatedScopes = tempScopes;
} else {
parentPath = CmsStringUtil.joinPaths(parentPath, elementName);
Set<String> tempScopes = new HashSet<String>();
if (evaluatedScopes.isEmpty()) {
tempScopes.add(elementName);
} else {
for (String evScope : evaluatedScopes) {
tempScopes.add(CmsStringUtil.joinPaths(evScope, elementName));
}
}
evaluatedScopes = tempScopes;
}
}
} else {
evaluatedScopes.add(scope);
}
return evaluatedScopes;
}
/**
* Evaluates the values of the locale independent fields and the paths to skip during locale synchronization.<p>
*
* @param content the XML content
* @param syncValues the map of synchronization values
* @param skipPaths the list o paths to skip
*/
private void evaluateSyncLocaleValues(
CmsXmlContent content,
Map<String, String> syncValues,
Collection<String> skipPaths) {
CmsObject cms = getCmsObject();
for (Locale locale : content.getLocales()) {
for (String elementPath : content.getContentDefinition().getContentHandler().getSynchronizations()) {
for (I_CmsXmlContentValue contentValue : content.getSimpleValuesBelowPath(elementPath, locale)) {
String valuePath = contentValue.getPath();
boolean skip = false;
for (String skipPath : skipPaths) {
if (valuePath.startsWith(skipPath)) {
skip = true;
break;
}
}
if (!skip) {
String value = contentValue.getStringValue(cms);
if (syncValues.containsKey(valuePath)) {
if (!syncValues.get(valuePath).equals(value)) {
// in case the current value does not match the previously stored value,
// remove it and add the parent path to the skipPaths list
syncValues.remove(valuePath);
int pathLevelDiff = (CmsResource.getPathLevel(valuePath)
- CmsResource.getPathLevel(elementPath)) + 1;
for (int i = 0; i < pathLevelDiff; i++) {
valuePath = CmsXmlUtils.removeLastXpathElement(valuePath);
}
skipPaths.add(valuePath);
}
} else {
syncValues.put(valuePath, value);
}
}
}
}
}
}
/**
* Returns the best available locale present in the given XML content, or the default locale.<p>
*
* @param resource the resource
* @param content the XML content
*
* @return the locale
*/
private Locale getBestAvailableLocale(CmsResource resource, CmsXmlContent content) {
CmsObject cms = getCmsObject();
Locale locale = OpenCms.getLocaleManager().getDefaultLocale(getCmsObject(), resource);
if (!content.hasLocale(locale)) {
// if the requested locale is not available, get the first matching default locale,
// or the first matching available locale
boolean foundLocale = false;
if (content.getLocales().size() > 0) {
List<Locale> locales = OpenCms.getLocaleManager().getDefaultLocales(cms, resource);
for (Locale defaultLocale : locales) {
if (content.hasLocale(defaultLocale)) {
locale = defaultLocale;
foundLocale = true;
break;
}
}
if (!foundLocale) {
locales = OpenCms.getLocaleManager().getAvailableLocales(cms, resource);
for (Locale availableLocale : locales) {
if (content.hasLocale(availableLocale)) {
locale = availableLocale;
foundLocale = true;
break;
}
}
}
}
}
return locale;
}
/**
* Returns the change handler scopes.<p>
*
* @param definition the content definition
*
* @return the scopes
*/
private Set<String> getChangeHandlerScopes(CmsXmlContentDefinition definition) {
List<I_CmsXmlContentEditorChangeHandler> changeHandlers = definition.getContentHandler().getEditorChangeHandlers();
Set<String> scopes = new HashSet<String>();
for (I_CmsXmlContentEditorChangeHandler handler : changeHandlers) {
String scope = handler.getScope();
scopes.addAll(evaluateScope(scope, definition));
}
return scopes;
}
/**
* Returns the XML content document.<p>
*
* @param file the resource file
* @param fromCache <code>true</code> to use the cached document
*
* @return the content document
*
* @throws CmsXmlException if reading the XML fails
*/
private CmsXmlContent getContentDocument(CmsFile file, boolean fromCache) throws CmsXmlException {
CmsXmlContent content = null;
if (fromCache) {
content = getSessionCache().getCacheXmlContent(file.getStructureId());
}
if (content == null) {
content = CmsXmlContentFactory.unmarshal(getCmsObject(), file);
getSessionCache().setCacheXmlContent(file.getStructureId(), content);
}
return content;
}
/**
* Returns the path elements for the given content value.<p>
*
* @param content the XML content
* @param value the content value
*
* @return the path elements
*/
private String[] getPathElements(CmsXmlContent content, I_CmsXmlContentValue value) {
List<String> pathElements = new ArrayList<String>();
String[] paths = value.getPath().split("/");
String path = "";
for (int i = 0; i < paths.length; i++) {
path += paths[i];
I_CmsXmlContentValue ancestor = content.getValue(path, value.getLocale());
int valueIndex = ancestor.getXmlIndex();
if (ancestor.isChoiceOption()) {
Element parent = ancestor.getElement().getParent();
valueIndex = parent.indexOf(ancestor.getElement());
}
String pathElement = getAttributeName(ancestor.getName(), getTypeUri(ancestor.getContentDefinition()));
pathElements.add(pathElement + "[" + valueIndex + "]");
path += "/";
}
return pathElements.toArray(new String[pathElements.size()]);
}
/**
* Returns the session cache.<p>
*
* @return the session cache
*/
private CmsADESessionCache getSessionCache() {
if (m_sessionCache == null) {
m_sessionCache = CmsADESessionCache.getCache(getRequest(), getCmsObject());
}
return m_sessionCache;
}
/**
* Returns the workplace locale.<p>
*
* @param cms the current OpenCms context
*
* @return the current users workplace locale
*/
private Locale getWorkplaceLocale(CmsObject cms) {
if (m_workplaceLocale == null) {
m_workplaceLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
}
return m_workplaceLocale;
}
/**
* Reads the content definition for the given resource and locale.<p>
*
* @param file the resource file
* @param content the XML content
* @param entityId the entity id
* @param locale the content locale
* @param newLocale if the locale content should be created as new
*
* @return the content definition
*
* @throws CmsException if something goes wrong
*/
private CmsContentDefinition readContentDefinition(
CmsFile file,
CmsXmlContent content,
String entityId,
Locale locale,
boolean newLocale) throws CmsException {
long timer = 0;
if (LOG.isDebugEnabled()) {
timer = System.currentTimeMillis();
}
CmsObject cms = getCmsObject();
List<Locale> availableLocalesList = OpenCms.getLocaleManager().getAvailableLocales(cms, file);
if (!availableLocalesList.contains(locale)) {
availableLocalesList.retainAll(content.getLocales());
List<Locale> defaultLocales = OpenCms.getLocaleManager().getDefaultLocales(cms, file);
Locale replacementLocale = OpenCms.getLocaleManager().getBestMatchingLocale(
locale,
defaultLocales,
availableLocalesList);
LOG.info(
"Can't edit locale "
+ locale
+ " of file "
+ file.getRootPath()
+ " because it is not configured as available locale. Using locale "
+ replacementLocale
+ " instead.");
locale = replacementLocale;
entityId = CmsContentDefinition.uuidToEntityId(file.getStructureId(), locale.toString());
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(entityId)) {
entityId = CmsContentDefinition.uuidToEntityId(file.getStructureId(), locale.toString());
}
boolean performedAutoCorrection = checkAutoCorrection(cms, content);
if (performedAutoCorrection) {
content.initDocument();
}
if (LOG.isDebugEnabled()) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_TAKE_UNMARSHALING_TIME_1,
"" + (System.currentTimeMillis() - timer)));
}
CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(cms, file, locale);
if (LOG.isDebugEnabled()) {
timer = System.currentTimeMillis();
}
visitor.visitTypes(content.getContentDefinition(), getWorkplaceLocale(cms));
if (LOG.isDebugEnabled()) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_TAKE_VISITING_TYPES_TIME_1,
"" + (System.currentTimeMillis() - timer)));
}
CmsEntity entity = null;
Map<String, String> syncValues = new HashMap<String, String>();
Collection<String> skipPaths = new HashSet<String>();
evaluateSyncLocaleValues(content, syncValues, skipPaths);
if (content.hasLocale(locale) && newLocale) {
// a new locale is requested, so remove the present one
content.removeLocale(locale);
}
if (!content.hasLocale(locale)) {
content.addLocale(cms, locale);
// sync the locale values
if (!visitor.getLocaleSynchronizations().isEmpty() && (content.getLocales().size() > 1)) {
for (Locale contentLocale : content.getLocales()) {
if (!contentLocale.equals(locale)) {
content.synchronizeLocaleIndependentValues(cms, skipPaths, contentLocale);
}
}
}
}
Element element = content.getLocaleNode(locale);
if (LOG.isDebugEnabled()) {
timer = System.currentTimeMillis();
}
entity = readEntity(
content,
element,
locale,
entityId,
"",
getTypeUri(content.getContentDefinition()),
visitor,
false);
if (LOG.isDebugEnabled()) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_TAKE_READING_ENTITY_TIME_1,
"" + (System.currentTimeMillis() - timer)));
}
List<String> contentLocales = new ArrayList<String>();
for (Locale contentLocale : content.getLocales()) {
contentLocales.add(contentLocale.toString());
}
Locale workplaceLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
TreeMap<String, String> availableLocales = new TreeMap<String, String>();
for (Locale availableLocale : OpenCms.getLocaleManager().getAvailableLocales(cms, file)) {
availableLocales.put(availableLocale.toString(), availableLocale.getDisplayName(workplaceLocale));
}
String title = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
try {
CmsGallerySearchResult searchResult = CmsGallerySearch.searchById(cms, file.getStructureId(), locale);
title = searchResult.getTitle();
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
String typeName = OpenCms.getResourceManager().getResourceType(file.getTypeId()).getTypeName();
boolean autoUnlock = OpenCms.getWorkplaceManager().shouldAcaciaUnlock();
Map<String, CmsEntity> entities = new HashMap<String, CmsEntity>();
entities.put(entityId, entity);
return new CmsContentDefinition(
entityId,
entities,
visitor.getAttributeConfigurations(),
visitor.getWidgetConfigurations(),
visitor.getComplexWidgetData(),
visitor.getTypes(),
visitor.getTabInfos(),
locale.toString(),
contentLocales,
availableLocales,
visitor.getLocaleSynchronizations(),
syncValues,
skipPaths,
title,
cms.getSitePath(file),
typeName,
performedAutoCorrection,
autoUnlock,
getChangeHandlerScopes(content.getContentDefinition()));
}
/**
* Creates a new resource according to the new link, or returns the model file informations
* modelFileId is <code>null</code> but required.<p>
*
* @param newLink the new link
* @param referenceResource the reference resource
* @param modelFileId the model file structure id
* @param locale the content locale
* @param mode the content creation mode
* @param postCreateHandler the class name for the post-create handler
*
* @return the content definition
*
* @throws CmsException if creating the resource failed
*/
private CmsContentDefinition readContentDefnitionForNew(
String newLink,
CmsResource referenceResource,
CmsUUID modelFileId,
Locale locale,
String mode,
String postCreateHandler) throws CmsException {
String sitePath = getCmsObject().getSitePath(referenceResource);
String resourceType = OpenCms.getResourceManager().getResourceType(referenceResource.getTypeId()).getTypeName();
String modelFile = null;
if (modelFileId == null) {
List<CmsResource> modelResources = CmsNewResourceXmlContent.getModelFiles(
getCmsObject(),
CmsResource.getFolderPath(sitePath),
resourceType);
if (!modelResources.isEmpty()) {
List<CmsModelResourceInfo> modelInfos = CmsContainerpageService.generateModelResourceList(
getCmsObject(),
resourceType,
modelResources,
locale);
return new CmsContentDefinition(
modelInfos,
newLink,
referenceResource.getStructureId(),
locale.toString());
}
} else if (!modelFileId.isNullUUID()) {
modelFile = getCmsObject().getSitePath(
getCmsObject().readResource(modelFileId, CmsResourceFilter.IGNORE_EXPIRATION));
}
String newFileName = A_CmsResourceCollector.createResourceForCollector(
getCmsObject(),
newLink,
locale,
sitePath,
modelFile,
mode,
postCreateHandler);
CmsResource resource = getCmsObject().readResource(newFileName, CmsResourceFilter.IGNORE_EXPIRATION);
CmsFile file = getCmsObject().readFile(resource);
CmsXmlContent content = getContentDocument(file, false);
CmsContentDefinition contentDefinition = readContentDefinition(file, content, null, locale, false);
contentDefinition.setDeleteOnCancel(true);
return contentDefinition;
}
/**
* Synchronizes the locale independent fields for the given entity.<p>
*
* @param file the content file
* @param content the XML content
* @param skipPaths the paths to skip during locale synchronization
* @param entity the entity
*
* @throws CmsXmlException if something goes wrong
*/
private void synchronizeLocaleIndependentForEntity(
CmsFile file,
CmsXmlContent content,
Collection<String> skipPaths,
CmsEntity entity) throws CmsXmlException {
CmsObject cms = getCmsObject();
String entityId = entity.getId();
Locale contentLocale = CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entityId));
CmsContentTypeVisitor visitor = null;
CmsEntity originalEntity = null;
if (content.getHandler().hasVisibilityHandlers()) {
visitor = new CmsContentTypeVisitor(cms, file, contentLocale);
visitor.visitTypes(content.getContentDefinition(), getWorkplaceLocale(cms));
}
if (content.hasLocale(contentLocale)) {
if ((visitor != null) && visitor.hasInvisibleFields()) {
// we need to add invisible content values to the entity before saving
Element element = content.getLocaleNode(contentLocale);
originalEntity = readEntity(
content,
element,
contentLocale,
entityId,
"",
getTypeUri(content.getContentDefinition()),
visitor,
true);
}
content.removeLocale(contentLocale);
}
content.addLocale(cms, contentLocale);
if ((visitor != null) && visitor.hasInvisibleFields()) {
transferInvisibleValues(originalEntity, entity, visitor);
}
addEntityAttributes(cms, content, "", entity, contentLocale);
content.synchronizeLocaleIndependentValues(cms, skipPaths, contentLocale);
}
/**
* Validates the given XML content.<p>
*
* @param cms the cms context
* @param structureId the structure id
* @param content the XML content
*
* @return the validation result
*/
private CmsValidationResult validateContent(CmsObject cms, CmsUUID structureId, CmsXmlContent content) {
return validateContent(cms, structureId, content, null);
}
/**
* Validates the given XML content.<p>
*
* @param cms the cms context
* @param structureId the structure id
* @param content the XML content
* @param fieldNames if not null, only validation errors in paths from this set will be added to the validation result
*
* @return the validation result
*/
private CmsValidationResult validateContent(
CmsObject cms,
CmsUUID structureId,
CmsXmlContent content,
Set<String> fieldNames) {
CmsXmlContentErrorHandler errorHandler = content.validate(cms);
Map<String, Map<String[], String>> errorsByEntity = new HashMap<String, Map<String[], String>>();
if (errorHandler.hasErrors()) {
boolean reallyHasErrors = false;
for (Entry<Locale, Map<String, String>> localeEntry : errorHandler.getErrors().entrySet()) {
Map<String[], String> errors = new HashMap<String[], String>();
for (Entry<String, String> error : localeEntry.getValue().entrySet()) {
I_CmsXmlContentValue value = content.getValue(error.getKey(), localeEntry.getKey());
if ((fieldNames == null) || fieldNames.contains(value.getPath())) {
errors.put(getPathElements(content, value), error.getValue());
reallyHasErrors = true;
}
}
if (reallyHasErrors) {
errorsByEntity.put(
CmsContentDefinition.uuidToEntityId(structureId, localeEntry.getKey().toString()),
errors);
}
}
}
Map<String, Map<String[], String>> warningsByEntity = new HashMap<String, Map<String[], String>>();
if (errorHandler.hasWarnings()) {
boolean reallyHasErrors = false;
for (Entry<Locale, Map<String, String>> localeEntry : errorHandler.getWarnings().entrySet()) {
Map<String[], String> warnings = new HashMap<String[], String>();
for (Entry<String, String> warning : localeEntry.getValue().entrySet()) {
I_CmsXmlContentValue value = content.getValue(warning.getKey(), localeEntry.getKey());
if ((fieldNames == null) || fieldNames.contains(value.getPath())) {
warnings.put(getPathElements(content, value), warning.getValue());
reallyHasErrors = true;
}
}
if (reallyHasErrors) {
warningsByEntity.put(
CmsContentDefinition.uuidToEntityId(structureId, localeEntry.getKey().toString()),
warnings);
}
}
}
return new CmsValidationResult(errorsByEntity, warningsByEntity);
}
/**
* Writes the xml content to the vfs and re-initializes the member variables.<p>
*
* @param cms the cms context
* @param file the file to write to
* @param content the content
* @param encoding the file encoding
*
* @return the content
*
* @throws CmsException if writing the file fails
*/
private CmsXmlContent writeContent(CmsObject cms, CmsFile file, CmsXmlContent content, String encoding)
throws CmsException {
String decodedContent = content.toString();
try {
file.setContents(decodedContent.getBytes(encoding));
} catch (UnsupportedEncodingException e) {
throw new CmsException(
org.opencms.workplace.editors.Messages.get().container(
org.opencms.workplace.editors.Messages.ERR_INVALID_CONTENT_ENC_1,
file.getRootPath()),
e);
}
// the file content might have been modified during the write operation
file = cms.writeFile(file);
return CmsXmlContentFactory.unmarshal(cms, file);
}
}
|
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */
package jp.oist.flint.parameter;
import java.io.File;
import java.io.IOException;
public class SbmlParameterModel extends ParameterModel {
public final static int INDEX_SPECIES_ID = 0;
public final static int INDEX_EXPRESSION = 1;
SbmlParameterModel(File paramFile, File dataFile) throws IOException {
super(paramFile, dataFile);
mColumns = new Object[] {"Id", "Expression"};
}
@Override
public boolean isCellEditable (int row, int column) {
return column == 1;
}
@Override
public Object getValueAt (int row, int column) {
Parameter p = mParameterList.get(row);
switch (column) {
case INDEX_SPECIES_ID: return p.getName();
case INDEX_EXPRESSION: return p.getValue();
}
return null;
}
@Override
public void setValueAt (Object value, int row, int column) {
Parameter p = mParameterList.get(row);
String v = (value == null)? "" : value.toString();
if (column == 1) p.setValue(v);
}
public String getSpeciesIdAt (int row) {
return (String)getValueAt(row, INDEX_SPECIES_ID);
}
public String getExpressionAt (int row) {
return (String)getValueAt(row, INDEX_EXPRESSION);
}
public void setExpressionAt (int row, Object expression) {
setValueAt(expression, row, INDEX_EXPRESSION);
}
}
|
package helloworld;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
return new ApplicationActionBarAdvisor(configurer);
}
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.getWindow().getShell().setMaximized(true);
configurer.setShowCoolBar(true);
configurer.setShowStatusLine(false);
configurer.setTitle("Hello World RCP (Temenos 123)"); //$NON-NLS-1$
}
}
|
package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import java.awt.BorderLayout;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.xml.parsers.DocumentBuilderFactory;
import nl.mpi.arbil.data.ArbilComponentBuilder;
import nl.mpi.arbil.ui.ArbilTableModel;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.kindata.GraphSorter;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
import nl.mpi.kinnate.kintypestrings.KinTermGroup;
import nl.mpi.kinnate.ui.HidePane;
import nl.mpi.kinnate.ui.KinDiagramPanel;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.swing.svg.LinkActivationEvent;
import org.apache.batik.swing.svg.LinkActivationListener;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGDocument;
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
protected JSVGCanvas svgCanvas;
protected SVGDocument doc;
protected ArbilTableModel arbilTableModel;
protected JScrollPane tableScrollPane;
protected HidePane editorHidePane;
private boolean requiresSave = false;
private File svgFile = null;
protected GraphPanelSize graphPanelSize;
protected LineLookUpTable lineLookUpTable;
protected ArrayList<UniqueIdentifier> selectedGroupId;
protected String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
public DataStoreSvg dataStoreSvg;
protected EntitySvg entitySvg;
// private URI[] egoPathsTemp = null;
public SvgUpdateHandler svgUpdateHandler;
private int currentZoom = 0;
private AffineTransform zoomAffineTransform = null;
public MouseListenerSvg mouseListenerSvg;
public GraphPanel(KinDiagramPanel kinDiagramPanel) {
dataStoreSvg = new DataStoreSvg();
entitySvg = new EntitySvg();
dataStoreSvg.setDefaults();
svgUpdateHandler = new SvgUpdateHandler(this, kinDiagramPanel);
selectedGroupId = new ArrayList<UniqueIdentifier>();
graphPanelSize = new GraphPanelSize();
this.setLayout(new BorderLayout());
svgCanvas = new JSVGCanvas();
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
currentZoom = currentZoom + e.getUnitsToScroll();
if (currentZoom > 8) {
currentZoom = 8;
}
if (currentZoom < -6) {
currentZoom = -6;
}
double scale = 1 - e.getUnitsToScroll() / 10.0;
double tx = -e.getX() * (scale - 1);
double ty = -e.getY() * (scale - 1);
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
at.scale(scale, scale);
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
// zoomDrawing();
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
mouseListenerSvg = new MouseListenerSvg(kinDiagramPanel, this);
svgCanvas.addMouseListener(mouseListenerSvg);
svgCanvas.addMouseMotionListener(mouseListenerSvg);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
// svgCanvas.setBackground(Color.LIGHT_GRAY);
this.add(BorderLayout.CENTER, jSVGScrollPane);
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(kinDiagramPanel, this, graphPanelSize));
svgCanvas.addLinkActivationListener(new LinkActivationListener() {
public void linkActivated(LinkActivationEvent lae) {
// todo: find a better way to block the built in hyper link handler that tries to load the url into the canvas
throw new UnsupportedOperationException("Not supported yet.");
}
});
}
// private void zoomDrawing() {
// AffineTransform scaleTransform = new AffineTransform();
// scaleTransform.scale(1 - currentZoom / 10.0, 1 - currentZoom / 10.0);
// System.out.println("currentZoom: " + currentZoom);
//// svgCanvas.setRenderingTransform(scaleTransform);
// Rectangle canvasBounds = this.getBounds();
// SVGRect bbox = ((SVGLocatable) doc.getRootElement()).getBBox();
// if (bbox != null) {
// System.out.println("previousZoomedWith: " + bbox.getWidth());
//// SVGElement rootElement = doc.getRootElement();
//// if (currentWidth < canvasBounds.width) {
// float drawingCenter = (currentWidth / 2);
//// float drawingCenter = (bbox.getX() + (bbox.getWidth() / 2));
// float canvasCenter = (canvasBounds.width / 2);
// zoomAffineTransform = new AffineTransform();
// zoomAffineTransform.translate((canvasCenter - drawingCenter), 1);
// zoomAffineTransform.concatenate(scaleTransform);
// svgCanvas.setRenderingTransform(zoomAffineTransform);
public void setArbilTableModel(JScrollPane tableScrollPane, ArbilTableModel arbilTableModelLocal, HidePane editorHidePane) {
this.tableScrollPane = tableScrollPane;
this.editorHidePane = editorHidePane;
arbilTableModel = arbilTableModelLocal;
}
public EntityData[] readSvg(File svgFilePath) {
svgFile = svgFilePath;
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toURI().toString());
svgCanvas.setDocument(doc);
dataStoreSvg = DataStoreSvg.loadDataFromSvg(doc);
requiresSave = false;
entitySvg.readEntityPositions(doc.getElementById("EntityGroup"));
entitySvg.readEntityPositions(doc.getElementById("LabelsGroup"));
entitySvg.readEntityPositions(doc.getElementById("GraphicsGroup"));
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
Element svgRoot = doc.getDocumentElement();
// make sure the diagram group exisits
Element diagramElement = doc.getElementById("DiagramGroup");
if (diagramElement == null) {
diagramElement = doc.createElementNS(svgNameSpace, "g");
diagramElement.setAttribute("id", "DiagramGroup");
svgRoot.appendChild(diagramElement);
}
// set up the mouse listeners that were lost in the save/re-open process
// add any groups that are required and add them in the required order
Element previousElement = null;
for (String groupForMouseListener : new String[]{"LabelsGroup", "EntityGroup", "GraphicsGroup"}) {
Element parentElement = doc.getElementById(groupForMouseListener);
if (parentElement == null) {
parentElement = doc.createElementNS(svgNameSpace, "g");
parentElement.setAttribute("id", groupForMouseListener);
diagramElement.insertBefore(parentElement, previousElement);
} else {
Node currentNode = parentElement.getFirstChild();
while (currentNode != null) {
((EventTarget) currentNode).addEventListener("mousedown", mouseListenerSvg, false);
currentNode = currentNode.getNextSibling();
}
}
previousElement = parentElement;
}
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc));
if (dataStoreSvg.graphData == null) {
return null;
}
svgCanvas.setSVGDocument(doc);
return dataStoreSvg.graphData.getDataNodes();
}
public void generateDefaultSvg() {
try {
Element diagramGroup;
Element relationGroupNode;
Element entityGroupNode;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
// set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// in order to add the extra namespaces to the svg document we use a string and parse it
// other methods have been tried but this is the most readable and the only one that actually works
// I think this is mainly due to the way the svg dom would otherwise be constructed
// others include:
// doc.getDomConfig()
// doc.getDocumentElement().setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:version", "");
// doc.getDocumentElement().setAttribute("xmlns:" + DataStoreSvg.kinDataNameSpace, DataStoreSvg.kinDataNameSpaceLocation); // this method of declaring multiple namespaces looks to me to be wrong but it is the only method that does not get stripped out by the transformer on save
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<svg xmlns:xlink=\"http:
+ "xmlns=\"http:
+ " zoomAndPan=\"magnify\" contentStyleType=\"text/css\" "
+ "preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\"/>";
// DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
doc = (SVGDocument) documentFactory.createDocument(svgNameSpace, new StringReader(templateXml));
entitySvg.insertSymbols(doc, svgNameSpace);
// add the diagram group to the root element (the 'svg' element)
diagramGroup = doc.createElementNS(svgNameSpace, "g");
diagramGroup.setAttribute("id", "DiagramGroup");
doc.getDocumentElement().appendChild(diagramGroup);
// add the graphics group below the entities and relations
Element graphicsGroup = doc.createElementNS(svgNameSpace, "g");
graphicsGroup.setAttribute("id", "GraphicsGroup");
diagramGroup.appendChild(graphicsGroup);
// add the relation symbols in a group below the relation lines
relationGroupNode = doc.createElementNS(svgNameSpace, "g");
relationGroupNode.setAttribute("id", "RelationGroup");
diagramGroup.appendChild(relationGroupNode);
// add the entity symbols in a group on top of the relation lines
entityGroupNode = doc.createElementNS(svgNameSpace, "g");
entityGroupNode.setAttribute("id", "EntityGroup");
diagramGroup.appendChild(entityGroupNode);
// add the labels group on top, also added on svg load if missing
Element labelsGroup = doc.createElementNS(svgNameSpace, "g");
labelsGroup.setAttribute("id", "LabelsGroup");
diagramGroup.appendChild(labelsGroup);
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc));
svgCanvas.setSVGDocument(doc);
dataStoreSvg.graphData = new GraphSorter();
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
// todo: make sure the file path ends in .svg lowercase
// start temp fix
selectedGroupId.clear();
svgUpdateHandler.drawEntities(); // todo: look into handling the runnable so that this cannot cause any issues
// end temp fix
// drawNodes(); // re draw the nodes so that any data changes such as the title/description in the kin term groups get updated into the file
// end previous menthod before temp fix
ArbilComponentBuilder.savePrettyFormatting(doc, svgFilePath);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
public String[] getKinTypeStrigs() {
return dataStoreSvg.kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
// this has set has been removed because it creates a discrepancy between what the user types and what is processed
// HashSet<String> kinTypeStringSet = new HashSet<String>();
// for (String kinTypeString : kinTypeStringArray) {
// if (kinTypeString != null && kinTypeString.trim().length() > 0) {
// kinTypeStringSet.add(kinTypeString.trim());
// dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
dataStoreSvg.kinTypeStrings = kinTypeStringArray;
}
public IndexerParameters getIndexParameters() {
return dataStoreSvg.indexParameters;
}
public KinTermGroup[] getkinTermGroups() {
return dataStoreSvg.kinTermGroups;
}
public void addKinTermGroup() {
ArrayList<KinTermGroup> kinTermsList = new ArrayList<KinTermGroup>(Arrays.asList(dataStoreSvg.kinTermGroups));
kinTermsList.add(new KinTermGroup());
dataStoreSvg.kinTermGroups = kinTermsList.toArray(new KinTermGroup[]{});
}
// public String[] getEgoUniquiIdentifiersList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// public String[] getEgoIdList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// public URI[] getEgoPaths() {
// if (egoPathsTemp != null) {
// return egoPathsTemp;
// ArrayList<URI> returnPaths = new ArrayList<URI>();
// for (String egoId : dataStoreSvg.egoIdentifierSet) {
// try {
// String entityPath = getPathForElementId(egoId);
//// if (entityPath != null) {
// returnPaths.add(new URI(entityPath));
// } catch (URISyntaxException ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
// // todo: warn user with a dialog
// return returnPaths.toArray(new URI[]{});
// public void setRequiredEntities(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities = new HashSet<String>(Arrays.asList(egoIdentifierArray));
// public void addRequiredEntity(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray));
// public void removeEgo(String[] egoIdentifierArray) {
// dataStoreSvg.egoIdentifierSet.removeAll(Arrays.asList(egoIdentifierArray));
public void setSelectedIds(UniqueIdentifier[] uniqueIdentifiers) {
selectedGroupId.clear();
selectedGroupId.addAll(Arrays.asList(uniqueIdentifiers));
mouseListenerSvg.updateSelectionDisplay();
}
public UniqueIdentifier[] getSelectedIds() {
return selectedGroupId.toArray(new UniqueIdentifier[]{});
}
public HashMap<UniqueIdentifier, EntityData> getEntitiesById(UniqueIdentifier[] uniqueIdentifiers) {
ArrayList<UniqueIdentifier> identifierList = new ArrayList<UniqueIdentifier>(Arrays.asList(uniqueIdentifiers));
HashMap<UniqueIdentifier, EntityData> returnMap = new HashMap<UniqueIdentifier, EntityData>();
for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) {
if (identifierList.contains(entityData.getUniqueIdentifier())) {
returnMap.put(entityData.getUniqueIdentifier(), entityData);
}
}
return returnMap;
}
// public boolean selectionContainsEgo() {
// for (String selectedId : selectedGroupId) {
// if (dataStoreSvg.egoIdentifierSet.contains(selectedId)) {
// return true;
// return false;
public String getPathForElementId(UniqueIdentifier elementId) {
// NamedNodeMap namedNodeMap = doc.getElementById(elementId).getAttributes();
// for (int attributeCounter = 0; attributeCounter < namedNodeMap.getLength(); attributeCounter++) {
// System.out.println(namedNodeMap.item(attributeCounter).getNodeName());
// System.out.println(namedNodeMap.item(attributeCounter).getNamespaceURI());
// System.out.println(namedNodeMap.item(attributeCounter).getNodeValue());
Element entityElement = doc.getElementById(elementId.getAttributeIdentifier());
if (entityElement == null) {
return null;
} else {
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path");
}
}
public String getKinTypeForElementId(UniqueIdentifier elementId) {
Element entityElement = doc.getElementById(elementId.getAttributeIdentifier());
if (entityElement != null) {
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kintype");
} else {
return "";
}
}
public void resetZoom() {
// todo: this should be moved to the svg update handler and put into a runnable
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void resetLayout() {
entitySvg = new EntitySvg();
dataStoreSvg.graphData.setEntitys(dataStoreSvg.graphData.getDataNodes());
dataStoreSvg.graphData.placeAllNodes(entitySvg.entityPositions);
drawNodes();
}
public void clearEntityLocations(UniqueIdentifier[] selectedIdentifiers) {
entitySvg.clearEntityLocations(selectedIdentifiers);
}
public void drawNodes() {
requiresSave = true;
selectedGroupId.clear();
svgUpdateHandler.updateEntities();
}
public void drawNodes(GraphSorter graphDataLocal) {
dataStoreSvg.graphData = graphDataLocal;
drawNodes();
if (graphDataLocal.getDataNodes().length == 0) {
// if all entities have been removed then reset the zoom so that new nodes are going to been centered
// todo: it would be better to move the window to cover the drawing area but not change the zoom
// resetZoom();
}
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public File getFileName() {
return svgFile;
}
public boolean requiresSave() {
return requiresSave;
}
public void setRequiresSave() {
requiresSave = true;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
public void updateGraph() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package org.smoothbuild.exec.algorithm;
import static org.smoothbuild.exec.algorithm.AlgorithmHashes.convertAlgorithmHash;
import org.smoothbuild.db.hashed.Hash;
import org.smoothbuild.db.object.base.Array;
import org.smoothbuild.db.object.base.ArrayBuilder;
import org.smoothbuild.db.object.base.Obj;
import org.smoothbuild.db.object.spec.AnySpec;
import org.smoothbuild.db.object.spec.ArraySpec;
import org.smoothbuild.db.object.spec.Spec;
import org.smoothbuild.exec.base.Input;
import org.smoothbuild.exec.base.Output;
import org.smoothbuild.plugin.NativeApi;
public class ConvertAlgorithm extends Algorithm {
public ConvertAlgorithm(Spec outputSpec) {
super(outputSpec);
}
@Override
public Hash hash() {
return convertAlgorithmHash(outputSpec());
}
@Override
public Output run(Input input, NativeApi nativeApi) {
if (input.objects().size() != 1) {
throw newBuildBrokenException("Expected input size == 1 but was " + input.objects().size());
}
Obj obj = input.objects().get(0);
assertThatSpecsAreNotEqual(obj);
return new Output(convert(outputSpec(), obj, nativeApi), nativeApi.messages());
}
private void assertThatSpecsAreNotEqual(Obj obj) {
if (outputSpec().equals(obj.spec())) {
throw newBuildBrokenException(
"Expected non equal specs but got " + outputSpec() + " " + obj.spec());
}
}
private static Obj convert(Spec destinationSpec, Obj obj, NativeApi nativeApi) {
if (destinationSpec instanceof AnySpec) {
return nativeApi.factory().any(obj.hash());
} else if (obj instanceof Array array) {
return convertArray(destinationSpec, array, nativeApi);
}
throw newBuildBrokenException("Expected `Array` spec but got " + obj.getClass());
}
private static Obj convertArray(Spec destinationSpec, Array array, NativeApi nativeApi) {
Spec elemSpec = ((ArraySpec) destinationSpec).elemSpec();
ArrayBuilder arrayBuilder = nativeApi.factory().arrayBuilder(elemSpec);
for (Obj element : array.asIterable(Obj.class)) {
arrayBuilder.add(convert(elemSpec, element, nativeApi));
}
return arrayBuilder.build();
}
private static RuntimeException newBuildBrokenException(String message) {
return new RuntimeException(
"This should not happen. It means smooth build release is broken." + message);
}
}
|
package org.xcolab.portlets.proposals.view.action;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.xcolab.portlets.proposals.exceptions.ProposalsAuthorizationException;
import org.xcolab.portlets.proposals.requests.UpdateProposalDetailsBean;
import org.xcolab.portlets.proposals.utils.ProposalsContext;
import org.xcolab.portlets.proposals.wrappers.ProposalSectionWrapper;
import org.xcolab.portlets.proposals.wrappers.ProposalTab;
import org.xcolab.portlets.proposals.wrappers.ProposalWrapper;
import com.ext.portlet.ProposalAttributeKeys;
import com.ext.portlet.model.Proposal;
import com.ext.portlet.service.ProposalLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
@Controller
@RequestMapping("view")
public class UdateProposalScenarioActionController {
@Autowired
private ProposalsContext proposalsContext;
@RequestMapping(params = {"action=updateProposalScenario"})
public void show(ActionRequest request, Model model,
ActionResponse response, @RequestParam(required = true) long scenarioId)
throws PortalException, SystemException, ProposalsAuthorizationException, IOException {
if (proposalsContext.getProposal(request) != null && !canEditImpactTab(request)){
throw new ProposalsAuthorizationException("User is not allowed to edit proposal, user: " +
proposalsContext.getUser(request).getUserId() + ", proposal: " + proposalsContext.getProposal(request).getProposalId());
}
ProposalWrapper proposal = proposalsContext.getProposalWrapped(request);
ProposalLocalServiceUtil.setAttribute(proposalsContext.getUser(request).getUserId(),
proposal.getProposalId(), ProposalAttributeKeys.SCENARIO_ID, proposal.getModelId(), scenarioId);
proposalsContext.invalidateContext(request);
}
private boolean canEditImpactTab(PortletRequest request) throws PortalException, SystemException{
return ProposalTab.IMPACT.getCanEdit(proposalsContext.getPermissions(request), proposalsContext, request);
}
}
|
package org.threeten.bp.format;
import static org.threeten.bp.temporal.ChronoField.DAY_OF_MONTH;
import static org.threeten.bp.temporal.ChronoField.HOUR_OF_DAY;
import static org.threeten.bp.temporal.ChronoField.INSTANT_SECONDS;
import static org.threeten.bp.temporal.ChronoField.MINUTE_OF_HOUR;
import static org.threeten.bp.temporal.ChronoField.MONTH_OF_YEAR;
import static org.threeten.bp.temporal.ChronoField.NANO_OF_SECOND;
import static org.threeten.bp.temporal.ChronoField.OFFSET_SECONDS;
import static org.threeten.bp.temporal.ChronoField.SECOND_OF_MINUTE;
import static org.threeten.bp.temporal.ChronoField.YEAR;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import org.threeten.bp.DateTimeException;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.chrono.Chronology;
import org.threeten.bp.format.SimpleDateTimeTextProvider.LocaleStore;
import org.threeten.bp.jdk8.Jdk8Methods;
import org.threeten.bp.temporal.ChronoField;
import org.threeten.bp.temporal.IsoFields;
import org.threeten.bp.temporal.TemporalAccessor;
import org.threeten.bp.temporal.TemporalField;
import org.threeten.bp.temporal.TemporalQueries;
import org.threeten.bp.temporal.TemporalQuery;
import org.threeten.bp.temporal.ValueRange;
import org.threeten.bp.zone.ZoneRulesProvider;
/**
* Builder to create date-time formatters.
* <p>
* This allows a {@code DateTimeFormatter} to be created.
* All date-time formatters are created ultimately using this builder.
* <p>
* The basic elements of date-time can all be added:
* <p><ul>
* <li>Value - a numeric value</li>
* <li>Fraction - a fractional value including the decimal place. Always use this when
* outputting fractions to ensure that the fraction is parsed correctly</li>
* <li>Text - the textual equivalent for the value</li>
* <li>OffsetId/Offset - the {@linkplain ZoneOffset zone offset}</li>
* <li>ZoneId - the {@linkplain ZoneId time-zone} id</li>
* <li>ZoneText - the name of the time-zone</li>
* <li>Literal - a text literal</li>
* <li>Nested and Optional - formats can be nested or made optional</li>
* <li>Other - the printer and parser interfaces can be used to add user supplied formatting</li>
* </ul><p>
* In addition, any of the elements may be decorated by padding, either with spaces or any other character.
* <p>
* Finally, a shorthand pattern, mostly compatible with {@code java.text.SimpleDateFormat SimpleDateFormat}
* can be used, see {@link #appendPattern(String)}.
* In practice, this simply parses the pattern and calls other methods on the builder.
*
* <h3>Specification for implementors</h3>
* This class is a mutable builder intended for use from a single thread.
*/
public final class DateTimeFormatterBuilder {
/**
* Query for a time-zone that is region-only.
*/
private static final TemporalQuery<ZoneId> QUERY_REGION_ONLY = new TemporalQuery<ZoneId>() {
public ZoneId queryFrom(TemporalAccessor temporal) {
ZoneId zone = temporal.query(TemporalQueries.zoneId());
return (zone != null && zone instanceof ZoneOffset == false ? zone : null);
}
};
/**
* The currently active builder, used by the outermost builder.
*/
private DateTimeFormatterBuilder active = this;
/**
* The parent builder, null for the outermost builder.
*/
private final DateTimeFormatterBuilder parent;
/**
* The list of printers that will be used.
*/
private final List<DateTimePrinterParser> printerParsers = new ArrayList<>();
/**
* Whether this builder produces an optional formatter.
*/
private final boolean optional;
/**
* The width to pad the next field to.
*/
private int padNextWidth;
/**
* The character to pad the next field with.
*/
private char padNextChar;
/**
* The index of the last variable width value parser.
*/
private int valueParserIndex = -1;
/**
* Constructs a new instance of the builder.
*/
public DateTimeFormatterBuilder() {
super();
parent = null;
optional = false;
}
/**
* Constructs a new instance of the builder.
*
* @param parent the parent builder, not null
* @param optional whether the formatter is optional, not null
*/
private DateTimeFormatterBuilder(DateTimeFormatterBuilder parent, boolean optional) {
super();
this.parent = parent;
this.optional = optional;
}
/**
* Changes the parse style to be case sensitive for the remainder of the formatter.
* <p>
* Parsing can be case sensitive or insensitive - by default it is case sensitive.
* This method allows the case sensitivity setting of parsing to be changed.
* <p>
* Calling this method changes the state of the builder such that all
* subsequent builder method calls will parse text in case sensitive mode.
* See {@link #parseCaseInsensitive} for the opposite setting.
* The parse case sensitive/insensitive methods may be called at any point
* in the builder, thus the parser can swap between case parsing modes
* multiple times during the parse.
* <p>
* Since the default is case sensitive, this method should only be used after
* a previous call to {@code #parseCaseInsensitive}.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder parseCaseSensitive() {
appendInternal(SettingsParser.SENSITIVE);
return this;
}
/**
* Changes the parse style to be case insensitive for the remainder of the formatter.
* <p>
* Parsing can be case sensitive or insensitive - by default it is case sensitive.
* This method allows the case sensitivity setting of parsing to be changed.
* <p>
* Calling this method changes the state of the builder such that all
* subsequent builder method calls will parse text in case sensitive mode.
* See {@link #parseCaseSensitive()} for the opposite setting.
* The parse case sensitive/insensitive methods may be called at any point
* in the builder, thus the parser can swap between case parsing modes
* multiple times during the parse.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder parseCaseInsensitive() {
appendInternal(SettingsParser.INSENSITIVE);
return this;
}
/**
* Changes the parse style to be strict for the remainder of the formatter.
* <p>
* Parsing can be strict or lenient - by default its strict.
* This controls the degree of flexibility in matching the text and sign styles.
* <p>
* When used, this method changes the parsing to be strict from this point onwards.
* As strict is the default, this is normally only needed after calling {@link #parseLenient()}.
* The change will remain in force until the end of the formatter that is eventually
* constructed or until {@code parseLenient} is called.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder parseStrict() {
appendInternal(SettingsParser.STRICT);
return this;
}
/**
* Changes the parse style to be lenient for the remainder of the formatter.
* Note that case sensitivity is set separately to this method.
* <p>
* Parsing can be strict or lenient - by default its strict.
* This controls the degree of flexibility in matching the text and sign styles.
* Applications calling this method should typically also call {@link #parseCaseInsensitive()}.
* <p>
* When used, this method changes the parsing to be strict from this point onwards.
* The change will remain in force until the end of the formatter that is eventually
* constructed or until {@code parseStrict} is called.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder parseLenient() {
appendInternal(SettingsParser.LENIENT);
return this;
}
/**
* Appends the value of a date-time field to the formatter using a normal
* output style.
* <p>
* The value of the field will be output during a print.
* If the value cannot be obtained then an exception will be thrown.
* <p>
* The value will be printed as per the normal print of an integer value.
* Only negative numbers will be signed. No padding will be added.
* <p>
* The parser for a variable width value such as this normally behaves greedily,
* requiring one digit, but accepting as many digits as possible.
* This behavior can be affected by 'adjacent value parsing'.
* See {@link #appendValue(TemporalField, int)} for full details.
*
* @param field the field to append, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendValue(TemporalField field) {
Objects.requireNonNull(field, "field");
active.valueParserIndex = appendInternal(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL));
return this;
}
public DateTimeFormatterBuilder appendValue(TemporalField field, int width) {
Objects.requireNonNull(field, "field");
if (width < 1 || width > 19) {
throw new IllegalArgumentException("The width must be from 1 to 19 inclusive but was " + width);
}
NumberPrinterParser pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE);
return appendFixedWidth(width, pp);
}
public DateTimeFormatterBuilder appendValue(
TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
return appendValue(field, maxWidth);
}
Objects.requireNonNull(field, "field");
Objects.requireNonNull(signStyle, "signStyle");
if (minWidth < 1 || minWidth > 19) {
throw new IllegalArgumentException("The minimum width must be from 1 to 19 inclusive but was " + minWidth);
}
if (maxWidth < 1 || maxWidth > 19) {
throw new IllegalArgumentException("The maximum width must be from 1 to 19 inclusive but was " + maxWidth);
}
if (maxWidth < minWidth) {
throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " +
maxWidth + " < " + minWidth);
}
NumberPrinterParser pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle);
if (minWidth == maxWidth) {
appendInternal(pp);
} else {
active.valueParserIndex = appendInternal(pp);
}
return this;
}
public DateTimeFormatterBuilder appendValueReduced(
TemporalField field, int width, int baseValue) {
Objects.requireNonNull(field, "field");
ReducedPrinterParser pp = new ReducedPrinterParser(field, width, baseValue);
appendFixedWidth(width, pp);
return this;
}
/**
* Appends a fixed width printer-parser.
*
* @param width the width
* @param pp the printer-parser, not null
* @return this, for chaining, not null
*/
private DateTimeFormatterBuilder appendFixedWidth(int width, NumberPrinterParser pp) {
if (active.valueParserIndex >= 0) {
// adjacent parsing mode, update setting in previous parsers
NumberPrinterParser basePP = (NumberPrinterParser) active.printerParsers.get(active.valueParserIndex);
basePP = basePP.withSubsequentWidth(width);
int activeValueParser = active.valueParserIndex;
active.printerParsers.set(active.valueParserIndex, basePP);
appendInternal(pp.withFixedWidth());
active.valueParserIndex = activeValueParser;
} else {
// not adjacent parsing
appendInternal(pp);
}
return this;
}
public DateTimeFormatterBuilder appendFraction(
TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
appendInternal(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint));
return this;
}
/**
* Appends the text of a date-time field to the formatter using the full
* text style.
* <p>
* The text of the field will be output during a print.
* The value must be within the valid range of the field.
* If the value cannot be obtained then an exception will be thrown.
* If the field has no textual representation, then the numeric value will be used.
* <p>
* The value will be printed as per the normal print of an integer value.
* Only negative numbers will be signed. No padding will be added.
*
* @param field the field to append, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendText(TemporalField field) {
return appendText(field, TextStyle.FULL);
}
/**
* Appends the text of a date-time field to the formatter.
* <p>
* The text of the field will be output during a print.
* The value must be within the valid range of the field.
* If the value cannot be obtained then an exception will be thrown.
* If the field has no textual representation, then the numeric value will be used.
* <p>
* The value will be printed as per the normal print of an integer value.
* Only negative numbers will be signed. No padding will be added.
*
* @param field the field to append, not null
* @param textStyle the text style to use, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendText(TemporalField field, TextStyle textStyle) {
Objects.requireNonNull(field, "field");
Objects.requireNonNull(textStyle, "textStyle");
appendInternal(new TextPrinterParser(field, textStyle, DateTimeTextProvider.getInstance()));
return this;
}
/**
* Appends the text of a date-time field to the formatter using the specified
* map to supply the text.
* <p>
* The standard text outputting methods use the localized text in the JDK.
* This method allows that text to be specified directly.
* The supplied map is not validated by the builder to ensure that printing or
* parsing is possible, thus an invalid map may throw an error during later use.
* <p>
* Supplying the map of text provides considerable flexibility in printing and parsing.
* For example, a legacy application might require or supply the months of the
* year as "JNY", "FBY", "MCH" etc. These do not match the standard set of text
* for localized month names. Using this method, a map can be created which
* defines the connection between each value and the text:
* <pre>
* Map<Long, String> map = new HashMap<>();
* map.put(1, "JNY");
* map.put(2, "FBY");
* map.put(3, "MCH");
* ...
* builder.appendText(MONTH_OF_YEAR, map);
* </pre>
* <p>
* Other uses might be to output the value with a suffix, such as "1st", "2nd", "3rd",
* or as Roman numerals "I", "II", "III", "IV".
* <p>
* During printing, the value is obtained and checked that it is in the valid range.
* If text is not available for the value then it is output as a number.
* During parsing, the parser will match against the map of text and numeric values.
*
* @param field the field to append, not null
* @param textLookup the map from the value to the text
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup) {
Objects.requireNonNull(field, "field");
Objects.requireNonNull(textLookup, "textLookup");
Map<Long, String> copy = new LinkedHashMap<>(textLookup);
Map<TextStyle, Map<Long, String>> map = Collections.singletonMap(TextStyle.FULL, copy);
final LocaleStore store = new LocaleStore(map);
DateTimeTextProvider provider = new DateTimeTextProvider() {
@Override
public String getText(TemporalField field, long value, TextStyle style, Locale locale) {
return store.getText(value, style);
}
@Override
public Iterator<Entry<String, Long>> getTextIterator(TemporalField field, TextStyle style, Locale locale) {
return store.getTextIterator(style);
}
@Override
public Locale[] getAvailableLocales() {
throw new UnsupportedOperationException();
}
};
appendInternal(new TextPrinterParser(field, TextStyle.FULL, provider));
return this;
}
/**
* Appends an instant using ISO-8601 to the formatter.
* <p>
* Instants have a fixed output format.
* They are converted to a date-time with a zone-offset of UTC and printed
* using the standard ISO-8601 format.
* <p>
* An alternative to this method is to print/parse the instant as a single
* epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendInstant() {
appendInternal(new InstantPrinterParser());
return this;
}
/**
* Appends the zone offset, such as '+01:00', to the formatter.
* <p>
* This appends an instruction to print/parse the offset ID to the builder.
* This is equivalent to calling {@code appendOffset("HH:MM:ss", "Z")}.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendOffsetId() {
appendInternal(OffsetIdPrinterParser.INSTANCE_ID);
return this;
}
/**
* Appends the zone offset, such as '+01:00', to the formatter.
* <p>
* This appends an instruction to print/parse the offset ID to the builder.
* <p>
* During printing, the offset is obtained using a mechanism equivalent
* to querying the temporal with {@link TemporalQueries#offset()}.
* It will be printed using the format defined below.
* If the offset cannot be obtained then an exception is thrown unless the
* section of the formatter is optional.
* <p>
* During parsing, the offset is parsed using the format defined below.
* If the offset cannot be parsed then an exception is thrown unless the
* section of the formatter is optional.
* <p>
* The format of the offset is controlled by a pattern which must be one
* of the following:
* <p><ul>
* <li>{@code +HH} - hour only, ignoring any minute
* <li>{@code +HHMM} - hour and minute, no colon
* <li>{@code +HH:MM} - hour and minute, with colon
* <li>{@code +HHMMss} - hour and minute, with second if non-zero and no colon
* <li>{@code +HH:MM:ss} - hour and minute, with second if non-zero and colon
* <li>{@code +HHMMSS} - hour, minute and second, no colon
* <li>{@code +HH:MM:SS} - hour, minute and second, with colon
* </ul><p>
* The "no offset" text controls what text is printed when the offset is zero.
* Example values would be 'Z', '+00:00', 'UTC' or 'GMT'.
* Three formats are accepted for parsing UTC - the "no offset" text, and the
* plus and minus versions of zero defined by the pattern.
*
* @param pattern the pattern to use, not null
* @param noOffsetText the text to use when the offset is zero, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendOffset(String pattern, String noOffsetText) {
appendInternal(new OffsetIdPrinterParser(noOffsetText, pattern));
return this;
}
/**
* Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to the formatter.
* <p>
* This appends an instruction to print/parse the zone ID to the builder.
* The zone ID is obtained in a strict manner suitable for {@code ZonedDateTime}.
* By contrast, {@code OffsetDateTime} does not have a zone ID suitable
* for use with this method, see {@link #appendZoneOrOffsetId()}.
* <p>
* During printing, the zone is obtained using a mechanism equivalent
* to querying the temporal with {@link TemporalQueries#zoneId()}.
* It will be printed using the result of {@link ZoneId#getId()}.
* If the zone cannot be obtained then an exception is thrown unless the
* section of the formatter is optional.
* <p>
* During parsing, the zone is parsed and must match a known zone or offset.
* If the zone cannot be parsed then an exception is thrown unless the
* section of the formatter is optional.
*
* @return this, for chaining, not null
* @see #appendZoneRegionId()
*/
public DateTimeFormatterBuilder appendZoneId() {
appendInternal(new ZoneIdPrinterParser(TemporalQueries.zoneId(), "ZoneId()"));
return this;
}
/**
* Appends the time-zone region ID, such as 'Europe/Paris', to the formatter,
* rejecting the zone ID if it is a {@code ZoneOffset}.
* <p>
* This appends an instruction to print/parse the zone ID to the builder
* only if it is a region-based ID.
* <p>
* During printing, the zone is obtained using a mechanism equivalent
* to querying the temporal with {@link TemporalQueries#zoneId()}.
* If the zone is a {@code ZoneOffset} or it cannot be obtained then
* an exception is thrown unless the section of the formatter is optional.
* If the zone is not an offset, then the zone will be printed using
* the zone ID from {@link ZoneId#getId()}.
* <p>
* During parsing, the zone is parsed and must match a known zone or offset.
* If the zone cannot be parsed then an exception is thrown unless the
* section of the formatter is optional.
* Note that parsing accepts offsets, whereas printing will never produce
* one, thus parsing is equivalent to {@code appendZoneId}.
*
* @return this, for chaining, not null
* @see #appendZoneId()
*/
public DateTimeFormatterBuilder appendZoneRegionId() {
appendInternal(new ZoneIdPrinterParser(QUERY_REGION_ONLY, "ZoneRegionId()"));
return this;
}
/**
* Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to
* the formatter, using the best available zone ID.
* <p>
* This appends an instruction to print/parse the best available
* zone or offset ID to the builder.
* The zone ID is obtained in a lenient manner that first attempts to
* find a true zone ID, such as that on {@code ZonedDateTime}, and
* then attempts to find an offset, such as that on {@code OffsetDateTime}.
* <p>
* During printing, the zone is obtained using a mechanism equivalent
* to querying the temporal with {@link TemporalQueries#zone()}.
* It will be printed using the result of {@link ZoneId#getId()}.
* If the zone cannot be obtained then an exception is thrown unless the
* section of the formatter is optional.
* <p>
* During parsing, the zone is parsed and must match a known zone or offset.
* If the zone cannot be parsed then an exception is thrown unless the
* section of the formatter is optional.
* <p>
* This method is is identical to {@code appendZoneId()} except in the
* mechanism used to obtain the zone.
*
* @return this, for chaining, not null
* @see #appendZoneId()
*/
public DateTimeFormatterBuilder appendZoneOrOffsetId() {
appendInternal(new ZoneIdPrinterParser(TemporalQueries.zone(), "ZoneOrOffsetId()"));
return this;
}
/**
* Appends the time-zone name, such as 'British Summer Time', to the formatter.
* <p>
* This appends an instruction to print the textual name of the zone to the builder.
* <p>
* During printing, the zone is obtained using a mechanism equivalent
* to querying the temporal with {@link TemporalQueries#zoneId()}.
* If the zone is a {@code ZoneOffset} it will be printed using the
* result of {@link ZoneOffset#getId()}.
* If the zone is not an offset, the textual name will be looked up
* for the locale set in the {@link DateTimeFormatter}.
* If the temporal object being printed represents an instant, then the text
* will be the summer or winter time text as appropriate.
* If the lookup for text does not find any suitable reuslt, then the
* {@link ZoneId#getId() ID} will be printed instead.
* If the zone cannot be obtained then an exception is thrown unless the
* section of the formatter is optional.
* <p>
* Parsing is not currently supported.
*
* @param textStyle the text style to use, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle) {
appendInternal(new ZoneTextPrinterParser(textStyle));
return this;
}
/**
* Appends the chronology ID to the formatter.
* <p>
* The chronology ID will be output during a print.
* If the chronology cannot be obtained then an exception will be thrown.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendChronologyId() {
appendInternal(new ChronoPrinterParser(null));
return this;
}
/**
* Appends the chronology ID, such as 'ISO' or 'ThaiBuddhist', to the formatter.
* <p>
* This appends an instruction to format/parse the chronology ID to the builder.
* <p>
* During printing, the chronology is obtained using a mechanism equivalent
* to querying the temporal with {@link Queries#chronology()}.
* It will be printed using the result of {@link Chronology#getId()}.
* If the chronology cannot be obtained then an exception is thrown unless the
* section of the formatter is optional.
* <p>
* During parsing, the chronology is parsed and must match one of the chronologies
* in {@link Chronology#getAvailableChronologies()}.
* If the chronology cannot be parsed then an exception is thrown unless the
* section of the formatter is optional.
* The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendChronologyText(TextStyle textStyle) {
Objects.requireNonNull(textStyle, "textStyle");
appendInternal(new ChronoPrinterParser(textStyle));
return this;
}
public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle) {
if (dateStyle == null && timeStyle == null) {
throw new IllegalArgumentException("Either the date or time style must be non-null");
}
appendInternal(new LocalizedPrinterParser(dateStyle, timeStyle));
return this;
}
/**
* Appends a character literal to the formatter.
* <p>
* This character will be output during a print.
*
* @param literal the literal to append, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendLiteral(char literal) {
appendInternal(new CharLiteralPrinterParser(literal));
return this;
}
/**
* Appends a string literal to the formatter.
* <p>
* This string will be output during a print.
* <p>
* If the literal is empty, nothing is added to the formatter.
*
* @param literal the literal to append, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendLiteral(String literal) {
Objects.requireNonNull(literal, "literal");
if (literal.length() > 0) {
if (literal.length() == 1) {
appendInternal(new CharLiteralPrinterParser(literal.charAt(0)));
} else {
appendInternal(new StringLiteralPrinterParser(literal));
}
}
return this;
}
/**
* Appends all the elements of a formatter to the builder.
* <p>
* This method has the same effect as appending each of the constituent
* parts of the formatter directly to this builder.
*
* @param formatter the formatter to add, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder append(DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
appendInternal(formatter.toPrinterParser(false));
return this;
}
/**
* Appends a formatter to the builder which will optionally print/parse.
* <p>
* This method has the same effect as appending each of the constituent
* parts directly to this builder surrounded by an {@link #optionalStart()} and
* {@link #optionalEnd()}.
* <p>
* The formatter will print if data is available for all the fields contained within it.
* The formatter will parse if the string matches, otherwise no error is returned.
*
* @param formatter the formatter to add, not null
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder appendOptional(DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
appendInternal(formatter.toPrinterParser(true));
return this;
}
public DateTimeFormatterBuilder appendPattern(String pattern) {
Objects.requireNonNull(pattern, "pattern");
parsePattern(pattern);
return this;
}
private void parsePattern(String pattern) {
for (int pos = 0; pos < pattern.length(); pos++) {
char cur = pattern.charAt(pos);
if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
int start = pos++;
for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++); // short loop
int count = pos - start;
// padding
if (cur == 'p') {
int pad = 0;
if (pos < pattern.length()) {
cur = pattern.charAt(pos);
if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
pad = count;
start = pos++;
for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++); // short loop
count = pos - start;
}
}
if (pad == 0) {
throw new IllegalArgumentException(
"Pad letter 'p' must be followed by valid pad pattern: " + pattern);
}
padNext(pad); // pad and continue parsing
}
// main rules
TemporalField field = FIELD_MAP.get(cur);
if (field != null) {
parseField(cur, count, field);
} else if (cur == 'z') {
if (count < 4) {
appendZoneText(TextStyle.SHORT);
} else {
appendZoneText(TextStyle.FULL);
}
} else if (cur == 'I') {
appendZoneId();
} else if (cur == 'Z') {
if (count > 3) {
throw new IllegalArgumentException("Too many pattern letters: " + cur);
}
if (count < 3) {
appendOffset("+HHMM", "+0000");
} else {
appendOffset("+HH:MM", "+00:00");
}
} else if (cur == 'X') {
if (count > 5) {
throw new IllegalArgumentException("Too many pattern letters: " + cur);
}
appendOffset(OffsetIdPrinterParser.PATTERNS[count - 1], "Z");
} else {
throw new IllegalArgumentException("Unknown pattern letter: " + cur);
}
pos
} else if (cur == '\'') {
// parse literals
int start = pos++;
for ( ; pos < pattern.length(); pos++) {
if (pattern.charAt(pos) == '\'') {
if (pos + 1 < pattern.length() && pattern.charAt(pos + 1) == '\'') {
pos++;
} else {
break; // end of literal
}
}
}
if (pos >= pattern.length()) {
throw new IllegalArgumentException("Pattern ends with an incomplete string literal: " + pattern);
}
String str = pattern.substring(start + 1, pos);
if (str.length() == 0) {
appendLiteral('\'');
} else {
appendLiteral(str.replace("''", "'"));
}
} else if (cur == '[') {
optionalStart();
} else if (cur == ']') {
if (active.parent == null) {
throw new IllegalArgumentException("Pattern invalid as it contains ] without previous [");
}
optionalEnd();
} else if (cur == '{' || cur == '}') {
throw new IllegalArgumentException("Pattern includes reserved character: '" + cur + "'");
} else {
appendLiteral(cur);
}
}
}
private void parseField(char cur, int count, TemporalField field) {
switch (cur) {
case 'y':
case 'Y':
if (count == 2) {
appendValueReduced(field, 2, 2000);
} else if (count < 4) {
appendValue(field, count, 19, SignStyle.NORMAL);
} else {
appendValue(field, count, 19, SignStyle.EXCEEDS_PAD);
}
break;
case 'G':
case 'M':
case 'Q':
case 'E':
switch (count) {
case 1:
appendValue(field);
break;
case 2:
appendValue(field, 2);
break;
case 3:
appendText(field, TextStyle.SHORT);
break;
case 4:
appendText(field, TextStyle.FULL);
break;
case 5:
appendText(field, TextStyle.NARROW);
break;
default:
throw new IllegalArgumentException("Too many pattern letters: " + cur);
}
break;
case 'a':
switch (count) {
case 1:
case 2:
case 3:
appendText(field, TextStyle.SHORT);
break;
case 4:
appendText(field, TextStyle.FULL);
break;
case 5:
appendText(field, TextStyle.NARROW);
break;
default:
throw new IllegalArgumentException("Too many pattern letters: " + cur);
}
break;
case 'S':
appendFraction(NANO_OF_SECOND, count, count, false);
break;
default:
if (count == 1) {
appendValue(field);
} else {
appendValue(field, count);
}
break;
}
}
/** Map of letters to fields. */
private static final Map<Character, TemporalField> FIELD_MAP = new HashMap<>();
static {
FIELD_MAP.put('G', ChronoField.ERA); // Java, CLDR (different to both for 1/2 chars)
FIELD_MAP.put('y', ChronoField.YEAR); // CLDR
// FIELD_MAP.put('y', ChronoField.YEAR_OF_ERA); // Java, CLDR // TODO redefine from above
// FIELD_MAP.put('u', ChronoField.YEAR); // CLDR // TODO
// FIELD_MAP.put('Y', ISODateTimeField.WEEK_BASED_YEAR); // Java7, CLDR (needs localized week number) // TODO
FIELD_MAP.put('Q', IsoFields.QUARTER_OF_YEAR); // CLDR
FIELD_MAP.put('M', ChronoField.MONTH_OF_YEAR); // Java, CLDR
// FIELD_MAP.put('w', WeekFields.weekOfYear()); // Java, CLDR (needs localized week number)
// FIELD_MAP.put('W', WeekFields.weekOfMonth()); // Java, CLDR (needs localized week number)
FIELD_MAP.put('D', ChronoField.DAY_OF_YEAR); // Java, CLDR
FIELD_MAP.put('d', ChronoField.DAY_OF_MONTH); // Java, CLDR
FIELD_MAP.put('F', ChronoField.ALIGNED_WEEK_OF_MONTH); // Java, CLDR
FIELD_MAP.put('E', ChronoField.DAY_OF_WEEK); // Java, CLDR (different to both for 1/2 chars)
// FIELD_MAP.put('e', WeekFields.dayOfWeek()); // CLDR (needs localized week number)
FIELD_MAP.put('a', ChronoField.AMPM_OF_DAY); // Java, CLDR
FIELD_MAP.put('H', ChronoField.HOUR_OF_DAY); // Java, CLDR
FIELD_MAP.put('k', ChronoField.CLOCK_HOUR_OF_DAY); // Java, CLDR
FIELD_MAP.put('K', ChronoField.HOUR_OF_AMPM); // Java, CLDR
FIELD_MAP.put('h', ChronoField.CLOCK_HOUR_OF_AMPM); // Java, CLDR
FIELD_MAP.put('m', ChronoField.MINUTE_OF_HOUR); // Java, CLDR
FIELD_MAP.put('s', ChronoField.SECOND_OF_MINUTE); // Java, CLDR
FIELD_MAP.put('S', ChronoField.NANO_OF_SECOND); // CLDR (Java uses milli-of-second number)
FIELD_MAP.put('A', ChronoField.MILLI_OF_DAY); // CLDR
FIELD_MAP.put('n', ChronoField.NANO_OF_SECOND); // ThreeTen
FIELD_MAP.put('N', ChronoField.NANO_OF_DAY); // ThreeTen
// reserved - z,Z,X,I,p
// Java - X - compatible, but extended to 4 and 5 letters
// Java - u - clashes with CLDR, go with CLDR (year-proleptic) here
// CLDR - U - cycle year name, not supported by ThreeTen yet
// CLDR - l - deprecated
// CLDR - j - not relevant
// CLDR - g - modified-julian-day
// CLDR - z - time-zone names // TODO properly
// CLDR - Z - different approach here // TODO bring ThreeTen in line with CLDR
// CLDR - v,V - extended time-zone names
// CLDR - q/c/L - standalone quarter/day-of-week/month
// ThreeTen - I - time-zone id
// ThreeTen - p - prefix for padding
}
public DateTimeFormatterBuilder padNext(int padWidth) {
return padNext(padWidth, ' ');
}
public DateTimeFormatterBuilder padNext(int padWidth, char padChar) {
if (padWidth < 1) {
throw new IllegalArgumentException("The pad width must be at least one but was " + padWidth);
}
active.padNextWidth = padWidth;
active.padNextChar = padChar;
active.valueParserIndex = -1;
return this;
}
/**
* Mark the start of an optional section.
* <p>
* The output of printing can include optional sections, which may be nested.
* An optional section is started by calling this method and ended by calling
* {@link #optionalEnd()} or by ending the build process.
* <p>
* All elements in the optional section are treated as optional.
* During printing, the section is only output if data is available in the
* {@code TemporalAccessor} for all the elements in the section.
* During parsing, the whole section may be missing from the parsed string.
* <p>
* For example, consider a builder setup as
* {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2)}.
* The optional section ends automatically at the end of the builder.
* During printing, the minute will only be output if its value can be obtained from the date-time.
* During parsing, the input will be successfully parsed whether the minute is present or not.
*
* @return this, for chaining, not null
*/
public DateTimeFormatterBuilder optionalStart() {
active.valueParserIndex = -1;
active = new DateTimeFormatterBuilder(active, true);
return this;
}
public DateTimeFormatterBuilder optionalEnd() {
if (active.parent == null) {
throw new IllegalStateException("Cannot call optionalEnd() as there was no previous call to optionalStart()");
}
if (active.printerParsers.size() > 0) {
CompositePrinterParser cpp = new CompositePrinterParser(active.printerParsers, active.optional);
active = active.parent;
appendInternal(cpp);
} else {
active = active.parent;
}
return this;
}
/**
* Appends a printer and/or parser to the internal list handling padding.
*
* @param pp the printer-parser to add, not null
* @return the index into the active parsers list
*/
private int appendInternal(DateTimePrinterParser pp) {
Objects.requireNonNull(pp, "pp");
if (active.padNextWidth > 0) {
if (pp != null) {
pp = new PadPrinterParserDecorator(pp, active.padNextWidth, active.padNextChar);
}
active.padNextWidth = 0;
active.padNextChar = 0;
}
active.printerParsers.add(pp);
active.valueParserIndex = -1;
return active.printerParsers.size() - 1;
}
/**
* Completes this builder by creating the DateTimeFormatter using the default locale.
* <p>
* This will create a formatter with the default locale.
* Numbers will be printed and parsed using the standard non-localized set of symbols.
* <p>
* Calling this method will end any open optional sections by repeatedly
* calling {@link #optionalEnd()} before creating the formatter.
* <p>
* This builder can still be used after creating the formatter if desired,
* although the state may have been changed by calls to {@code optionalEnd}.
*
* @return the created formatter, not null
*/
public DateTimeFormatter toFormatter() {
return toFormatter(Locale.getDefault());
}
/**
* Completes this builder by creating the DateTimeFormatter using the specified locale.
* <p>
* This will create a formatter with the specified locale.
* Numbers will be printed and parsed using the standard non-localized set of symbols.
* <p>
* Calling this method will end any open optional sections by repeatedly
* calling {@link #optionalEnd()} before creating the formatter.
* <p>
* This builder can still be used after creating the formatter if desired,
* although the state may have been changed by calls to {@code optionalEnd}.
*
* @param locale the locale to use for formatting, not null
* @return the created formatter, not null
*/
public DateTimeFormatter toFormatter(Locale locale) {
Objects.requireNonNull(locale, "locale");
while (active.parent != null) {
optionalEnd();
}
CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false);
return new DateTimeFormatter(pp, locale, DateTimeFormatSymbols.STANDARD, null, null);
}
/**
* Strategy for printing/parsing date-time information.
* <p>
* The printer may print any part, or the whole, of the input date-time object.
* Typically, a complete print is constructed from a number of smaller
* units, each outputting a single field.
* <p>
* The parser may parse any piece of text from the input, storing the result
* in the context. Typically, each individual parser will just parse one
* field, such as the day-of-month, storing the value in the context.
* Once the parse is complete, the caller will then convert the context
* to a {@link DateTimeBuilder} to merge the parsed values to create the
* desired object, such as a {@code LocalDate}.
* <p>
* The parse position will be updated during the parse. Parsing will start at
* the specified index and the return value specifies the new parse position
* for the next parser. If an error occurs, the returned index will be negative
* and will have the error position encoded using the complement operator.
*
* <h3>Specification for implementors</h3>
* This interface must be implemented with care to ensure other classes operate correctly.
* All implementations that can be instantiated must be final, immutable and thread-safe.
* <p>
* The context is not a thread-safe object and a new instance will be created
* for each print that occurs. The context must not be stored in an instance
* variable or shared with any other threads.
*/
interface DateTimePrinterParser {
/**
* Prints the date-time object to the buffer.
* <p>
* The context holds information to use during the print.
* It also contains the date-time information to be printed.
* <p>
* The buffer must not be mutated beyond the content controlled by the implementation.
*
* @param context the context to print using, not null
* @param buf the buffer to append to, not null
* @return false if unable to query the value from the date-time, true otherwise
* @throws DateTimeException if the date-time cannot be printed successfully
*/
boolean print(DateTimePrintContext context, StringBuilder buf);
/**
* Parses text into date-time information.
* <p>
* The context holds information to use during the parse.
* It is also used to store the parsed date-time information.
*
* @param context the context to use and parse into, not null
* @param text the input text to parse, not null
* @param position the position to start parsing at, from 0 to the text length
* @return the new parse position, where negative means an error with the
* error position encoded using the complement ~ operator
* @throws NullPointerException if the context or text is null
* @throws IndexOutOfBoundsException if the position is invalid
*/
int parse(DateTimeParseContext context, CharSequence text, int position);
}
/**
* Composite printer and parser.
*/
static final class CompositePrinterParser implements DateTimePrinterParser {
private final DateTimePrinterParser[] printerParsers;
private final boolean optional;
CompositePrinterParser(List<DateTimePrinterParser> printerParsers, boolean optional) {
this(printerParsers.toArray(new DateTimePrinterParser[printerParsers.size()]), optional);
}
CompositePrinterParser(DateTimePrinterParser[] printerParsers, boolean optional) {
this.printerParsers = printerParsers;
this.optional = optional;
}
/**
* Returns a copy of this printer-parser with the optional flag changed.
*
* @param optional the optional flag to set in the copy
* @return the new printer-parser, not null
*/
public CompositePrinterParser withOptional(boolean optional) {
if (optional == this.optional) {
return this;
}
return new CompositePrinterParser(printerParsers, optional);
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
int length = buf.length();
if (optional) {
context.startOptional();
}
try {
for (DateTimePrinterParser pp : printerParsers) {
if (pp.print(context, buf) == false) {
buf.setLength(length); // reset buffer
return true;
}
}
} finally {
if (optional) {
context.endOptional();
}
}
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
if (optional) {
context.startOptional();
int pos = position;
for (DateTimePrinterParser pp : printerParsers) {
pos = pp.parse(context, text, pos);
if (pos < 0) {
context.endOptional(false);
return position; // return original position
}
}
context.endOptional(true);
return pos;
} else {
for (DateTimePrinterParser pp : printerParsers) {
position = pp.parse(context, text, position);
if (position < 0) {
break;
}
}
return position;
}
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
if (printerParsers != null) {
buf.append(optional ? "[" : "(");
for (DateTimePrinterParser pp : printerParsers) {
buf.append(pp);
}
buf.append(optional ? "]" : ")");
}
return buf.toString();
}
}
/**
* Pads the output to a fixed width.
*/
static final class PadPrinterParserDecorator implements DateTimePrinterParser {
private final DateTimePrinterParser printerParser;
private final int padWidth;
private final char padChar;
/**
* Constructor.
*
* @param printerParser the printer, not null
* @param padWidth the width to pad to, 1 or greater
* @param padChar the pad character
*/
PadPrinterParserDecorator(DateTimePrinterParser printerParser, int padWidth, char padChar) {
// input checked by DateTimeFormatterBuilder
this.printerParser = printerParser;
this.padWidth = padWidth;
this.padChar = padChar;
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
int preLen = buf.length();
if (printerParser.print(context, buf) == false) {
return false;
}
int len = buf.length() - preLen;
if (len > padWidth) {
throw new DateTimeException(
"Cannot print as output of " + len + " characters exceeds pad width of " + padWidth);
}
for (int i = 0; i < padWidth - len; i++) {
buf.insert(preLen, padChar);
}
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
// cache context before changed by decorated parser
final boolean strict = context.isStrict();
final boolean caseSensitive = context.isCaseSensitive();
// parse
if (position > text.length()) {
throw new IndexOutOfBoundsException();
}
if (position == text.length()) {
return ~position; // no more characters in the string
}
int endPos = position + padWidth;
if (endPos > text.length()) {
if (strict) {
return ~position; // not enough characters in the string to meet the parse width
}
endPos = text.length();
}
int pos = position;
while (pos < endPos &&
(caseSensitive ? text.charAt(pos) == padChar : context.charEquals(text.charAt(pos), padChar))) {
pos++;
}
text = text.subSequence(0, endPos);
int resultPos = printerParser.parse(context, text, pos);
if (resultPos != endPos && strict) {
return ~(position + pos); // parse of decorated field didn't parse to the end
}
return resultPos;
}
@Override
public String toString() {
return "Pad(" + printerParser + "," + padWidth + (padChar == ' ' ? ")" : ",'" + padChar + "')");
}
}
/**
* Enumeration to apply simple parse settings.
*/
static enum SettingsParser implements DateTimePrinterParser {
SENSITIVE,
INSENSITIVE,
STRICT,
LENIENT;
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
return true; // nothing to do here
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
// using ordinals to avoid javac synthetic inner class
switch (ordinal()) {
case 0: context.setCaseSensitive(true); break;
case 1: context.setCaseSensitive(false); break;
case 2: context.setStrict(true); break;
case 3: context.setStrict(false); break;
}
return position;
}
@Override
public String toString() {
// using ordinals to avoid javac synthetic inner class
switch (ordinal()) {
case 0: return "ParseCaseSensitive(true)";
case 1: return "ParseCaseSensitive(false)";
case 2: return "ParseStrict(true)";
case 3: return "ParseStrict(false)";
}
throw new IllegalStateException("Unreachable");
}
}
/**
* Prints or parses a character literal.
*/
static final class CharLiteralPrinterParser implements DateTimePrinterParser {
private final char literal;
CharLiteralPrinterParser(char literal) {
this.literal = literal;
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
buf.append(literal);
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
int length = text.length();
if (position == length) {
return ~position;
}
char ch = text.charAt(position);
if (context.charEquals(literal, ch) == false) {
return ~position;
}
return position + 1;
}
@Override
public String toString() {
if (literal == '\'') {
return "''";
}
return "'" + literal + "'";
}
}
/**
* Prints or parses a string literal.
*/
static final class StringLiteralPrinterParser implements DateTimePrinterParser {
private final String literal;
StringLiteralPrinterParser(String literal) {
this.literal = literal; // validated by caller
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
buf.append(literal);
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
int length = text.length();
if (position > length || position < 0) {
throw new IndexOutOfBoundsException();
}
if (context.subSequenceEquals(text, position, literal, 0, literal.length()) == false) {
return ~position;
}
return position + literal.length();
}
@Override
public String toString() {
String converted = literal.replace("'", "''");
return "'" + converted + "'";
}
}
/**
* Prints and parses a numeric date-time field with optional padding.
*/
static class NumberPrinterParser implements DateTimePrinterParser {
/**
* Array of 10 to the power of n.
*/
static final int[] EXCEED_POINTS = new int[] {
0,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
};
final TemporalField field;
final int minWidth;
private final int maxWidth;
private final SignStyle signStyle;
private final int subsequentWidth;
/**
* Constructor.
*
* @param field the field to print, not null
* @param minWidth the minimum field width, from 1 to 19
* @param maxWidth the maximum field width, from minWidth to 19
* @param signStyle the positive/negative sign style, not null
*/
NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
// validated by caller
this.field = field;
this.minWidth = minWidth;
this.maxWidth = maxWidth;
this.signStyle = signStyle;
this.subsequentWidth = 0;
}
/**
* Constructor.
*
* @param field the field to print, not null
* @param minWidth the minimum field width, from 1 to 19
* @param maxWidth the maximum field width, from minWidth to 19
* @param signStyle the positive/negative sign style, not null
* @param subsequentWidth the width of subsequent non-negative numbers, 0 or greater,
* -1 if fixed width due to active adjacent parsing
*/
private NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth) {
// validated by caller
this.field = field;
this.minWidth = minWidth;
this.maxWidth = maxWidth;
this.signStyle = signStyle;
this.subsequentWidth = subsequentWidth;
}
/**
* Returns a new instance with fixed width flag set.
*
* @return a new updated printer-parser, not null
*/
NumberPrinterParser withFixedWidth() {
return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, -1);
}
/**
* Returns a new instance with an updated subsequent width.
*
* @param subsequentWidth the width of subsequent non-negative numbers, 0 or greater
* @return a new updated printer-parser, not null
*/
NumberPrinterParser withSubsequentWidth(int subsequentWidth) {
return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, this.subsequentWidth + subsequentWidth);
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
Long valueLong = context.getValue(field);
if (valueLong == null) {
return false;
}
long value = getValue(valueLong);
DateTimeFormatSymbols symbols = context.getSymbols();
String str = (value == Long.MIN_VALUE ? "9223372036854775808" : Long.toString(Math.abs(value)));
if (str.length() > maxWidth) {
throw new DateTimeException("Field " + field.getName() +
" cannot be printed as the value " + value +
" exceeds the maximum print width of " + maxWidth);
}
str = symbols.convertNumberToI18N(str);
if (value >= 0) {
switch (signStyle) {
case EXCEEDS_PAD:
if (minWidth < 19 && value >= EXCEED_POINTS[minWidth]) {
buf.append(symbols.getPositiveSign());
}
break;
case ALWAYS:
buf.append(symbols.getPositiveSign());
break;
}
} else {
switch (signStyle) {
case NORMAL:
case EXCEEDS_PAD:
case ALWAYS:
buf.append(symbols.getNegativeSign());
break;
case NOT_NEGATIVE:
throw new DateTimeException("Field " + field.getName() +
" cannot be printed as the value " + value +
" cannot be negative according to the SignStyle");
}
}
for (int i = 0; i < minWidth - str.length(); i++) {
buf.append(symbols.getZeroDigit());
}
buf.append(str);
return true;
}
/**
* Gets the value to output.
*
* @param value the base value of the field, not null
* @return the value
*/
long getValue(long value) {
return value;
}
boolean isFixedWidth() {
return subsequentWidth == -1;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
int length = text.length();
if (position == length) {
return ~position;
}
char sign = text.charAt(position); // IOOBE if invalid position
boolean negative = false;
boolean positive = false;
if (sign == context.getSymbols().getPositiveSign()) {
if (signStyle.parse(true, context.isStrict(), minWidth == maxWidth) == false) {
return ~position;
}
positive = true;
position++;
} else if (sign == context.getSymbols().getNegativeSign()) {
if (signStyle.parse(false, context.isStrict(), minWidth == maxWidth) == false) {
return ~position;
}
negative = true;
position++;
} else {
if (signStyle == SignStyle.ALWAYS && context.isStrict()) {
return ~position;
}
}
int effMinWidth = (context.isStrict() || isFixedWidth() ? minWidth : 1);
int minEndPos = position + effMinWidth;
if (minEndPos > length) {
return ~position;
}
int effMaxWidth = maxWidth + Math.max(subsequentWidth, 0);
long total = 0;
BigInteger totalBig = null;
int pos = position;
for (int pass = 0; pass < 2; pass++) {
int maxEndPos = Math.min(pos + effMaxWidth, length);
while (pos < maxEndPos) {
char ch = text.charAt(pos++);
int digit = context.getSymbols().convertToDigit(ch);
if (digit < 0) {
pos
if (pos < minEndPos) {
return ~position; // need at least min width digits
}
break;
}
if ((pos - position) > 18) {
if (totalBig == null) {
totalBig = BigInteger.valueOf(total);
}
totalBig = totalBig.multiply(BigInteger.TEN).add(BigInteger.valueOf(digit));
} else {
total = total * 10 + digit;
}
}
if (subsequentWidth > 0 && pass == 0) {
// re-parse now we know the correct width
int parseLen = pos - position;
effMaxWidth = Math.max(effMinWidth, parseLen - subsequentWidth);
pos = position;
total = 0;
totalBig = null;
} else {
break;
}
}
if (negative) {
if (totalBig != null) {
if (totalBig.equals(BigInteger.ZERO) && context.isStrict()) {
return ~(position - 1); // minus zero not allowed
}
totalBig = totalBig.negate();
} else {
if (total == 0 && context.isStrict()) {
return ~(position - 1); // minus zero not allowed
}
total = -total;
}
} else if (signStyle == SignStyle.EXCEEDS_PAD && context.isStrict()) {
int parseLen = pos - position;
if (positive) {
if (parseLen <= minWidth) {
return ~(position - 1); // '+' only parsed if minWidth exceeded
}
} else {
if (parseLen > minWidth) {
return ~position; // '+' must be parsed if minWidth exceeded
}
}
}
if (totalBig != null) {
if (totalBig.bitLength() > 63) {
// overflow, parse 1 less digit
totalBig = totalBig.divide(BigInteger.TEN);
pos
}
return setValue(context, totalBig.longValue(), position, pos);
}
return setValue(context, total, position, pos);
}
/**
* Stores the value.
*
* @param context the context to store into, not null
* @param value the value
* @param errorPos the position of the field being parsed
* @param successPos the position after the field being parsed
* @return the new position
*/
int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) {
return context.setParsedField(field, value, errorPos, successPos);
}
@Override
public String toString() {
if (minWidth == 1 && maxWidth == 19 && signStyle == SignStyle.NORMAL) {
return "Value(" + field.getName() + ")";
}
if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
return "Value(" + field.getName() + "," + minWidth + ")";
}
return "Value(" + field.getName() + "," + minWidth + "," + maxWidth + "," + signStyle + ")";
}
}
/**
* Prints and parses a reduced numeric date-time field.
*/
static final class ReducedPrinterParser extends NumberPrinterParser {
private final int baseValue;
private final int range;
/**
* Constructor.
*
* @param field the field to print, validated not null
* @param width the field width, from 1 to 18
* @param baseValue the base value
*/
ReducedPrinterParser(TemporalField field, int width, int baseValue) {
super(field, width, width, SignStyle.NOT_NEGATIVE);
if (width < 1 || width > 18) {
throw new IllegalArgumentException("The width must be from 1 to 18 inclusive but was " + width);
}
if (field.range().isValidValue(baseValue) == false) {
throw new IllegalArgumentException("The base value must be within the range of the field");
}
this.baseValue = baseValue;
this.range = EXCEED_POINTS[width];
if ((((long) baseValue) + range) > Integer.MAX_VALUE) {
throw new DateTimeException("Unable to add printer-parser as the range exceeds the capacity of an int");
}
}
@Override
long getValue(long value) {
return Math.abs(value % range);
}
@Override
int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) {
int lastPart = baseValue % range;
if (baseValue > 0) {
value = baseValue - lastPart + value;
} else {
value = baseValue - lastPart - value;
}
if (value < baseValue) {
value += range;
}
return context.setParsedField(field, value, errorPos, successPos);
}
@Override
NumberPrinterParser withFixedWidth() {
return this;
}
@Override
boolean isFixedWidth() {
return true;
}
@Override
public String toString() {
return "ReducedValue(" + field.getName() + "," + minWidth + "," + baseValue + ")";
}
}
/**
* Prints and parses a numeric date-time field with optional padding.
*/
static final class FractionPrinterParser implements DateTimePrinterParser {
private final TemporalField field;
private final int minWidth;
private final int maxWidth;
private final boolean decimalPoint;
/**
* Constructor.
*
* @param field the field to output, not null
* @param minWidth the minimum width to output, from 0 to 9
* @param maxWidth the maximum width to output, from 0 to 9
* @param decimalPoint whether to output the localized decimal point symbol
*/
FractionPrinterParser(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
Objects.requireNonNull(field, "field");
if (field.range().isFixed() == false) {
throw new IllegalArgumentException("Field must have a fixed set of values: " + field.getName());
}
if (minWidth < 0 || minWidth > 9) {
throw new IllegalArgumentException("Minimum width must be from 0 to 9 inclusive but was " + minWidth);
}
if (maxWidth < 1 || maxWidth > 9) {
throw new IllegalArgumentException("Maximum width must be from 1 to 9 inclusive but was " + maxWidth);
}
if (maxWidth < minWidth) {
throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
maxWidth + " < " + minWidth);
}
this.field = field;
this.minWidth = minWidth;
this.maxWidth = maxWidth;
this.decimalPoint = decimalPoint;
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
Long value = context.getValue(field);
if (value == null) {
return false;
}
DateTimeFormatSymbols symbols = context.getSymbols();
BigDecimal fraction = convertToFraction(value);
if (fraction.scale() == 0) { // scale is zero if value is zero
if (minWidth > 0) {
if (decimalPoint) {
buf.append(symbols.getDecimalSeparator());
}
for (int i = 0; i < minWidth; i++) {
buf.append(symbols.getZeroDigit());
}
}
} else {
int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth);
fraction = fraction.setScale(outputScale, RoundingMode.FLOOR);
String str = fraction.toPlainString().substring(2);
str = symbols.convertNumberToI18N(str);
if (decimalPoint) {
buf.append(symbols.getDecimalSeparator());
}
buf.append(str);
}
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
int effectiveMin = (context.isStrict() ? minWidth : 0);
int effectiveMax = (context.isStrict() ? maxWidth : 9);
int length = text.length();
if (position == length) {
// valid if whole field is optional, invalid if minimum width
return (effectiveMin > 0 ? ~position : position);
}
if (decimalPoint) {
if (text.charAt(position) != context.getSymbols().getDecimalSeparator()) {
// valid if whole field is optional, invalid if minimum width
return (effectiveMin > 0 ? ~position : position);
}
position++;
}
int minEndPos = position + effectiveMin;
if (minEndPos > length) {
return ~position; // need at least min width digits
}
int maxEndPos = Math.min(position + effectiveMax, length);
int total = 0; // can use int because we are only parsing up to 9 digits
int pos = position;
while (pos < maxEndPos) {
char ch = text.charAt(pos++);
int digit = context.getSymbols().convertToDigit(ch);
if (digit < 0) {
if (pos < minEndPos) {
return ~position; // need at least min width digits
}
pos
break;
}
total = total * 10 + digit;
}
BigDecimal fraction = new BigDecimal(total).movePointLeft(pos - position);
long value = convertFromFraction(fraction);
return context.setParsedField(field, value, position, pos);
}
/**
* Converts a value for this field to a fraction between 0 and 1.
* <p>
* The fractional value is between 0 (inclusive) and 1 (exclusive).
* It can only be returned if the {@link TemporalField#range() value range} is fixed.
* The fraction is obtained by calculation from the field range using 9 decimal
* places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
* The calculation is inaccurate if the values do not run continuously from smallest to largest.
* <p>
* For example, the second-of-minute value of 15 would be returned as 0.25,
* assuming the standard definition of 60 seconds in a minute.
*
* @param value the value to convert, must be valid for this rule
* @return the value as a fraction within the range, from 0 to 1, not null
* @throws DateTimeException if the value cannot be converted to a fraction
*/
private BigDecimal convertToFraction(long value) {
ValueRange range = field.range();
range.checkValidValue(value, field);
BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
// stripTrailingZeros bug
return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
}
/**
* Converts a fraction from 0 to 1 for this field to a value.
* <p>
* The fractional value must be between 0 (inclusive) and 1 (exclusive).
* It can only be returned if the {@link TemporalField#range() value range} is fixed.
* The value is obtained by calculation from the field range and a rounding
* mode of {@link RoundingMode#FLOOR FLOOR}.
* The calculation is inaccurate if the values do not run continuously from smallest to largest.
* <p>
* For example, the fractional second-of-minute of 0.25 would be converted to 15,
* assuming the standard definition of 60 seconds in a minute.
*
* @param fraction the fraction to convert, not null
* @return the value of the field, valid for this rule
* @throws DateTimeException if the value cannot be converted
*/
private long convertFromFraction(BigDecimal fraction) {
ValueRange range = field.range();
BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
return valueBD.longValueExact();
}
@Override
public String toString() {
String decimal = (decimalPoint ? ",DecimalPoint" : "");
return "Fraction(" + field.getName() + "," + minWidth + "," + maxWidth + decimal + ")";
}
}
/**
* Prints or parses field text.
*/
static final class TextPrinterParser implements DateTimePrinterParser {
private final TemporalField field;
private final TextStyle textStyle;
private final DateTimeTextProvider provider;
/**
* The cached number printer parser.
* Immutable and volatile, so no synchronization needed.
*/
private volatile NumberPrinterParser numberPrinterParser;
/**
* Constructor.
*
* @param field the field to output, not null
* @param textStyle the text style, not null
* @param provider the text provider, not null
*/
TextPrinterParser(TemporalField field, TextStyle textStyle, DateTimeTextProvider provider) {
// validated by caller
this.field = field;
this.textStyle = textStyle;
this.provider = provider;
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
Long value = context.getValue(field);
if (value == null) {
return false;
}
String text = provider.getText(field, value, textStyle, context.getLocale());
if (text == null) {
return numberPrinterParser().print(context, buf);
}
buf.append(text);
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence parseText, int position) {
int length = parseText.length();
if (position < 0 || position > length) {
throw new IndexOutOfBoundsException();
}
TextStyle style = (context.isStrict() ? textStyle : null);
Iterator<Entry<String, Long>> it = provider.getTextIterator(field, style, context.getLocale());
if (it != null) {
while (it.hasNext()) {
Entry<String, Long> entry = it.next();
String itText = entry.getKey();
if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) {
return context.setParsedField(field, entry.getValue(), position, position + itText.length());
}
}
if (context.isStrict()) {
return ~position;
}
}
return numberPrinterParser().parse(context, parseText, position);
}
/**
* Create and cache a number printer parser.
* @return the number printer parser for this field, not null
*/
private NumberPrinterParser numberPrinterParser() {
if (numberPrinterParser == null) {
numberPrinterParser = new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL);
}
return numberPrinterParser;
}
@Override
public String toString() {
if (textStyle == TextStyle.FULL) {
return "Text(" + field.getName() + ")";
}
return "Text(" + field.getName() + "," + textStyle + ")";
}
}
/**
* Prints or parses an ISO-8601 instant.
*/
static final class InstantPrinterParser implements DateTimePrinterParser {
// days in a 400 year cycle = 146097
// days in a 10,000 year cycle = 146097 * 25
// seconds per day = 86400
private static final long SECONDS_PER_10000_YEARS = 146097L * 25L * 86400L;
private static final long SECONDS_0000_TO_1970 = ((146097L * 5L) - (30L * 365L + 7L)) * 86400L;
private static final CompositePrinterParser PARSER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME).appendLiteral('Z')
.toFormatter().toPrinterParser(false);
InstantPrinterParser() {
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
// use INSTANT_SECONDS, thus this code is not bound by Instant.MAX
Long inSecs = context.getValue(INSTANT_SECONDS);
Long inNanos = context.getValue(NANO_OF_SECOND);
if (inSecs == null || inNanos == null) {
return false;
}
long inSec = inSecs;
int inNano = NANO_OF_SECOND.checkValidIntValue(inNanos);
if (inSec >= -SECONDS_0000_TO_1970) {
// current era
long zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970;
long hi = Jdk8Methods.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1;
long lo = Jdk8Methods.floorMod(zeroSecs, SECONDS_PER_10000_YEARS);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, inNano, ZoneOffset.UTC);
if (hi > 0) {
buf.append('+').append(hi);
}
buf.append(ldt).append('Z');
} else {
// before current era
long zeroSecs = inSec + SECONDS_0000_TO_1970;
long hi = zeroSecs / SECONDS_PER_10000_YEARS;
long lo = zeroSecs % SECONDS_PER_10000_YEARS;
LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, inNano, ZoneOffset.UTC);
int pos = buf.length();
buf.append(ldt).append('Z');
if (hi < 0) {
if (ldt.getYear() == -10_000) {
buf.replace(pos, pos + 2, Long.toString(hi - 1));
} else if (lo == 0) {
buf.insert(pos, hi);
} else {
buf.insert(pos + 1, Math.abs(hi));
}
}
}
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
// new context to avoid overwriting fields like year/month/day
DateTimeParseContext newContext = context.copy();
int pos = PARSER.parse(newContext, text, position);
if (pos < 0) {
return pos;
}
// parser restricts most fields to 2 digits, so definitely int
// correctly parsed nano is also guaranteed to be valid
long yearParsed = newContext.getParsed(YEAR);
int month = newContext.getParsed(MONTH_OF_YEAR).intValue();
int day = newContext.getParsed(DAY_OF_MONTH).intValue();
int hour = newContext.getParsed(HOUR_OF_DAY).intValue();
int min = newContext.getParsed(MINUTE_OF_HOUR).intValue();
Long secVal = newContext.getParsed(SECOND_OF_MINUTE);
Long nanoVal = newContext.getParsed(NANO_OF_SECOND);
int sec = (secVal != null ? secVal.intValue() : 0);
int nano = (nanoVal != null ? nanoVal.intValue() : 0);
int year = (int) yearParsed % 10_000;
long instantSecs;
try {
LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0);
instantSecs = ldt.toEpochSecond(ZoneOffset.UTC);
instantSecs += Jdk8Methods.safeMultiply(yearParsed / 10_000L, SECONDS_PER_10000_YEARS);
} catch (RuntimeException ex) {
return ~position;
}
int successPos = text.length();
successPos = context.setParsedField(INSTANT_SECONDS, instantSecs, position, successPos);
return context.setParsedField(NANO_OF_SECOND, nano, position, successPos);
}
@Override
public String toString() {
return "Instant()";
}
}
/**
* Prints or parses an offset ID.
*/
static final class OffsetIdPrinterParser implements DateTimePrinterParser {
static final String[] PATTERNS = new String[] {
"+HH", "+HHMM", "+HH:MM", "+HHMMss", "+HH:MM:ss", "+HHMMSS", "+HH:MM:SS",
}; // order used in pattern builder
static final OffsetIdPrinterParser INSTANCE_ID = new OffsetIdPrinterParser("Z", "+HH:MM:ss");
private final String noOffsetText;
private final int type;
/**
* Constructor.
*
* @param noOffsetText the text to use for UTC, not null
* @param pattern the pattern
*/
OffsetIdPrinterParser(String noOffsetText, String pattern) {
Objects.requireNonNull(noOffsetText, "noOffsetText");
Objects.requireNonNull(pattern, "pattern");
this.noOffsetText = noOffsetText;
this.type = checkPattern(pattern);
}
private int checkPattern(String pattern) {
for (int i = 0; i < PATTERNS.length; i++) {
if (PATTERNS[i].equals(pattern)) {
return i;
}
}
throw new IllegalArgumentException("Invalid zone offset pattern: " + pattern);
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
Long offsetSecs = context.getValue(OFFSET_SECONDS);
if (offsetSecs == null) {
return false;
}
int totalSecs = Jdk8Methods.safeToInt(offsetSecs);
if (totalSecs == 0) {
buf.append(noOffsetText);
} else {
int absHours = Math.abs((totalSecs / 3600) % 100); // anything larger than 99 silently dropped
int absMinutes = Math.abs((totalSecs / 60) % 60);
int absSeconds = Math.abs(totalSecs % 60);
buf.append(totalSecs < 0 ? "-" : "+")
.append((char) (absHours / 10 + '0')).append((char) (absHours % 10 + '0'));
if (type >= 1) {
buf.append((type % 2) == 0 ? ":" : "")
.append((char) (absMinutes / 10 + '0')).append((char) (absMinutes % 10 + '0'));
if (type >= 5 || (type >= 3 && absSeconds > 0)) {
buf.append((type % 2) == 0 ? ":" : "")
.append((char) (absSeconds / 10 + '0')).append((char) (absSeconds % 10 + '0'));
}
}
}
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
int length = text.length();
int noOffsetLen = noOffsetText.length();
if (noOffsetLen == 0) {
if (position == length) {
return context.setParsedField(OFFSET_SECONDS, 0, position, position);
}
} else {
if (position == length) {
return ~position;
}
if (context.subSequenceEquals(text, position, noOffsetText, 0, noOffsetLen)) {
return context.setParsedField(OFFSET_SECONDS, 0, position, position + noOffsetLen);
}
}
// parse normal plus/minus offset
char sign = text.charAt(position); // IOOBE if invalid position
if (sign == '+' || sign == '-') {
// starts
int negative = (sign == '-' ? -1 : 1);
int[] array = new int[4];
array[0] = position + 1;
if (parseNumber(array, 1, text, true) ||
parseNumber(array, 2, text, type > 0) ||
parseNumber(array, 3, text, false)) {
return ~position;
}
long offsetSecs = negative * (array[1] * 3600L + array[2] * 60L + array[3]);
return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, array[0]);
} else {
// handle special case of empty no offset text
if (noOffsetLen == 0) {
return context.setParsedField(OFFSET_SECONDS, 0, position, position + noOffsetLen);
}
return ~position;
}
}
/**
* Parse a two digit zero-prefixed number.
*
* @param array the array of parsed data, 0=pos,1=hours,2=mins,3=secs, not null
* @param arrayIndex the index to parse the value into
* @param parseText the offset ID, not null
* @param required whether this number is required
* @return true if an error occurred
*/
private boolean parseNumber(int[] array, int arrayIndex, CharSequence parseText, boolean required) {
if ((type + 3) / 2 < arrayIndex) {
return false; // ignore seconds/minutes
}
int pos = array[0];
if ((type % 2) == 0 && arrayIndex > 1) {
if (pos + 1 > parseText.length() || parseText.charAt(pos) != ':') {
return required;
}
pos++;
}
if (pos + 2 > parseText.length()) {
return required;
}
char ch1 = parseText.charAt(pos++);
char ch2 = parseText.charAt(pos++);
if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') {
return required;
}
int value = (ch1 - 48) * 10 + (ch2 - 48);
if (value < 0 || value > 59) {
return required;
}
array[arrayIndex] = value;
array[0] = pos;
return false;
}
@Override
public String toString() {
String converted = noOffsetText.replace("'", "''");
return "Offset('" + converted + "'," + PATTERNS[type] + ")";
}
}
/**
* Prints or parses a zone ID.
*/
static final class ZoneTextPrinterParser implements DateTimePrinterParser {
// TODO: remove this as it is incomplete
/** The text style to output. */
private final TextStyle textStyle;
ZoneTextPrinterParser(TextStyle textStyle) {
this.textStyle = Objects.requireNonNull(textStyle, "textStyle");
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
ZoneId zone = context.getValue(TemporalQueries.zoneId());
if (zone == null) {
return false;
}
// TODO: fix getText(textStyle, context.getLocale())
buf.append(zone.getId()); // TODO: Use symbols
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return "ZoneText(" + textStyle + ")";
}
}
/**
* Prints or parses a zone ID.
*/
static final class ZoneIdPrinterParser implements DateTimePrinterParser {
private final TemporalQuery<ZoneId> query;
private final String description;
ZoneIdPrinterParser(TemporalQuery<ZoneId> query, String description) {
this.query = query;
this.description = description;
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
ZoneId zone = context.getValue(query);
if (zone == null) {
return false;
}
buf.append(zone.getId());
return true;
}
/**
* The cached tree to speed up parsing.
*/
private static volatile Entry<Integer, SubstringTree> cachedSubstringTree;
/**
* This implementation looks for the longest matching string.
* For example, parsing Etc/GMT-2 will return Etc/GMC-2 rather than just
* Etc/GMC although both are valid.
* <p>
* This implementation uses a tree to search for valid time-zone names in
* the parseText. The top level node of the tree has a length equal to the
* length of the shortest time-zone as well as the beginning characters of
* all other time-zones.
*/
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
// TODO case insensitive?
int length = text.length();
if (position > length) {
throw new IndexOutOfBoundsException();
}
if (position == length) {
return ~position;
}
// handle fixed time-zone IDs
char nextChar = text.charAt(position);
if (nextChar == '+' || nextChar == '-') {
DateTimeParseContext newContext = context.copy();
int endPos = OffsetIdPrinterParser.INSTANCE_ID.parse(newContext, text, position);
if (endPos < 0) {
return endPos;
}
int offset = (int) newContext.getParsed(OFFSET_SECONDS).longValue();
ZoneId zone = ZoneOffset.ofTotalSeconds(offset);
context.setParsed(zone);
return endPos;
} else if (length >= position + 2) {
char nextNextChar = text.charAt(position + 1);
if (nextChar == 'U' && nextNextChar == 'T') {
if (length >= position + 3 && text.charAt(position + 2) == 'C') {
return parsePrefixedOffset(context, text, position + 3);
}
return parsePrefixedOffset(context, text, position + 2);
} else if (nextChar == 'G' && length >= position + 3 &&
nextNextChar == 'M' && text.charAt(position + 2) == 'T') {
return parsePrefixedOffset(context, text, position + 3);
}
}
// prepare parse tree
Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
final int regionIdsSize = regionIds.size();
Entry<Integer, SubstringTree> cached = cachedSubstringTree;
if (cached == null || cached.getKey() != regionIdsSize) {
synchronized (this) {
cached = cachedSubstringTree;
if (cached == null || cached.getKey() != regionIdsSize) {
cachedSubstringTree = cached = new SimpleImmutableEntry<>(regionIdsSize, prepareParser(regionIds));
}
}
}
SubstringTree tree = cached.getValue();
// parse
String parsedZoneId = null;
while (tree != null) {
int nodeLength = tree.length;
if (position + nodeLength > length) {
break;
}
parsedZoneId = text.subSequence(position, position + nodeLength).toString();
tree = tree.get(parsedZoneId);
}
if (parsedZoneId == null || regionIds.contains(parsedZoneId) == false) {
if (nextChar == 'Z') {
context.setParsed(ZoneOffset.UTC);
return position + 1;
}
return ~position;
}
context.setParsed(ZoneId.of(parsedZoneId));
return position + parsedZoneId.length();
}
private int parsePrefixedOffset(DateTimeParseContext context, CharSequence text, int position) {
DateTimeParseContext newContext = context.copy();
int endPos = OffsetIdPrinterParser.INSTANCE_ID.parse(newContext, text, position);
if (endPos < 0) {
context.setParsed(ZoneOffset.UTC);
return position;
}
int offset = (int) newContext.getParsed(OFFSET_SECONDS).longValue();
ZoneId zone = ZoneOffset.ofTotalSeconds(offset);
context.setParsed(zone);
return endPos;
}
/**
* Model a tree of substrings to make the parsing easier. Due to the nature
* of time-zone names, it can be faster to parse based in unique substrings
* rather than just a character by character match.
* <p>
* For example, to parse America/Denver we can look at the first two
* character "Am". We then notice that the shortest time-zone that starts
* with Am is America/Nome which is 12 characters long. Checking the first
* 12 characters of America/Denver gives America/Denv which is a substring
* of only 1 time-zone: America/Denver. Thus, with just 3 comparisons that
* match can be found.
* <p>
* This structure maps substrings to substrings of a longer length. Each
* node of the tree contains a length and a map of valid substrings to
* sub-nodes. The parser gets the length from the root node. It then
* extracts a substring of that length from the parseText. If the map
* contains the substring, it is set as the possible time-zone and the
* sub-node for that substring is retrieved. The process continues until the
* substring is no longer found, at which point the matched text is checked
* against the real time-zones.
*/
private static final class SubstringTree {
/**
* The length of the substring this node of the tree contains.
* Subtrees will have a longer length.
*/
final int length;
/**
* Map of a substring to a set of substrings that contain the key.
*/
private final Map<CharSequence, SubstringTree> substringMap = new HashMap<>();
/**
* Constructor.
*
* @param length the length of this tree
*/
private SubstringTree(int length) {
this.length = length;
}
private SubstringTree get(CharSequence substring2) {
return substringMap.get(substring2);
}
/**
* Values must be added from shortest to longest.
*
* @param newSubstring the substring to add, not null
*/
private void add(String newSubstring) {
int idLen = newSubstring.length();
if (idLen == length) {
substringMap.put(newSubstring, null);
} else if (idLen > length) {
String substring = newSubstring.substring(0, length);
SubstringTree parserTree = substringMap.get(substring);
if (parserTree == null) {
parserTree = new SubstringTree(idLen);
substringMap.put(substring, parserTree);
}
parserTree.add(newSubstring);
}
}
}
/**
* Builds an optimized parsing tree.
*
* @param availableIDs the available IDs, not null, not empty
* @return the tree, not null
*/
private static SubstringTree prepareParser(Set<String> availableIDs) {
// sort by length
List<String> ids = new ArrayList<>(availableIDs);
Collections.sort(ids, LENGTH_SORT);
// build the tree
SubstringTree tree = new SubstringTree(ids.get(0).length());
for (String id : ids) {
tree.add(id);
}
return tree;
}
@Override
public String toString() {
return description;
}
}
/**
* Prints or parses a chronology.
*/
static final class ChronoPrinterParser implements DateTimePrinterParser {
/** The text style to output, null means the ID. */
private final TextStyle textStyle;
ChronoPrinterParser(TextStyle textStyle) {
// validated by caller
this.textStyle = textStyle;
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
Chronology chrono = context.getValue(TemporalQueries.chronology());
if (chrono == null) {
return false;
}
if (textStyle == null) {
buf.append(chrono.getId());
} else {
buf.append(chrono.getId()); // TODO: Use symbols
}
return true;
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
// simple looping parser to find the chronology
if (position < 0 || position > text.length()) {
throw new IndexOutOfBoundsException();
}
Set<Chronology> chronos = Chronology.getAvailableChronologies();
Chronology bestMatch = null;
int matchLen = -1;
for (Chronology chrono : chronos) {
String id = chrono.getId();
int idLen = id.length();
if (idLen > matchLen && context.subSequenceEquals(text, position, id, 0, idLen)) {
bestMatch = chrono;
matchLen = idLen;
}
}
if (bestMatch == null) {
return ~position;
}
context.setParsed(bestMatch);
return position + matchLen;
}
}
/**
* Prints or parses a localized pattern.
*/
static final class LocalizedPrinterParser implements DateTimePrinterParser {
private final FormatStyle dateStyle;
private final FormatStyle timeStyle;
/**
* Constructor.
*
* @param dateStyle the date style to use, may be null
* @param timeStyle the time style to use, may be null
*/
LocalizedPrinterParser(FormatStyle dateStyle, FormatStyle timeStyle) {
// validated by caller
this.dateStyle = dateStyle;
this.timeStyle = timeStyle;
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
Chronology chrono = Chronology.from(context.getTemporal());
return formatter(context.getLocale(), chrono).toPrinterParser(false).print(context, buf);
}
@Override
public int parse(DateTimeParseContext context, CharSequence text, int position) {
Chronology chrono = context.getEffectiveChronology();
return formatter(context.getLocale(), chrono).toPrinterParser(false).parse(context, text, position);
}
private DateTimeFormatter formatter(Locale locale, Chronology chrono) {
return DateTimeFormatStyleProvider.getInstance()
.getFormatter(dateStyle, timeStyle, chrono, locale);
}
@Override
public String toString() {
return "Localized(" + (dateStyle != null ? dateStyle : "") + "," +
(timeStyle != null ? timeStyle : "") + ")";
}
}
/**
* Length comparator.
*/
static final Comparator<String> LENGTH_SORT = new Comparator<String>() {
@Override
public int compare(String str1, String str2) {
return str1.length() == str2.length() ? str1.compareTo(str2) : str1.length() - str2.length();
}
};
}
|
package com.cosylab.cdb.jdal;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import org.omg.PortableServer.POA;
import com.cosylab.CDB.DAOOperations;
import alma.acs.logging.AcsLogLevel;
import alma.cdbErrType.CDBFieldDoesNotExistEx;
import alma.cdbErrType.WrongCDBDataTypeEx;
import alma.cdbErrType.wrappers.AcsJCDBFieldDoesNotExistEx;
import alma.cdbErrType.wrappers.AcsJWrongCDBDataTypeEx;
public class DAOImpl implements DAOOperations {
private final String m_name;
private XMLTreeNode m_rootNode;
private final POA m_poa;
private boolean m_silent;
private final Logger m_logger;
public DAOImpl(String name, XMLTreeNode rootNode, POA poa, Logger logger) {
this(name, rootNode, poa, logger, false);
}
public DAOImpl(String name, XMLTreeNode rootNode, POA poa, Logger logger, boolean silent) {
m_name = name;
m_rootNode = rootNode;
m_poa = poa;
m_silent = silent;
m_logger = logger;
}
public void destroy() {
try {
if (m_poa != null) {
// we trust that m_name (the curl) was used to activate this DAO
byte[] thisId = m_name.getBytes();
m_poa.deactivate_object(thisId);
}
} catch (Exception e) {
if (!m_silent) {
m_logger.log(AcsLogLevel.NOTICE,"Exception destroying object "+ this +" : " + e);
e.printStackTrace();
}
}
}
private String getField(String strFieldName)
throws AcsJCDBFieldDoesNotExistEx {
XMLTreeNode pNode = m_rootNode;
if (strFieldName.length() == 0
|| strFieldName.equals(m_rootNode.m_name)) {
return pNode.getAttributeAndNodeNames();
}
StringTokenizer st = new StringTokenizer(strFieldName, "/");
String fieldName = st.nextToken();
while (st.hasMoreTokens()) {
XMLTreeNode child = (XMLTreeNode) pNode.m_subNodesMap.get(fieldName);
if (child == null)
{
fieldName += "/" + st.nextToken();
}
else
{
pNode = child;
fieldName = st.nextToken();
}
}
if (pNode == null){
AcsJCDBFieldDoesNotExistEx e2 = new AcsJCDBFieldDoesNotExistEx();
e2.setFieldName(strFieldName);
throw e2;
}
String value;
value = getFieldValue(pNode, fieldName);
if (value == null) {
// we should try to get it as node
XMLTreeNode node =
(XMLTreeNode) pNode.m_subNodesMap.get(fieldName);
if (node == null) {
// Components.xml Name="PARENT/CHILD/field" support
int lpos = strFieldName.lastIndexOf('/');
if (lpos > 0)
{
pNode = (XMLTreeNode) m_rootNode.m_subNodesMap.get(strFieldName.substring(0, lpos));
if (pNode != null)
{
fieldName = strFieldName.substring(lpos+1);
value = getFieldValue(pNode, fieldName);
if (value != null) {
if (!m_silent)
m_logger.log(AcsLogLevel.DEBUG, "DAO:'" + m_name + "' returned '" + strFieldName + "'=" + value);
return value;
}
}
}
if (!m_silent)
m_logger.log(AcsLogLevel.NOTICE, "DAO:'" + m_name + "' Unable to return field: '" + strFieldName + "'");
AcsJCDBFieldDoesNotExistEx e2 = new AcsJCDBFieldDoesNotExistEx();
e2.setFieldName(strFieldName);
throw e2;
}
value = node.getAttributeAndNodeNames();
}
if (!m_silent)
m_logger.log(AcsLogLevel.DEBUG, "DAO:'" + m_name + "' returned '" + strFieldName + "'=" + value);
return value;
}
private String getFieldValue(XMLTreeNode pNode, String fieldName) {
String value;
// backward compatibility
if (fieldName.equals("_characteristics")) {
value = pNode.getAttributeAndNodeNames();
} else if (fieldName.equals("_attributes")) {
value = pNode.getAttributeNames();
} else if (fieldName.equals("_elements")) {
value = pNode.getElementNames();
} else if (fieldName.equals("_subnodes")) {
value = pNode.getSubNodeNames();
} else {
value = (String) pNode.m_fieldMap.get(fieldName);
}
return value;
}
public int get_long(String propertyName)
throws WrongCDBDataTypeEx, CDBFieldDoesNotExistEx {
String stringValue;
try{
stringValue = getField(propertyName);
}catch(AcsJCDBFieldDoesNotExistEx e){
throw e.toCDBFieldDoesNotExistEx();
}
try {
return Integer.parseInt(stringValue);
} catch (NumberFormatException nfe) {
if (!m_silent)
m_logger.log(AcsLogLevel.NOTICE, "Failed to cast '" + stringValue + "' to long: " + nfe);
AcsJWrongCDBDataTypeEx e2 = new AcsJWrongCDBDataTypeEx(nfe);
e2.setValue(stringValue);
e2.setDataType("long");
throw e2.toWrongCDBDataTypeEx();
}
}
public double get_double(String propertyName)
throws WrongCDBDataTypeEx, CDBFieldDoesNotExistEx {
String stringValue;
try{
stringValue = getField(propertyName);
}catch(AcsJCDBFieldDoesNotExistEx e){
throw e.toCDBFieldDoesNotExistEx();
}
try {
return Double.parseDouble(stringValue);
} catch (NumberFormatException nfe) {
m_logger.log(AcsLogLevel.NOTICE, "Failed to cast '" + stringValue + "' to double: " + nfe);
AcsJWrongCDBDataTypeEx e2 = new AcsJWrongCDBDataTypeEx(nfe);
e2.setValue(stringValue);
e2.setDataType("double");
throw e2.toWrongCDBDataTypeEx();
}
}
public String get_string(String propertyName)
throws WrongCDBDataTypeEx, CDBFieldDoesNotExistEx {
try{
return getField(propertyName);
}catch(AcsJCDBFieldDoesNotExistEx e){
throw e.toCDBFieldDoesNotExistEx();
}
}
public String get_field_data(String propertyName)
throws WrongCDBDataTypeEx, CDBFieldDoesNotExistEx {
try{
return getField(propertyName);
}catch(AcsJCDBFieldDoesNotExistEx e){
throw e.toCDBFieldDoesNotExistEx();
}
}
public String[] get_string_seq(String propertyName)
throws WrongCDBDataTypeEx, CDBFieldDoesNotExistEx {
String stringValue;
try{
stringValue = getField(propertyName);
}catch(AcsJCDBFieldDoesNotExistEx e){
throw e.toCDBFieldDoesNotExistEx();
}
ArrayList list = new ArrayList();
StringTokenizer st = new StringTokenizer(stringValue, ",");
while (st.hasMoreTokens())
list.add(st.nextToken());
String[] seq = new String[list.size()];
list.toArray(seq);
return seq;
}
public int[] get_long_seq(String propertyName)
throws WrongCDBDataTypeEx, CDBFieldDoesNotExistEx {
String stringValue;
try{
stringValue = getField(propertyName);
}catch(AcsJCDBFieldDoesNotExistEx e){
throw e.toCDBFieldDoesNotExistEx();
}
ArrayList list = new ArrayList();
String val = null;
try {
StringTokenizer st = new StringTokenizer(stringValue, ",");
while (st.hasMoreTokens()) {
val = st.nextToken().trim();
list.add(new Integer(val));
}
} catch (NumberFormatException nfe) {
if (!m_silent)
m_logger.log(AcsLogLevel.NOTICE,
"Failed to cast element
+ list.size()
+ " of value '"
+ val
+ "' to long: "
+ nfe);
AcsJWrongCDBDataTypeEx e2 = new AcsJWrongCDBDataTypeEx(nfe);
e2.setValue(val);
e2.setDataType("long");
throw e2.toWrongCDBDataTypeEx();
}
int[] seq = new int[list.size()];
for (int i = 0; i < list.size(); i++)
seq[i] = ((Integer) list.get(i)).intValue();
return seq;
}
public double[] get_double_seq(String propertyName)
throws WrongCDBDataTypeEx, CDBFieldDoesNotExistEx {
String stringValue;
try{
stringValue = getField(propertyName);
}catch(AcsJCDBFieldDoesNotExistEx e){
throw e.toCDBFieldDoesNotExistEx();
}
ArrayList list = new ArrayList();
String val = null;
try {
StringTokenizer st = new StringTokenizer(stringValue, ",");
while (st.hasMoreTokens()) {
val = st.nextToken().trim();
list.add(new Double(val));
}
} catch (NumberFormatException nfe) {
if (!m_silent)
m_logger.log(AcsLogLevel.NOTICE,
"Failed to cast element
+ list.size()
+ " of value '"
+ val
+ "' to double: "
+ nfe);
AcsJWrongCDBDataTypeEx e = new AcsJWrongCDBDataTypeEx(nfe);
e.setValue(val);
e.setDataType("double");
throw e.toWrongCDBDataTypeEx();
}
double[] seq = new double[list.size()];
for (int i = 0; i < list.size(); i++)
seq[i] = ((Double) list.get(i)).doubleValue();
return seq;
}
/**
* @return
*/
public XMLTreeNode getRootNode() {
return m_rootNode;
}
public void setRootNode(XMLTreeNode mRootNode) {
m_rootNode = mRootNode;
}
/**
* @return
*/
public String getName() {
return m_name;
}
/**
* @return
*/
public POA getPOA() {
return m_poa;
}
}
|
package org.opendroidphp.app.common.tasks;
import android.os.Environment;
import org.apache.commons.io.FileUtils;
import org.opendroidphp.app.Constants;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import eu.chainfire.libsuperuser.Shell;
public class ConnectServer implements Runnable {
protected String SERV_PORT_REGEX = "server.port.*";
protected static String EXTERNAL_DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/droidphp/";
protected final static String CHANGE_SBIN_PERMISSION = "/system/bin/chmod 777";
protected String baseShell;
protected String basePort;
/**
* Set shell binary to use. Usually "sh" or "su"
*
* @param shell Shell to use
*/
public ConnectServer setShell(String shell) {
baseShell = shell;
return this;
}
/**
* Set port to use
*
* @param port port to use
*/
public ConnectServer setServerPort(String port) {
basePort = port;
return this;
}
@Override
public void run() {
initialize();
}
protected void initialize() {
List<String> command = new ArrayList<String>();
command.add(CHANGE_SBIN_PERMISSION + " " + Constants.LIGHTTPD_SBIN_LOCATION);
command.add(CHANGE_SBIN_PERMISSION + " " + Constants.PHP_SBIN_LOCATION);
command.add(CHANGE_SBIN_PERMISSION + " " + Constants.MYSQL_DAEMON_SBIN_LOCATION);
command.add(CHANGE_SBIN_PERMISSION + " " + Constants.MYSQL_MONITOR_SBIN_LOCATION);
command.add(CHANGE_SBIN_PERMISSION + " " + Constants.BUSYBOX_SBIN_LOCATION);
try {
checkFilesystem();
createOrRestoreConfiguration(
Constants.LIGTTTPD_CONF_LOCATION, "lighttpd.conf");
createOrRestoreConfiguration(
Constants.PHP_INI_LOCATION, "php.ini");
createOrRestoreConfiguration(
Constants.MYSQL_INI_LOCATION, "mysql.ini");
if (basePort != null) {
changeServerData(basePort);
}
} catch (Exception e) {
e.printStackTrace();
}
command.add(String.format(
Locale.ENGLISH,
"%s -b 127.0.0.1:9786 -c %s >> %s",
Constants.PHP_SBIN_LOCATION,
Constants.PHP_INI_LOCATION,
EXTERNAL_DIRECTORY + "/logs/php/fcgiserver.log"));
command.add(String.format(
Locale.ENGLISH,
"%s -f %s -D",
Constants.LIGHTTPD_SBIN_LOCATION,
Constants.PROJECT_LOCATION + "/conf/lighttpd.conf"
));
command.add(String.format(
Locale.ENGLISH,
"%s --defaults-file=%s --user=root --language=%s",
Constants.MYSQL_DAEMON_SBIN_LOCATION,
Constants.PROJECT_LOCATION + "/conf/mysql.ini",
Constants.MYSQL_SHARE_DATA_LOCATION + "/mysql/english"
));
command.add("/system/bin/chmod 755 " + Constants.INTERNAL_LOCATION + "/tmp");
//PHP Environment Variable
String[] envs = new String[]{
"PHP_FCGI_CHILDERN=3",
"PHP_FCGI_MAX_REQUEST=1000"
};
String commands[] = new String[command.size()];
int i = 0;
//@TODO: simpler way to convert List to String[]
for (String eachCommand : command) {
commands[i] = eachCommand;
i++;
}
command.clear();
if (baseShell == null) baseShell = "sh";
Shell.run(baseShell, commands, envs, false);
}
protected void checkFilesystem() {
String[] filesUri = new String[]{
Constants.PROJECT_LOCATION + "/logs/lighttpd",
Constants.PROJECT_LOCATION + "/logs/mysql",
Constants.PROJECT_LOCATION + "/logs/php",
Constants.PROJECT_LOCATION + "/conf",
Constants.PROJECT_LOCATION + "/sessions",
Constants.INTERNAL_LOCATION + "/tmp"
};
for (String fileUri : filesUri) {
File file = new File(fileUri);
if (!file.exists()) file.mkdirs();
}
}
protected void changeServerData(String port) {
try {
File confFile = new File(EXTERNAL_DIRECTORY + "/conf/lighttpd.conf");
String sb = FileUtils.readFileToString(confFile, "UTF-8");
sb.replaceFirst(SERV_PORT_REGEX, String.format(Locale.ENGLISH, "server.port = %s", port));
FileUtils.writeStringToFile(confFile, sb, "UTF-8");
} catch (Exception e) {
}
}
protected void createOrRestoreConfiguration(String confFilename, String fileName) throws Exception {
File f = new File(EXTERNAL_DIRECTORY + "/conf/" + fileName);
if (f.exists()) {
//ya, file does exist we don't need to recreate the configuration
// lets return from the method
return;
}
String confValue = FileUtils.readFileToString(
new File(confFilename), "UTF-8");
FileUtils.writeStringToFile(f, confValue, "UTF-8");
}
}
|
package org.ofbiz.webapp;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.ilscipio.scipio.ce.util.SafeOptional;
import org.apache.tomcat.util.descriptor.web.WebXml;
import org.ofbiz.base.component.ComponentConfig.WebappInfo;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.webapp.control.ConfigXMLReader.ControllerConfig;
import org.ofbiz.webapp.control.WebAppConfigurationException;
import org.ofbiz.webapp.renderer.RenderEnvType;
import org.ofbiz.webapp.website.WebSiteProperties;
import org.ofbiz.webapp.website.WebSiteWorker;
import org.xml.sax.SAXException;
public class FullWebappInfo {
//private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
//private final Delegator delegator; // REMOVED lazy initialization - not worth it
private ExtWebappInfo extWebappInfo;
private WebSiteProperties webSiteProperties;
private SafeOptional<ControllerConfig> controllerConfig;
private OfbizUrlBuilder ofbizUrlBuilder;
protected FullWebappInfo(Delegator delegator, ExtWebappInfo extWebappInfo, WebSiteProperties webSiteProperties,
SafeOptional<ControllerConfig> controllerConfig, OfbizUrlBuilder ofbizUrlBuilder) {
//this.delegator = delegator; // can be null if all others are non-null
this.extWebappInfo = extWebappInfo;
this.webSiteProperties = webSiteProperties;
this.controllerConfig = controllerConfig;
this.ofbizUrlBuilder = ofbizUrlBuilder;
}
protected FullWebappInfo(Delegator delegator, ExtWebappInfo extWebappInfo) {
//this.delegator = delegator;
this.extWebappInfo = extWebappInfo;
}
protected FullWebappInfo(HttpServletRequest request) {
try {
// SPECIAL: in this case we must initialize WebSiteProperties immediately because
// we can't store the HttpServletRequest object in FullWebappInfo
this.ofbizUrlBuilder = OfbizUrlBuilder.from(request);
this.extWebappInfo = ExtWebappInfo.fromRequest(request);
this.webSiteProperties = this.ofbizUrlBuilder.getWebSiteProperties();
this.controllerConfig = SafeOptional.ofNullable(this.ofbizUrlBuilder.getControllerConfig());
} catch (GenericEntityException e) {
throw new IllegalArgumentException(e);
} catch (WebAppConfigurationException e) {
throw new IllegalArgumentException(e);
}
}
protected FullWebappInfo(ExtWebappInfo extWebappInfo, HttpServletRequest request) {
try {
// SPECIAL: in this case we must initialize WebSiteProperties immediately because
// we can't store the HttpServletRequest object in FullWebappInfo
this.ofbizUrlBuilder = OfbizUrlBuilder.from(extWebappInfo, request);
this.extWebappInfo = extWebappInfo;
this.webSiteProperties = this.ofbizUrlBuilder.getWebSiteProperties();
this.controllerConfig = SafeOptional.ofNullable(this.ofbizUrlBuilder.getControllerConfig());
} catch (GenericEntityException e) {
throw new IllegalArgumentException(e);
} catch (WebAppConfigurationException e) {
throw new IllegalArgumentException(e);
}
}
protected FullWebappInfo(ExtWebappInfo extWebappInfo, Map<String, Object> context) {
this(extWebappInfo, (Delegator) context.get("delegator"));
}
protected FullWebappInfo(ExtWebappInfo extWebappInfo, Delegator delegator) {
try {
// SPECIAL: in this case we must initialize WebSiteProperties immediately because
// we can't store the HttpServletRequest object in FullWebappInfo
this.ofbizUrlBuilder = OfbizUrlBuilder.from(extWebappInfo, delegator);
this.extWebappInfo = extWebappInfo;
this.webSiteProperties = this.ofbizUrlBuilder.getWebSiteProperties();
this.controllerConfig = SafeOptional.ofNullable(this.ofbizUrlBuilder.getControllerConfig());
} catch (GenericEntityException e) {
throw new IllegalArgumentException(e);
} catch (WebAppConfigurationException e) {
throw new IllegalArgumentException(e);
} catch (IOException e) {
throw new IllegalArgumentException(e);
} catch (SAXException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Gets webapp info for current webapp from request.
* For intra-webapp links.
*/
public static FullWebappInfo fromRequest(HttpServletRequest request) throws IllegalArgumentException {
return fromRequest(request, Cache.fromRequest(request));
}
/**
* Gets webapp info for current webapp from request.
* For intra-webapp links.
*/
public static FullWebappInfo fromRequest(HttpServletRequest request, Cache cache) throws IllegalArgumentException {
if (cache == null) return new FullWebappInfo(request);
FullWebappInfo fullWebappInfo = cache.getCurrentWebappInfo();
if (fullWebappInfo == null) {
fullWebappInfo = new FullWebappInfo(request);
cache.setCurrentWebappInfo(fullWebappInfo);
}
return fullWebappInfo;
}
/**
* Reads webapp info from request, but if the request does not appear set up properly
* yet (i.e. by ContextFilter), prevent caching the result, so as to not pollute the rest
* of the request with an uncertain state.
* For intra-webapp links.
* <p>
* DEV NOTE: WARN: This is dirty to maintain, beware.
*/
public static FullWebappInfo fromRequestFilterSafe(HttpServletRequest request) throws IllegalArgumentException {
if (request.getAttribute("delegator") != null) {
// request appears set up already (e.g. by ContextFilter)
return fromRequest(request);
} else {
// no delegator, request is not set up
request.setAttribute("delegator", WebAppUtil.getDelegatorFilterSafe(request));
boolean hadOfbizUrlBuilderAttr = (request.getAttribute("_OFBIZ_URL_BUILDER_") != null);
boolean hadWebSitePropsAttr = (request.getAttribute("_WEBSITE_PROPS_") != null);
boolean addedControlPathAttr = false;
if (request.getAttribute("_CONTROL_PATH_") == null) {
// From ControlServlet logic
addedControlPathAttr = true;
String contextPath = request.getContextPath();
if (contextPath == null || "/".equals(contextPath)) {
contextPath = "";
}
request.setAttribute("_CONTROL_PATH_", contextPath + request.getServletPath());
}
try {
return new FullWebappInfo(request);
} finally {
// do not let filter state affect rest of request - clear cached objects
if (!hadOfbizUrlBuilderAttr) request.removeAttribute("_OFBIZ_URL_BUILDER_");
if (!hadWebSitePropsAttr) request.removeAttribute("_WEBSITE_PROPS_");
if (addedControlPathAttr) request.removeAttribute("_CONTROL_PATH_");
Cache.clearRequestCache(request);
request.removeAttribute("delegator");
}
}
}
/**
* Gets full webapp info, using webapp request for caching and context information.
* For inter-webapp links.
*/
public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, HttpServletRequest request) throws IllegalArgumentException {
return fromWebapp(extWebappInfo, request, Cache.fromRequest(request));
}
/**
* Gets full webapp info, using webapp request for caching and context information.
* For inter-webapp links.
*/
public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, HttpServletRequest request, Cache cache) throws IllegalArgumentException {
if (cache == null) return new FullWebappInfo(extWebappInfo, request);
FullWebappInfo fullWebappInfo = cache.getByContextPath(extWebappInfo.getContextPath());
if (fullWebappInfo == null) {
fullWebappInfo = new FullWebappInfo(extWebappInfo, request);
cache.addWebappInfo(fullWebappInfo);
}
return fullWebappInfo;
}
/**
* Gets webapp info for current webapp from render context.
* For intra-webapp links.
* <p>
* NOTE: This only works if there is a webSiteId (or baseWebSiteId) in context..
* For now only webapp requests can return an instance without webSiteId.
*/
public static FullWebappInfo fromContext(Map<String, Object> context, RenderEnvType renderEnvType) throws IllegalArgumentException {
return fromContext(context, renderEnvType, Cache.fromContext(context, renderEnvType));
}
/**
* Gets webapp info for current webapp from render context.
* For intra-webapp links.
* <p>
* NOTE: This only works if there is a webSiteId (or baseWebSiteId) in context..
* For now only webapp requests can return an instance without webSiteId.
*/
public static FullWebappInfo fromContext(Map<String, Object> context) throws IllegalArgumentException {
RenderEnvType renderEnvType = RenderEnvType.fromContext(context);
return fromContext(context, renderEnvType, Cache.fromContext(context, renderEnvType));
}
/**
* Gets webapp info for current webapp from render context.
* For intra-webapp links.
* <p>
* NOTE: This only works if there is a webSiteId (or baseWebSiteId) in context..
* For now only webapp requests can return an instance without webSiteId.
*/
public static FullWebappInfo fromContext(Map<String, Object> context, RenderEnvType renderEnvType, Cache cache) throws IllegalArgumentException {
if (renderEnvType.isStatic()) {
FullWebappInfo fullWebappInfo = null;
if (cache != null) {
fullWebappInfo = cache.getCurrentWebappInfo();
if (fullWebappInfo != null) {
return fullWebappInfo;
}
}
String webSiteId = WebSiteWorker.getWebSiteIdFromContext(context, renderEnvType);
if (webSiteId != null) {
fullWebappInfo = FullWebappInfo.fromWebapp(ExtWebappInfo.fromWebSiteId(webSiteId),
(Delegator) context.get("delegator"), cache);
if (cache != null) {
cache.setCurrentWebappInfoOnly(fullWebappInfo);
}
}
return fullWebappInfo;
} else if (renderEnvType.isWebapp()) { // NOTE: it is important to check isWebapp here and not (request != null), because these could disassociate in future
return fromRequest((HttpServletRequest) context.get("request"), cache);
}
return null;
}
/**
* Gets webapp info, using render context for caching and context information.
* For inter-webapp links.
*/
public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, Map<String, Object> context) throws IllegalArgumentException {
return fromWebapp(extWebappInfo, context, Cache.fromContext(context));
}
/**
* Gets webapp info, using render context for caching and context information.
* For inter-webapp links.
*/
public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, Map<String, Object> context, Cache cache) throws IllegalArgumentException {
if (cache == null) return new FullWebappInfo(extWebappInfo, context);
FullWebappInfo fullWebappInfo = cache.getByContextPath(extWebappInfo.getContextPath());
if (fullWebappInfo == null) {
fullWebappInfo = new FullWebappInfo(extWebappInfo, context);
cache.addWebappInfo(fullWebappInfo);
}
return fullWebappInfo;
}
/**
* Gets webapp info, without any context information (low-level no-context factory method).
* For inter-webapp links.
* <p>
* WARN: Prefer method with context or request wherever available, instead of this one.
* This method has less information to work with compared to request and context overloads.
*/
public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, Delegator delegator, Cache cache) throws IllegalArgumentException {
if (cache == null) return new FullWebappInfo(extWebappInfo, delegator);
FullWebappInfo fullWebappInfo = cache.getByContextPath(extWebappInfo.getContextPath());
if (fullWebappInfo == null) {
fullWebappInfo = new FullWebappInfo(extWebappInfo, delegator);
cache.addWebappInfo(fullWebappInfo);
}
return fullWebappInfo;
}
/**
* Gets webapp info, without any context information (low-level no-context factory method) - no caching.
* For inter-webapp links.
* <p>
* WARN: Prefer method with context or request wherever available, instead of this one.
* This method has less information to work with compared to request and context overloads.
*/
public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, Delegator delegator) throws IllegalArgumentException {
return new FullWebappInfo(extWebappInfo, delegator);
}
/**
* Gets webapp info for webSiteId or contextPath, otherwise null (high-level factory method).
* Caches in request if available, otherwise context.
*/
public static FullWebappInfo fromWebSiteIdOrContextPathOrNull(String webSiteId,
String contextPath, HttpServletRequest request, Map<String, Object> context) throws IllegalArgumentException {
if (UtilValidate.isNotEmpty(webSiteId)) {
if (request != null) {
return fromWebapp(ExtWebappInfo.fromWebSiteId(webSiteId), request, Cache.fromRequest(request));
} else {
return fromWebapp(ExtWebappInfo.fromWebSiteId(webSiteId), context, Cache.fromContext(context));
}
} else if (UtilValidate.isNotEmpty(contextPath)) {
if (request != null) {
return fromWebapp(ExtWebappInfo.fromContextPath(WebAppUtil.getServerId(request), contextPath), request, Cache.fromRequest(request));
} else {
return fromWebapp(ExtWebappInfo.fromContextPath(WebAppUtil.getServerId(context), contextPath), context, Cache.fromContext(context));
}
}
return null;
}
public static OfbizUrlBuilder getOfbizUrlBuilderFromWebSiteIdOrDefaults(String webSiteId, Delegator delegator, Cache cache) throws IllegalArgumentException {
if (UtilValidate.isNotEmpty(webSiteId)) {
if (cache != null && cache.getByWebSiteId(webSiteId) != null) {
return cache.getByWebSiteId(webSiteId).getOfbizUrlBuilder();
}
try {
return OfbizUrlBuilder.fromWebSiteId(webSiteId, delegator);
} catch (Exception e) {
throw new IllegalStateException(e);
}
} else {
if (cache != null && cache.getDefaultOfbizUrlBuilder() != null) {
return cache.getDefaultOfbizUrlBuilder();
}
OfbizUrlBuilder builder;
try {
builder = OfbizUrlBuilder.fromServerDefaults(delegator);
} catch (Exception e) {
throw new IllegalStateException(e);
}
if (cache != null) cache.setDefaultOfbizUrlBuilder(builder);
return builder;
}
}
public ExtWebappInfo getExtWebappInfo() {
return extWebappInfo;
}
public WebSiteProperties getWebSiteProperties() {
return webSiteProperties;
}
/**
* Returns the ControllerConfig for this webapp or null if it has none.
*/
public ControllerConfig getControllerConfig() {
SafeOptional<ControllerConfig> controllerConfig = this.controllerConfig;
if (controllerConfig == null) {
controllerConfig = SafeOptional.ofNullable(extWebappInfo.getControllerConfig());
this.controllerConfig = controllerConfig;
}
return controllerConfig.orElse(null);
}
/**
* Returns a URL builder or throws exception.
*/
public OfbizUrlBuilder getOfbizUrlBuilder() throws IllegalArgumentException {
return ofbizUrlBuilder;
}
@Override
public int hashCode() {
return extWebappInfo.hashCode();
}
@Override
public boolean equals(Object obj) {
return (this == obj) ||
((obj instanceof FullWebappInfo) && this.isSameServerWebapp(((FullWebappInfo) obj)));
}
public boolean equalsProtoHostPort(FullWebappInfo other) {
return this.getWebSiteProperties().equalsServerFields(other.getWebSiteProperties());
}
public boolean equalsProtoHostPortWithHardDefaults(FullWebappInfo other) {
return this.getWebSiteProperties().equalsServerFieldsWithHardDefaults(other.getWebSiteProperties());
}
@Override
public String toString() {
return "[contextPath=" + getContextPath() + ", webSiteId=" + getWebSiteId() + "]";
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getServerId()
*/
public String getServerId() {
return extWebappInfo.getServerId();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getWebSiteId()
*/
public String getWebSiteId() {
return extWebappInfo.getWebSiteId();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getWebappInfo()
*/
public WebappInfo getWebappInfo() {
return extWebappInfo.getWebappInfo();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getWebXml()
*/
public WebXml getWebXml() {
return extWebappInfo.getWebXml();
}
public String getWebappName() {
return extWebappInfo.getWebappName();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getContextPath()
*/
public String getContextPath() {
return extWebappInfo.getContextPath();
}
/**
* @return
* @deprecated
* @see org.ofbiz.webapp.ExtWebappInfo#getContextRoot()
*/
public String getContextRoot() {
return extWebappInfo.getContextRoot();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getControlServletPath()
*/
public String getControlServletPath() {
return extWebappInfo.getControlServletPath();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getControlServletMapping()
*/
public String getControlServletMapping() {
return extWebappInfo.getControlServletMapping();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getFullControlPath()
*/
public String getFullControlPath() {
return extWebappInfo.getFullControlPath();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getContextParams()
*/
public Map<String, String> getContextParams() {
return extWebappInfo.getContextParams();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getForwardRootControllerUris()
*/
public Boolean getForwardRootControllerUris() {
return extWebappInfo.getForwardRootControllerUris();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getForwardRootControllerUrisValidated()
*/
public Boolean getForwardRootControllerUrisValidated() {
return extWebappInfo.getForwardRootControllerUrisValidated();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#hasUrlRewriteFilter()
*/
public boolean hasUrlRewriteFilter() {
return extWebappInfo.hasUrlRewriteFilter();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getUrlRewriteConfPath()
*/
public String getUrlRewriteConfPath() {
return extWebappInfo.getUrlRewriteConfPath();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getUrlRewriteFullConfPath()
*/
public String getUrlRewriteFullConfPath() {
return extWebappInfo.getUrlRewriteFullConfPath();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#getUrlRewriteRealConfPath()
*/
public String getUrlRewriteRealConfPath() {
return extWebappInfo.getUrlRewriteRealConfPath();
}
/**
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#useUrlManualInterWebappFilter()
*/
public boolean useUrlManualInterWebappFilter() {
return extWebappInfo.useUrlManualInterWebappFilter();
}
/**
* @param request
* @return
* @see org.ofbiz.webapp.ExtWebappInfo#isRequestWebapp(javax.servlet.http.HttpServletRequest)
*/
public boolean isRequestWebapp(HttpServletRequest request) {
return extWebappInfo.isRequestWebapp(request);
}
public boolean isSameServerWebapp(ExtWebappInfo other) {
return extWebappInfo.isSameServerWebapp(other);
}
public boolean isSameWebSite(ExtWebappInfo other) {
return extWebappInfo.isSameWebSite(other);
}
public boolean isSameServerWebapp(FullWebappInfo other) {
return extWebappInfo.isSameServerWebapp(other.extWebappInfo);
}
public boolean isSameWebSite(FullWebappInfo other) {
return extWebappInfo.isSameWebSite(other.extWebappInfo);
}
/**
* WARN: not thread-safe at current time (meant for request scope only).
*/
public static class Cache {
public static final String FIELD_NAME = "scpFWICache";
private FullWebappInfo currentWebappInfo;
private WebSiteProperties defaultWebSiteProperties;
private OfbizUrlBuilder defaultOfbizUrlBuilder;
private Map<String, FullWebappInfo> webSiteIdCache = new HashMap<>();
private Map<String, FullWebappInfo> contextPathCache = new HashMap<>();
protected Cache(Delegator delegator) {
//this.delegator = delegator;
}
public static Cache newCache(Delegator delegator) {
return new Cache(delegator);
}
public static Cache fromRequest(HttpServletRequest request) {
Cache cache = (Cache) request.getAttribute(FIELD_NAME);
if (cache == null) {
cache = new Cache((Delegator) request.getAttribute("delegator"));
request.setAttribute(FIELD_NAME, cache);
}
return cache;
}
public static void clearRequestCache(HttpServletRequest request) {
request.removeAttribute(FIELD_NAME);
}
public static Cache fromContext(Map<String, Object> context, RenderEnvType renderEnvType) {
if (renderEnvType.isStatic()) {
@SuppressWarnings("unchecked")
Map<String, Object> srcContext = (Map<String, Object>) context.get("globalContext");
if (srcContext == null) srcContext = context; // fallback
Cache cache = (Cache) srcContext.get(FIELD_NAME);
if (cache == null) {
cache = new Cache((Delegator) context.get("delegator"));
srcContext.put(FIELD_NAME, cache);
}
return cache;
} else if (renderEnvType.isWebapp()) { // NOTE: it is important to check isWebapp here and not (request != null), because these could disassociate in future
return fromRequest((HttpServletRequest) context.get("request"));
}
return null;
}
public static Cache fromContext(Map<String, Object> context) {
return fromContext(context, RenderEnvType.fromContext(context)); // TODO?: optimize
}
public static void clearContextCache(Map<String, Object> context, RenderEnvType renderEnvType) {
if (renderEnvType.isStatic()) {
@SuppressWarnings("unchecked")
Map<String, Object> srcContext = (Map<String, Object>) context.get("globalContext");
if (srcContext == null) srcContext = context; // fallback
srcContext.remove(FIELD_NAME);
} else if (renderEnvType.isWebapp()) {
clearRequestCache((HttpServletRequest) context.get("request"));
}
}
public static void clearContextCache(Map<String, Object> context) {
clearContextCache(context, RenderEnvType.fromContext(context)); // TODO?: optimize
}
public static Cache fromRequestOrContext(HttpServletRequest request, Map<String, Object> context,
RenderEnvType renderEnvType) {
return (request != null) ? fromRequest(request) : fromContext(context, renderEnvType);
}
public FullWebappInfo getCurrentWebappInfo() {
return currentWebappInfo;
}
public String getCurrentWebappWebSiteId() {
return (currentWebappInfo != null) ? currentWebappInfo.getWebSiteId() : null;
}
public void setCurrentWebappInfo(FullWebappInfo currentWebappInfo) {
this.currentWebappInfo = currentWebappInfo;
addWebappInfo(currentWebappInfo);
}
public void setCurrentWebappInfoOnly(FullWebappInfo currentWebappInfo) {
this.currentWebappInfo = currentWebappInfo;
}
public WebSiteProperties getDefaultWebSiteProperties() {
return defaultWebSiteProperties;
}
public void setDefaultWebSiteProperties(WebSiteProperties defaultWebSiteProperties) {
this.defaultWebSiteProperties = defaultWebSiteProperties;
}
public OfbizUrlBuilder getDefaultOfbizUrlBuilder() {
return defaultOfbizUrlBuilder;
}
public void setDefaultOfbizUrlBuilder(OfbizUrlBuilder defaultOfbizUrlBuilder) {
this.defaultOfbizUrlBuilder = defaultOfbizUrlBuilder;
}
public void addWebappInfo(FullWebappInfo webappInfo) {
contextPathCache.put(webappInfo.getContextPath(), webappInfo);
if (webappInfo.getWebSiteId() != null) {
webSiteIdCache.put(webappInfo.getWebSiteId(), webappInfo);
}
}
public FullWebappInfo getByWebSiteId(String webSiteId) {
return webSiteIdCache.get(webSiteId);
}
public FullWebappInfo getByContextPath(String contextPath) {
return contextPathCache.get(contextPath);
}
}
}
|
package com.opengamma.financial.analytics.volatility.surface;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.time.InstantProvider;
import javax.time.calendar.Clock;
import javax.time.calendar.LocalDate;
import javax.time.calendar.OffsetTime;
import javax.time.calendar.TimeZone;
import javax.time.calendar.ZoneOffset;
import javax.time.calendar.ZonedDateTime;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.core.marketdatasnapshot.VolatilitySurfaceData;
import com.opengamma.core.security.Security;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.CompiledFunctionDefinition;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.id.Identifier;
import com.opengamma.livedata.normalization.MarketDataRequirementNames;
import com.opengamma.util.time.DateUtil;
import com.opengamma.util.tuple.Pair;
//TODO this class needs to be re-written, as each instrument type needs a different set of inputs
public class EquityOptionVolatilitySurfaceDataFunction extends AbstractFunction {
private static final Logger s_logger = LoggerFactory.getLogger(EquityOptionVolatilitySurfaceDataFunction.class);
/**
* Resultant value specification property for the surface result. Note these should be moved into either the ValuePropertyNames class
* if there are generic terms, or an OpenGammaValuePropertyNames if they are more specific to our financial integration.
*/
//TODO replace with ValuePropertyNames.SURFACE?
//public static final String PROPERTY_SURFACE_DEFINITION_NAME = "NAME";
/**
* Value specification property for the surface result. This allows surface to be distinguished by instrument type (e.g. an FX volatility
* surface, swaption ATM volatility surface).
*/
public static final String PROPERTY_SURFACE_INSTRUMENT_TYPE = "InstrumentType";
private VolatilitySurfaceDefinition<?, ?> _definition;
private ValueSpecification _result;
private Set<ValueSpecification> _results;
private String _underlyingIdentifierAsString;
private final String _definitionName;
private final String _specificationName;
private String _instrumentType;
private VolatilitySurfaceSpecification _specification;
public EquityOptionVolatilitySurfaceDataFunction(final String definitionName, final String instrumentType, final String specificationName) {
Validate.notNull(definitionName, "Definition Name");
Validate.notNull(instrumentType, "Instrument Type");
Validate.notNull(specificationName, "Specification Name");
_definition = null;
_definitionName = definitionName;
_instrumentType = instrumentType;
_specificationName = specificationName;
_result = null;
_results = null;
}
public String getCurrencyLabel() {
return _underlyingIdentifierAsString;
}
public String getDefinitionName() {
return _definitionName;
}
public String getSpecificationName() {
return _specificationName;
}
@Override
public void init(final FunctionCompilationContext context) {
final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context);
final ConfigDBVolatilitySurfaceDefinitionSource volSurfaceDefinitionSource = new ConfigDBVolatilitySurfaceDefinitionSource(configSource);
_definition = volSurfaceDefinitionSource.getDefinition(_definitionName, _instrumentType);
final ConfigDBVolatilitySurfaceSpecificationSource volatilitySurfaceSpecificationSource = new ConfigDBVolatilitySurfaceSpecificationSource(configSource);
_specification = volatilitySurfaceSpecificationSource.getSpecification(_specificationName, _instrumentType);
_result = new ValueSpecification(ValueRequirementNames.VOLATILITY_SURFACE_DATA, new ComputationTargetSpecification(_definition.getTarget().getUniqueId()),
createValueProperties().with(ValuePropertyNames.SURFACE, _definitionName).with(PROPERTY_SURFACE_INSTRUMENT_TYPE, _instrumentType).get());
_results = Collections.singleton(_result);
}
@Override
public String getShortName() {
return _underlyingIdentifierAsString + "-" + _definitionName + " for " + _instrumentType + " from " + _specificationName + " Volatility Surface Data";
}
public static <X, Y> Set<ValueRequirement> buildRequirements(final VolatilitySurfaceSpecification specification,
final VolatilitySurfaceDefinition<X, Y> definition,
final FunctionCompilationContext context,
final ZonedDateTime atInstant) {
final Set<ValueRequirement> result = new HashSet<ValueRequirement>();
final BloombergEquityOptionVolatilitySurfaceInstrumentProvider provider = (BloombergEquityOptionVolatilitySurfaceInstrumentProvider) specification.getSurfaceInstrumentProvider();
for (final X x : definition.getXs()) {
// don't care what these are
for (final Y y : definition.getYs()) {
provider.init(true); // generate puts
final Identifier putIdentifier = provider.getInstrument((LocalDate) x, (Double) y, atInstant.toLocalDate());
result.add(new ValueRequirement(provider.getDataFieldName(), putIdentifier));
provider.init(false);
final Identifier callIdentifier = provider.getInstrument((LocalDate) x, (Double) y, atInstant.toLocalDate());
result.add(new ValueRequirement(provider.getDataFieldName(), callIdentifier));
}
}
// add the underlying
result.add(new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE, ComputationTargetType.PRIMITIVE, definition.getTarget().getUniqueId()));
return result;
}
@Override
public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final InstantProvider atInstantProvider) {
final ZonedDateTime atInstant = ZonedDateTime.ofInstant(atInstantProvider, TimeZone.UTC);
final Set<ValueRequirement> requirements = Collections.unmodifiableSet(buildRequirements(_specification, _definition, context, atInstant));
//TODO ENG-252 see MarketInstrumentImpliedYieldCurveFunction; need to work out the expiry more efficiently
return new AbstractInvokingCompiledFunction(atInstant.withTime(0, 0), atInstant.plusDays(1).withTime(0, 0).minusNanos(1000000)) {
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.PRIMITIVE;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
if (canApplyTo(context, target)) {
return _results;
}
return null;
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
if (canApplyTo(context, target)) {
return requirements;
}
return null;
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
if (target.getType() != ComputationTargetType.PRIMITIVE) {
return false;
}
return ObjectUtils.equals(target.getUniqueId(), _definition.getTarget().getUniqueId());
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues) {
final Clock snapshotClock = executionContext.getValuationClock();
final ValueRequirement underlyingSpotValueRequirement = new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE, ComputationTargetType.PRIMITIVE, _definition.getTarget().getUniqueId());
final Double underlyingSpot = (Double) inputs.getValue(underlyingSpotValueRequirement);
if (underlyingSpot == null) {
s_logger.error("Could not get underlying spot value for " + _definition.getTarget().getUniqueId());
return Collections.emptySet();
}
final ZonedDateTime now = snapshotClock.zonedDateTime();
final Map<Pair<Object, Object>, Double> volatilityValues = new HashMap<Pair<Object, Object>, Double>();
int numFound = 0;
for (final Object x : _definition.getXs()) {
for (final Object y : _definition.getYs()) {
double strike = (Double) y;
LocalDate expiry = (LocalDate) x;
final BloombergEquityOptionVolatilitySurfaceInstrumentProvider provider = (BloombergEquityOptionVolatilitySurfaceInstrumentProvider) _specification.getSurfaceInstrumentProvider();
if (strike < underlyingSpot) {
provider.init(false); // generate identifiers for call options
} else {
provider.init(true); // generate identifiers for put options
}
final Identifier identifier = provider.getInstrument(expiry, strike, now.toLocalDate());
final ValueRequirement requirement = new ValueRequirement(provider.getDataFieldName(), identifier);
final double relativeStrikeBps = ((underlyingSpot - strike) / underlyingSpot) * 100;
// TODO: totally bogus
@SuppressWarnings("unused")
final double relativeExpiry = DateUtil.getDifferenceInYears(now, expiry.atTime(now.toOffsetTime()));
if (inputs.getValue(requirement) != null) {
numFound++;
final Double volatility = (Double) inputs.getValue(requirement);
volatilityValues.put(Pair.of((Object) expiry, (Object) strike), volatility / 100);
//s_logger.warn("adding data for " + expiry + " relativeStrike=" + relativeStrikeBps + " absStrike = " + strike);
}
}
}
//s_logger.warn("Number of Equity Option Vols found = " + numFound);
final VolatilitySurfaceData<?, ?> volSurfaceData = new VolatilitySurfaceData<Object, Object>(_definition.getName(), _specification.getName(),
_definition.getTarget().getUniqueId(),
_definition.getXs(), _definition.getYs(), volatilityValues);
final ComputedValue resultValue = new ComputedValue(_result, volSurfaceData);
return Collections.singleton(resultValue);
}
@Override
public boolean canHandleMissingInputs() {
return true;
}
};
}
}
|
package com.sunzn.utils.library;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class DrawableUtils {
private DrawableUtils() {
throw new RuntimeException("Stub!");
}
/**
*
* Drawable
*
* context
* id
*
* void
*
*/
public static Drawable getDrawable(@NonNull Context context, @DrawableRes int id) {
return ContextCompat.getDrawable(context, id);
}
/**
*
* TextView DrawableLeft
*
* view TextView
* left Drawable
*
* void
*
*/
public static void setDrawableLeft(@NonNull TextView view, @Nullable Drawable left) {
if (left != null) left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
view.setCompoundDrawables(left, null, null, null);
}
/**
*
* TextView DrawableRight
*
* view TextView
* right Drawable
*
* void
*
*/
public static void setDrawableRight(@NonNull TextView view, @Nullable Drawable right) {
if (right != null) right.setBounds(0, 0, right.getMinimumWidth(), right.getMinimumHeight());
view.setCompoundDrawables(null, null, right, null);
}
/**
*
* TextView DrawableTop
*
* view TextView
* top Drawable
*
* void
*
*/
public static void setDrawableTop(@NonNull TextView view, @Nullable Drawable top) {
if (top != null) top.setBounds(0, 0, top.getMinimumWidth(), top.getMinimumHeight());
view.setCompoundDrawables(null, top, null, null);
}
/**
*
* TextView DrawableBottom
*
* view TextView
* btm Drawable
*
* void
*
*/
public static void setDrawableBottom(@NonNull TextView view, @Nullable Drawable btm) {
if (btm != null) btm.setBounds(0, 0, btm.getMinimumWidth(), btm.getMinimumHeight());
view.setCompoundDrawables(null, null, null, btm);
}
/**
*
* TextView DrawableLeft
*
* context
* view TextView
* id
*
* void
*
*/
public static void setDrawableLeft(@NonNull Context context, @NonNull TextView view, @DrawableRes int id) {
Drawable drawable = getDrawable(context, id);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(drawable, null, null, null);
}
/**
*
* TextView DrawableRight
*
* context
* view TextView
* id
*
* void
*
*/
public static void setDrawableRight(@NonNull Context context, @NonNull TextView view, @DrawableRes int id) {
Drawable drawable = getDrawable(context, id);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(null, null, drawable, null);
}
/**
*
* TextView DrawableTop
*
* context
* view TextView
* id
*
* void
*
*/
public static void setDrawableTop(@NonNull Context context, @NonNull TextView view, @DrawableRes int id) {
Drawable drawable = getDrawable(context, id);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(null, drawable, null, null);
}
/**
*
* TextView DrawableBottom
*
* context
* view TextView
* id
*
* void
*
*/
public static void setDrawableBottom(@NonNull Context context, @NonNull TextView view, @DrawableRes int id) {
Drawable drawable = getDrawable(context, id);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(null, null, null, drawable);
}
/**
*
* TextView DrawableLeft
*
* context
* view TextView
* id
* color
*
* void
*
*/
public static void setColorDrawableLeft(@NonNull Context context, @NonNull TextView view, @DrawableRes int id, @ColorRes int color) {
Drawable drawable = getDrawable(context, id).mutate();
drawable.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(drawable, null, null, null);
}
/**
*
* TextView DrawableRight
*
* context
* view TextView
* id
* color
*
* void
*
*/
public static void setColorDrawableRight(@NonNull Context context, @NonNull TextView view, @DrawableRes int id, @ColorRes int color) {
Drawable drawable = getDrawable(context, id).mutate();
drawable.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(null, null, drawable, null);
}
/**
*
* TextView DrawableTop
*
* context
* view TextView
* id
* color
*
* void
*
*/
public static void setColorDrawableTop(@NonNull Context context, @NonNull TextView view, @DrawableRes int id, @ColorRes int color) {
Drawable drawable = getDrawable(context, id).mutate();
drawable.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(null, drawable, null, null);
}
/**
*
* TextView DrawableBottom
*
* context
* view TextView
* id
* color
*
* void
*
*/
public static void setColorDrawableBottom(@NonNull Context context, @NonNull TextView view, @DrawableRes int id, @ColorRes int color) {
Drawable drawable = getDrawable(context, id).mutate();
drawable.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
view.setCompoundDrawables(null, null, null, drawable);
}
/**
*
* View Drawable
*
* view
* drawable
*
* void
*
*/
public static void setBackground(@NonNull View view, @NonNull Drawable drawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(drawable);
} else {
view.setBackgroundDrawable(drawable);
}
}
/**
*
* ImageView
*
* context
* view ImageView
* color
*
* void
*
*/
public static void setColorDrawable(@NonNull Context context, @NonNull ImageView view, @ColorRes int color) {
Drawable drawable = view.getDrawable().mutate();
drawable.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP);
}
/**
*
* TextView
*
* view TextView
* tintColor
*
* void
*
*/
public static void setNinePatchColorDrawable(@NonNull TextView view, @ColorInt int tintColor) {
NinePatchDrawable drawable = (NinePatchDrawable) view.getBackground();
drawable.setColorFilter(new PorterDuffColorFilter(tintColor, PorterDuff.Mode.SRC_IN));
setBackground(view, drawable);
}
/**
*
* TextView
*
* context
* view TextView
* tintColor
*
* void
*
*/
public static void setNinePatchColorDrawable(@NonNull Context context, @NonNull TextView view, @ColorRes int color) {
NinePatchDrawable drawable = (NinePatchDrawable) view.getBackground();
drawable.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_IN));
setBackground(view, drawable);
}
/**
*
* NinePatchDrawable
*
* context
* tintColor
* id
*
* void
*
*/
public static Drawable getTintNinePatchDrawable(@NonNull Context context, @ColorInt int tintColor, @DrawableRes int id) {
final NinePatchDrawable drawable = (NinePatchDrawable) getDrawable(context, id);
drawable.setColorFilter(new PorterDuffColorFilter(tintColor, PorterDuff.Mode.SRC_IN));
return drawable;
}
}
|
package nl.idgis.publisher.provider.database.messages;
import java.io.Serializable;
import nl.idgis.publisher.domain.service.Type;
public class DatabaseColumnInfo implements Serializable {
private static final long serialVersionUID = 8052868017910750424L;
private final String name;
private final String typeName;
public DatabaseColumnInfo(String name, String typeName) {
this.name = name;
this.typeName = typeName;
}
public String getName() {
return name;
}
public String getTypeName() {
return typeName;
}
public Type getType() {
switch(typeName.toUpperCase()) {
case "NUMBER":
case "FLOAT":
return Type.NUMERIC;
case "DATE":
return Type.DATE;
case "VARCHAR2":
case "NVARCHAR2":
case "NCHAR":
case "CHAR":
case "CLOB":
case "NCLOB":
return Type.TEXT;
case "SDO_GEOMETRY":
case "ST_GEOMETRY":
return Type.GEOMETRY;
}
return null;
}
@Override
public String toString() {
return "DatabaseColumnInfo [name=" + name + ", typeName=" + typeName + "]";
}
}
|
/**
* Holds an object that represents the value of a variable
*
* @author squirlemaster42
*/
package org.usfirst.frc.team1699.utils.autonomous;
public class Value {
private Object value;
public Value(Object value){
this.value = value;
//Converts value to a variable
}
}
|
package org.zalando.nakadi.controller;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.zalando.nakadi.exceptions.NakadiRuntimeException;
import org.zalando.nakadi.exceptions.IllegalClientIdException;
import org.zalando.nakadi.exceptions.IllegalScopeException;
import org.zalando.nakadi.exceptions.NakadiException;
import org.zalando.nakadi.exceptions.runtime.InconsistentStateException;
import org.zalando.nakadi.exceptions.runtime.MyNakadiRuntimeException1;
import org.zalando.nakadi.exceptions.runtime.RepositoryProblemException;
import org.zalando.problem.Problem;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import org.zalando.problem.spring.web.advice.Responses;
import javax.ws.rs.core.Response;
@ControllerAdvice
public final class ExceptionHandling implements ProblemHandling {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionHandling.class);
@Override
public String formatFieldName(final String fieldName) {
return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fieldName);
}
@Override
@ExceptionHandler
public ResponseEntity<Problem> handleThrowable(final Throwable throwable, final NativeWebRequest request) {
final String errorTraceId = generateErrorTraceId();
LOG.error("InternalServerError (" + errorTraceId + "):", throwable);
return Responses.create(Response.Status.INTERNAL_SERVER_ERROR, "An internal error happened. Please report it. ("
+ errorTraceId + ")", request);
}
private String generateErrorTraceId() {
return "ETI" + RandomStringUtils.randomAlphanumeric(24);
}
@Override
@ExceptionHandler
public ResponseEntity<Problem> handleMessageNotReadableException(final HttpMessageNotReadableException exception,
final NativeWebRequest request) {
/*
Unwrap nested JsonMappingException because the enclosing HttpMessageNotReadableException adds some ugly, Java
class and stacktrace like information.
*/
final Throwable mostSpecificCause = exception.getMostSpecificCause();
final String message;
if (mostSpecificCause instanceof JsonMappingException) {
message = mostSpecificCause.getMessage();
} else {
message = exception.getMessage();
}
return Responses.create(Response.Status.BAD_REQUEST, message, request);
}
@ExceptionHandler(IllegalScopeException.class)
public ResponseEntity<Problem> handleIllegalScopeException(final IllegalScopeException exception,
final NativeWebRequest request) {
return Responses.create(Response.Status.FORBIDDEN, exception.getMessage(), request);
}
@ExceptionHandler(IllegalClientIdException.class)
public ResponseEntity<Problem> handleIllegalClientIdException(final IllegalClientIdException exception,
final NativeWebRequest request) {
return Responses.create(Response.Status.FORBIDDEN, exception.getMessage(), request);
}
@ExceptionHandler
public ResponseEntity<Problem> handleExceptionWrapper(final NakadiRuntimeException exception,
final NativeWebRequest request) throws Exception
{
final Throwable cause = exception.getCause();
if (cause instanceof NakadiException) {
final NakadiException ne = (NakadiException) cause;
return Responses.create(ne.asProblem(), request);
}
throw exception.getException();
}
@ExceptionHandler(RepositoryProblemException.class)
public ResponseEntity<Problem> handleRepositoryProblem(final RepositoryProblemException exception,
final NativeWebRequest request) {
LOG.error("Repository problem occurred", exception);
return Responses.create(Response.Status.SERVICE_UNAVAILABLE, exception.getMessage(), request);
}
@ExceptionHandler(InconsistentStateException.class)
public ResponseEntity<Problem> handleInternalError(final MyNakadiRuntimeException1 exception,
final NativeWebRequest request) {
LOG.error("Unexpected problem occurred", exception);
return Responses.create(Response.Status.INTERNAL_SERVER_ERROR, exception.getMessage(), request);
}
}
|
package pl.hycom.pip.messanger.pipeline;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.xml.bind.JAXBContext;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import lombok.extern.log4j.Log4j2;
import pl.hycom.pip.messanger.pipeline.model.*;
@Log4j2
@Service
public class PipelineManager implements ApplicationContextAware, InitializingBean {
private ApplicationContext applicationContext;
private Pipeline pipeline;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(getClass().getResourceAsStream("/pipeline.xml")));
pipeline = (Pipeline) JAXBContext.newInstance(Pipeline.class).createUnmarshaller().unmarshal(xsr);
}
private void runProcessForChain(PipelineContext context, PipelineChain pipelineChain) throws PipelineException {
runProcessForLink(context, pipelineChain, pipelineChain.getHeadLink());
}
private void runProcessForLink(PipelineContext context, PipelineChain pipelineChain, String name) throws PipelineException {
if (StringUtils.isEmpty(name)) {
return;
}
//find link
PipelineLink link = findPipelineLink(name, pipelineChain);
//run process
Processor processor = link.getProcessor();
PipelineProcessor pipelineProcessor = applicationContext.getBean(processor.getBean(), PipelineProcessor.class);
log.debug("Started process of pipelineLink with name[" + link.getName() + "]");
Integer processResult = pipelineProcessor.runProcess(context);
List<Transition> transitions = link.getTransitions().stream()
.filter(t -> StringUtils.equals(t.getReturnValue(), processResult.toString())).collect(Collectors.toList());
log.debug("size of transision links" + transitions.size());
if(transitions.isEmpty()) {
return;
}
//start for transitions
for (Transition transition : transitions) {
runProcessForLink(context, pipelineChain, transition.getLink());
}
}
public void runProcess(String pipelineChainName, Map<String, Object> params) throws PipelineException {
log.info("Starting pipeline[" + pipelineChainName + "] with params[" + params + "]");
PipelineContext ctx = new PipelineContext(params);
PipelineChain pipelineChain = findPipelineChain(pipelineChainName);
runProcessForChain(ctx, pipelineChain);
// TODO: pobrac procesor,
// pobrac beana z kontekstu,
// uruchomic procesor z ctx,
// sprawdzic wynik i poszukac nastepnego pipelineLinka w transition,
// jak transition nie ma albo nie ma linka to koniec
// TODO: bazujac na MessengerProductsRecommendationHandler trzeba stworzyc 2 procesory i wpiac w pipeline
// pierwszy ma pobrac produkty i zapisac w ctx
// drugi ma wyslac produkty w ramach odpowiedzi
}
private PipelineChain findPipelineChain(String pipelineChainName) throws PipelineException {
log.debug("Started finding pipelineChain with name[" + pipelineChainName + "]");
for (PipelineChain pc : pipeline.getPipelineChains()) {
if (StringUtils.equals(pc.getName(), pipelineChainName)) {
log.debug("Found pipelineLink with name[" + pipelineChainName + "]");
return pc;
}
}
throw new PipelineException("No pipelineChain with name[" + pipelineChainName + "]");
}
private PipelineLink findPipelineLink(String pipelineLinkName, PipelineChain pipelineChain) throws PipelineException {
log.debug("Started finding pipelineLink with name[" + pipelineLinkName + "] in pipelineChain with name[" + pipelineChain.getName() + "]");
for (PipelineLink pl : pipelineChain.getPipelineLinks()) {
if (StringUtils.equals(pl.getName(), pipelineLinkName)) {
log.debug("Found pipelineLink with name[" + pipelineLinkName + "] in pipelineChain with name[" + pipelineChain.getName() + "]");
return pl;
}
}
throw new PipelineException("No pipelineLink with name[" + pipelineLinkName + "] in pipelineChain with name[" + pipelineChain.getName() + "]");
}
}
|
package selling.sunshine.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import common.sunshine.model.selling.admin.Admin;
import common.sunshine.model.selling.agent.Agent;
import common.sunshine.model.selling.goods.Goods4Agent;
import common.sunshine.model.selling.goods.Goods4Customer;
import common.sunshine.model.selling.goods.Thumbnail;
import common.sunshine.model.selling.order.CustomerOrder;
import common.sunshine.model.selling.user.User;
import common.sunshine.pagination.DataTablePage;
import common.sunshine.pagination.DataTableParam;
import common.sunshine.utils.ResponseCode;
import common.sunshine.utils.ResultData;
import common.sunshine.utils.SortRule;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import selling.sunshine.form.GoodsForm;
import selling.sunshine.model.BackOperationLog;
import selling.sunshine.model.sum.Vendition;
import selling.sunshine.service.*;
import selling.sunshine.utils.WechatConfig;
import selling.sunshine.utils.WechatUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequestMapping("/commodity")
@RestController
public class CommodityController {
private Logger logger = LoggerFactory.getLogger(CommodityController.class);
@Autowired
private CommodityService commodityService;
@Autowired
private AgentService agentService;
@Autowired
private OrderService orderService;
@Autowired
private UploadService uploadService;
@Autowired
private ToolService toolService;
@Autowired
private LogService logService;
@Autowired
private StatisticService statisticService;
@RequestMapping(method = RequestMethod.GET, value = "/create")
public ModelAndView create() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/goods/create");
return view;
}
@RequestMapping(method = RequestMethod.POST, value = "/create")
public ModelAndView create(@Valid GoodsForm form, BindingResult result, HttpServletRequest request) {
ModelAndView view = new ModelAndView();
if (result.hasErrors()) {
view.setViewName("redirect:/commodity/create");
return view;
}
Goods4Customer goods = new Goods4Customer(form.getName(), Double.parseDouble(form.getAgentPrice()),
Double.parseDouble(form.getPrice()), form.getDescription(), form.getStandard());
goods.setBlockFlag(form.isBlock());
ResultData response = commodityService.createGoods4Customer(goods);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
List<Thumbnail> thumbnails = (List<Thumbnail>) commodityService.fetchThumbnail().getData();
for (Thumbnail thumbnail : thumbnails) {
thumbnail.setGoods((Goods4Customer) response.getData());
}
commodityService.updateThumbnails(thumbnails);
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
if (user == null) {
view.setViewName("redirect:/commodity/create");
return view;
}
Admin admin = user.getAdmin();
BackOperationLog backOperationLog = new BackOperationLog(admin.getUsername(), toolService.getIP(request),
"" + admin.getUsername() + ":" + form.getName());
logService.createbackOperationLog(backOperationLog);
view.setViewName("redirect:/commodity/overview");
return view;
} else {
view.setViewName("redirect:/commodity/create");
return view;
}
}
@RequestMapping(method = RequestMethod.GET, value = "/edit/{goodsId}")
public ModelAndView edit(@PathVariable("goodsId") String goodsId) {
ModelAndView view = new ModelAndView();
Map<String, Object> condition = new HashMap<>();
condition.put("goodsId", goodsId);
ResultData resultData = commodityService.fetchGoods4Customer(condition);
if (resultData.getResponseCode() != ResponseCode.RESPONSE_OK) {
view.setViewName("redirect:/commodity/overview");
return view;
}
Goods4Customer target = ((ArrayList<Goods4Customer>) resultData.getData()).get(0);
view.addObject("goods", target);
view.setViewName("/backend/goods/update");
return view;
}
@RequestMapping(method = RequestMethod.POST, value = "/thumbnails/{goodsId}")
@ResponseBody
public String thumbnails(@PathVariable("goodsId") String goodsId) {
Map<String, Object> condition = new HashMap<>();
condition.put("goodsId", goodsId);
condition.put("type", "slide");
ResultData resultData = commodityService.fetchThumbnail(condition);
List<Thumbnail> thumbnails = (List<Thumbnail>) resultData.getData();
JSONArray resultArray = new JSONArray();
JSONArray initialPreviewArray = new JSONArray();
JSONArray initialPreviewConfigArray = new JSONArray();
if (thumbnails.size() == 0) {
resultArray.add(initialPreviewArray);
resultArray.add(initialPreviewConfigArray);
return resultArray.toJSONString();
}
for (Thumbnail thumbnail : thumbnails) {
JSONObject initialPreviewConfigObject = new JSONObject();
// initialPreviewArray.add("/selling" + thumbnail.getPath());
initialPreviewArray.add(thumbnail.getPath());
// initialPreviewConfigObject.put(
// "url",
// "/selling/commodity/delete/Thumbnail/"
// + thumbnail.getThumbnailId());
initialPreviewConfigObject.put("url", "/commodity/delete/Thumbnail/" + thumbnail.getThumbnailId());
initialPreviewConfigObject.put("key", thumbnail.getThumbnailId());
initialPreviewConfigArray.add(initialPreviewConfigObject);
}
resultArray.add(initialPreviewArray);
resultArray.add(initialPreviewConfigArray);
return resultArray.toJSONString();
}
@RequestMapping(method = RequestMethod.POST, value = "/picture/{goodsId}")
@ResponseBody
public String picture(@PathVariable("goodsId") String goodsId) {
Map<String, Object> condition = new HashMap<>();
condition.put("goodsId", goodsId);
condition.put("type", "cover");
ResultData resultData = commodityService.fetchThumbnail(condition);
List<Thumbnail> thumbnails = (List<Thumbnail>) resultData.getData();
JSONArray resultArray = new JSONArray();
JSONArray initialPreviewArray = new JSONArray();
JSONArray initialPreviewConfigArray = new JSONArray();
if (thumbnails.size() == 0) {
resultArray.add(initialPreviewArray);
resultArray.add(initialPreviewConfigArray);
return resultArray.toJSONString();
}
for (Thumbnail thumbnail : thumbnails) {
JSONObject initialPreviewConfigObject = new JSONObject();
// initialPreviewArray.add("/selling" + thumbnail.getPath());
initialPreviewArray.add(thumbnail.getPath());
// initialPreviewConfigObject.put(
// "url",
// "/selling/commodity/delete/Thumbnail/"
// + thumbnail.getThumbnailId());
initialPreviewConfigObject.put("url", "/commodity/delete/Thumbnail/" + thumbnail.getThumbnailId());
initialPreviewConfigObject.put("key", thumbnail.getThumbnailId());
initialPreviewConfigArray.add(initialPreviewConfigObject);
}
resultArray.add(initialPreviewArray);
resultArray.add(initialPreviewConfigArray);
return resultArray.toJSONString();
}
@RequestMapping(method = RequestMethod.POST, value = "/edit/{goodsId}")
public ModelAndView edit(@PathVariable("goodsId") String goodsId, @Valid GoodsForm form, BindingResult result,
HttpServletRequest request) {
ModelAndView view = new ModelAndView();
if (result.hasErrors()) {
view.setViewName("redirect:/commodity/overview");
return view;
}
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("goodsId", goodsId);
ResultData queryData = commodityService.fetchGoods4Customer(condition);
Goods4Customer oldGoods = ((List<Goods4Customer>) queryData.getData()).get(0);
Goods4Customer goods = new Goods4Customer(form.getName(), Double.parseDouble(form.getAgentPrice()),
Double.parseDouble(form.getPrice()), form.getDescription(), form.getStandard());
goods.setBlockFlag(form.isBlock());
goods.setGoodsId(goodsId);
ResultData response = commodityService.updateGoods4Customer(goods);
List<Thumbnail> thumbnails = (List<Thumbnail>) commodityService.fetchThumbnail().getData();
for (Thumbnail thumbnail : thumbnails) {
thumbnail.setGoods((Goods4Customer) response.getData());
}
commodityService.updateThumbnails(thumbnails);
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
if (user == null) {
view.setViewName("redirect:/commodity/overview");
return view;
}
Admin admin = user.getAdmin();
BackOperationLog backOperationLog = new BackOperationLog(admin.getUsername(), toolService.getIP(request),
"" + admin.getUsername() + "" + oldGoods.getName() + "");
logService.createbackOperationLog(backOperationLog);
view.setViewName("redirect:/commodity/overview");
return view;
}
@RequestMapping(method = RequestMethod.GET, value = "/overview")
public ModelAndView overview() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/goods/overview");
return view;
}
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/overview")
public DataTablePage<Goods4Customer> overview(DataTableParam param) {
DataTablePage<Goods4Customer> result = new DataTablePage<>(param);
if (StringUtils.isEmpty(param)) {
return result;
}
Map<String, Object> condition = new HashMap<>();
ResultData response = commodityService.fetchGoods4Customer(condition, param);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
result = (DataTablePage<Goods4Customer>) response.getData();
}
return result;
}
@RequestMapping(method = RequestMethod.GET, value = "/viewlist")
public ModelAndView viewList(HttpServletRequest request, String agentId, String code, String state) {
ModelAndView view = new ModelAndView();
String openId = null;
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state)) {
HttpSession session = request.getSession();
if (session.getAttribute("openId") == null || session.getAttribute("openId").equals("")) {
WechatConfig.oauthWechat(view, "/customer/component/goods_error_msg");
view.setViewName("/customer/component/goods_error_msg");
return view;
}
}
if (code != null && !code.equals("")) {
openId = WechatUtil.queryOauthOpenId(code);
}
if (openId == null || openId.equals("")) {
HttpSession session = request.getSession();
if (session.getAttribute("openId") != null && !session.getAttribute("openId").equals("")) {
openId = (String) session.getAttribute("openId");
}
}
if (openId == null || openId.equals("")) {
WechatConfig.oauthWechat(view, "/customer/component/goods_error_msg");
view.setViewName("/customer/component/goods_error_msg");
return view;
}
if (!StringUtils.isEmpty(openId)) {
HttpSession session = request.getSession();
session.setAttribute("openId", openId);
}
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("blockFlag", false);
ResultData fetchGoodsData = commodityService.fetchGoods4Customer(condition);
if (fetchGoodsData.getResponseCode() != ResponseCode.RESPONSE_OK) {
WechatConfig.oauthWechat(view, "/customer/component/goods_error_msg");
view.setViewName("/customer/component/goods_error_msg");
return view;
}
List<Goods4Customer> goods4Customers = (List<Goods4Customer>) fetchGoodsData.getData();
for (Goods4Customer goods : goods4Customers) {
List<Thumbnail> thumbnails = goods.getThumbnails();
List<Thumbnail> newThumbnails = new ArrayList<Thumbnail>();
for (Thumbnail thumbnail : thumbnails) {
if (thumbnail.getType().equals("cover")) {
newThumbnails.add(thumbnail);
}
}
goods.setThumbnails(newThumbnails);
}
view.addObject("goodsList", goods4Customers);
view.setViewName("/customer/goods/goods_list");
return view;
}
@RequestMapping(method = RequestMethod.GET, value = "/{goodsId}")
public ModelAndView view(HttpServletRequest request, @PathVariable("goodsId") String goodsId, String agentId,
String code, String state) {
ModelAndView view = new ModelAndView();
String openId = null;
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state)) {
HttpSession session = request.getSession();
if (session.getAttribute("openId") == null || session.getAttribute("openId").equals("")) {
WechatConfig.oauthWechat(view, "/customer/component/goods_error_msg");
view.setViewName("/customer/component/goods_error_msg");
return view;
}
}
if (code != null && !code.equals("")) {
openId = WechatUtil.queryOauthOpenId(code);
}
if (openId == null || openId.equals("")) {
HttpSession session = request.getSession();
if (session.getAttribute("openId") != null && !session.getAttribute("openId").equals("")) {
openId = (String) session.getAttribute("openId");
}
}
view.addObject("wechat", openId);
if (openId == null || openId.equals("")) {
WechatConfig.oauthWechat(view, "/customer/component/goods_error_msg");
view.setViewName("/customer/component/goods_error_msg");
return view;
}
if (!StringUtils.isEmpty(openId)) {
HttpSession session = request.getSession();
session.setAttribute("openId", openId);
}
Map<String, Object> condition = new HashMap<>();
condition.put("wechat", openId);
List<SortRule> rules = new ArrayList<>();
rules.add(new SortRule("create_time", "desc"));
condition.put("sort", rules);
ResultData response = orderService.fetchCustomerOrder(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
List<CustomerOrder> list = (List<CustomerOrder>) response.getData();
view.addObject("history", list.get(0));
}
condition.clear();
condition.put("goodsId", goodsId);
condition.put("blockFlag", false);
ResultData fetchCommodityData = commodityService.fetchGoods4Customer(condition);
if (fetchCommodityData.getResponseCode() != ResponseCode.RESPONSE_OK) {
WechatConfig.oauthWechat(view, "/customer/component/goods_error_msg");
view.setViewName("/customer/component/goods_error_msg");
return view;
}
Goods4Customer goods = ((List<Goods4Customer>) fetchCommodityData.getData()).get(0);
if (!StringUtils.isEmpty(agentId)) {
condition.clear();
condition.put("agentId", agentId);
condition.put("granted", true);
condition.put("blockFlag", false);
ResultData fetchAgentData = agentService.fetchAgent(condition);
if (fetchAgentData.getResponseCode() != ResponseCode.RESPONSE_OK) {
WechatConfig.oauthWechat(view, "/customer/component/agent_error_msg");
view.setViewName("/customer/component/agent_error_msg");
return view;
}
Agent agent = ((List<Agent>) fetchAgentData.getData()).get(0);
view.addObject("agent", agent);
}
for (int i = 0; i < goods.getThumbnails().size(); i++) {
if (goods.getThumbnails().get(i).getType().equals("cover")) {
goods.getThumbnails().remove(i);
break;
}
}
view.addObject("goods", goods);
WechatConfig.oauthWechat(view, "/customer/goods/detail");
view.setViewName("/customer/goods/detail");
return view;
}
@RequestMapping(method = RequestMethod.GET, value = "/customerorder")
public ModelAndView customerOrder(String orderId) {
ModelAndView view = new ModelAndView();
Map<String, Object> condition = new HashMap<>();
if (!StringUtils.isEmpty(orderId)) {
condition.put("orderId", orderId);
}
if (condition.isEmpty()) {
WechatConfig.oauthWechat(view, "/customer/component/order_error_msg");
view.setViewName("/customer/component/order_error_msg");
return view;
}
ResultData fetchCustomerOrderData = orderService.fetchCustomerOrder(condition);
if (fetchCustomerOrderData.getResponseCode() != ResponseCode.RESPONSE_OK) {
WechatConfig.oauthWechat(view, "/customer/component/order_error_msg");
view.setViewName("/customer/component/order_error_msg");
return view;
}
CustomerOrder customerOrder = ((List<CustomerOrder>) fetchCustomerOrderData.getData()).get(0);
view.addObject("customerOrder", customerOrder);
WechatConfig.oauthWechat(view, "/customer/order/detail");
view.setViewName("/customer/order/detail");
return view;
}
@RequestMapping(method = RequestMethod.POST, value = "/detail/{goodsId}")
public ResultData detail(@PathVariable("goodsId") String goodsId) {
ResultData resultData = new ResultData();
Map<String, Object> dataMap = new HashMap<>();
Map<String, Object> condition = new HashMap<>();
condition.put("goodsId", goodsId);
ResultData queryData = commodityService.fetchGoods4Customer(condition);
if (queryData.getData() != null) {
Goods4Customer goods = ((List<Goods4Customer>) queryData.getData()).get(0);
dataMap.put("goods", goods);
List<Thumbnail> thumbnails = (List<Thumbnail>) commodityService.fetchThumbnail(condition).getData();
if (thumbnails.size() != 0) {
dataMap.put("thumbnails", thumbnails);
} else {
dataMap.put("thumbnails", 0);
}
}
resultData.setData(dataMap);
return resultData;
}
@RequestMapping(method = RequestMethod.GET, value = "/forbid/{goodsId}")
public ModelAndView forbid(@PathVariable("goodsId") String goodsId, HttpServletRequest request) {
ModelAndView view = new ModelAndView();
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("goodsId", goodsId);
ResultData resultData = commodityService.fetchGoods4Customer(condition);
if (resultData.getResponseCode() != ResponseCode.RESPONSE_OK) {
view.setViewName("redirect:/commodity/overview");
return view;
}
Goods4Customer target = ((List<Goods4Customer>) resultData.getData()).get(0);
target.setBlockFlag(true);
ResultData response = commodityService.updateGoods4Customer(target);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
if (user == null) {
view.setViewName("redirect:/commodity/overview");
return view;
}
Admin admin = user.getAdmin();
BackOperationLog backOperationLog = new BackOperationLog(admin.getUsername(), toolService.getIP(request),
"" + admin.getUsername() + "" + target.getName() + "");
logService.createbackOperationLog(backOperationLog);
view.setViewName("redirect:/commodity/overview");
} else {
view.setViewName("redirect:/commodity/overview");
}
return view;
}
@RequestMapping(method = RequestMethod.GET, value = "/enable/{goodsId}")
public ModelAndView enable(@PathVariable("goodsId") String goodsId, HttpServletRequest request) {
ModelAndView view = new ModelAndView();
Map<String, Object> condition = new HashMap<>();
condition.put("goodsId", goodsId);
ResultData resultData = commodityService.fetchGoods4Customer(condition);
if (resultData.getResponseCode() != ResponseCode.RESPONSE_OK) {
view.setViewName("redirect:/commodity/overview");
return view;
}
Goods4Customer target = ((List<Goods4Customer>) resultData.getData()).get(0);
target.setBlockFlag(false);
ResultData response = commodityService.updateGoods4Customer(target);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
if (user == null) {
view.setViewName("redirect:/commodity/overview");
return view;
}
Admin admin = user.getAdmin();
BackOperationLog backOperationLog = new BackOperationLog(admin.getUsername(), toolService.getIP(request),
"" + admin.getUsername() + "" + target.getName() + "");
logService.createbackOperationLog(backOperationLog);
view.setViewName("redirect:/commodity/overview");
} else {
view.setViewName("redirect:/commodity/overview");
}
return view;
}
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String upload(MultipartHttpServletRequest request) {
String context = request.getSession().getServletContext().getRealPath("/");
JSONObject resultObject = new JSONObject();
try {
String filename = "thumbnail";
MultipartFile file = request.getFile(filename);
if (file != null) {
ResultData response = uploadService.upload(file, context);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
Thumbnail thumbnail = new Thumbnail((String) response.getData(), "slide");
String thumbnailId = ((Thumbnail) commodityService.createThumbnail(thumbnail).getData())
.getThumbnailId();
JSONArray initialPreviewArray = new JSONArray();
JSONArray initialPreviewConfigArray = new JSONArray();
JSONObject initialPreviewConfigObject = new JSONObject();
// initialPreviewArray.add("/selling" +
// response.getData().toString());
initialPreviewArray.add(response.getData().toString());
// initialPreviewConfigObject.put("url",
// "/selling/commodity/delete/Thumbnail/"+thumbnailId);
initialPreviewConfigObject.put("url", "/commodity/delete/Thumbnail/" + thumbnailId);
initialPreviewConfigObject.put("key", thumbnailId);
initialPreviewConfigArray.add(initialPreviewConfigObject);
resultObject.put("initialPreview", initialPreviewArray);
resultObject.put("initialPreviewConfig", initialPreviewConfigArray);
return resultObject.toJSONString();
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
resultObject.put("error", "");
return resultObject.toJSONString();
}
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/uploadthumbnail")
public String uploadThumbnail(MultipartHttpServletRequest request) {
String context = request.getSession().getServletContext().getRealPath("/");
JSONObject resultObject = new JSONObject();
try {
String filename = "picture";
MultipartFile file = request.getFile(filename);
if (file != null) {
ResultData response = uploadService.upload(file, context);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
Thumbnail thumbnail = new Thumbnail((String) response.getData(), "cover");
String thumbnailId = ((Thumbnail) commodityService.createThumbnail(thumbnail).getData())
.getThumbnailId();
JSONArray initialPreviewArray = new JSONArray();
JSONArray initialPreviewConfigArray = new JSONArray();
JSONObject initialPreviewConfigObject = new JSONObject();
// initialPreviewArray.add("/selling" +
// response.getData().toString());
initialPreviewArray.add(response.getData().toString());
// initialPreviewConfigObject.put("url",
// "/selling/commodity/delete/Thumbnail/"+thumbnailId);
initialPreviewConfigObject.put("url", "/commodity/delete/Thumbnail/" + thumbnailId);
initialPreviewConfigObject.put("key", thumbnailId);
initialPreviewConfigArray.add(initialPreviewConfigObject);
resultObject.put("initialPreview", initialPreviewArray);
resultObject.put("initialPreviewConfig", initialPreviewConfigArray);
return resultObject.toJSONString();
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
resultObject.put("error", "");
return resultObject.toJSONString();
}
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/delete/Thumbnail/{thumbnailId}")
public String deleteThumbnail(@PathVariable("thumbnailId") String thumbnailId) {
commodityService.deleteGoodsThumbnail(thumbnailId);
JSONObject resultObject = new JSONObject();
JSONArray initialPreviewArray = new JSONArray();
JSONArray initialPreviewConfigArray = new JSONArray();
resultObject.put("initialPreview", initialPreviewArray);
resultObject.put("initialPreviewConfig", initialPreviewConfigArray);
return resultObject.toJSONString();
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/volume")
public ResultData volume() {
ResultData resultData = new ResultData();
JSONArray array = new JSONArray();
Map<String, Object> condition = new HashMap<>();
condition.put("blockFlag", false);
ResultData queryData = commodityService.fetchGoods4Agent(condition);
if (queryData.getResponseCode() == ResponseCode.RESPONSE_OK) {
List<Goods4Agent> goodsList = (List<Goods4Agent>) queryData.getData();
Map<String, List<Object>> map = new HashMap<>();
for (Goods4Agent goods : goodsList) {
List<Object> list = new ArrayList<>();
list.add(goods.getName());
list.add(0);
list.add(0);
map.put(goods.getGoodsId(), list);
}
condition.clear();
condition.put("type", 0);
queryData = statisticService.purchaseRecord(condition);
if (queryData.getResponseCode() == ResponseCode.RESPONSE_OK) {
List<Vendition> venditions = (List<Vendition>) queryData.getData();
for (Vendition vendition : venditions) {
if (map.containsKey(vendition.getGoodsId())) {
List<Object> list = map.get(vendition.getGoodsId());
list.set(2, vendition.getGoodsQuantity());
map.put(vendition.getGoodsId(), list);
}
}
}
condition.put("monthly", true);
queryData = statisticService.purchaseRecord(condition);
if (queryData.getResponseCode() == ResponseCode.RESPONSE_OK) {
List<Vendition> monthlyVenditions = (List<Vendition>) queryData.getData();
for (Vendition vendition : monthlyVenditions) {
if (map.containsKey(vendition.getGoodsId())) {
List<Object> list = map.get(vendition.getGoodsId());
list.set(1, vendition.getGoodsQuantity());
map.put(vendition.getGoodsId(), list);
}
}
}
for (String key : map.keySet()) {
JSONObject object = new JSONObject();
List<Object> list = map.get(key);
object.put("goodsId", key);
object.put("goodsName", list.get(0).toString());
object.put("monthQuantity", list.get(1).toString());
object.put("overallQuantity", list.get(2).toString());
array.add(object);
}
resultData.setData(array);
return resultData;
}
resultData.setResponseCode(ResponseCode.RESPONSE_NULL);
return resultData;
}
}
|
package ru.thewizardplusplus.wizardbudget;
import java.util.*;
import android.content.*;
import android.preference.*;
import org.bostonandroid.datepreference.*;
import java.util.regex.*;
public class Settings {
public static final String SETTING_NAME_CURRENT_PAGE = "current_page";
public static final String SETTING_NAME_ACTIVE_SPENDING = "active_spending";
public static Settings getCurrent(Context context) {
Settings settings = new Settings(context);
SharedPreferences preferences =
PreferenceManager
.getDefaultSharedPreferences(context);
settings.current_page = preferences.getString(
SETTING_NAME_CURRENT_PAGE,
DEFAULT_PAGE
);
settings.active_spending = preferences.getString(
SETTING_NAME_ACTIVE_SPENDING,
DEFAULT_SPENDING
);
settings.use_custom_date = preferences.getBoolean(
"preference_use_custom_date",
false
);
Date current_date = new Date();
settings.custom_date_base_day = DatePreference.getDateFor(
preferences,
"preference_custom_date_base_day",
current_date
);
settings.parse_sms = preferences.getBoolean(
"preference_parse_sms",
false
);
try {
settings.sms_number_pattern = Pattern.compile(
preferences.getString(
"preference_sms_number_pattern",
context.getString(R.string.preference_sms_number_pattern_default)
),
Pattern.CASE_INSENSITIVE
);
} catch (PatternSyntaxException exception) {
settings.parse_sms = false;
}
try {
settings.sms_spending_pattern = Pattern.compile(
preferences.getString(
"preference_sms_spending_pattern",
context.getString(R.string.preference_sms_spending_pattern_default)
),
Pattern.CASE_INSENSITIVE
);
} catch (PatternSyntaxException exception) {
settings.parse_sms = false;
}
try {
settings.sms_income_pattern = Pattern.compile(
preferences.getString(
"preference_sms_income_pattern",
context.getString(R.string.preference_sms_income_pattern_default)
),
Pattern.CASE_INSENSITIVE
);
} catch (PatternSyntaxException exception) {
settings.parse_sms = false;
}
settings.sms_spending_comment = preferences.getString(
"preference_sms_spending_comment",
context.getString(R.string.preference_sms_spending_comment_default)
);
settings.sms_income_comment = preferences.getString(
"preference_sms_income_comment",
context.getString(R.string.preference_sms_income_comment_default)
);
return settings;
}
public String getCurrentPage() {
return current_page;
}
public void setCurrentPage(String current_page) {
this.current_page = current_page;
}
public String getActiveSpending() {
return active_spending;
}
public void setActiveSpending(String active_spending) {
this.active_spending = active_spending;
}
public boolean isUseCustomDate() {
return use_custom_date;
}
public Calendar getCustomDateBaseDay() {
return custom_date_base_day;
}
public boolean isParseSms() {
return parse_sms;
}
public Pattern getSmsNumberPattern() {
return sms_number_pattern;
}
public Pattern getSmsSpendingPattern() {
return sms_spending_pattern;
}
public Pattern getSmsIncomePattern() {
return sms_income_pattern;
}
public String getSmsSpendingComment() {
return sms_spending_comment;
}
public String getSmsIncomeComment() {
return sms_income_comment;
}
public void save() {
SharedPreferences preferences =
PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SETTING_NAME_CURRENT_PAGE, current_page);
editor.putString(SETTING_NAME_ACTIVE_SPENDING, active_spending);
editor.commit();
}
private static final String DEFAULT_PAGE = "history";
private static final String DEFAULT_SPENDING = "null";
private Context context;
private String current_page = DEFAULT_PAGE;
private String active_spending = DEFAULT_SPENDING;
private boolean use_custom_date = false;
private Calendar custom_date_base_day = Calendar.getInstance();
private boolean parse_sms = false;
private Pattern sms_number_pattern;
private Pattern sms_spending_pattern;
private Pattern sms_income_pattern;
private String sms_spending_comment = "";
private String sms_income_comment = "";
private Settings(Context context) {
this.context = context;
}
}
|
package controllers;
import com.mashape.unirest.http.exceptions.UnirestException;
import factories.BidirectionalLoginDataCustomFactory;
import factories.BidirectionalPendingPasswordResetFactory;
import factories.BidirectionalQuestionFactory;
import factories.BidirectionalUserFactory;
import funWebMailer.FunWebMailer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import pojos.LoginDataCustom;
import pojos.PendingPasswordReset;
import pojos.Question;
import pojos.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Controller
@SessionAttributes(value = "username")
public class MainController {
User loggedInUser = null;
@RequestMapping(value ="statistics", method = RequestMethod.GET)
public String getStatistics(HttpServletRequest request) {
String username = (String) request.getSession().getAttribute("username");
if (username == null) {
return "error";
}
return "statistics";
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String getRegisterPage(HttpServletRequest request) {
return "register";
}
@RequestMapping(value = "/change_password", method = RequestMethod.GET)
public String getChangePassword(HttpServletRequest request) {
return "change_password";
}
@RequestMapping(value = "/change_password", method = RequestMethod.POST)
public String postChangePassword(HttpServletRequest request) {
return "success_recover";
}
@RequestMapping(value = "/recover_password", method = RequestMethod.GET)
public String getRecoverPasswordPage() {
return "recover_password";
}
@RequestMapping(
value = "/recoverPassword",
method = RequestMethod.POST
)
public ModelAndView postRecoverPassword(
@RequestParam(name = "username") String username) {
User user = null;
try {
user = BidirectionalUserFactory.newInstance(username);
} catch (UnirestException e) {
e.printStackTrace();
}
String recoverUrlToken = UUID.randomUUID().toString();
// send mail with reset link for the password
String recoverUrl = String.format("localhost:8089/reset_password/%s", recoverUrlToken);
PendingPasswordReset pendingPasswordReset = new PendingPasswordReset();
pendingPasswordReset.setId(0l); // Dummy
pendingPasswordReset.setToken(recoverUrlToken);
pendingPasswordReset.setUsername(user.getName());
try {
BidirectionalPendingPasswordResetFactory.persist(pendingPasswordReset);
} catch (UnirestException e) {
e.printStackTrace();
}
FunWebMailer.setResetPasswordLink(user.getName(), user.getEmail(), recoverUrl);
return new ModelAndView("success_recover");
}
@RequestMapping(value = "reset_password/{token}", method = RequestMethod.GET)
public ModelAndView getResetPassword(@PathVariable String token) {
PendingPasswordReset pendingPasswordReset = null;
try {
pendingPasswordReset = BidirectionalPendingPasswordResetFactory.newInstance(token);
} catch (UnirestException e) {
e.printStackTrace();
}
if (pendingPasswordReset == null) {
return null; // some error page
}
return new ModelAndView("reset_password");
}
@RequestMapping(value = "reset_password/{token}", method = RequestMethod.POST)
public ModelAndView postResetPassword(
@PathVariable String token,
@RequestParam(name = "new_password1") String newPassword1,
@RequestParam(name = "new_password2") String newPassword2) {
if (!newPassword1.equals(newPassword2)) {
return null;
}
PendingPasswordReset pendingPasswordReset = null;
try {
pendingPasswordReset = BidirectionalPendingPasswordResetFactory.newInstance(token);
} catch (UnirestException e) {
e.printStackTrace();
}
User user = null;
try {
user = BidirectionalUserFactory.newInstance(pendingPasswordReset.getUsername());
} catch (UnirestException e) {
e.printStackTrace();
}
try {
BidirectionalLoginDataCustomFactory.update(user.getId(), String.valueOf(newPassword1.hashCode()));
} catch (UnirestException e) {
e.printStackTrace();
}
return new ModelAndView("reset_password_success");
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView doLogin(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(name = "username") String username,
@RequestParam(name = "password") String password) {
User user = null;
try {
user = BidirectionalUserFactory.newInstance(username);
} catch (UnirestException e) {
e.printStackTrace();
}
String actualPassword = null; // That's not the way it supposed to be
try {
actualPassword = BidirectionalLoginDataCustomFactory.getPassword(user.getId());
} catch (UnirestException e) {
e.printStackTrace();
}
if (String.valueOf(password.hashCode()).equals(actualPassword)) {
request.getSession().setAttribute("loggedIn", Boolean.TRUE);
request.getSession().setAttribute("username", user.getName());
}
return new ModelAndView("redirect:/main_menu");
}
@RequestMapping(value="/pvp", method = RequestMethod.GET)
public ModelAndView getPvpPage(HttpServletRequest request) {
String username = (String) request.getSession().getAttribute("username");
if (username == null) {
return new ModelAndView("error");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("username", request.getSession().getAttribute("username"));
return modelAndView;
}
@RequestMapping(value="/main_menu", method = RequestMethod.GET)
public String getMainMenuPage(HttpServletRequest request){
String username = (String) request.getSession().getAttribute("username");
if (username == null) {
return "error";
}
return "main_menu";
}
@RequestMapping(value="/chat_room", method = RequestMethod.GET)
public String getChatRoomPage(HttpServletRequest request){
String username = (String) request.getSession().getAttribute("username");
if (request.getSession().getAttribute("username").equals("")) {
return "error";
}
return "chat_room";
}
@RequestMapping(value="/add_question", method = RequestMethod.GET)
public String getAddQuestionPage(HttpServletRequest request) {
if (request.getSession().getAttribute("username").equals("")) {
return "error";
}
return "add_question";
}
@ResponseBody
@RequestMapping(value = "/checkUsernameAvailable", method = RequestMethod.POST)
public String checkValidUsername(@RequestParam String username) {
// JSONObject json = new JSONObject();
// JSONArray jsonArray = new JSONArray();
// String suggestion = dao.checkIfValidUsername(username);
// if (suggestion != null) {
// try {
// json.put("status", "taken");
// json.put("suggestion", suggestion);
// } catch (JSONException e) {
// e.printStackTrace();
// return json.toString();
// } else {
// try {
// json.put("status", "ok");
// } catch (JSONException e) {
// e.printStackTrace();
// return json.toString();
return null;
}
@ResponseBody
@RequestMapping(value = "/checkPasswordStrength", method = RequestMethod.POST)
public String checkPasswordStrength(@RequestParam String password) {
// JSONObject json = new JSONObject();
// int strength = dao.checkPasswordStrengthness(password);
// try {
// json.put("strength", strength);
// } catch (JSONException e) {
// e.printStackTrace();
// return json.toString();
return null;
}
@RequestMapping(value = "/validateRegistration", method = RequestMethod.POST)
public ModelAndView validateRegistration(
@RequestParam(name = "email") String email,
@RequestParam(name = "username") String username,
@RequestParam(name = "password") String password) {
if (email.equals("") || username.equals("") || password.equals("")) {
ModelAndView modelAndView = new ModelAndView("redirect:/register");
modelAndView.addObject("error", "Invalid credentials");
return modelAndView;
}
FunWebMailer.sendTextRegisterNotification(username, email);
try {
if (BidirectionalUserFactory.newInstance(username) == null) {
ModelAndView modelAndView = new ModelAndView("redirect:/register");
modelAndView.addObject("error", "Username already taken");
return modelAndView;
}
} catch (UnirestException e) {
e.printStackTrace();
}
User user = new User();
user.setName(username);
user.setUserRole("user");
user.setEmail(email);
user.setLoginType("custom");
user.setLevel(0);
user.setHintsLeft(0);
user.setGoldLeft(0);
user.setAvatarPath("/home");
user.setId(0l);
try {
BidirectionalUserFactory.persist(user);
} catch (UnirestException e) {
e.printStackTrace();
ModelAndView modelAndView = new ModelAndView("redirect:/register");
modelAndView.addObject("error", "Error storing the new user");
}
try {
user = BidirectionalUserFactory.newInstance(username);
} catch (UnirestException e) {
ModelAndView modelAndView = new ModelAndView("redirect:/register");
modelAndView.addObject("error", "Error accessing the db service");
e.printStackTrace();
}
LoginDataCustom loginDataCustom = new LoginDataCustom();
loginDataCustom.setPassword(String.valueOf(password.hashCode()));
loginDataCustom.setId(0l);
loginDataCustom.setUserId(user.getId());
try {
BidirectionalLoginDataCustomFactory.persist(loginDataCustom);
} catch (UnirestException e) {
ModelAndView modelAndView = new ModelAndView("redirect:/register");
modelAndView.addObject("error", "Error accesing the db service");
e.printStackTrace();
}
return new ModelAndView("redirect:/");
}
@ResponseBody
@RequestMapping(value = "/weakestChapter", method = RequestMethod.POST)
public String getWeakestChapter() {
// JSONObject json = new JSONObject();
// try {
// json.put("weakestChapter", dao.weakestChapter((int) loggedInUser.getId()));
// } catch (JSONException e) {
// e.printStackTrace();
// return json.toString();
return null;
}
@ResponseBody
@RequestMapping(value = "/isRelevant", method = RequestMethod.POST)
public String getRelevance(@RequestParam(name ="id") Long id){
// JSONObject json = new JSONObject();
// try{
// json.put("relevance", qDao.isRelevant(id));
// if (qDao.getError() != null) {
// json.put("error", "yes");
// json.put("errorMessage", qDao.getError());
// } else {
// json.put("error", "no");
// } catch (JSONException e){
// e.printStackTrace();
// return json.toString();
return null;
}
@RequestMapping(value = "/adminPanel", method = RequestMethod.GET)
public ModelAndView getAdminPannel(HttpServletRequest request) {
String username = (String) request.getSession().getAttribute("username");
if (username == null) {
return new ModelAndView("error");
}
return new ModelAndView("admin");
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logout(HttpServletRequest request) {
request.getSession().removeAttribute("username");
return new ModelAndView("register");
}
@ResponseBody
@RequestMapping(value="/getUsersList" , method = RequestMethod.POST)
public String getUsersList(){
JSONArray jsonArray = new JSONArray();
List<String> users = new ArrayList<String>();
try {
users = BidirectionalUserFactory.getAll();
} catch (UnirestException e) {
e.printStackTrace();
}
for (String user : users) {
JSONObject jsonUser = new JSONObject();
try {
jsonUser.put("username", user);
jsonArray.put(jsonUser);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
@ResponseBody
@RequestMapping(value="/banUser" , method = RequestMethod.POST)
public String banUser(@RequestParam(name = "username") String username) {
User toBan = new User();
toBan.setName(username);
System.out.println(toBan.getName());
try {
BidirectionalUserFactory.remove(toBan);
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
@ResponseBody
@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
public String updatePassword(@RequestParam(name = "newPassword") String newPassword) {
// JSONObject json = new JSONObject();
// dao.updateUserPassword(loggedInUser, newPassword);
// try {
// json.put("status", "success");
// } catch (JSONException e) {
// e.printStackTrace();
// return json.toString();
return null;
}
@ResponseBody
@RequestMapping(value = "/checkAlreadyReceived", method = RequestMethod.POST)
public String checkAlreadyReceived(@RequestParam(name = "id") String id) {
JSONObject json = new JSONObject();
try {
json.put("receivedStatus", null);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@RequestMapping(value = "/arena", method = RequestMethod.GET)
public ModelAndView getArena(HttpServletRequest request) {
String username = (String) request.getSession().getAttribute("username");
if (username == null) {
return new ModelAndView("error");
}
return new ModelAndView("arena");
}
@RequestMapping(value = "/quick_chat", method = RequestMethod.GET)
public ModelAndView quickChatPage(HttpServletRequest request, HttpServletResponse response) {
String username = (String) request.getSession().getAttribute("username");
if (username == null) {
return new ModelAndView("error");
}
ModelAndView modelAndView = new ModelAndView("quick_chat");
modelAndView.addObject("username", username);
return modelAndView;
}
}
|
package org.zkoss.ganttz;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.zkoss.ganttz.adapters.IDisabilityConfiguration;
import org.zkoss.ganttz.data.Milestone;
import org.zkoss.ganttz.data.Task;
import org.zkoss.ganttz.data.TaskContainer;
import org.zkoss.lang.Objects;
import org.zkoss.xml.HTMLs;
import org.zkoss.zk.au.AuRequest;
import org.zkoss.zk.au.Command;
import org.zkoss.zk.au.ComponentCommand;
import org.zkoss.zk.au.out.AuInvoke;
import org.zkoss.zk.mesg.MZk;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.ext.AfterCompose;
import org.zkoss.zul.Div;
/**
* @author javi
*/
public class TaskComponent extends Div implements AfterCompose {
private static final Log LOG = LogFactory.getLog(TaskComponent.class);
private static final int HEIGHT_PER_TASK = 10;
private static final String STANDARD_TASK_COLOR = "#007bbe";
private static Pattern pixelsSpecificationPattern = Pattern
.compile("\\s*(\\d+)px\\s*;?\\s*");
private static int stripPx(String pixels) {
Matcher matcher = pixelsSpecificationPattern.matcher(pixels);
if (!matcher.matches())
throw new IllegalArgumentException("pixels " + pixels
+ " is not valid. It must be "
+ pixelsSpecificationPattern.pattern());
return Integer.valueOf(matcher.group(1));
}
private static Command _updatecmd = new ComponentCommand(
"onUpdatePosition", 0) {
protected void process(AuRequest request) {
final TaskComponent ta = (TaskComponent) request.getComponent();
if (ta == null) {
throw new UiException(MZk.ILLEGAL_REQUEST_COMPONENT_REQUIRED,
this);
}
String[] requestData = request.getData();
if (requestData == null || requestData.length != 2) {
throw new UiException(MZk.ILLEGAL_REQUEST_WRONG_DATA,
new Object[] { Objects.toString(requestData), this });
} else {
ta.doUpdatePosition(requestData[0], requestData[1]);
Events.postEvent(new Event(getId(), ta, request.getData()));
}
}
};
private static Command _updatewidthcmd = new ComponentCommand(
"onUpdateWidth", 0) {
protected void process(AuRequest request) {
final TaskComponent ta = (TaskComponent) request.getComponent();
if (ta == null) {
throw new UiException(MZk.ILLEGAL_REQUEST_COMPONENT_REQUIRED,
this);
}
String[] requestData = request.getData();
if ((requestData != null) && (requestData.length != 1)) {
throw new UiException(MZk.ILLEGAL_REQUEST_WRONG_DATA,
new Object[] { Objects.toString(requestData), this });
} else {
ta.doUpdateSize(requestData[0]);
Events.postEvent(new Event(getId(), ta, request.getData()));
}
}
};
private static Command _adddependencycmd = new ComponentCommand(
"onAddDependency", 0) {
protected void process(AuRequest request) {
final TaskComponent taskComponent = (TaskComponent) request.getComponent();
if (taskComponent == null) {
throw new UiException(MZk.ILLEGAL_REQUEST_COMPONENT_REQUIRED,
this);
}
String[] requestData = request.getData();
if (requestData == null || requestData.length != 1) {
throw new UiException(MZk.ILLEGAL_REQUEST_WRONG_DATA,
new Object[] { Objects.toString(requestData), this });
} else {
taskComponent.doAddDependency(requestData[0]);
Events.postEvent(new Event(getId(), taskComponent, request.getData()));
}
}
};
private final IDisabilityConfiguration disabilityConfiguration;
public static TaskComponent asTaskComponent(Task task, TaskList taskList,
boolean isTopLevel) {
final TaskComponent result;
if (task.isContainer()) {
result = TaskContainerComponent.asTask((TaskContainer) task,
taskList);
} else if (task instanceof Milestone) {
result = new MilestoneComponent(task, taskList
.getDisabilityConfiguration());
} else {
result = new TaskComponent(task, taskList
.getDisabilityConfiguration());
}
result.isTopLevel = isTopLevel;
return result;
}
public static TaskComponent asTaskComponent(Task task, TaskList taskList) {
return asTaskComponent(task, taskList, true);
}
public TaskComponent(Task task,
IDisabilityConfiguration disabilityConfiguration) {
setHeight(HEIGHT_PER_TASK + "px");
setContext("idContextMenuTaskAssignment");
this.task = task;
setColor(STANDARD_TASK_COLOR);
setId(UUID.randomUUID().toString());
this.disabilityConfiguration = disabilityConfiguration;
}
protected String calculateClass() {
return "box";
}
protected void updateClass() {
response(null, new AuInvoke(this, "setClass",
new Object[] { calculateClass() }));
}
public final void afterCompose() {
updateProperties();
if (propertiesListener == null) {
propertiesListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (isInPage()) {
updateProperties();
}
}
};
}
this.task
.addFundamentalPropertiesChangeListener(propertiesListener);
updateClass();
}
private String _color;
private boolean isTopLevel;
private final Task task;
private PropertyChangeListener propertiesListener;
public Task getTask() {
return task;
}
public String getTaskName() {
return task.getName();
}
public String getLength() {
return null;
}
public Command getCommand(String cmdId) {
Command result = null;
if ("updatePosition".equals(cmdId)
&& isMovingTasksEnabled()) {
result = _updatecmd;
} else if ("updateSize".equals(cmdId)
&& isResizingTasksEnabled()) {
result = _updatewidthcmd;
} else if ("addDependency".equals(cmdId)) {
result = _adddependencycmd;
}
return result;
}
public boolean isResizingTasksEnabled() {
return disabilityConfiguration.isResizingTasksEnabled();
}
public boolean isMovingTasksEnabled() {
return disabilityConfiguration.isMovingTasksEnabled();
}
// Command action to do
void doUpdatePosition(String leftX, String topY) {
this.task.setBeginDate(getMapper().toDate(stripPx(leftX)));
}
void doUpdateSize(String size) {
int pixels = stripPx(size);
this.task.setLengthMilliseconds(getMapper().toMilliseconds(pixels));
}
void doAddDependency(String destinyTaskId) {
getTaskList().addDependency(this,
((TaskComponent) getFellow(destinyTaskId)));
}
public String getColor() {
return _color;
}
public void setColor(String color) {
if ((color != null) && (color.length() == 0)) {
color = null;
}
if (!Objects.equals(_color, color)) {
_color = color;
}
}
/*
* We override the method of getRealStyle to put the color property as part
* of the style
*/
protected String getRealStyle() {
final StringBuffer sb = new StringBuffer(super.getRealStyle());
if (getColor() != null) {
HTMLs.appendStyle(sb, "background-color", getColor());
}
HTMLs.appendStyle(sb, "position", "absolute");
return sb.toString();
}
/*
* We send a response to the client to create the arrow we are going to use
* to create the dependency
*/
public void addDependency() {
response("depkey", new AuInvoke(this, "addDependency"));
}
private IDatesMapper getMapper() {
return getTaskList().getMapper();
}
public TaskList getTaskList() {
return (TaskList) getParent();
}
@Override
public void setParent(Component parent) {
if (parent != null && !(parent instanceof TaskList))
throw new UiException("Unsupported parent for rows: " + parent);
super.setParent(parent);
}
public final void zoomChanged() {
updateProperties();
}
private void updateProperties() {
if (!isInPage())
return;
setLeft("0");
setLeft(getMapper().toPixels(this.task.getBeginDate()) + "px");
setWidth("0");
setWidth(getMapper().toPixels(this.task.getLengthMilliseconds())
+ "px");
smartUpdate("name", this.task.getName());
DependencyList dependencyList = getDependencyList();
if (dependencyList != null) {
dependencyList.redrawDependenciesConnectedTo(this);
}
updateCompletionIfPossible();
}
private void updateCompletionIfPossible() {
try {
updateCompletion();
} catch (Exception e) {
LOG.error("failure at updating completion", e);
}
}
private void updateCompletion() {
long beginMilliseconds = this.task.getBeginDate().getTime();
long hoursAdvanceEndMilliseconds = this.task.getHoursAdvanceEndDate()
.getTime()
- beginMilliseconds;
if (hoursAdvanceEndMilliseconds < 0) {
hoursAdvanceEndMilliseconds = 0;
}
String widthHoursAdvancePercentage = getMapper().toPixels(
hoursAdvanceEndMilliseconds)
+ "px";
response(null, new AuInvoke(this, "resizeCompletionAdvance",
widthHoursAdvancePercentage));
long advanceEndMilliseconds = this.task.getAdvanceEndDate()
.getTime()
- beginMilliseconds;
if (advanceEndMilliseconds < 0) {
advanceEndMilliseconds = 0;
}
String widthAdvancePercentage = getMapper().toPixels(
advanceEndMilliseconds)
+ "px";
response(null, new AuInvoke(this, "resizeCompletion2Advance",
widthAdvancePercentage));
}
private DependencyList getDependencyList() {
return getGanntPanel().getDependencyList();
}
private GanttPanel getGanntPanel() {
return getTaskList().getGanttPanel();
}
private boolean isInPage() {
return getPage() != null;
}
void publishTaskComponents(Map<Task, TaskComponent> resultAccumulated) {
resultAccumulated.put(getTask(), this);
publishDescendants(resultAccumulated);
}
protected void publishDescendants(Map<Task, TaskComponent> resultAccumulated) {
}
protected void remove() {
this.detach();
}
public boolean isTopLevel() {
return isTopLevel;
}
public String getTooltipText() {
return task.getTooltipText();
}
}
|
package se.raddo.raddose3D.tests;
import java.util.HashMap;
import org.testng.Assert;
import org.testng.annotations.*;
import se.raddo.raddose3D.Crystal;
import se.raddo.raddose3D.CrystalCuboid;
import se.raddo.raddose3D.Wedge;
/**
* Tests for the Cuboid crystal class.
*/
public class CrystalCuboidTest {
final static double dblRoundingTolerance = 1e-13;
/**
* Tests value against target. Includes testing for null and nice error
* messages
*/
private void EqualsAssertion(Double value, Double target, String name) {
Assert.assertNotNull(value, name + " is null");
Assert.assertTrue(Math.abs(value - target) < dblRoundingTolerance,
name + " set incorrectly (" + value + ")");
}
@Test(groups = { "advanced" })
/** Checks that a full 360 rotation in P or L makes the crystal invariant,
* and that you get correct negatives under 180deg rotation.
**/
public void testCuboidCrystalPandL() {
final Double ang360 = 360d;
final Double ang180 = 180d;
HashMap<Object, Object> properties = new HashMap<Object, Object>();
properties.put(Crystal.CRYSTAL_DIM_X, 100d);
properties.put(Crystal.CRYSTAL_DIM_Y, 100d);
properties.put(Crystal.CRYSTAL_DIM_Z, 100d);
properties.put(Crystal.CRYSTAL_RESOLUTION, 0.5d);
properties.put(Crystal.CRYSTAL_ANGLE_P, 0d);
properties.put(Crystal.CRYSTAL_ANGLE_L, 0d);
Crystal c = new CrystalCuboid(properties);
properties.put(Crystal.CRYSTAL_ANGLE_P, ang360);
properties.put(Crystal.CRYSTAL_ANGLE_L, 0d);
Crystal cEquivalentP360 = new CrystalCuboid(properties);
// Should be the same as c
properties.put(Crystal.CRYSTAL_ANGLE_P, 0d);
properties.put(Crystal.CRYSTAL_ANGLE_L, ang360);
Crystal cEquivalentL360 = new CrystalCuboid(properties);
// Should be the same as c
properties.put(Crystal.CRYSTAL_ANGLE_P, ang360);
properties.put(Crystal.CRYSTAL_ANGLE_L, ang360);
Crystal cEquivalentPL360 = new CrystalCuboid(properties);
// Should be the same as c
properties.put(Crystal.CRYSTAL_ANGLE_P, ang180);
properties.put(Crystal.CRYSTAL_ANGLE_L, 0d);
Crystal cP180 = new CrystalCuboid(properties);
// (i,j,k) should = c(-i, -j, k)
properties.put(Crystal.CRYSTAL_ANGLE_P, 0d);
properties.put(Crystal.CRYSTAL_ANGLE_L, ang180);
Crystal cL180 = new CrystalCuboid(properties);
// (i,j,k) should = c(i , -j, -k)
int x = c.getCrystSizeVoxels()[0];
int y = c.getCrystSizeVoxels()[1];
int z = c.getCrystSizeVoxels()[2];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
for (int k = 0; k < z; k++) {
double id[] = c.getCrystCoord(i, j, k);
EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[0], id[0],
"P360-x");
EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[1], id[1],
"P360-y");
EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[2], id[2],
"P360-z");
EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[0], id[0],
"L360-x");
EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[1], id[1],
"L360-y");
EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[2], id[2],
"L360-z");
EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[0], id[0],
"PL360-x");
EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[1], id[1],
"PL360-y");
EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[2], id[2],
"PL360-z");
EqualsAssertion(-1 * cP180.getCrystCoord(i, j, k)[0], id[0], "P180-x");
EqualsAssertion(-1 * cP180.getCrystCoord(i, j, k)[1], id[1], "P180-y");
EqualsAssertion(cP180.getCrystCoord(i, j, k)[2], id[2], "P180-z");
EqualsAssertion(cL180.getCrystCoord(i, j, k)[0], id[0], "L180-x");
EqualsAssertion(-1 * cL180.getCrystCoord(i, j, k)[1], id[1], "L180-y");
EqualsAssertion(-1 * cL180.getCrystCoord(i, j, k)[2], id[2], "L180-z");
}
}
}
System.out.println("@Test - testCuboidCrystalPandL");
}
//This should work now... Am going to tart up Wedge and have another go.
@Test(groups = { "advanced" })
public static void testFindDepthSymmetry() {
HashMap<Object, Object> properties = new HashMap<Object, Object>();
properties.put(Crystal.CRYSTAL_DIM_X, 100d);
properties.put(Crystal.CRYSTAL_DIM_Y, 100d);
properties.put(Crystal.CRYSTAL_DIM_Z, 100d);
properties.put(Crystal.CRYSTAL_RESOLUTION, 1d);
properties.put(Crystal.CRYSTAL_ANGLE_P, 0d);
properties.put(Crystal.CRYSTAL_ANGLE_L, 0d);
Crystal c = new CrystalCuboid(properties);
Wedge w = new Wedge(2d, 0d, 90d, 100d, 0d, 0d, 0d, 0d, 0d, 0d, 0d);
/* Some random test coordinates to work on */
double[] testCoords = { 0, 0, 0 };//{ 12.23, 21.56, -44.32};
double[] testInvCoords = { 0, 0, 0 };//{-12.23, 21.56, 44.32};
for (double angles = 0; angles < Math.toRadians(500); angles += Math
.toRadians(18.8)) {
// Loop over y as well, to make it more thorough
//System.out.println(String.format("%n%n angle is %g", angles));
/* Rotating crystal into position */
double[] tempCoords = new double[3];
double[] tempInvCoords = new double[3];
//Debug System.out.println(i+j+k);
tempCoords[0] = testCoords[0] * Math.cos(angles) - testCoords[2]
* Math.sin(angles); //Rotate X
tempCoords[1] = testCoords[1];
tempCoords[2] = testCoords[0] * Math.sin(angles) + testCoords[2]
* Math.cos(angles); //Rotate Z
/* Symmetry related pair of tempCoords */
tempInvCoords[0] = testInvCoords[0] * Math.cos(angles) - testInvCoords[2]
* Math.sin(angles); //Rotate X
tempInvCoords[1] = testInvCoords[1];
tempInvCoords[2] = testInvCoords[0] * Math.sin(angles) + testInvCoords[2]
* Math.cos(angles); //Rotate Z
Assert.assertTrue(Math.abs(tempCoords[1] - tempInvCoords[1]) <= 1e-10,
"y does not match under inversion");
if (Math.abs(tempCoords[1] - tempInvCoords[1]) <= 1e-10)
System.out.println("y coords match");
// System.out.println("tempcoords = " + tempCoords[0] + ", " + tempCoords[1] + ", " + tempCoords[2]);
// System.out.println("tempInvCoords = " + tempInvCoords[0] + ", " + tempInvCoords[1] + ", " + tempInvCoords[2]);
// System.out.println("depth tempCoords @ theta = 0: " + c.findDepth(tempCoords, angles, w));
// System.out.println("depth tempInvCoords @ theta = 0: " + c.findDepth(tempInvCoords, angles, w));
// System.out.println("depth tempCoords @ theta = 180: " + c.findDepth(tempCoords, angles + Math.PI, w));
// System.out.println("depth tempInvCoords @ theta = 180: "+ c.findDepth(tempInvCoords, angles + Math.PI, w));
/* um of depths should be constant under 180Deg rotation */
c.setupDepthFinding(angles, w);
double sumdepths1 = c.findDepth(tempCoords, angles, w)
+ c.findDepth(tempInvCoords, angles, w);
c.setupDepthFinding(angles + Math.PI, w);
double sumdepths2 = c.findDepth(tempCoords, angles + Math.PI, w)
+ c.findDepth(tempInvCoords, angles + Math.PI, w);
// System.out.println("sumdepths1 = " + sumdepths1);
// System.out.println("sumdepths2 = " + sumdepths2);
double depthDelta = sumdepths1 - sumdepths2;
System.out.println("depthdelta = " + depthDelta);
Assert.assertTrue(Math.abs(sumdepths1 - sumdepths2) <= 1e-10,
"depths are not matched under symmetry");
}
}
@Test
public static void testFindDepth() {
int xdim = 90;
int ydim = 74;
int zdim = 40;
Double resolution = 0.5d;
// make a new map for a Cuboid Crystal, dimensions 90 x 74 x 40 um,
// 0.5 voxels per um, no starting rotation.
HashMap<Object, Object> properties = new HashMap<Object, Object>();
properties.put(Crystal.CRYSTAL_DIM_X, Double.valueOf(xdim));
properties.put(Crystal.CRYSTAL_DIM_Y, Double.valueOf(ydim));
properties.put(Crystal.CRYSTAL_DIM_Z, Double.valueOf(zdim));
properties.put(Crystal.CRYSTAL_RESOLUTION, resolution);
properties.put(Crystal.CRYSTAL_ANGLE_P, 0d);
properties.put(Crystal.CRYSTAL_ANGLE_L, 0d);
Crystal c = new CrystalCuboid(properties);
// create a new wedge with no rotation at 100 seconds' exposure
// (doesn't matter)
Wedge w = new Wedge(0d, 0d, 0d, 100d, 0d, 0d, 0d, 0d, 0d, 0d, 0d);
// beam is along z axis. So when the crystal is not rotated, the
// maximum depth along the z axis should be zdim um (length of crystal).
double[] crystCoords;
// this coordinate is in voxel coordinates.
// this translates to bottom left corner of the crystal
// in crystCoords (-45, -37, -20)
// and should therefore be first to intercept the beam and have
// a depth of 0.
for (int x = 0; x < xdim * resolution; x++) {
for (int y = 0; y < ydim * resolution; y++) {
for (int z = 0; z < zdim * resolution; z++) {
crystCoords = c.getCrystCoord(x, y, z);
Assertion.equals(crystCoords[0], -(xdim / 2) + (x / resolution),
"crystal coordinate x axis");
Assertion.equals(crystCoords[1], -(ydim / 2) + (y / resolution),
"crystal coordinate y axis");
Assertion.equals(crystCoords[2], -(zdim / 2) + (z / resolution),
"crystal coordinate z axis");
c.setupDepthFinding(0, w);
double depth = c.findDepth(crystCoords, 0, w);
// The depth finding overestimates by 10/resolution :(
// depth -= (10 / resolution);
// Because the crystal has not been rotated,
// the depth should just be z / resolution
Assertion.equals(depth, z / resolution, "depth at z=" + z);
}
}
}
}
}
|
package uk.ac.ox.oucs.erewhon.oxpq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Collection;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.oucs.gaboto.GabotoConfiguration;
import org.oucs.gaboto.GabotoLibrary;
import org.oucs.gaboto.entities.GabotoEntity;
import org.oucs.gaboto.entities.pool.GabotoEntityPool;
import org.oucs.gaboto.entities.pool.GabotoEntityPoolConfiguration;
import org.oucs.gaboto.transformation.EntityPoolTransformer;
import org.oucs.gaboto.transformation.RDFPoolTransformerFactory;
import org.oucs.gaboto.transformation.json.GeoJSONPoolTransfomer;
import org.oucs.gaboto.transformation.json.JSONPoolTransformer;
import org.oucs.gaboto.transformation.kml.KMLPoolTransformer;
import org.oucs.gaboto.exceptions.ResourceDoesNotExistException;
import org.oucs.gaboto.exceptions.UnsupportedFormatException;
import org.oucs.gaboto.model.Gaboto;
import org.oucs.gaboto.model.GabotoFactory;
import org.oucs.gaboto.model.GabotoSnapshot;
import org.oucs.gaboto.model.query.GabotoQuery;
import org.oucs.gaboto.timedim.TimeInstant;
import org.oucs.gaboto.util.GabotoOntologyLookup;
import org.oucs.gaboto.vocabulary.OxPointsVocab;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
public class OxPointsQueryServlet extends HttpServlet {
private static final long serialVersionUID = 4155078999145248554L;
private static Logger logger = Logger.getLogger(OxPointsQueryServlet.class.getName());
private static Gaboto gaboto;
private static GabotoSnapshot snapshot;
private static GabotoConfiguration config;
private static Calendar startTime;
public void init() {
logger.debug("init");
config = GabotoConfiguration.fromConfigFile();
GabotoLibrary.init(config);
gaboto = GabotoFactory.getEmptyInMemoryGaboto();
gaboto.read(getResourceOrDie("graphs.rdf"), getResourceOrDie("cdg.rdf"));
gaboto.recreateTimeDimensionIndex();
startTime = Calendar.getInstance();
snapshot = gaboto.getSnapshot(TimeInstant.from(startTime));
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
outputPool(request, response);
} catch (AnticipatedException e) {
error(request, response, e);
}
}
void error(HttpServletRequest request, HttpServletResponse response, AnticipatedException exception) {
response.setContentType("text/html");
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e) {
throw new RuntimeException(e);
}
out.println("<html><head><title>OxPoints Anticipated Error</title></head>");
out.println("<body>");
out.println("<h2>OxPoints Anticipated Error</h2>");
out.println("<h3>" + exception.getMessage() + "</h3>");
out.println("<p>An anticipated error has occured in the application");
out.println("that runs this website, please contact <a href='mailto:");
out.println(getSysAdminEmail() + "'>" + getSysAdminName() + "</a>");
out.println(", with the information given below.</p>");
out.println("<h3> Invoked with " + request.getRequestURL().toString() + "</h3>");
if (request.getQueryString() != null)
out.println("<h3> query " + request.getQueryString() + "</h3>");
out.println("<h4><font color='red'><pre>");
exception.printStackTrace(out);
out.println("</pre></font></h4>");
out.println("</body></html>");
}
private String getSysAdminEmail() {
return "Tim.Pizey@oucs.ox.ac.uk";
}
private String getSysAdminName() {
return "Tim Pizey";
}
void outputPool(HttpServletRequest request, HttpServletResponse response) {
Query query = Query.fromRequest(request);
switch (query.getReturnType()) {
case META_TIMESTAMP:
try {
response.getWriter().write(new Long(startTime.getTimeInMillis()).toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
return;
case META_TYPES:
output(GabotoOntologyLookup.getRegisteredEntityClassesAsClassNames(), query, response);
return;
case ALL:
output(GabotoEntityPool.createFrom(snapshot), query, response);
return;
case INDIVIDUAL:
GabotoEntityPool pool = new GabotoEntityPool(gaboto, snapshot);
try {
pool.addEntity(snapshot.loadEntity(query.getUri()));
} catch (ResourceDoesNotExistException e) {
throw new AnticipatedException("Resource not found with uri " + query.getUri(), e);
}
output(pool, query, response);
return;
case TYPE_COLLECTION:
output(loadPoolWithEntitiesOfType(query.getType()), query, response);
return;
case COLLECTION:
output(loadPoolWithEntitiesOfProperty(query.getRequestedProperty(), query.getRequestedPropertyValue()), query,
response);
return;
case NOT_FILTERED_TYPE_COLLECTION:
GabotoEntityPool p = loadPoolWithEntitiesOfType(query.getType());
GabotoEntityPool p2 = loadPoolWithEntitiesOfType(query.getType());
for (GabotoEntity e : p.getEntities())
if (e.getPropertyValue(query.getNotProperty(), false, false) != null)
p2.removeEntity(e);
output(p2, query,
response);
return;
default:
throw new RuntimeException("Fell through case with value " + query.getReturnType());
}
}
private GabotoEntityPool loadPoolWithEntitiesOfProperty(Property prop, String value) {
if (prop == null)
throw new NullPointerException();
GabotoEntityPool pool = null;
if (value == null) {
pool = snapshot.loadEntitiesWithProperty(prop);
} else {
String values[] = value.split("[|]");
for (String v : values) {
if (requiresResource(prop)) {
Resource r = getResource(v);
System.err.println("Found r: " + r + " for prop " + prop + " with value " + v);
pool = becomeOrAdd(pool, snapshot.loadEntitiesWithProperty(prop, r));
} else {
pool = becomeOrAdd(pool, snapshot.loadEntitiesWithProperty(prop, v));
}
}
}
return pool;
}
private GabotoEntityPool becomeOrAdd(GabotoEntityPool pool, GabotoEntityPool poolToAdd) {
if (poolToAdd == null)
throw new NullPointerException();
if (pool == null) {
return poolToAdd;
} else {
for (GabotoEntity e : poolToAdd.getEntities())
pool.addEntity(e);
return pool;
}
}
private Resource getResource(String v) {
String vUri = config.getNSData() + v;
return snapshot.getResource(vUri);
}
private boolean requiresResource(Property property) {
if (property.getLocalName().endsWith("subsetOf")) {
return true;
} else if (property.getLocalName().endsWith("physicallyContainedWithin")) {
return true;
} else if (property.getLocalName().endsWith("hasPrimaryPlace")) {
return true;
} else if (property.getLocalName().endsWith("occupies")) {
return true;
} else if (property.getLocalName().endsWith("associatedWith")) {
return true;
}
return false;
}
private GabotoEntityPool loadPoolWithEntitiesOfType(String type) {
System.err.println("Type:" + type);
String types[] = type.split("[|]");
GabotoEntityPoolConfiguration conf = new GabotoEntityPoolConfiguration(snapshot);
for (String t : types) {
if (!GabotoOntologyLookup.isValidName(t))
throw new IllegalArgumentException("Found no URI matching type " + t);
String typeURI = OxPointsVocab.NS + t;
conf.addAcceptedType(typeURI);
}
return GabotoEntityPool.createFrom(conf);
}
private void output(Collection<String> them, Query query, HttpServletResponse response) {
try {
if (query.getFormat().equals("txt")) {
boolean doneOne = false;
for (String member : them) {
if (doneOne)
response.getWriter().write("|");
response.getWriter().write(member);
doneOne = true;
}
response.getWriter().write("\n");
} else if (query.getFormat().equals("csv")) {
boolean doneOne = false;
for (String member : them) {
if (doneOne)
response.getWriter().write(",");
response.getWriter().write(member);
doneOne = true;
}
response.getWriter().write("\n");
} else if (query.getFormat().equals("js")) {
boolean doneOne = false;
response.getWriter().write("var oxpointsTypes = [");
for (String member : them) {
if (doneOne)
response.getWriter().write(",");
response.getWriter().write("'");
response.getWriter().write(member);
response.getWriter().write("'");
doneOne = true;
}
response.getWriter().write("];\n");
} else if (query.getFormat().equals("xml")) {
response.getWriter().write("<c>");
for (String member : them) {
response.getWriter().write("<i>");
response.getWriter().write(member);
response.getWriter().write("</i>");
}
response.getWriter().write("</c>");
response.getWriter().write("\n");
} else
throw new AnticipatedException("Unexpected format " + query.getFormat());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void output(GabotoEntityPool pool, Query query, HttpServletResponse response) {
System.err.println("Pool has " + pool.getSize() + " elements");
System.err.println("output.Format:" + query.getFormat() + ":");
String output = "";
if (query.getFormat().equals("kml")) {
output = createKml(pool, query);
response.setContentType("application/vnd.google-earth.kml+xml");
} else if (query.getFormat().equals("json") || query.getFormat().equals("js")) {
System.err.println("output.Format:" + query.getFormat());
JSONPoolTransformer transformer = new JSONPoolTransformer();
transformer.setNesting(query.getJsonDepth());
output = transformer.transform(pool);
if (query.getFormat().equals("js")) {
output = query.getJsCallback() + "(" + output + ");";
}
response.setContentType("text/javascript");
} else if (query.getFormat().equals("gjson")) {
GeoJSONPoolTransfomer transformer = new GeoJSONPoolTransfomer();
if (query.getArc() != null) {
transformer.addEntityFolderType(query.getFolderClassURI(), query.getArcProperty().getURI());
}
if (query.getOrderBy() != null) {
transformer.setOrderBy(query.getOrderByProperty().getURI());
}
transformer.setDisplayParentName(query.getDisplayParentName());
output += transformer.transform(pool);
if (query.getJsCallback() != null)
output = query.getJsCallback() + "(" + output + ");";
response.setContentType("text/javascript");
} else if (query.getFormat().equals("xml")) {
System.err.println("Pool has " + pool.getSize() + " elements");
EntityPoolTransformer transformer;
try {
transformer = RDFPoolTransformerFactory.getRDFPoolTransformer(GabotoQuery.FORMAT_RDF_XML_ABBREV);
output = transformer.transform(pool);
} catch (UnsupportedFormatException e) {
throw new IllegalArgumentException(e);
}
response.setContentType("text/xml");
} else {
output = runGPSBabel(createKml(pool, query), "kml", query.getFormat());
if (output.equals(""))
throw new RuntimeException("No output created by GPSBabel");
}
// System.err.println("output:" + output + ":");
try {
response.getWriter().write(output);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String createKml(GabotoEntityPool pool, Query query) {
String output;
KMLPoolTransformer transformer = new KMLPoolTransformer();
if (query.getArc() != null) {
transformer.addEntityFolderType(query.getFolderClassURI(), query.getArcProperty().getURI());
}
if (query.getOrderBy() != null) {
transformer.setOrderBy(query.getOrderByProperty().getURI());
}
transformer.setDisplayParentName(query.getDisplayParentName());
output = transformer.transform(pool);
return output;
}
/**
* @param input
* A String, normally kml
* @param formatIn
* format name, other than kml
* @param formatOut
* what you want out
* @return the reformatted String
*/
public static String runGPSBabel(String input, String formatIn, String formatOut) {
// '/usr/bin/gpsbabel -i kml -o ' . $format . ' -f ' . $In . ' -F ' . $Out;
if (formatIn == null)
formatIn = "kml";
if (formatOut == null)
throw new IllegalArgumentException("Missing output format for GPSBabel");
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
String output = "";
String command = "/usr/bin/gpsbabel -i " + formatIn + " -o " + formatOut + " -f - -F -";
System.err.println("GPSBabel command:" + command);
Process process;
try {
process = Runtime.getRuntime().exec(command, null, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
stdin = process.getOutputStream();
stdout = process.getInputStream();
stderr = process.getErrorStream();
try {
stdin.write(input.getBytes());
stdin.flush();
stdin.close();
} catch (IOException e) {
// clean up if any output in stderr
BufferedReader errBufferedReader = new BufferedReader(new InputStreamReader(stderr));
String stderrString = "";
String stderrLine = null;
try {
while ((stderrLine = errBufferedReader.readLine()) != null) {
System.err.println("[Stderr Ex] " + stderrLine);
stderrString += stderrLine;
}
errBufferedReader.close();
} catch (IOException e2) {
throw new RuntimeException("Command " + command + " stderr reader failed:" + e2);
}
throw new RuntimeException("Command " + command + " gave error:\n" + stderrString);
}
BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
String line;
try {
while ((line = brCleanUp.readLine()) != null) {
System.out.println("[Stdout] " + line);
output += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
// clean up if any output in stderr
brCleanUp = new BufferedReader(new InputStreamReader(stderr));
String stderrString = "";
try {
while ((line = brCleanUp.readLine()) != null) {
System.err.println("[Stderr] " + line);
stderrString += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!stderrString.equals(""))
throw new RuntimeException("Command " + command + " gave error:\n" + stderrString);
} finally {
process.destroy();
}
return output;
}
private InputStream getResourceOrDie(String fileName) {
String resourceName = fileName;
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
if (is == null)
throw new NullPointerException("File " + resourceName + " cannot be loaded");
return is;
}
}
|
package org.xwiki.user.script;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.script.service.ScriptService;
import org.xwiki.script.service.ScriptServiceManager;
import org.xwiki.stability.Unstable;
import org.xwiki.user.CurrentUserReference;
import org.xwiki.user.GuestUserReference;
import org.xwiki.user.SuperAdminUserReference;
import org.xwiki.user.UserManager;
import org.xwiki.user.UserProperties;
import org.xwiki.user.UserPropertiesResolver;
import org.xwiki.user.UserReference;
/**
* Users related script API.
*
* @version $Id$
* @since 10.8RC1
*/
@Component
@Named(UserScriptService.ROLEHINT)
@Singleton
public class UserScriptService implements ScriptService
{
/**
* The role hint of this component.
*/
public static final String ROLEHINT = "user";
@Inject
private UserPropertiesResolver userPropertiesResolver;
@Inject
@Named("all")
private UserPropertiesResolver allUserPropertiesResolver;
@Inject
private ScriptServiceManager scriptServiceManager;
@Inject
private UserManager userManager;
/**
* @param <S> the type of the {@link ScriptService}
* @param serviceName the name of the sub {@link ScriptService}
* @return the {@link ScriptService} or null of none could be found
*/
@SuppressWarnings("unchecked")
public <S extends ScriptService> S get(String serviceName)
{
return (S) this.scriptServiceManager.get(ROLEHINT + '.' + serviceName);
}
/**
* @param userReference the reference to the user properties to resolve
* @param parameters optional parameters that have a meaning only for the specific resolver implementation used
* @return the User Properties object
* @since 12.2RC1
*/
@Unstable
public UserProperties getProperties(UserReference userReference, Object... parameters)
{
return this.userPropertiesResolver.resolve(userReference, parameters);
}
/**
* @param parameters optional parameters that have a meaning only for the specific resolver implementation used
* @return the User Properties object for the current user
* @since 12.2RC1
*/
@Unstable
public UserProperties getProperties(Object... parameters)
{
return this.userPropertiesResolver.resolve(CurrentUserReference.INSTANCE, parameters);
}
/**
* @return the User Properties object for the current user
* @since 12.2RC1
*/
@Unstable
public UserProperties getProperties()
{
return this.userPropertiesResolver.resolve(CurrentUserReference.INSTANCE);
}
/**
* @param userReference the reference to the user properties to resolve
* @param parameters optional parameters that have a meaning only for the specific resolver implementation used
* @return the User Properties object
* @since 12.2RC1
*/
@Unstable
public UserProperties getAllProperties(UserReference userReference, Object... parameters)
{
return this.allUserPropertiesResolver.resolve(userReference, parameters);
}
/**
* @param parameters optional parameters that have a meaning only for the specific resolver implementation used
* @return the User Properties object for the current user
* @since 12.2RC1
*/
@Unstable
public UserProperties getAllProperties(Object... parameters)
{
return this.allUserPropertiesResolver.resolve(CurrentUserReference.INSTANCE, parameters);
}
/**
* @return the User Properties object for the current user
* @since 12.2RC1
*/
@Unstable
public UserProperties getAllProperties()
{
return this.allUserPropertiesResolver.resolve(CurrentUserReference.INSTANCE);
}
/**
* @return the Guest User reference
* @since 12.2RC1
*/
@Unstable
public UserReference getGuestUserReference()
{
return GuestUserReference.INSTANCE;
}
/**
* @return the SuperAdmin User reference
* @since 12.2RC1
*/
@Unstable
public UserReference getSuperAdminUserReference()
{
return SuperAdminUserReference.INSTANCE;
}
/**
* @return the current User reference
* @since 12.2RC1
*/
@Unstable
public UserReference getCurrentUserReference()
{
return CurrentUserReference.INSTANCE;
}
/**
* @param userReference the reference to the user to test for existence (i.e. if the user pointed to by the
* reference exists or not - for example the superadmin users or the guest users don't exist,
* and a "document"-based User can be constructed and have no profile page and thus not exist)
* @return true if the user exists in the store or false otherwise
* @since 12.2RC1
*/
@Unstable
public boolean exists(UserReference userReference)
{
return this.userManager.exists(userReference);
}
}
|
package com.highstreet.technologies.odl.app.spectrum.impl.api;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import com.highstreet.technologies.odl.app.spectrum.impl.meta.*;
import com.highstreet.technologies.odl.app.spectrum.impl.primitive.JsonUtil;
import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.net.URL;
import static com.highstreet.technologies.odl.app.spectrum.impl.primitive.JsonUtil.newArrayNode;
public class MosAgent implements DataAgent
{
private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static JsonRpcHttpClient client;
private static String sessionId;
public MosAgent(String url) throws MalformedURLException
{
client = new JsonRpcHttpClient(new URL(url));
}
@Override
public Object get(Attribute attr)
{
try
{
Result<Mo> result = get(attr.getDn());
} catch (Exception e)
{
return null;
}
return null;
}
protected <T> Result<T> methodShell(Executor<T> executor) throws Exception
{
StackTraceElement[] stackTraceElements = new Throwable().getStackTrace();
logger.debug(stackTraceElements[2] + " is calling " + stackTraceElements[1]);
try
{
return executor.post(executor.exec(), this);
} catch (SessionNotFoundException e)
{
this.login();
return executor.post(executor.exec(), this);
} catch (Throwable e)
{
return executor.postException(e, this);
}
}
protected void login()
throws Exception
{
JsonNode node;
try
{
node = client.invoke(
"login",
new Object[]{"MOSSERVICE", "ems", "ems", JsonUtil.toNode(new Maybe<Server>(null))},
JsonNode.class);
} catch (Throwable throwable)
{
throw new Exception(throwable);
}
if (node.findValue("result").intValue() != 1)
{
sessionId = node.findValue("sessionId").textValue();
} else
{
throw new Exception("login failed!");
}
}
public Result<Mo> get(final DN... dns) throws Exception
{
return methodShell(
new GetExecutor()
{
@Override
public JsonNode exec() throws Exception
{
ArrayNode node = newArrayNode();
for (DN dn : dns)
{
try
{
ObjectNode mo = client.invoke(
"get",
new Object[]{sessionId, dn.toString(), new Maybe<Integer>(null)},
ObjectNode.class);
node.add(mo);
} catch (Throwable throwable)
{
throw new Exception(throwable);
}
}
return node;
}
});
}
@Override
public Result<Mo> find(String typeName)
{
return null;
}
}
|
package org.eclipse.birt.report.designer.ui.cubebuilder.dialog;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.birt.report.designer.core.commands.DeleteCommand;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.util.WidgetUtil;
import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages;
import org.eclipse.birt.report.designer.ui.cubebuilder.util.BuilderConstancts;
import org.eclipse.birt.report.designer.ui.cubebuilder.util.OlapUtil;
import org.eclipse.birt.report.designer.ui.cubebuilder.util.UIHelper;
import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.command.NameException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.HierarchyHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;
import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle;
import org.eclipse.birt.report.model.api.olap.TabularLevelHandle;
import org.eclipse.birt.report.model.elements.interfaces.IHierarchyModel;
import org.eclipse.birt.report.model.elements.interfaces.ILevelModel;
import org.eclipse.birt.report.model.metadata.MetaDataDictionary;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
public class GroupDialog extends TitleAreaDialog
{
private boolean isNew;
public GroupDialog( boolean isNew )
{
super( UIUtil.getDefaultShell( ) );
this.isNew = isNew;
}
private String dataField;
private TabularHierarchyHandle hierarchy;
private List levelList = new ArrayList( );
public void setInput( TabularHierarchyHandle hierarchy, String dataField )
{
this.dataField = dataField;
this.hierarchy = hierarchy;
TabularLevelHandle[] levels = (TabularLevelHandle[]) hierarchy.getContents( IHierarchyModel.LEVELS_PROP )
.toArray( new TabularLevelHandle[0] );
for ( int i = 0; i < levels.length; i++ )
{
if ( levels[i].getDateTimeLevelType( ) != null )
levelList.add( levels[i].getDateTimeLevelType( ) );
}
dateTypeSelectedList.addAll( levelList );
}
protected Control createDialogArea( Composite parent )
{
UIUtil.bindHelp( parent, IHelpContextIds.CUBE_BUILDER_GROUP_DIALOG ); //$NON-NLS-1$
setTitle( Messages.getString( "DateGroupDialog.Title" ) ); //$NON-NLS-1$
getShell( ).setText( Messages.getString( "DateGroupDialog.Shell.Title" ) ); //$NON-NLS-1$
setMessage( Messages.getString( "DateGroupDialog.Message" ) ); //$NON-NLS-1$
Composite area = (Composite) super.createDialogArea( parent );
Composite contents = new Composite( area, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.marginWidth = 20;
contents.setLayout( layout );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = convertWidthInCharsToPixels( 80 );
data.heightHint = 300;
contents.setLayoutData( data );
createGroupTypeArea( contents );
createContentArea( contents );
WidgetUtil.createGridPlaceholder( contents, 1, true );
initDialog( );
parent.layout( );
return contents;
}
private void createGroupTypeArea( Composite contents )
{
regularButton = new Button( contents, SWT.RADIO );
regularButton.setText( "Regular Group" );
regularButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
handleButtonSelection( regularButton );
}
} );
dateButton = new Button( contents, SWT.RADIO );
dateButton.setText( "Date Group" );
dateButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
handleButtonSelection( dateButton );
}
} );
}
protected void handleButtonSelection( Button button )
{
if ( button == regularButton )
{
regularButton.setSelection( true );
dateButton.setSelection( false );
levelViewer.getTree( ).setVisible( false );
setMessage( "" );
}
else
{
regularButton.setSelection( false );
dateButton.setSelection( true );
if ( dataField != null )
{
levelViewer.getTree( ).setVisible( true );
setMessage( Messages.getString( "DateGroupDialog.Message" ) );
}
else
{
levelViewer.getTree( ).setVisible( false );
setMessage( "" );
}
}
checkOKButtonStatus( );
}
private void initDialog( )
{
nameText.setText( hierarchy.getContainer( ).getName( ) );
if ( !isNew )
{
if ( ( (DimensionHandle) hierarchy.getContainer( ) ).isTimeType( ) )
{
dateButton.setSelection( true );
handleButtonSelection( dateButton );
}
else
{
regularButton.setSelection( true );
handleButtonSelection( regularButton );
}
}
else
{
dateButton.setSelection( true );
handleButtonSelection( dateButton );
}
if(!isNew){
WidgetUtil.setExcludeGridData( regularButton, true );
WidgetUtil.setExcludeGridData( dateButton, true );
}
if ( !isNew
&& !( (DimensionHandle) hierarchy.getContainer( ) ).isTimeType( ) )
levelViewer.getTree( ).setVisible( false );
levelViewer.setInput( getDateTypeNames( ) );
levelViewer.expandAll( );
TreeItem topNode = (TreeItem) levelViewer.getTree( ).getItem( 0 );
do
{
if ( levelList.contains( topNode.getData( ) ) )
topNode.setChecked( true );
topNode = topNode.getItem( 0 );
} while ( topNode.getItemCount( ) > 0 );
if ( levelList.contains( topNode.getData( ) ) )
topNode.setChecked( true );
checkOKButtonStatus( );
}
private IChoice[] DATE_TIME_LEVEL_TYPE_ALL = MetaDataDictionary.getInstance( )
.getElement( ReportDesignConstants.TABULAR_LEVEL_ELEMENT )
.getProperty( DesignChoiceConstants.CHOICE_DATE_TIME_LEVEL_TYPE )
.getAllowedChoices( )
.getChoices( );
private List getDateTypeNames( )
{
IChoice[] choices = DATE_TIME_LEVEL_TYPE_ALL;
List dateTypeList = new ArrayList( );
if ( choices == null )
return dateTypeList;
for ( int i = 0; i < choices.length; i++ )
{
dateTypeList.add( choices[i].getName( ) );
}
return dateTypeList;
}
private String getDateTypeDisplayName( String name )
{
return ChoiceSetFactory.getDisplayNameFromChoiceSet( name,
DEUtil.getMetaDataDictionary( )
.getElement( ReportDesignConstants.LEVEL_ELEMENT )
.getProperty( ILevelModel.DATA_TYPE_PROP )
.getAllowedChoices( ) );
}
class DateLevelProvider extends LabelProvider implements
ITreeContentProvider
{
public Object[] getChildren( Object parentElement )
{
int index = getDateTypeNames( ).indexOf( parentElement );
return new Object[]{
getDateTypeNames( ).get( index + 1 )
};
}
public Object getParent( Object element )
{
int index = getDateTypeNames( ).indexOf( element );
if ( index == 0 )
return null;
else
return getDateTypeNames( ).get( index - 1 );
}
public boolean hasChildren( Object element )
{
int index = getDateTypeNames( ).indexOf( element );
if ( index >= getDateTypeNames( ).size( ) - 1 )
return false;
return true;
}
public Object[] getElements( Object inputElement )
{
return new Object[]{
getDateTypeNames( ).get( 0 )
};
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
// TODO Auto-generated method stub
}
public Image getImage( Object element )
{
return UIHelper.getImage( BuilderConstancts.IMAGE_LEVEL );
}
public String getText( Object element )
{
return getDateTypeDisplayName( element.toString( ) );
}
}
protected void okPressed( )
{
try
{
hierarchy.getContainer( ).setName( nameText.getText( ).trim( ) );
}
catch ( NameException e1 )
{
ExceptionHandler.handle( e1 );
}
if ( regularButton.getSelection( ) )
{
try
{
if ( ( (DimensionHandle) hierarchy.getContainer( ) ).isTimeType( ) )
{
while ( hierarchy.getContentCount( IHierarchyModel.LEVELS_PROP ) > 0 )
{
hierarchy.dropAndClear( IHierarchyModel.LEVELS_PROP, 0 );
}
}
( (DimensionHandle) hierarchy.getContainer( ) ).setTimeType( false );
if ( isNew )
{
TabularLevelHandle level = DesignElementFactory.getInstance( )
.newTabularLevel( (DimensionHandle) hierarchy.getContainer( ),
dataField );
level.setColumnName( dataField );
DataSetHandle dataset = hierarchy.getDataSet( );
if(dataset == null){
dataset = ((TabularCubeHandle)hierarchy.getContainer( ).getContainer( )).getDataSet( );
}
level.setDataType( OlapUtil.getDataField( dataset,
dataField )
.getDataType( ) );
hierarchy.add( IHierarchyModel.LEVELS_PROP, level );
}
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else
{
try
{
if ( !( (DimensionHandle) hierarchy.getContainer( ) ).isTimeType( ) )
{
while ( hierarchy.getContentCount( IHierarchyModel.LEVELS_PROP ) > 0 )
{
hierarchy.dropAndClear( IHierarchyModel.LEVELS_PROP, 0 );
}
}
( (DimensionHandle) hierarchy.getContainer( ) ).setTimeType( true );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
// remove unused level
if ( levelList.size( ) > 0 )
{
for ( int i = 0; i < DATE_TIME_LEVEL_TYPE_ALL.length; i++ )
{
String dateType = DATE_TIME_LEVEL_TYPE_ALL[i].getName( );
if ( levelList.contains( dateType )
&& !dateTypeSelectedList.contains( dateType ) )
{
LevelHandle level = hierarchy.getLevel( levelList.indexOf( dateType ) );
boolean hasExecuted = OlapUtil.enableDrop( level );
if ( hasExecuted )
{
new DeleteCommand( level ).execute( );
levelList.remove( dateType );
}
}
}
}
// New
if ( levelList.size( ) == 0 )
{
for ( int i = 0; i < dateTypeSelectedList.size( ); i++ )
{
String dateType = (String) dateTypeSelectedList.get( i );
TabularLevelHandle level = DesignElementFactory.getInstance( )
.newTabularLevel( (DimensionHandle) hierarchy.getContainer( ),
dateType );
try
{
level.setDataType( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER );
level.setDateTimeLevelType( dateType );
level.setColumnName( dataField );
hierarchy.add( HierarchyHandle.LEVELS_PROP, level );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
}
// Edit
else
{
int j = 0;
for ( int i = 0; i < dateTypeSelectedList.size( ); i++ )
{
String dateType = (String) dateTypeSelectedList.get( i );
if ( !levelList.contains( dateType ) )
{
boolean exit = false;
// in the old level list: month in (year,day)
for ( ; j < levelList.size( ); j++ )
{
if ( getDateTypeNames( ).indexOf( dateType ) < getDateTypeNames( ).indexOf( levelList.get( j ) ) )
{
TabularLevelHandle level = DesignElementFactory.getInstance( )
.newTabularLevel( (DimensionHandle) hierarchy.getContainer( ),
dateType );
try
{
level.setDataType( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER );
level.setDateTimeLevelType( dateType );
level.setColumnName( dataField );
hierarchy.add( HierarchyHandle.LEVELS_PROP,
level,
j );
levelList.add( j, dateType );
exit = true;
break;
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
}
if ( exit )
continue;
// out of old level list:month out (year,quarter)
TabularLevelHandle level = DesignElementFactory.getInstance( )
.newTabularLevel( (DimensionHandle) hierarchy.getContainer( ),
dateType );
try
{
level.setDataType( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER );
level.setDateTimeLevelType( dateType );
level.setColumnName( dataField );
hierarchy.add( HierarchyHandle.LEVELS_PROP, level );
levelList.add( j++, dateType );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
}
}
}
super.okPressed( );
}
private List dateTypeSelectedList = new ArrayList( );
private Text nameText;
private CheckboxTreeViewer levelViewer;
private Button regularButton;
private Button dateButton;
private void createContentArea( Composite parent )
{
Composite content = new Composite( parent, SWT.NONE );
content.setLayoutData( new GridData( GridData.FILL_BOTH ) );
GridLayout layout = new GridLayout( );
layout.numColumns = 2;
content.setLayout( layout );
new Label( content, SWT.NONE ).setText( Messages.getString( "DateGroupDialog.Name" ) ); //$NON-NLS-1$
nameText = new Text( content, SWT.BORDER );
nameText.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
nameText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOKButtonStatus( );
}
} );
levelViewer = new CheckboxTreeViewer( content, SWT.SINGLE | SWT.BORDER );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.horizontalSpan = 2;
levelViewer.getTree( ).setLayoutData( gd );
DateLevelProvider provider = new DateLevelProvider( );
levelViewer.setContentProvider( provider );
levelViewer.setLabelProvider( provider );
levelViewer.addCheckStateListener( new ICheckStateListener( ) {
public void checkStateChanged( CheckStateChangedEvent event )
{
String item = (String) event.getElement( );
if ( event.getChecked( ) )
{
if ( !dateTypeSelectedList.contains( item ) )
dateTypeSelectedList.add( item );
}
else
{
if ( dateTypeSelectedList.contains( item ) )
dateTypeSelectedList.remove( item );
}
checkOKButtonStatus( );
}
} );
}
protected void checkOKButtonStatus( )
{
if ( nameText.getText( ).trim( ).length( ) == 0 )
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( false );
}
else
{
if ( dateButton.getSelection( )
&& dateTypeSelectedList.size( ) == 0
&& ( isNew || dataField != null ) )
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( false );
}
else if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( true );
}
}
protected void createButtonsForButtonBar( Composite parent )
{
super.createButtonsForButtonBar( parent );
checkOKButtonStatus( );
}
public void setInput( TabularHierarchyHandle hierarchy )
{
if ( hierarchy.getLevelCount( ) == 0 )
setInput( hierarchy, null );
else
{
if ( !isDateType( hierarchy,( (TabularLevelHandle) hierarchy.getLevel( 0 ) ).getColumnName( ) ) )
setInput( hierarchy, null );
else
setInput( hierarchy,
( (TabularLevelHandle) hierarchy.getLevel( 0 ) ).getColumnName( ) );
}
}
private boolean isDateType( TabularHierarchyHandle hierarchy,String columnName )
{
ResultSetColumnHandle column = OlapUtil.getDataField( OlapUtil.getHierarchyDataset(hierarchy),
columnName );
if ( column == null )
return false;
String dataType = column.getDataType( );
return dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME )
|| dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATE )
|| dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_TIME );
}
}
|
package edu.ucdenver.ccp.nlp.wrapper.conceptmapper.dictionary.obo;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import edu.ucdenver.ccp.common.file.FileUtil;
import edu.ucdenver.ccp.common.file.FileUtil.CleanDirectory;
import edu.ucdenver.ccp.datasource.fileparsers.obo.OntologyUtil;
import edu.ucdenver.ccp.datasource.fileparsers.obo.OntologyUtil.SynonymType;
import edu.ucdenver.ccp.datasource.fileparsers.obo.impl.GeneOntologyClassIterator;
/**
* @author Center for Computational Pharmacology, UC Denver;
* ccpsupport@ucdenver.edu
*
*/
public class GoDictionaryFactory {
public enum GoNamespace {
BP("biological_process"), MF("molecular_function"), CC("cellular_component");
private final String namespace;
private GoNamespace(String namespace) {
this.namespace = namespace;
}
public String namespace() {
return namespace;
}
}
public static File buildConceptMapperDictionary(EnumSet<GoNamespace> namespacesToInclude, File workDirectory,
CleanDirectory cleanWorkDirectory, SynonymType synonymType) throws IOException, IllegalArgumentException,
IllegalAccessException, OWLOntologyCreationException {
if (namespacesToInclude.isEmpty())
return null;
boolean doClean = cleanWorkDirectory.equals(CleanDirectory.YES);
GeneOntologyClassIterator goIter = new GeneOntologyClassIterator(workDirectory, doClean);
File geneOntologyOboFile = goIter.getGeneOntologyOboFile();
goIter.close();
return buildConceptMapperDictionary(namespacesToInclude, workDirectory, geneOntologyOboFile, doClean, synonymType);
}
/**
* @param namespacesToInclude
* @param outputDirectory
* @param ontUtil
* @param synonymType
* @return
* @throws IOException
* @throws OWLOntologyCreationException
*/
private static File buildConceptMapperDictionary(EnumSet<GoNamespace> namespacesToInclude, File outputDirectory,
File ontFile, boolean cleanDictFile, SynonymType synonymType) throws IOException, OWLOntologyCreationException {
String dictionaryKey = "";
List<String> nsKeys = new ArrayList<String>();
for (GoNamespace ns : namespacesToInclude) {
nsKeys.add(ns.name());
}
Collections.sort(nsKeys);
for (String ns : nsKeys) {
dictionaryKey += ns;
}
File dictionaryFile = new File(outputDirectory, "cmDict-GO-" + dictionaryKey + ".xml");
if (dictionaryFile.exists()) {
if (cleanDictFile) {
FileUtil.deleteFile(dictionaryFile);
} else {
return dictionaryFile;
}
}
Set<String> namespaces = new HashSet<String>();
for (GoNamespace ns : namespacesToInclude) {
namespaces.add(ns.namespace());
}
OntologyUtil ontUtil = new OntologyUtil(ontFile);
OboToDictionary.buildDictionary(dictionaryFile, ontUtil, new HashSet<String>(namespaces), synonymType);
return dictionaryFile;
}
}
|
package org.chromium.chrome.browser.partnercustomizations;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.PopupMenu;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.test.partnercustomizations.TestPartnerBrowserCustomizationsProvider;
import org.chromium.chrome.test.util.TestHttpServerClient;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* Integration tests for the partner disabling incognito mode feature.
*/
public class PartnerDisableIncognitoModeIntegrationTest extends
BasePartnerBrowserCustomizationIntegrationTest {
private static final String TEST_URLS[] = {
TestHttpServerClient.getUrl("chrome/test/data/android/about.html"),
TestHttpServerClient.getUrl("chrome/test/data/android/ok.txt"),
TestHttpServerClient.getUrl("chrome/test/data/android/test.html")
};
@Override
public void startMainActivity() throws InterruptedException {
// Each test will launch main activity, so purposefully omit here.
}
private void setParentalControlsEnabled(boolean enabled) {
Uri uri = PartnerBrowserCustomizations.buildQueryUri(
PartnerBrowserCustomizations.PARTNER_DISABLE_INCOGNITO_MODE_PATH);
Bundle bundle = new Bundle();
bundle.putBoolean(
TestPartnerBrowserCustomizationsProvider.INCOGNITO_MODE_DISABLED_KEY, enabled);
Context context = getInstrumentation().getTargetContext();
context.getContentResolver().call(uri, "setIncognitoModeDisabled", null, bundle);
}
private void assertIncognitoMenuItemEnabled(boolean enabled) throws ExecutionException {
Menu menu = ThreadUtils.runOnUiThreadBlocking(new Callable<Menu>() {
@Override
public Menu call() throws Exception {
// PopupMenu is a convenient way of building a temp menu.
PopupMenu tempMenu = new PopupMenu(
getActivity(), getActivity().findViewById(R.id.menu_anchor_stub));
tempMenu.inflate(R.menu.main_menu);
Menu menu = tempMenu.getMenu();
getActivity().prepareMenu(menu);
return menu;
}
});
for (int i = 0; i < menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item.getItemId() == R.id.new_incognito_tab_menu_id && item.isVisible()) {
assertEquals("Menu item enabled state is not correct.", enabled, item.isEnabled());
}
}
}
private boolean waitForParentalControlsEnabledState(final boolean parentalControlsEnabled)
throws InterruptedException {
return CriteriaHelper.pollForCriteria(new Criteria() {
@Override
public boolean isSatisfied() {
return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// areParentalControlsEnabled is updated on a background thread, so we
// also wait on the isIncognitoModeEnabled to ensure the updates on the
// UI thread have also triggered.
boolean retVal = parentalControlsEnabled
== PartnerBrowserCustomizations.isIncognitoDisabled();
retVal &= parentalControlsEnabled
!= PrefServiceBridge.getInstance().isIncognitoModeEnabled();
return retVal;
}
});
}
});
}
private void toggleActivityForegroundState() {
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
getActivity().onPause();
}
});
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
getActivity().onStop();
}
});
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
getActivity().onStart();
}
});
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
getActivity().onResume();
}
});
}
@MediumTest
@Feature({"DisableIncognitoMode"})
public void testIncognitoEnabledIfNoParentalControls() throws InterruptedException {
setParentalControlsEnabled(false);
startMainActivityOnBlankPage();
assertTrue(waitForParentalControlsEnabledState(false));
newIncognitoTabFromMenu();
}
@MediumTest
@Feature({"DisableIncognitoMode"})
public void testIncognitoMenuItemEnabledBasedOnParentalControls()
throws InterruptedException, ExecutionException {
setParentalControlsEnabled(true);
startMainActivityOnBlankPage();
assertTrue(waitForParentalControlsEnabledState(true));
assertIncognitoMenuItemEnabled(false);
setParentalControlsEnabled(false);
toggleActivityForegroundState();
assertTrue(waitForParentalControlsEnabledState(false));
assertIncognitoMenuItemEnabled(true);
}
@DisabledTest
@MediumTest
@Feature({"DisableIncognitoMode"})
public void testEnabledParentalControlsClosesIncognitoTabs() throws InterruptedException {
setParentalControlsEnabled(false);
startMainActivityOnBlankPage();
assertTrue(waitForParentalControlsEnabledState(false));
loadUrlInNewTab(TEST_URLS[0], true);
loadUrlInNewTab(TEST_URLS[1], true);
loadUrlInNewTab(TEST_URLS[2], true);
loadUrlInNewTab(TEST_URLS[0], false);
setParentalControlsEnabled(true);
toggleActivityForegroundState();
assertTrue(waitForParentalControlsEnabledState(true));
assertTrue("Incognito tabs did not close as expected",
CriteriaHelper.pollForCriteria(new Criteria() {
@Override
public boolean isSatisfied() {
return incognitoTabsCount() == 0;
}
}));
}
}
|
package org.deviceconnect.android.deviceplugin.hitoe.data;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import org.deviceconnect.android.deviceplugin.hitoe.BuildConfig;
import org.deviceconnect.android.deviceplugin.hitoe.util.RawDataParseUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import jp.ne.docomo.smt.dev.hitoetransmitter.HitoeSdkAPI;
import jp.ne.docomo.smt.dev.hitoetransmitter.sdk.HitoeSdkAPIImpl;
/**
* This class manages a Hitoe devices.
* @author NTT DOCOMO, INC.
*/
public class HitoeManager {
/** Log's tag name. */
private static final String TAG = "HitoeManager";
/**
* Instance of ScheduledExecutorService.
*/
private ScheduledExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();
/**
* ScheduledFuture of scan timer.
*/
private ScheduledFuture<?> mScanTimerFuture;
/**
* Defines a delay 1 second at first execution.
*/
private static final long SCAN_FIRST_WAIT_PERIOD = 30 * 1000;
/**
* Defines a period 10 seconds between successive executions.
*/
private static final long SCAN_WAIT_PERIOD = 20 * 1000;
/**
* Stops scanning after 1 second.
*/
private static final long SCAN_PERIOD = 2000;
/** Wait 5000 msec. */
private static final int CONNECTING_RETRY_WAIT = 500;
/** Connecting retry count. */
private static final int CONNECTING_RETRY_COUNT = 10;
/** Device scanning flag. */
private boolean mScanning;
/** Device scanning running. */
private boolean mIsCallbackRunning;
/** Device scan timestamp. */
private final Map<HitoeDevice, Long> mNowTimestamps;
/** Handler. */
private Handler mHandler = new Handler();
/**
* Application context.
*/
private Context mContext;
/**
* Instance of {@link HitoeDBHelper}.
*/
private HitoeDBHelper mDBHelper;
/**
* Hitoe SDK API.
*/
private HitoeSdkAPI mHitoeSdkAPI;
// Listener.
/** Hitoe Discovery Listener. */
private List<OnHitoeConnectionListener> mConnectionListeners;
/** Notify HeartRate data listener. */
private OnHitoeHeartRateEventListener mHeartRataListener;
/** Notify Accleration data listener. */
private OnHitoeDeviceOrientationEventListener mDeviceOrientationListener;
/** Notify ECG data listener. */
private OnHitoeECGEventListener mECGListener;
/** Notify Pose Estimation data listener. */
private OnHitoePoseEstimationEventListener mPoseEstimationListener;
/** Notify Stress Estimation data listener. */
private OnHitoeStressEstimationEventListener mStressEstimationListener;
/** Notify Walk state data listener. */
private OnHitoeWalkStateEventListener mWalkStateListener;
/** Registered Hitoe devices .*/
private final List<HitoeDevice> mRegisterDevices;
/** HeartRate Datas. */
private final Map<HitoeDevice, HeartRateData> mHRData;
/** Acceleration Datas. */
private final Map<HitoeDevice, AccelerationData> mAccelData;
/** ECG Datas. */
private final Map<HitoeDevice, HeartRateData> mECGData;
/** Pose Estimation datas. */
private final Map<HitoeDevice, PoseEstimationData> mPoseEstimationData;
/** Stress Estimation datas. */
private final Map<HitoeDevice, StressEstimationData> mStressEstimationData;
/** Walk State datas. */
private final Map<HitoeDevice, WalkStateData> mWalkStateData;
/** Save data for extended analysis. */
private ArrayList<TempExData> mListForEx;
/** Lock for the extension analysis. */
private ReentrantLock mLockForEx;
/** Expanded analysis flag. */
private boolean mFlagForEx;
/** Acceleration's interval. */
private long mInterval = 0;
/** Temporary storage data for pose estimation. */
private ArrayList<String> mListForPosture;
/** Lock for pose estimation. */
private ReentrantLock mLockForPosture;
/** Temporary storage data for walking state estimation. */
private ArrayList<String> mListForWalk;
/** Lock for walking state estimation. */
private ReentrantLock mLockForWalk;
/** Temporary storage data for the left and right balance estimation. */
private ArrayList<String> mListForLRBalance;
/** Lock for the left and right balance estimation. */
private ReentrantLock mLockForLRBalance;
/** Hitoe API Callback. */
HitoeSdkAPI.APICallback mAPICallback = new HitoeSdkAPI.APICallback() {
@Override
public void onResponse(final int apiId, final int responseId, final String responseString) {
final StringBuilder messageTextBuilder = new StringBuilder();
if (BuildConfig.DEBUG) {
Log.d(TAG, "CbCallback:apiId=" + String.valueOf(apiId) + ",responseId="
+ String.valueOf(responseId) + ",resonseObject="
+ responseString.replace(HitoeConstants.BR, HitoeConstants.VB));
}
switch (apiId) {
case HitoeConstants.API_ID_GET_AVAILABLE_SENSOR:
notifyDiscoveryHitoeDevice(responseId, responseString);
break;
case HitoeConstants.API_ID_CONNECT:
notifyConnectHitoeDevice(responseId, responseString);
break;
case HitoeConstants.API_ID_DISCONNECT:
// disconnect sensor
try{
mLockForEx.lock();
mListForEx.clear();
mFlagForEx = false;
}finally {
mLockForEx.unlock();
}
break;
case HitoeConstants.API_ID_GET_AVAILABLE_DATA:
notifyAvailableData(responseId, responseString);
break;
case HitoeConstants.API_ID_ADD_RECIVER:
notifyAddReceiver(responseId, responseString);
break;
case HitoeConstants.API_ID_REMOVE_RECEIVER:
notifyRemoveReceiver(responseId, responseString);
break;
case HitoeConstants.API_ID_GET_STATUS:
break;
default:
if (BuildConfig.DEBUG) {
Log.e(TAG, "etc state");
}
break;
}
}
};
/**
* Data receiver.
*/
HitoeSdkAPI.DataReceiverCallback mDataReceiverCallback = new HitoeSdkAPI.DataReceiverCallback() {
@Override
public void onDataReceive(final String connectionId, final int responseId,
final String dataKey, final String rawData) {
int pos = getPosForConnectionId(connectionId);
if (pos == -1) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "no connectionId");
}
return;
}
HitoeDevice receiveDevice = mRegisterDevices.get(pos);
if (receiveDevice.getSessionId() == null) {
return;
}
if (dataKey.equals("raw.ecg")) {
extractHealth(HeartData.HeartRateType.ECG, rawData, receiveDevice);
} else if (dataKey.equals("raw.acc")) {
analyzeAccelerationData(rawData, receiveDevice);
AccelerationData currentAccel = mAccelData.get(receiveDevice);
if (currentAccel == null) {
currentAccel = new AccelerationData();
}
currentAccel = RawDataParseUtils.parseAccelerationData(currentAccel, rawData);
mAccelData.put(receiveDevice, currentAccel);
} else if (dataKey.equals("raw.rri")) {
extractHealth(HeartData.HeartRateType.RRI, rawData, receiveDevice);
} else if (dataKey.equals("raw.bat")) {
extractBattery(rawData, receiveDevice);
} else if (dataKey.equals("raw.hr")) {
extractHealth(HeartData.HeartRateType.Rate, rawData, receiveDevice);
} else if (dataKey.equals("ba.freq_domain")) {
parseFreqDomain(receiveDevice, rawData);
} else if (dataKey.equals("ex.stress")) {
StressEstimationData stress = RawDataParseUtils.parseStressEstimation(rawData);
mStressEstimationData.put(receiveDevice, stress);
} else if (dataKey.equals("ex.posture")) {
PoseEstimationData pose = RawDataParseUtils.parsePoseEstimation(rawData);
mPoseEstimationData.put(receiveDevice, pose);
} else if (dataKey.equals("ex.walk")) {
WalkStateData walk = mWalkStateData.get(receiveDevice);
if (walk == null) {
walk = new WalkStateData();
}
walk = RawDataParseUtils.parseWalkState(walk, rawData);
mWalkStateData.put(receiveDevice, walk);
} else if (dataKey.equals("ex.lr_balance")) {
WalkStateData walk = mWalkStateData.get(receiveDevice);
if (walk == null) {
walk = new WalkStateData();
}
walk = RawDataParseUtils.parseWalkStateForBalance(walk, rawData);
mWalkStateData.put(receiveDevice, walk);
}
if (dataKey.startsWith(HitoeConstants.EX_DATA_PREFFIX)) {
// Expanded analysis discard the connection
receiveDevice.removeConnectionId(connectionId);
} else {
// Perform any extension
//Do not run if it is already running
TempExData exData = null;
try {
mLockForEx.lock();
if (!mFlagForEx && mListForEx.size() > 0) {
mFlagForEx = true;
exData = mListForEx.get(0);
mListForEx.remove(0);
}
} finally {
mLockForEx.unlock();
}
if (exData != null) {
addExReceiverProcess(pos, exData);
}
}
notifyListeners(receiveDevice);
}
};
/**
* Constructor.
*
* @param context application context
*/
public HitoeManager(final Context context) {
mContext = context;
mDBHelper = new HitoeDBHelper(context);
mListForEx = new ArrayList<>();
mLockForEx = new ReentrantLock();
mRegisterDevices = Collections.synchronizedList(
new ArrayList<HitoeDevice>());
mHRData = new ConcurrentHashMap<>();
mECGData = new ConcurrentHashMap<>();
mPoseEstimationData = new ConcurrentHashMap<>();
mStressEstimationData = new ConcurrentHashMap<>();
mWalkStateData = new ConcurrentHashMap<>();
mAccelData = new ConcurrentHashMap<>();
mConnectionListeners = new ArrayList<>();
mListForPosture = new ArrayList<>();
mLockForPosture = new ReentrantLock();
mListForWalk = new ArrayList<>();
mLockForWalk = new ReentrantLock();
mListForLRBalance = new ArrayList<>();
mLockForLRBalance = new ReentrantLock();
mListForEx = new ArrayList<>();
mLockForEx = new ReentrantLock();
mNowTimestamps = new ConcurrentHashMap<>();
mHitoeSdkAPI = HitoeSdkAPIImpl.getInstance(context);
mHitoeSdkAPI.setAPICallback(mAPICallback);
readHitoeDeviceForDB();
}
// Public Method
/**
* Set Hitoe Connection Listener.
* @param l listener
*/
public void addHitoeConnectionListener(final OnHitoeConnectionListener l) {
mConnectionListeners.add(l);
}
/**
* Remove Hitoe Connection listener.
* @param l connection listener
*/
public void removeHitoeConnectionListener(final OnHitoeConnectionListener l) {
mConnectionListeners.remove(l);
}
/**
* Set Hitoe HeartRate Listener.
* @param l listener
*/
public void setHitoeHeartRateEventListener(final OnHitoeHeartRateEventListener l) {
mHeartRataListener = l;
}
/**
* Set Hitoe Acceleration Listener.
* @param l listener
*/
public void setHitoeDeviceOrientationEventListener(final OnHitoeDeviceOrientationEventListener l) {
mDeviceOrientationListener = l;
}
/**
* Set Hitoe ECG listener.
* @param l listener
*/
public void setHitoeECGEventListener(final OnHitoeECGEventListener l) {
mECGListener = l;
}
/**
* Set Hitoe Pose Estimation listener.
* @param l listener
*/
public void setHitoePoseEstimationEventListener(final OnHitoePoseEstimationEventListener l) {
mPoseEstimationListener = l;
}
/**
* Set Hitoe Stress Estimation listener.
* @param l listener
*/
public void setHitoeStressEstimationEventListener(final OnHitoeStressEstimationEventListener l) {
mStressEstimationListener = l;
}
/**
* Set Hitoe Walk state listener.
* @param l listener
*/
public void setHitoeWalkStateEventListener(final OnHitoeWalkStateEventListener l) {
mWalkStateListener = l;
}
/**
* Gets the list of BLE device that was registered to automatic connection.
*
* @return list of BLE device
*/
public List<HitoeDevice> getRegisterDevices() {
return mRegisterDevices;
}
/**
* Read device info.
*/
public void readHitoeDeviceForDB() {
List<HitoeDevice> list = mDBHelper.getHitoeDevices(null);
for (int i = 0; i < list.size(); i++) {
HitoeDevice device = list.get(i);
if (mRegisterDevices.size() > 0) {
if (!containsDevice(device.getId())) {
mRegisterDevices.add(device);
}
} else {
mRegisterDevices.add(device);
}
}
}
/**
* Get mRegisterDevice for service id.
* @param serviceId service Id
* @return Hitoe Device object
*/
public HitoeDevice getHitoeDeviceForServiceId(final String serviceId) {
for (int i = 0; i < mRegisterDevices.size(); i++) {
if (mRegisterDevices.get(i).getId() != null) {
if (mRegisterDevices.get(i).getId().equals(serviceId)) {
return mRegisterDevices.get(i);
}
}
}
return null;
}
/**
* Get HeartRateData.
* @param serviceId index id
* @return HeartRateData
*/
public HeartRateData getHeartRateData(final String serviceId) {
int pos = getPosForServiceId(serviceId);
if (pos == -1) {
return null;
}
return mHRData.get(mRegisterDevices.get(pos));
}
/**
* Get ECG Data.
* @param serviceId index id
* @return ECGData
*/
public HeartRateData getECGData(final String serviceId) {
int pos = getPosForServiceId(serviceId);
if (pos == -1) {
return null;
}
return mECGData.get(mRegisterDevices.get(pos));
}
/**
* Get Stress Estimation Data.
* @param serviceId index id
* @return StressEstimationData
*/
public StressEstimationData getStressEstimationData(final String serviceId) {
int pos = getPosForServiceId(serviceId);
if (pos == -1) {
return null;
}
return mStressEstimationData.get(mRegisterDevices.get(pos));
}
/**
* Get Pose Estimation Data.
* @param serviceId index id
* @return Pose Estimation Data
*/
public PoseEstimationData getPoseEstimationData(final String serviceId) {
int pos = getPosForServiceId(serviceId);
if (pos == -1) {
return null;
}
return mPoseEstimationData.get(mRegisterDevices.get(pos));
}
/**
* Get Walk State Data.
* @param serviceId index id
* @return Walk State data
*/
public WalkStateData getWalkStateData(final String serviceId) {
int pos = getPosForServiceId(serviceId);
if (pos == -1) {
return null;
}
return mWalkStateData.get(mRegisterDevices.get(pos));
}
/**
* Get AccelerationData.
* @param serviceId index id
* @return AccelerationData
*/
public AccelerationData getAccelerationData(final String serviceId) {
int pos = getPosForServiceId(serviceId);
if (pos == -1) {
return null;
}
return mAccelData.get(mRegisterDevices.get(pos));
}
/**
* Stats the HitoeManager.
*/
public void start() {
synchronized (mRegisterDevices) {
for (int i = 0; i < mRegisterDevices.size(); i++) {
HitoeDevice device = mRegisterDevices.get(i);
if (device.isRegisterFlag()) {
connectHitoeDevice(device);
}
}
}
}
/**
* Stops the HitoeManager.
*/
public void stop() {
for (int i = 0; i < mRegisterDevices.size(); i++) {
mHitoeSdkAPI.disconnect(mRegisterDevices.get(i).getSessionId());
mRegisterDevices.get(i).setRegisterFlag(false);
mDBHelper.updateHitoeDevice(mRegisterDevices.get(i));
mRegisterDevices.get(i).setSessionId(null);
}
scanHitoeDevice(false);
}
/**
* Discovery hitoe device.
*/
public void discoveryHitoeDevices() {
StringBuilder paramStringBuilder = new StringBuilder();
paramStringBuilder.append("search_time=")
.append(String.valueOf(HitoeConstants.GET_AVAILABLE_SENSOR_PARAM_SEARCH_TIME));
mHitoeSdkAPI.getAvailableSensor(HitoeConstants.GET_AVAILABLE_SENSOR_DEVICE_TYPE, paramStringBuilder.toString());
if (mRegisterDevices.size() > 0) {
for (OnHitoeConnectionListener l: mConnectionListeners) {
if (l != null) {
l.onDiscovery(mRegisterDevices);
}
}
}
}
/**
* Connect to Hitoe Device by address.
*
* @param device device for hitoe device
*/
public void connectHitoeDevice(final HitoeDevice device) {
mExecutor.submit(new Runnable() {
@Override
public void run() {
if (device == null || device.getPinCode() == null) {
return;
}
StringBuilder paramBuilder = new StringBuilder();
paramBuilder.append("disconnect_retry_time=" + HitoeConstants.CONNECT_DISCONNECT_RETRY_TIME);
if (paramBuilder.length() > 0) {
paramBuilder.append(HitoeConstants.BR);
}
paramBuilder.append("disconnect_retry_count=" + HitoeConstants.CONNECT_DISCONNECT_RETRY_COUNT);
if (paramBuilder.length() > 0) {
paramBuilder.append(HitoeConstants.BR);
}
paramBuilder.append("nopacket_retry_time=" + HitoeConstants.CONNECT_NOPACKET_RETRY_TIME);
if (paramBuilder.length() > 0) {
paramBuilder.append(HitoeConstants.BR);
}
paramBuilder.append("pincode=");
paramBuilder.append(device.getPinCode());
String param = paramBuilder.toString();
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice remoteDevice = adapter.getRemoteDevice(device.getId());
if (remoteDevice.getName() == null) {
// If RemoteDevice is Null, Discovery process needs to be done once.
// Retry 10 times and continue processing when RemoteDevice is found.
discoveryHitoeDevices();
int i = 0;
for (i = 0; i < CONNECTING_RETRY_COUNT; i++) {
try {
Thread.sleep(CONNECTING_RETRY_WAIT);
} catch (InterruptedException e) {
e.printStackTrace();
}
remoteDevice = adapter.getRemoteDevice(device.getId());
if (remoteDevice.getName() != null) {
break;
}
}
if (i == CONNECTING_RETRY_COUNT && remoteDevice.getName() == null) {
return;
}
}
mHitoeSdkAPI.connect(device.getType(), device.getId(), device.getConnectMode(), param);
device.setResponseId(HitoeConstants.RES_ID_SENSOR_CONNECT);
mDBHelper.addHitoeDevice(device);
mStressEstimationData.put(device, new StressEstimationData());
for (int i = 0; i < mRegisterDevices.size(); i++) {
if (mRegisterDevices.get(i).getId().equals(device.getId())) {
mRegisterDevices.set(i, device);
} else {
mRegisterDevices.get(i).setResponseId(HitoeConstants.RES_ID_SENSOR_DISCONECT_NOTICE);
}
}
}
});
}
/**
* Disconnect hitoe device.
* @param device hitoe device
*/
public void disconnectHitoeDevice(final HitoeDevice device) {
mExecutor.submit(new Runnable() {
@Override
public void run() {
HitoeDevice current = getHitoeDeviceForServiceId(device.getId());
int res = mHitoeSdkAPI.disconnect(current.getSessionId());
current.setRegisterFlag(false);
current.setSessionId(null);
mDBHelper.updateHitoeDevice(current);
if (!existConnected()) {
scanHitoeDevice(false);
}
for (OnHitoeConnectionListener l: mConnectionListeners) {
if (l != null) {
l.onDisconnected(res, device);
}
}
}
});
}
/**
* Delete hitoe device info for db.
* @param device hitoe device
*/
public void deleteHitoeDevice(final HitoeDevice device) {
mDBHelper.removeHitoeDevice(device);
for (int i = 0; i < mRegisterDevices.size(); i++) {
if (mRegisterDevices.get(i).getId().equals(device.getId())) {
HitoeDevice d = mRegisterDevices.remove(i);
for (OnHitoeConnectionListener l: mConnectionListeners) {
if (l != null) {
l.onDeleted(d);
}
}
}
}
}
/**
* Tests whether this mConnectedDevices contains the address.
* @param id address will be checked
* @return true if address is an element of mConnectedDevices, false otherwise
*/
public boolean containConnectedHitoeDevice(final String id) {
synchronized (mRegisterDevices) {
for (HitoeDevice d : mRegisterDevices) {
if (d.getId().equals(id) && d.getSessionId() != null) {
return true;
}
}
}
return false;
}
// Private method
// Notify
/**
* Notify for found Hitoe Devices.
* @param responseId Response id
* @param responseString Response String
*/
private void notifyDiscoveryHitoeDevice(final int responseId, final String responseString) {
if (responseId != HitoeConstants.RES_ID_SUCCESS || responseString == null) {
return;
}
String[] sensorList = responseString.split(HitoeConstants.BR, -1);
List<HitoeDevice> pins = mDBHelper.getHitoeDevices(null);
for (int i = 0; i < sensorList.length; i++) {
String sensorStr = sensorList[i].trim();
if (sensorStr.length() == 0) {
continue;
}
if (!sensorStr.contains("memory_setting") && !sensorStr.contains("memory_get")) {
HitoeDevice device = new HitoeDevice(sensorStr);
if (mRegisterDevices.size() == 0) {
mRegisterDevices.add(device);
}
if (!containsDevice(device.getId())) {
mRegisterDevices.add(device);
}
}
}
for (HitoeDevice pin : pins) {
for (HitoeDevice register: mRegisterDevices) {
if (register.getId().equals(pin.getId())) {
register.setPinCode(pin.getPinCode());
register.setRegisterFlag(pin.isRegisterFlag());
}
}
}
for (OnHitoeConnectionListener l: mConnectionListeners) {
if (l != null) {
l.onDiscovery(mRegisterDevices);
}
}
}
/**
* Notify for connected hitoe devices.
* @param responseId Response id
* @param responseString Response string
*/
private void notifyConnectHitoeDevice(final int responseId, final String responseString) {
int pos = getCurrentPos(responseId);
if (pos == -1) {
for (OnHitoeConnectionListener l: mConnectionListeners) {
if (l != null) {
l.onConnectFailed(null);
}
}
return;
}
if (responseId == HitoeConstants.RES_ID_SENSOR_DISCONECT_NOTICE) {
try{
mLockForEx.lock();
mListForEx.clear();
mFlagForEx = false;
}finally {
mLockForEx.unlock();
}
for (OnHitoeConnectionListener l: mConnectionListeners) {
if (l != null) {
l.onConnectFailed(mRegisterDevices.get(pos));
}
}
return;
} else if (responseId == HitoeConstants.RES_ID_SENSOR_CONNECT_NOTICE) {
for (OnHitoeConnectionListener l: mConnectionListeners) {
l.onConnected(mRegisterDevices.get(pos));
}
return;
} else if (responseId != HitoeConstants.RES_ID_SENSOR_CONNECT) {
for (OnHitoeConnectionListener l: mConnectionListeners) {
if (l != null) {
l.onConnectFailed(mRegisterDevices.get(pos));
}
}
return;
}
mRegisterDevices.get(pos).setSessionId(responseString);
mRegisterDevices.get(pos).setRegisterFlag(true);
mDBHelper.updateHitoeDevice(mRegisterDevices.get(pos));
mHitoeSdkAPI.getAvailableData(mRegisterDevices.get(pos).getSessionId());
mRegisterDevices.get(pos).setResponseId(HitoeConstants.RES_ID_SUCCESS);
for (OnHitoeConnectionListener l: mConnectionListeners) {
if (l != null) {
l.onConnected(mRegisterDevices.get(pos));
}
}
}
/**
* Notify AvailableData.
* @param responseId response id
* @param responseString Response string
*/
private void notifyAvailableData(final int responseId, final String responseString) {
if (responseId != HitoeConstants.RES_ID_SUCCESS || responseString == null) {
return;
}
int pos = getCurrentPos(responseId);
if (pos == -1) {
return;
}
mRegisterDevices.get(pos).setAvailableData(responseString);
List<String> keyList = mRegisterDevices.get(pos).getAvailableRawDataList();
StringBuilder paramStringBuilder = new StringBuilder();
String[] keys = new String[keyList.size()];
String paramString;
for (int i = 0; i < keyList.size(); i++) {
keys[i] = keyList.get(i);
if (keyList.get(i).equals("raw.ecg")) {
if (paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("raw.ecg_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_ECG_SAMPLING_INTERVAL));
} else if (keyList.get(i).equals("raw.acc")) {
if (paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("raw.acc_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_ACC_SAMPLING_INTERVAL));
} else if (keyList.get(i).equals("raw.rri")) {
if (paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("raw.rri_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_RRI_SAMPLING_INTERVAL));
} else if (keyList.get(i).equals("raw.hr")) {
if (paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("raw.hr_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_HR_SAMPLING_INTERVAL));
} else if (keyList.get(i).equals("raw.bat")) {
if (paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("raw.bat_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BAT_SAMPLING_INTERVAL));
}
}
paramString = paramStringBuilder.toString();
mHitoeSdkAPI.addReceiver(mRegisterDevices.get(pos).getSessionId(),
keys, mDataReceiverCallback, paramString, null);
scanHitoeDevice(true);
}
/**
* Notify add receiver.
* @param responseId response id
* @param responseString response string
*/
private void notifyAddReceiver(final int responseId, final String responseString) {
if (responseId != HitoeConstants.RES_ID_SUCCESS || responseString == null) {
mFlagForEx = false;
return;
}
int pos = getCurrentPos(responseId);
if (pos == -1) {
return;
}
mRegisterDevices.get(pos).setConnectionId(responseString);
if (responseString.startsWith(HitoeConstants.RAW_CONNECTION_PREFFIX)) {
addBaReceiverProcess(pos);
} else {
TempExData exData = null;
try {
mLockForEx.lock();
if (mListForEx.size() > 0) {
exData = mListForEx.get(0);
mListForEx.remove(0);
} else {
mFlagForEx = false;
}
} finally {
mLockForEx.unlock();
}
if (exData != null) {
addExReceiverProcess(pos, exData);
}
}
}
/**
* Notify Remove receiver.
* @param responseId response id
* @param responseString response string
*/
private void notifyRemoveReceiver(final int responseId, final String responseString) {
if (responseId != HitoeConstants.RES_ID_SUCCESS || responseString == null) {
return;
}
int pos = getCurrentPos(responseId);
if (pos == -1) {
return;
}
mRegisterDevices.get(pos).setRegisterFlag(false);
mRegisterDevices.get(pos).removeConnectionId(responseString);
mDBHelper.updateHitoeDevice(mRegisterDevices.get(pos));
if (responseString.startsWith(HitoeConstants.BA_CONNECTION_PREFFIX)) {
removeRawReceiverProcess(mRegisterDevices.get(pos).getRawConnectionId());
} else if (responseString.startsWith(HitoeConstants.RAW_CONNECTION_PREFFIX)) {
disconnectProcess(pos);
}
}
/**
* Notify Listeners.
* @param receiveDevice now receive device
*/
private void notifyListeners(final HitoeDevice receiveDevice) {
if (mHeartRataListener != null) {
mHeartRataListener.onReceivedData(receiveDevice, mHRData.get(receiveDevice));
}
if (mECGListener != null) {
mECGListener.onReceivedData(receiveDevice, mHRData.get(receiveDevice));
}
if (mPoseEstimationListener != null) {
mPoseEstimationListener.onReceivedData(receiveDevice, mPoseEstimationData.get(receiveDevice));
}
if (mStressEstimationListener != null) {
mStressEstimationListener.onReceivedData(receiveDevice, mStressEstimationData.get(receiveDevice));
}
if (mWalkStateListener != null) {
mWalkStateListener.onReceivedData(receiveDevice, mWalkStateData.get(receiveDevice));
}
if (mDeviceOrientationListener != null) {
mDeviceOrientationListener.onReceivedData(receiveDevice, mAccelData.get(receiveDevice));
}
if (mECGListener != null) {
mECGListener.onReceivedData(receiveDevice, mECGData.get(receiveDevice));
}
if (mStressEstimationListener != null) {
mStressEstimationListener.onReceivedData(receiveDevice, mStressEstimationData.get(receiveDevice));
}
if (mPoseEstimationListener != null) {
mPoseEstimationListener.onReceivedData(receiveDevice, mPoseEstimationData.get(receiveDevice));
}
}
/**
* Add ba Receiver process.
* @param pos device pos
*/
private void addBaReceiverProcess(final int pos) {
List<String> keyList = mRegisterDevices.get(pos).getAvailableBaDataList();
StringBuilder paramStringBuilder = new StringBuilder();
String[] keys = new String[keyList.size()];
String paramString;
if (keyList.size() == 0) {
return;
}
for (int i = 0; i < keyList.size(); i++) {
keys[i] = keyList.get(i);
if (keyList.get(i).equals("ba.extracted_rri")) {
if (paramStringBuilder.indexOf("ba.sampling_interval") == -1) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.sampling_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_SAMPLING_INTERVAL));
}
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.ecg_threshhold=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_ECG_THRESHHOLD));
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.ecg_skip_count=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_SKIP_COUNT));
} else if (keyList.get(i).equals("ba.cleaned_rri")) {
if (paramStringBuilder.indexOf("ba.sampling_interval") == -1) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.sampling_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_SAMPLING_INTERVAL));
}
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.rri_min=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_RRI_MIN));
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.rri_max=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_RRI_MAX));
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.sample_count=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_SAMPLE_COUNT));
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.rri_input=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_RRI_INPUT));
} else if (keyList.get(i).equals("ba.interpolated_rri")) {
if (paramStringBuilder.indexOf("ba.freq_sampling_interval") == -1) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.freq_sampling_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_FREQ_SAMPLING_INTERVAL));
}
if (paramStringBuilder.indexOf("ba.freq_sampling_window") == -1) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.freq_sampling_window=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_FREQ_SAMPLING_WINDOW));
}
if (paramStringBuilder.indexOf("ba.rri_sampling_rate") == -1) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.rri_sampling_rate=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_RRI_SAMPLING_RATE));
}
} else if (keyList.get(i).equals("ba.freq_domain")) {
if (paramStringBuilder.indexOf("ba.freq_sampling_interval") == -1) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.freq_sampling_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_FREQ_SAMPLING_INTERVAL));
}
if (paramStringBuilder.indexOf("ba.freq_sampling_window") == -1) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.freq_sampling_window=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_FREQ_SAMPLING_WINDOW));
}
if (paramStringBuilder.indexOf("ba.rri_sampling_rate") == -1) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.rri_sampling_rate=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_RRI_SAMPLING_RATE));
}
} else if (keyList.get(i).equals("ba.time_domain")) {
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.time_sampling_interval=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_TIME_SAMPLING_INTERVAL));
if (paramStringBuilder.length() > 0
&& paramStringBuilder.lastIndexOf(HitoeConstants.BR) != paramStringBuilder.length() - 1) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ba.time_sampling_window=")
.append(String.valueOf(HitoeConstants.ADD_RECEIVER_PARAM_BA_TIME_SAMPLING_WINDOW));
}
}
paramString = paramStringBuilder.toString();
int resId = mHitoeSdkAPI.addReceiver(mRegisterDevices.get(pos).getSessionId(),
keys, mDataReceiverCallback, paramString, null);
mRegisterDevices.get(pos).setResponseId(resId);
}
/**
* Register Ex receiver.
* @param pos device pos
* @param exData ex data
*/
private void addExReceiverProcess(final int pos, final TempExData exData) {
String keyString = exData.getKey();
ArrayList<String> dataList = exData.getDataList();
if (!mRegisterDevices.get(pos).getAvailableExDataList().contains(keyString)) {
try {
mLockForEx.lock();
mFlagForEx = false;
} finally {
mLockForEx.unlock();
}
return;
}
int responseId;
String[] keys = new String[1];
keys[0] = keyString;
StringBuilder paramStringBuilder = new StringBuilder();
StringBuilder dataStringBuilder = new StringBuilder();
String paramString;
String dataString;
for (int i = 0; i < dataList.size(); i++) {
if (dataStringBuilder.length() > 0) {
dataStringBuilder.append(HitoeConstants.BR);
}
dataStringBuilder.append(dataList.get(i));
}
if (keyString.equals("ex.posture")) {
if (paramStringBuilder.length() > 0) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ex.acc_axis_xyz=")
.append(HitoeConstants.ADD_RECEIVER_PARAM_EX_ACC_AXIS_XYZ);
if (paramStringBuilder.length() > 0) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ex.posture_window=")
.append(HitoeConstants.ADD_RECEIVER_PARAM_EX_POSTURE_WINDOW);
} else if (keyString.equals("ex.walk")) {
if (paramStringBuilder.length() > 0) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ex.acc_axis_xyz=")
.append(HitoeConstants.ADD_RECEIVER_PARAM_EX_ACC_AXIS_XYZ);
if (paramStringBuilder.length() > 0) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ex.walk_stride=")
.append(HitoeConstants.ADD_RECEIVER_PARAM_EX_WALK_STRIDE);
if (paramStringBuilder.length() > 0) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ex.run_stride_cof=")
.append(HitoeConstants.ADD_RECEIVER_PARAM_EX_RUN_STRIDE_COF);
if (paramStringBuilder.length() > 0) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ex.run_stride_int=")
.append(HitoeConstants.ADD_RECEIVER_PARAM_EX_RUN_STRIDE_INT);
} else if (keyString.equals("ex.lr_balance")) {
if (paramStringBuilder.length() > 0) {
paramStringBuilder.append(HitoeConstants.BR);
}
paramStringBuilder.append("ex.acc_axis_xyz=")
.append(HitoeConstants.ADD_RECEIVER_PARAM_EX_ACC_AXIS_XYZ);
}
paramString = paramStringBuilder.toString();
dataString = dataStringBuilder.toString();
mHitoeSdkAPI.removeReceiver(null);
responseId = mHitoeSdkAPI.addReceiver(null, keys, mDataReceiverCallback, paramString, dataString);
if (responseId != HitoeConstants.RES_ID_SUCCESS) {
try {
mLockForEx.lock();
mFlagForEx = false;
} finally {
mLockForEx.unlock();
}
}
}
/**
* Remove raw receiver process.
* @param rawConnectionId raw connection id
*/
private void removeRawReceiverProcess(final String rawConnectionId) {
if (rawConnectionId == null) {
return;
}
mHitoeSdkAPI.removeReceiver(rawConnectionId);
}
/**
* Disconnect Hitoe device.
* @param pos hitoe devie position
*/
private void disconnectProcess(final int pos) {
if (pos == -1) {
return;
}
HitoeDevice device = mRegisterDevices.get(pos);
if (device.getSessionId() == null) {
return;
}
mRegisterDevices.get(pos).setSessionId(null);
mRegisterDevices.get(pos).setRegisterFlag(false);
mDBHelper.updateHitoeDevice(mRegisterDevices.get(pos));
mHitoeSdkAPI.disconnect(device.getSessionId());
if (mRegisterDevices.size() == 0) {
scanHitoeDevice(false);
}
}
/**
* Get Current register device.
* @param responseId current response id
* @return current register pos
*/
private int getCurrentPos(final int responseId) {
int pos = -1;
for (int i = 0; i < mRegisterDevices.size(); i++) {
if (mRegisterDevices.get(i).getResponseId() == responseId) {
pos = i;
break;
}
}
return pos;
}
/**
* Is exist register device.
* @param id service id
* @return true:exist false: non exist
*/
private boolean containsDevice(final String id) {
boolean isRegister = false;
for (int i = 0; i < mRegisterDevices.size(); i++) {
if (mRegisterDevices.get(i).getId().equals(id)) {
isRegister = true;
}
}
return isRegister;
}
/**
* Get mRegisterDevice's Position for Connection id.
* @param connectionId connection Id
* @return position
*/
private int getPosForConnectionId(final String connectionId) {
int pos = -1;
for (int i = 0; i < mRegisterDevices.size(); i++) {
if (mRegisterDevices.get(i).getRawConnectionId() != null) {
if (mRegisterDevices.get(i).getRawConnectionId().equals(connectionId)) {
pos = i;
break;
}
}
if (mRegisterDevices.get(i).getBaConnectionId() != null) {
if (mRegisterDevices.get(i).getBaConnectionId().equals(connectionId)) {
pos = i;
break;
}
}
if (mRegisterDevices.get(i).getExConnectionList().size() > 0) {
for (int j = 0; j < mRegisterDevices.get(i).getExConnectionList().size(); j++) {
String exConnectionId = mRegisterDevices.get(i).getExConnectionList().get(j);
if (exConnectionId == null) {
continue;
}
if (exConnectionId.equals(connectionId)) {
pos = i;
break;
}
}
}
}
return pos;
}
/**
* Get mRegisterDevice's Position for service id.
* @param serviceId service Id
* @return position
*/
private int getPosForServiceId(final String serviceId) {
int pos = -1;
for (int i = 0; i < mRegisterDevices.size(); i++) {
if (mRegisterDevices.get(i).getId() != null) {
if (mRegisterDevices.get(i).getId().equals(serviceId)) {
pos = i;
break;
}
}
}
return pos;
}
/**
* .
* @param receiveDevice ReceiveDevice
* @param data
*/
private void parseFreqDomain(final HitoeDevice receiveDevice, final String data) {
String[] lineList = data.split(HitoeConstants.BR);
ArrayList<String> stressInputList = new ArrayList<String>();
if (receiveDevice.getAvailableExDataList().contains("ex.stress")) {
for (int i = 0; i < lineList.length; i++) {
stressInputList.add(lineList[i]);
}
try {
mLockForEx.lock();
mListForEx.add(new TempExData("ex.stress", stressInputList));
} finally {
mLockForEx.unlock();
}
}
}
/**
* Extract health data.
* @param type Health data type
* @param rawData raw data
* @param receiveDevice Hitoe device
*/
private void extractHealth(final HeartData.HeartRateType type,
final String rawData, final HitoeDevice receiveDevice) {
HeartRateData currentHeartRate = mHRData.get(receiveDevice);
if (currentHeartRate == null) {
currentHeartRate = new HeartRateData();
}
if (type == HeartData.HeartRateType.Rate) {
HeartData heart = RawDataParseUtils.parseHeartRate(rawData);
currentHeartRate.setHeartRate(heart);
mHRData.put(receiveDevice, currentHeartRate);
} else if (type == HeartData.HeartRateType.RRI) {
HeartData rri = RawDataParseUtils.parseRRI(rawData);
currentHeartRate.setRRInterval(rri);
mHRData.put(receiveDevice, currentHeartRate);
} else if (type == HeartData.HeartRateType.EnergyExpended) {
HeartData energy = RawDataParseUtils.parseEnergyExpended(rawData);
currentHeartRate.setEnergyExpended(energy);
mHRData.put(receiveDevice, currentHeartRate);
} else if (type == HeartData.HeartRateType.ECG) {
HeartData ecg = RawDataParseUtils.parseECG(rawData);
currentHeartRate.setECG(ecg);
mECGData.put(receiveDevice, currentHeartRate);
}
}
/**
* Extract Battery data.
* @param rawData raw data
* @param receiveDevice Hitoe device
*/
private void extractBattery(final String rawData, final HitoeDevice receiveDevice) {
String[] lineList = rawData.split(HitoeConstants.BR);
String levelString = lineList[lineList.length - 1];
String[] level = levelString.split(",", -1);
TargetDeviceData current = RawDataParseUtils.parseDeviceData(receiveDevice,
Float.parseFloat(level[1]));
HeartRateData currentHeartRate = mHRData.get(receiveDevice);
if (currentHeartRate == null) {
currentHeartRate = new HeartRateData();
}
currentHeartRate.setDevice(current);
mHRData.put(receiveDevice, currentHeartRate);
}
/**
* Analyze Acceleration data.
* Get Posture Data, Walk State data, LR Balance data.
* @param rawData raw data
* @param receiveDevice receive device
*/
private void analyzeAccelerationData(final String rawData, final HitoeDevice receiveDevice) {
String[] lineList = rawData.split(HitoeConstants.BR);
ArrayList<String> postureInputList = new ArrayList<String>();
ArrayList<String> walkInputList = new ArrayList<String>();
ArrayList<String> lrBalanceInputList = new ArrayList<String>();
ArrayList<String> workList = new ArrayList<String>();
for (int i = 0; i < lineList.length; i++) {
if (receiveDevice.getAvailableExDataList().contains("ex.posture")) {
try {
mLockForPosture.lock();
mListForPosture.add(lineList[i]);
if (mListForPosture.size() > HitoeConstants.EX_POSTURE_UNIT_NUM + 5) {
for (int j = 0; j < HitoeConstants.EX_POSTURE_UNIT_NUM; j++) {
postureInputList.add(mListForPosture.get(j));
}
for (int j = HitoeConstants.EX_POSTURE_UNIT_NUM;
j < HitoeConstants.EX_POSTURE_UNIT_NUM + 5; j++) {
postureInputList.add(mListForPosture.get(j));
}
workList = new ArrayList<>();
for (int j = 25; j < mListForPosture.size(); j++) {
workList.add(mListForPosture.get(j));
}
mListForPosture = workList;
}
} finally {
mLockForPosture.unlock();
}
if (postureInputList.size() > 0) {
try {
mLockForEx.lock();
mListForEx.add(new TempExData("ex.posture", postureInputList));
} finally {
mLockForEx.unlock();
}
postureInputList.clear();
}
}
if (receiveDevice.getAvailableExDataList().contains("ex.walk")) {
try {
mLockForWalk.lock();
mListForWalk.add(lineList[i]);
if (mListForWalk.size() > HitoeConstants.EX_WALK_UNIT_NUM + 5) {
for (int j = 0; j < HitoeConstants.EX_WALK_UNIT_NUM; j++) {
walkInputList.add(mListForWalk.get(j));
}
for (int j = HitoeConstants.EX_WALK_UNIT_NUM;
j < HitoeConstants.EX_WALK_UNIT_NUM + 5; j++) {
walkInputList.add(mListForWalk.get(j));
}
workList = new ArrayList<>();
for (int j = 25; j < mListForWalk.size(); j++) {
workList.add(mListForWalk.get(j));
}
mListForWalk = workList;
}
} finally {
mLockForWalk.unlock();
}
if (walkInputList.size() > 0) {
try {
mLockForEx.lock();
mListForEx.add(new TempExData("ex.walk", walkInputList));
} finally {
mLockForEx.unlock();
}
walkInputList.clear();
}
}
if (receiveDevice.getAvailableExDataList().contains("ex.lr_balance")) {
try {
mLockForLRBalance.lock();
mListForLRBalance.add(lineList[i]);
if (mListForLRBalance.size() > HitoeConstants.EX_LR_BALANCE_UNIT_NUM + 5) {
for (int j = 0; j < HitoeConstants.EX_LR_BALANCE_UNIT_NUM; j++) {
lrBalanceInputList.add(mListForLRBalance.get(j));
}
for (int j = HitoeConstants.EX_LR_BALANCE_UNIT_NUM;
j < HitoeConstants.EX_LR_BALANCE_UNIT_NUM + 5; j++) {
lrBalanceInputList.add(mListForLRBalance.get(j));
}
workList = new ArrayList<>();
for (int j = 25; j < mListForLRBalance.size(); j++) {
workList.add(mListForLRBalance.get(j));
}
mListForLRBalance = workList;
}
} finally {
mLockForLRBalance.unlock();
}
if (lrBalanceInputList.size() > 0) {
try {
mLockForEx.lock();
mListForEx.add(new TempExData("ex.lr_balance", lrBalanceInputList));
} finally {
mLockForEx.unlock();
}
lrBalanceInputList.clear();
}
}
}
}
/**
* Scan Hitoe device.
* @param enable scan flag
*/
private synchronized void scanHitoeDevice(final boolean enable) {
if (enable) {
if (mScanning || mScanTimerFuture != null) {
// scan have already started.
return;
}
mScanning = true;
mIsCallbackRunning = true;
mNowTimestamps.clear();
for (HitoeDevice heart: mRegisterDevices) {
mNowTimestamps.put(heart, System.currentTimeMillis());
}
mScanTimerFuture = mExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
for (HitoeDevice heart: mHRData.keySet()) {
HeartRateData data = mHRData.get(heart);
long timestamp = data.getHeartRate().getTimeStamp();
long history = mNowTimestamps.get(heart);
if (BuildConfig.DEBUG) {
Log.d(TAG, "================>");
Log.d(TAG, "timestamp:" + timestamp);
Log.d(TAG, "history:" + history);
Log.d(TAG, "CallbackRunning:" + mIsCallbackRunning);
Log.d(TAG, "isRegisterFlag:" + heart.isRegisterFlag());
Log.d(TAG, "<================");
}
if (mIsCallbackRunning && history == timestamp && heart.isRegisterFlag()) {
final String name = heart.getName();
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, "Disconnect to " + name,
Toast.LENGTH_SHORT).show();
}
});
mIsCallbackRunning = false;
} else if (!mIsCallbackRunning && history < timestamp && heart.isRegisterFlag()) {
final String name = heart.getName();
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, "Connect to " + name,
Toast.LENGTH_SHORT).show();
}
});
mIsCallbackRunning = true;
}
mNowTimestamps.put(heart, timestamp);
if (!mIsCallbackRunning && heart.isRegisterFlag()) {
connectHitoeDevice(heart);
}
}
}
}, SCAN_FIRST_WAIT_PERIOD, SCAN_WAIT_PERIOD, TimeUnit.MILLISECONDS);
} else {
mScanning = false;
cancelScanTimer();
}
}
/**
* Stopped the scan timer.
*/
private synchronized void cancelScanTimer() {
if (mScanTimerFuture != null) {
mScanTimerFuture.cancel(true);
mScanTimerFuture = null;
}
}
/**
* Is Exist Disconnected.
* @return true:exist connect, false: non exist connect
*/
private boolean existConnected() {
int connectCount = 0;
for (int i = 0; i < mRegisterDevices.size(); i++) {
if (mRegisterDevices.get(i).isRegisterFlag()) {
connectCount++;
}
}
return (connectCount > 0);
}
// Listener.
/**
* Hitoe Device Discovery Listener.
*/
public interface OnHitoeConnectionListener {
/**
* Connected Device.
* @param device Hitoe device
*/
void onConnected(final HitoeDevice device);
/**
* Connect fail device.
* @param device Hitoe device
*/
void onConnectFailed(final HitoeDevice device);
/**
* Discovery Listener.
* @param devices Found hitoe devices
*/
void onDiscovery(List<HitoeDevice> devices);
/**
* Disconnected Listener.
* @param res response id
* @param device disconnect device
*/
void onDisconnected(final int res, final HitoeDevice device);
/**
* Deleted Listener.
* @param device delte device
*/
void onDeleted(final HitoeDevice device);
}
/**
* Hitoe Device HeartRate Listener.
*/
public interface OnHitoeHeartRateEventListener {
/**
* Received data for Hitoe HeartRate data.
* @param device Hitoe device
* @param data HeartRate data
*/
void onReceivedData(final HitoeDevice device, final HeartRateData data);
}
/**
* Hitoe Device ECG Listener.
*/
public interface OnHitoeECGEventListener {
/**
* Received data for Hitoe ECG Data.
* @param device Hitoe device
* @param data ECG data
*/
void onReceivedData(final HitoeDevice device, final HeartRateData data);
}
/**
* Hitoe Device Pose Estimation Listener.
*/
public interface OnHitoePoseEstimationEventListener {
/**
* Received data for Hitoe Pose estimation data.
* @param device Hitoe device
* @param data pose estimation data
*/
void onReceivedData(final HitoeDevice device, final PoseEstimationData data);
}
/**
* Hitoe Device Stress Estimation Listener.
*/
public interface OnHitoeStressEstimationEventListener {
/**
* Received data for Hitoe Stress Estimation data.
* @param device Hitoe device
* @param data stress estimation data
*/
void onReceivedData(final HitoeDevice device, final StressEstimationData data);
}
/**
* Hitoe Device Walk State Listener.
*/
public interface OnHitoeWalkStateEventListener {
/**
* Received data for Hitoe walk state data.
* @param device Hitoe device
* @param data walk state
*/
void onReceivedData(final HitoeDevice device, final WalkStateData data);
}
/**
* Hitoe Device Device Orientation Listener.
*/
public interface OnHitoeDeviceOrientationEventListener {
/**
* Received data for Hitoe device orientation data.
* @param device Hitoe device
* @param data device orientation
*/
void onReceivedData(final HitoeDevice device, final AccelerationData data);
}
}
|
package org.hisp.dhis.analytics.event.data;
import static org.hisp.dhis.common.DimensionalObject.ORGUNIT_DIM_ID;
import static org.hisp.dhis.common.DimensionalObject.PERIOD_DIM_ID;
import static org.hisp.dhis.common.DimensionalObjectUtils.getDimensionalItemIds;
import static org.hisp.dhis.common.DimensionalObjectUtils.asTypedList;
import static org.hisp.dhis.organisationunit.OrganisationUnit.getParentGraphMap;
import static org.hisp.dhis.organisationunit.OrganisationUnit.getParentNameGraphMap;
import static org.hisp.dhis.analytics.DataQueryParams.NUMERATOR_ID;
import static org.hisp.dhis.analytics.DataQueryParams.DENOMINATOR_ID;
import static org.hisp.dhis.analytics.DataQueryParams.FACTOR_ID;
import static org.hisp.dhis.analytics.DataQueryParams.VALUE_ID;
import static org.hisp.dhis.analytics.DataQueryParams.NUMERATOR_HEADER_NAME;
import static org.hisp.dhis.analytics.DataQueryParams.DENOMINATOR_HEADER_NAME;
import static org.hisp.dhis.analytics.DataQueryParams.FACTOR_HEADER_NAME;
import static org.hisp.dhis.analytics.DataQueryParams.VALUE_HEADER_NAME;
import static org.hisp.dhis.common.IdentifiableObjectUtils.getLocalPeriodIdentifiers;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hisp.dhis.analytics.AnalyticsMetaDataKey;
import org.hisp.dhis.analytics.AnalyticsSecurityManager;
import org.hisp.dhis.analytics.DataQueryParams;
import org.hisp.dhis.analytics.Rectangle;
import org.hisp.dhis.analytics.event.EventAnalyticsManager;
import org.hisp.dhis.analytics.event.EventAnalyticsService;
import org.hisp.dhis.analytics.event.EventDataQueryService;
import org.hisp.dhis.analytics.event.EventQueryParams;
import org.hisp.dhis.analytics.event.EventQueryPlanner;
import org.hisp.dhis.calendar.Calendar;
import org.hisp.dhis.common.AnalyticalObject;
import org.hisp.dhis.common.DimensionType;
import org.hisp.dhis.common.DimensionalItemObject;
import org.hisp.dhis.common.DimensionalObject;
import org.hisp.dhis.common.DisplayProperty;
import org.hisp.dhis.common.EventAnalyticalObject;
import org.hisp.dhis.common.Grid;
import org.hisp.dhis.common.GridHeader;
import org.hisp.dhis.common.IdentifiableObjectUtils;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.common.NameableObjectUtils;
import org.hisp.dhis.common.Pager;
import org.hisp.dhis.common.QueryItem;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.system.database.DatabaseInfo;
import org.hisp.dhis.system.grid.ListGrid;
import org.hisp.dhis.user.User;
import org.hisp.dhis.util.Timer;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author Lars Helge Overland
*/
public class DefaultEventAnalyticsService
implements EventAnalyticsService
{
@Autowired
private EventAnalyticsManager analyticsManager;
@Autowired
private EventDataQueryService eventDataQueryService;
@Autowired
private AnalyticsSecurityManager securityManager;
@Autowired
private EventQueryPlanner queryPlanner;
@Autowired
private DatabaseInfo databaseInfo;
// EventAnalyticsService implementation
// TODO use ValueType for type in grid headers
// TODO use [longitude/latitude] format for event points
// TODO order event analytics tables on execution date to avoid default sort
// TODO sorting in queries
@Override
public Grid getAggregatedEventData( EventQueryParams params )
{
securityManager.decideAccess( params );
queryPlanner.validate( params );
params.removeProgramIndicatorItems(); // Not supported as items for aggregate
Grid grid = new ListGrid();
int maxLimit = queryPlanner.getMaxLimit();
// Headers and data
if ( !params.isSkipData() )
{
// Headers
if ( params.isCollapseDataDimensions() || params.isAggregateData() )
{
grid.addHeader( new GridHeader( DimensionalObject.DATA_COLLAPSED_DIM_ID, DataQueryParams.DISPLAY_NAME_DATA_X, ValueType.TEXT, String.class.getName(), false, true ) );
}
else
{
for ( QueryItem item : params.getItems() )
{
String legendSet = item.hasLegendSet() ? item.getLegendSet().getUid() : null;
grid.addHeader( new GridHeader( item.getItem().getUid(), item.getItem().getName(), item.getValueType(), item.getTypeAsString(), false, true, item.getOptionSetUid(), legendSet ) );
}
}
for ( DimensionalObject dimension : params.getDimensions() )
{
grid.addHeader( new GridHeader( dimension.getDimension(), dimension.getDisplayName(), ValueType.TEXT, String.class.getName(), false, true ) );
}
grid.addHeader( new GridHeader( VALUE_ID, VALUE_HEADER_NAME, ValueType.NUMBER, Double.class.getName(), false, false ) );
if ( params.isIncludeNumDen() )
{
grid.addHeader( new GridHeader( NUMERATOR_ID, NUMERATOR_HEADER_NAME, ValueType.NUMBER, Double.class.getName(), false, false ) )
.addHeader( new GridHeader( DENOMINATOR_ID, DENOMINATOR_HEADER_NAME, ValueType.NUMBER, Double.class.getName(), false, false ) )
.addHeader( new GridHeader( FACTOR_ID, FACTOR_HEADER_NAME, ValueType.NUMBER, Double.class.getName(), false, false ) );
}
// Data
Timer timer = new Timer().start().disablePrint();
List<EventQueryParams> queries = queryPlanner.planAggregateQuery( params );
timer.getSplitTime( "Planned event query, got partitions: " + params.getPartitions() );
for ( EventQueryParams query : queries )
{
analyticsManager.getAggregatedEventData( query, grid, maxLimit );
}
timer.getTime( "Got aggregated events" );
if ( maxLimit > 0 && grid.getHeight() > maxLimit )
{
throw new IllegalQueryException( "Number of rows produced by query is larger than the max limit: " + maxLimit );
}
// Limit and sort, done again due to potential multiple partitions
if ( params.hasSortOrder() )
{
grid.sortGrid( 1, params.getSortOrderAsInt() );
}
if ( params.hasLimit() && grid.getHeight() > params.getLimit() )
{
grid.limitGrid( params.getLimit() );
}
}
addMetadata( params, grid );
return grid;
}
@Override
public Grid getAggregatedEventData( AnalyticalObject object )
{
EventQueryParams params = eventDataQueryService.getFromAnalyticalObject( (EventAnalyticalObject) object );
return getAggregatedEventData( params );
}
@Override
public Grid getEvents( EventQueryParams params )
{
securityManager.decideAccessEventQuery( params );
queryPlanner.validate( params );
params.replacePeriodsWithStartEndDates();
Grid grid = new ListGrid();
// Headers
grid.addHeader( new GridHeader( ITEM_EVENT, "Event", ValueType.TEXT, String.class.getName(), false, true ) )
.addHeader( new GridHeader( ITEM_PROGRAM_STAGE, "Program stage", ValueType.TEXT, String.class.getName(), false, true ) )
.addHeader( new GridHeader( ITEM_EXECUTION_DATE, "Event date", ValueType.TEXT, String.class.getName(), false, true ) )
.addHeader( new GridHeader( ITEM_LONGITUDE, "Longitude", ValueType.NUMBER, Double.class.getName(), false, true ) )
.addHeader( new GridHeader( ITEM_LATITUDE, "Latitude", ValueType.NUMBER, Double.class.getName(), false, true ) )
.addHeader( new GridHeader( ITEM_ORG_UNIT_NAME, "Organisation unit name", ValueType.TEXT, String.class.getName(), false, true ) )
.addHeader( new GridHeader( ITEM_ORG_UNIT_CODE, "Organisation unit code", ValueType.TEXT, String.class.getName(), false, true ) );
for ( DimensionalObject dimension : params.getDimensions() )
{
grid.addHeader( new GridHeader( dimension.getDimension(), dimension.getDisplayName(), ValueType.TEXT, String.class.getName(), false, true ) );
}
for ( QueryItem item : params.getItems() )
{
grid.addHeader( new GridHeader( item.getItem().getUid(), item.getItem().getName(), item.getValueType(), item.getTypeAsString(), false, true, item.getOptionSetUid(), item.getLegendSetUid() ) );
}
// Data
Timer timer = new Timer().start().disablePrint();
params = queryPlanner.planEventQuery( params );
timer.getSplitTime( "Planned event query, got partitions: " + params.getPartitions() );
long count = 0;
if ( params.getPartitions().hasAny() )
{
if ( params.isPaging() )
{
count += analyticsManager.getEventCount( params );
}
analyticsManager.getEvents( params, grid, queryPlanner.getMaxLimit() );
timer.getTime( "Got events " + grid.getHeight() );
}
// Meta-data
Map<String, Object> metaData = new HashMap<>();
metaData.put( AnalyticsMetaDataKey.NAMES.getKey(), getUidNameMap( params ) );
User user = securityManager.getCurrentUser( params );
Collection<OrganisationUnit> roots = user != null ? user.getOrganisationUnits() : null;
if ( params.isHierarchyMeta() )
{
Map<String, String> parentMap = getParentGraphMap( asTypedList( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) ), roots );
metaData.put( AnalyticsMetaDataKey.ORG_UNIT_HIERARCHY.getKey(), parentMap );
}
if ( params.isPaging() )
{
Pager pager = new Pager( params.getPageWithDefault(), count, params.getPageSizeWithDefault() );
metaData.put( AnalyticsMetaDataKey.PAGER.getKey(), pager );
}
return grid.setMetaData( metaData );
}
@Override
public Grid getEventClusters( EventQueryParams params )
{
if ( !databaseInfo.isSpatialSupport() )
{
throw new IllegalQueryException( "Spatial database support is not enabled" );
}
params = new EventQueryParams.Builder( params )
.withGeometryOnly( true )
.build();
securityManager.decideAccess( params );
queryPlanner.validate( params );
params.replacePeriodsWithStartEndDates();
Grid grid = new ListGrid();
// Headers
grid.addHeader( new GridHeader( ITEM_COUNT, "Count", ValueType.NUMBER, Long.class.getName(), false, false ) )
.addHeader( new GridHeader( ITEM_CENTER, "Center", ValueType.TEXT, String.class.getName(), false, false ) )
.addHeader( new GridHeader( ITEM_EXTENT, "Extent", ValueType.TEXT, String.class.getName(), false, false ) )
.addHeader( new GridHeader( ITEM_POINTS, "Points", ValueType.TEXT, String.class.getName(), false, false ) );
// Data
params = queryPlanner.planEventQuery( params );
analyticsManager.getEventClusters( params, grid, queryPlanner.getMaxLimit() );
return grid;
}
@Override
public Rectangle getRectangle( EventQueryParams params )
{
if ( !databaseInfo.isSpatialSupport() )
{
throw new IllegalQueryException( "Spatial database support is not enabled" );
}
params = new EventQueryParams.Builder( params )
.withGeometryOnly( true )
.build();
securityManager.decideAccess( params );
queryPlanner.validate( params );
params.replacePeriodsWithStartEndDates();
params = queryPlanner.planEventQuery( params );
return analyticsManager.getRectangle( params );
}
// Supportive methods
/**
* Adds meta data values to the given grid based on the given data query
* parameters.
*
* @param params the data query parameters.
* @param grid the grid.
*/
private void addMetadata( EventQueryParams params, Grid grid )
{
if ( !params.isSkipMeta() )
{
Calendar calendar = PeriodType.getCalendar();
List<String> periodUids = calendar.isIso8601() ?
getDimensionalItemIds( params.getDimensionOrFilterItems( PERIOD_DIM_ID ) ) :
getLocalPeriodIdentifiers( params.getDimensionOrFilterItems( PERIOD_DIM_ID ), calendar );
Map<String, Object> metaData = new HashMap<>();
metaData.put( AnalyticsMetaDataKey.NAMES.getKey(), getUidNameMap( params ) );
metaData.put( PERIOD_DIM_ID, periodUids );
for ( DimensionalObject dim : params.getDimensionsAndFilters() )
{
if ( !metaData.keySet().contains( dim.getDimension() ) )
{
metaData.put( dim.getDimension(), getDimensionalItemIds( dim.getItems() ) );
}
}
for ( QueryItem item : params.getItemsAndItemFilters() )
{
if ( item.hasLegendSet() )
{
metaData.put( item.getItemId(), IdentifiableObjectUtils.getUids( item.getLegendSet().getLegends() ) );
}
}
User user = securityManager.getCurrentUser( params );
List<OrganisationUnit> organisationUnits = asTypedList( params.getDimensionOrFilterItems( ORGUNIT_DIM_ID ) );
Collection<OrganisationUnit> roots = user != null ? user.getOrganisationUnits() : null;
if ( params.isHierarchyMeta() )
{
metaData.put( AnalyticsMetaDataKey.ORG_UNIT_HIERARCHY.getKey(), getParentGraphMap( organisationUnits, roots ) );
}
if ( params.isShowHierarchy() )
{
metaData.put( AnalyticsMetaDataKey.ORG_UNIT_NAME_HIERARCHY.getKey(), getParentNameGraphMap( organisationUnits, roots, true ) );
}
grid.setMetaData( metaData );
}
}
private Map<String, String> getUidNameMap( EventQueryParams params )
{
Map<String, String> map = new HashMap<>();
Program program = params.getProgram();
ProgramStage stage = params.getProgramStage();
map.put( program.getUid(), program.getDisplayProperty( params.getDisplayProperty() ) );
if ( stage != null )
{
map.put( stage.getUid(), stage.getName() );
}
else
{
for ( ProgramStage st : program.getProgramStages() )
{
map.put( st.getUid(), st.getName() );
}
}
if ( params.hasValueDimension() )
{
map.put( params.getValue().getUid(), params.getValue().getDisplayProperty( params.getDisplayProperty() ) );
}
map.putAll( getUidNameMap( params.getItems(), params.getDisplayProperty() ) );
map.putAll( getUidNameMap( params.getItemFilters(), params.getDisplayProperty() ) );
map.putAll( getUidNameMap( params.getDimensions(), params.isHierarchyMeta(), params.getDisplayProperty() ) );
map.putAll( getUidNameMap( params.getFilters(), params.isHierarchyMeta(), params.getDisplayProperty() ) );
map.putAll( IdentifiableObjectUtils.getUidNameMap( params.getLegends() ) );
return map;
}
private Map<String, String> getUidNameMap( List<QueryItem> queryItems, DisplayProperty displayProperty )
{
Map<String, String> map = new HashMap<>();
for ( QueryItem item : queryItems )
{
map.put( item.getItem().getUid(), item.getItem().getDisplayProperty( displayProperty ) );
}
return map;
}
private Map<String, String> getUidNameMap( List<DimensionalObject> dimensions, boolean hierarchyMeta, DisplayProperty displayProperty )
{
Map<String, String> map = new HashMap<>();
for ( DimensionalObject dimension : dimensions )
{
boolean hierarchy = hierarchyMeta && DimensionType.ORGANISATION_UNIT.equals( dimension.getDimensionType() );
for ( DimensionalItemObject object : dimension.getItems() )
{
Set<DimensionalItemObject> objects = new HashSet<>();
objects.add( object );
if ( hierarchy )
{
OrganisationUnit unit = (OrganisationUnit) object;
objects.addAll( unit.getAncestors() );
}
map.putAll( NameableObjectUtils.getUidDisplayPropertyMap( objects, displayProperty ) );
}
map.put( dimension.getDimension(), dimension.getDisplayProperty( displayProperty ) );
}
return map;
}
}
|
package com.intellij.diagnostic;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* @author yole
*/
public class ThreadDumper {
private static final Comparator<ThreadInfo> THREAD_INFO_COMPARATOR =
Comparator.comparing((ThreadInfo o1) -> isEDT(o1.getThreadName()))
.thenComparing(o -> o.getThreadState() == Thread.State.RUNNABLE)
.thenComparingInt(o -> o.getStackTrace().length)
.reversed();
private ThreadDumper() {
}
@NotNull
public static String dumpThreadsToString() {
StringWriter writer = new StringWriter();
dumpThreadInfos(getThreadInfos(ManagementFactory.getThreadMXBean()), writer);
return writer.toString();
}
@NotNull
public static String dumpEdtStackTrace(ThreadInfo[] threadInfos) {
StringWriter writer = new StringWriter();
if (threadInfos.length > 0) {
StackTraceElement[] trace = threadInfos[0].getStackTrace();
printStackTrace(writer, trace);
}
return writer.toString();
}
@NotNull
public static ThreadInfo[] getThreadInfos() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
return sort(threadMXBean.dumpAllThreads(false, false));
}
@NotNull
public static ThreadDump getThreadDumpInfo(@NotNull final ThreadMXBean threadMXBean) {
StringWriter writer = new StringWriter();
ThreadInfo[] threadInfos = getThreadInfos(threadMXBean);
StackTraceElement[] edtStack = dumpThreadInfos(threadInfos, writer);
return new ThreadDump(writer.toString(), edtStack, threadInfos);
}
@NotNull
private static ThreadInfo[] getThreadInfos(@NotNull ThreadMXBean threadMXBean) {
ThreadInfo[] threads;
try {
threads = sort(threadMXBean.dumpAllThreads(false, false));
}
catch (Exception ignored) {
threads = sort(threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), Integer.MAX_VALUE));
}
return threads;
}
public static boolean isEDT(@NotNull ThreadInfo info) {
return isEDT(info.getThreadName());
}
public static boolean isEDT(@NotNull String threadName) {
return threadName.startsWith("AWT-EventQueue");
}
private static StackTraceElement[] dumpThreadInfos(@NotNull ThreadInfo[] threadInfo, @NotNull Writer f) {
StackTraceElement[] edtStack = null;
for (ThreadInfo info : threadInfo) {
if (info != null) {
if (isEDT(info)) {
edtStack = info.getStackTrace();
}
dumpThreadInfo(info, f);
}
}
return edtStack;
}
@NotNull
private static ThreadInfo[] sort(@NotNull ThreadInfo[] threads) {
Arrays.sort(threads, THREAD_INFO_COMPARATOR);
return threads;
}
private static void dumpThreadInfo(@NotNull ThreadInfo info, @NotNull Writer f) {
dumpCallStack(info, f, info.getStackTrace());
}
private static void dumpCallStack(@NotNull ThreadInfo info, @NotNull Writer f, @NotNull StackTraceElement[] stackTraceElements) {
try {
@NonNls StringBuilder sb = new StringBuilder("\"").append(info.getThreadName()).append("\"");
sb.append(" prio=0 tid=0x0 nid=0x0 ").append(getReadableState(info.getThreadState())).append("\n");
sb.append(" java.lang.Thread.State: ").append(info.getThreadState()).append("\n");
if (info.getLockName() != null) {
sb.append(" on ").append(info.getLockName());
}
if (info.getLockOwnerName() != null) {
sb.append(" owned by \"").append(info.getLockOwnerName()).append("\" Id=").append(info.getLockOwnerId());
}
if (info.isSuspended()) {
sb.append(" (suspended)");
}
if (info.isInNative()) {
sb.append(" (in native)");
}
f.write(sb + "\n");
printStackTrace(f, stackTraceElements);
f.write("\n");
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void dumpCallStack(@NotNull Thread thread, @NotNull Writer f, @NotNull StackTraceElement[] stackTraceElements) {
try {
@NonNls StringBuilder sb = new StringBuilder("\"").append(thread.getName()).append("\"");
sb.append(" prio=0 tid=0x0 nid=0x0 ").append(getReadableState(thread.getState())).append("\n");
sb.append(" java.lang.Thread.State: ").append(thread.getState()).append("\n");
f.write(sb + "\n");
printStackTrace(f, stackTraceElements);
f.write("\n");
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void printStackTrace(@NotNull Writer f, @NotNull StackTraceElement[] stackTraceElements) {
try {
for (StackTraceElement element : stackTraceElements) {
f.write("\tat " + element + "\n");
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Returns the EDT stack in a form that Google Crash understands, or null if the EDT stack cannot be determined.
*
* @param fullThreadDump lines comprising a thread dump as formatted by {@link #dumpCallStack(ThreadInfo, Writer, StackTraceElement[])}
*/
@Nullable
public static String getEdtStackForCrash(@NotNull String fullThreadDump, @NotNull String exceptionType) {
// We know that the AWT-EventQueue-* thread is dumped out first (see #sort above), and for each thread, there are at the very least
// 3 lines printed out before the stack trace. If we don't see any of this, then return early
List<String> threadDump = Arrays.asList(fullThreadDump.split("\n"));
if (threadDump.size() < 3) {
return null;
}
String line = threadDump.get(0); // e.g. "AWT-EventQueue-0 ...
int i = line.indexOf(' ');
if (i <= 1) {
return null;
}
StringBuilder sb = new StringBuilder(200);
sb.append(exceptionType + ": ");
sb.append(line.substring(1, i)); // append thread name (e.g. AWT-EventQueue-0)
line = threadDump.get(1); // e.g. " java.lang.Thread.State: RUNNABLE"
String[] words = line.trim().split(" ");
if (words.length < 2) {
return null;
}
sb.append(' ');
sb.append(words[1]); // e.g. "RUNNABLE"
// the 3rd line contains lock information (or is empty)
line = threadDump.get(2);
if (!line.trim().isEmpty()) {
sb.append(' ');
sb.append(line.trim());
}
sb.append('\n');
// the rest of the lines correspond to the stack trace until we reach an empty line
for (i = 3; i < threadDump.size(); i++) {
line = threadDump.get(i);
if (line.trim().isEmpty()) {
break;
}
sb.append(line);
sb.append('\n');
}
return sb.toString().trim();
}
private static String getReadableState(@NotNull Thread.State state) {
switch (state) {
case BLOCKED: return "blocked";
case TIMED_WAITING:
case WAITING: return "waiting on condition";
case RUNNABLE: return "runnable";
case NEW: return "new";
case TERMINATED: return "terminated";
}
return null;
}
}
|
package org.hisp.dhis.program.notification;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.DeliveryChannel;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.message.MessageConversationParams;
import org.hisp.dhis.message.MessageService;
import org.hisp.dhis.message.MessageType;
import org.hisp.dhis.notification.NotificationMessage;
import org.hisp.dhis.notification.NotificationMessageRenderer;
import org.hisp.dhis.notification.SendStrategy;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.program.ProgramInstance;
import org.hisp.dhis.program.ProgramInstanceStore;
import org.hisp.dhis.program.ProgramStageInstance;
import org.hisp.dhis.program.ProgramStageInstanceStore;
import org.hisp.dhis.program.message.ProgramMessage;
import org.hisp.dhis.program.message.ProgramMessageRecipients;
import org.hisp.dhis.program.message.ProgramMessageService;
import org.hisp.dhis.outboundmessage.BatchResponseStatus;
import org.hisp.dhis.programrule.ProgramRule;
import org.hisp.dhis.programrule.engine.ProgramRuleEngine;
import org.hisp.dhis.rules.models.RuleAction;
import org.hisp.dhis.rules.models.RuleActionAssign;
import org.hisp.dhis.rules.models.RuleEffect;
import org.hisp.dhis.system.util.Clock;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue;
import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue;
import org.hisp.dhis.user.User;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nullable;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Halvdan Hoem Grelland
*/
public class DefaultProgramNotificationService
implements ProgramNotificationService
{
private static final Log log = LogFactory.getLog( DefaultProgramNotificationService.class );
// Dependencies
private ProgramMessageService programMessageService;
public void setProgramMessageService( ProgramMessageService programMessageService )
{
this.programMessageService = programMessageService;
}
private MessageService messageService;
public void setMessageService( MessageService messageService )
{
this.messageService = messageService;
}
private ProgramInstanceStore programInstanceStore;
public void setProgramInstanceStore( ProgramInstanceStore programInstanceStore )
{
this.programInstanceStore = programInstanceStore;
}
private ProgramStageInstanceStore programStageInstanceStore;
public void setProgramStageInstanceStore( ProgramStageInstanceStore programStageInstanceStore )
{
this.programStageInstanceStore = programStageInstanceStore;
}
private IdentifiableObjectManager identifiableObjectManager;
public void setIdentifiableObjectManager( IdentifiableObjectManager identifiableObjectManager )
{
this.identifiableObjectManager = identifiableObjectManager;
}
private NotificationMessageRenderer<ProgramInstance> programNotificationRenderer;
public void setProgramNotificationRenderer( NotificationMessageRenderer<ProgramInstance> programNotificationRenderer )
{
this.programNotificationRenderer = programNotificationRenderer;
}
private NotificationMessageRenderer<ProgramStageInstance> programStageNotificationRenderer;
public void setProgramStageNotificationRenderer( NotificationMessageRenderer<ProgramStageInstance> programStageNotificationRenderer )
{
this.programStageNotificationRenderer = programStageNotificationRenderer;
}
private ProgramRuleEngine programRuleEngine;
public void setProgramRuleEngine( ProgramRuleEngine programRuleEngine )
{
this.programRuleEngine = programRuleEngine;
}
// ProgramStageNotificationService implementation
@Transactional
@Override
public void sendScheduledNotificationsForDay( Date notificationDate )
{
Clock clock = new Clock( log ).startClock()
.logTime( "Processing ProgramStageNotification messages" );
List<ProgramNotificationTemplate> scheduledTemplates = getScheduledTemplates();
int totalMessageCount = 0;
for ( ProgramNotificationTemplate template : scheduledTemplates )
{
MessageBatch batch = createScheduledMessageBatchForDay( template, notificationDate );
sendAll( batch );
totalMessageCount += batch.messageCount();
}
clock.logTime( String.format( "Created and sent %d messages in %s", totalMessageCount, clock.time() ) );
}
@Transactional
@Override
public void sendCompletionNotifications( ProgramStageInstance programStageInstance )
{
sendProgramStageInstanceNotifications( programStageInstance, NotificationTrigger.COMPLETION );
}
@Transactional
@Override
public void sendCompletionNotifications( ProgramInstance programInstance )
{
sendProgramInstanceNotifications( programInstance, NotificationTrigger.COMPLETION );
}
@Transactional
@Override
public void sendEnrollmentNotifications( ProgramInstance programInstance )
{
sendProgramInstanceNotifications( programInstance, NotificationTrigger.ENROLLMENT );
}
@Transactional
@Override
public void sendProgramRuleTriggeredNotifications( ProgramInstance programInstance )
{
sendProgramInstanceNotifications( programInstance, NotificationTrigger.PROGRAM_RULE );
}
@Transactional
@Override
public void sendProgramRuleTriggeredNotifications( ProgramStageInstance programStageInstance )
{
sendProgramStageInstanceNotifications( programStageInstance, NotificationTrigger.PROGRAM_RULE );
}
// Supportive methods
private MessageBatch createScheduledMessageBatchForDay( ProgramNotificationTemplate template, Date day )
{
List<ProgramStageInstance> programStageInstances =
programStageInstanceStore.getWithScheduledNotifications( template, day );
List<ProgramInstance> programInstances =
programInstanceStore.getWithScheduledNotifications( template, day );
MessageBatch psiBatch = createProgramStageInstanceMessageBatch( template, programStageInstances );
MessageBatch psBatch = createProgramInstanceMessageBatch( template, programInstances );
return new MessageBatch( psiBatch, psBatch );
}
private List<ProgramNotificationTemplate> getScheduledTemplates()
{
return identifiableObjectManager.getAll( ProgramNotificationTemplate.class ).stream()
.filter( n -> n.getNotificationTrigger().isScheduled() )
.collect( Collectors.toList() );
}
private void sendProgramStageInstanceNotifications( ProgramStageInstance programStageInstance, NotificationTrigger trigger )
{
Set<ProgramNotificationTemplate> templates = resolveTemplates( programStageInstance, trigger );
if ( templates.isEmpty() )
{
return;
}
Map<NotificationTrigger, Set<ProgramNotificationTemplate>> segregatedMap = segregateTemplates( templates );
// send event complete notifications
for ( ProgramNotificationTemplate t : segregatedMap.get( NotificationTrigger.COMPLETION ) )
{
MessageBatch batch = createProgramStageInstanceMessageBatch( t, Lists.newArrayList( programStageInstance ) );
sendAll( batch );
}
Set<ProgramNotificationTemplate> pnts = segregatedMap.get( NotificationTrigger.PROGRAM_RULE );
if ( pnts != null && !pnts.isEmpty() )
{
triggerRuleEngineForEvent( programStageInstance );
}
}
private void triggerRuleEngineForEvent( ProgramStageInstance programStageInstance )
{
List<RuleEffect> ruleEffects = programRuleEngine.evaluateEvent( programStageInstance );
List<RuleAction> ruleActions = ruleEffects.stream().map( RuleEffect::ruleAction ).collect( Collectors.toList() );
//TODO look for RuleActionSendMessage and send PNT
}
private void triggerRuleEngineForEnrollment( ProgramInstance programInstance )
{
List<RuleEffect> ruleEffects = programRuleEngine.evaluateEnrollment( programInstance );
List<RuleAction> ruleActions = ruleEffects.stream().map( RuleEffect::ruleAction ).collect( Collectors.toList() );
//TODO look for RuleActionSendMessage and send PNT
}
private Map<NotificationTrigger, Set<ProgramNotificationTemplate>> segregateTemplates( Set<ProgramNotificationTemplate> programNotificationTemplates )
{
Map<NotificationTrigger, Set<ProgramNotificationTemplate>> segregatedMap = new HashMap<>();
for ( ProgramNotificationTemplate pnt : programNotificationTemplates )
{
if ( NotificationTrigger.COMPLETION.equals( pnt.getNotificationTrigger() ) )
{
segregatedMap.computeIfAbsent( NotificationTrigger.COMPLETION, k -> Sets.newHashSet() )
.add( pnt );
}
if ( NotificationTrigger.PROGRAM_RULE.equals( pnt.getNotificationTrigger() ) )
{
segregatedMap.computeIfAbsent( NotificationTrigger.PROGRAM_RULE, k -> Sets.newHashSet() )
.add( pnt );
}
}
return segregatedMap;
}
private void sendProgramInstanceNotifications( ProgramInstance programInstance, NotificationTrigger trigger )
{
Set<ProgramNotificationTemplate> templates = resolveTemplates( programInstance, trigger );
if ( templates.isEmpty() )
{
return;
}
Map<NotificationTrigger, Set<ProgramNotificationTemplate>> segregatedMap = segregateTemplates( templates );
// send event complete notifications
for ( ProgramNotificationTemplate t : segregatedMap.get( NotificationTrigger.COMPLETION ) )
{
MessageBatch batch = createProgramInstanceMessageBatch( t, Lists.newArrayList( programInstance ) );
sendAll( batch );
}
Set<ProgramNotificationTemplate> pnts = segregatedMap.get( NotificationTrigger.PROGRAM_RULE );
if ( pnts != null && !pnts.isEmpty() )
{
triggerRuleEngineForEnrollment( programInstance );
}
}
private MessageBatch createProgramStageInstanceMessageBatch( ProgramNotificationTemplate template, List<ProgramStageInstance> programStageInstances )
{
MessageBatch batch = new MessageBatch();
if ( template.getNotificationRecipient().isExternalRecipient() )
{
batch.programMessages.addAll(
programStageInstances.stream()
.map( psi -> createProgramMessage( psi, template ) )
.collect( Collectors.toSet() )
);
}
else
{
batch.dhisMessages.addAll(
programStageInstances.stream()
.map( psi -> createDhisMessage( psi, template ) )
.collect( Collectors.toSet() )
);
}
return batch;
}
private MessageBatch createProgramInstanceMessageBatch( ProgramNotificationTemplate template, List<ProgramInstance> programInstances )
{
MessageBatch batch = new MessageBatch();
if ( template.getNotificationRecipient().isExternalRecipient() )
{
batch.programMessages.addAll(
programInstances.stream()
.map( pi -> createProgramMessage( pi, template ) )
.collect( Collectors.toSet() )
);
}
else
{
batch.dhisMessages.addAll(
programInstances.stream()
.map( ps -> createDhisMessage( ps, template ) )
.collect( Collectors.toSet() )
);
}
return batch;
}
private ProgramMessage createProgramMessage( ProgramStageInstance psi, ProgramNotificationTemplate template )
{
NotificationMessage message = programStageNotificationRenderer.render( psi, template );
return new ProgramMessage(
message.getSubject(), message.getMessage(), resolveProgramStageNotificationRecipients( template, psi.getOrganisationUnit(),
psi ), template.getDeliveryChannels(), psi );
}
private ProgramMessage createProgramMessage( ProgramInstance programInstance, ProgramNotificationTemplate template )
{
NotificationMessage message = programNotificationRenderer.render( programInstance, template );
return new ProgramMessage(
message.getSubject(), message.getMessage(),
resolveProgramNotificationRecipients( template, programInstance.getOrganisationUnit(), programInstance ),
template.getDeliveryChannels(), programInstance );
}
private Set<User> resolveDhisMessageRecipients(
ProgramNotificationTemplate template, @Nullable ProgramInstance programInstance, @Nullable ProgramStageInstance programStageInstance )
{
if ( programInstance == null && programStageInstance == null )
{
throw new IllegalArgumentException( "Either of the arguments [programInstance, programStageInstance] must be non-null" );
}
Set<User> recipients = Sets.newHashSet();
ProgramNotificationRecipient recipientType = template.getNotificationRecipient();
if ( recipientType == ProgramNotificationRecipient.USER_GROUP )
{
recipients.addAll( template.getRecipientUserGroup().getMembers() );
}
else if ( recipientType == ProgramNotificationRecipient.USERS_AT_ORGANISATION_UNIT )
{
OrganisationUnit organisationUnit =
programInstance != null ? programInstance.getOrganisationUnit() : programStageInstance.getOrganisationUnit();
recipients.addAll( organisationUnit.getUsers() );
}
return recipients;
}
private ProgramMessageRecipients resolveProgramNotificationRecipients(
ProgramNotificationTemplate template, OrganisationUnit organisationUnit, ProgramInstance programInstance )
{
return resolveRecipients( template, organisationUnit, programInstance.getEntityInstance(), programInstance );
}
private ProgramMessageRecipients resolveProgramStageNotificationRecipients(
ProgramNotificationTemplate template, OrganisationUnit organisationUnit, ProgramStageInstance psi )
{
ProgramMessageRecipients recipients = new ProgramMessageRecipients();
if ( template.getNotificationRecipient() == ProgramNotificationRecipient.DATA_ELEMENT
&& template.getRecipientDataElement() != null )
{
List<String> recipientList = psi.getDataValues().stream()
.filter( dv -> template.getRecipientDataElement().getUid().equals( dv.getDataElement().getUid() ) )
.map( TrackedEntityDataValue::getValue )
.collect( Collectors.toList() );
if ( template.getDeliveryChannels().contains( DeliveryChannel.SMS ) )
{
recipients.getPhoneNumbers().addAll( recipientList );
}
else if ( template.getDeliveryChannels().contains( DeliveryChannel.EMAIL ) )
{
recipients.getEmailAddresses().addAll( recipientList );
}
return recipients;
}
else
{
TrackedEntityInstance trackedEntityInstance = psi.getProgramInstance().getEntityInstance();
return resolveRecipients( template, organisationUnit, trackedEntityInstance, psi.getProgramInstance() );
}
}
private ProgramMessageRecipients resolveRecipients( ProgramNotificationTemplate template, OrganisationUnit ou,
TrackedEntityInstance tei, ProgramInstance pi)
{
ProgramMessageRecipients recipients = new ProgramMessageRecipients();
ProgramNotificationRecipient recipientType = template.getNotificationRecipient();
if ( recipientType == ProgramNotificationRecipient.ORGANISATION_UNIT_CONTACT )
{
recipients.setOrganisationUnit( ou );
}
else if ( recipientType == ProgramNotificationRecipient.TRACKED_ENTITY_INSTANCE )
{
recipients.setTrackedEntityInstance( tei );
}
else if ( recipientType == ProgramNotificationRecipient.PROGRAM_ATTRIBUTE
&& template.getRecipientProgramAttribute() != null )
{
List<String> recipientList = pi.getEntityInstance().getTrackedEntityAttributeValues().stream()
.filter( av -> template.getRecipientProgramAttribute().getUid().equals( av.getAttribute().getUid() ) )
.map( TrackedEntityAttributeValue::getPlainValue )
.collect( Collectors.toList() );
if ( template.getDeliveryChannels().contains( DeliveryChannel.SMS ) )
{
recipients.getPhoneNumbers().addAll( recipientList );
}
else if ( template.getDeliveryChannels().contains( DeliveryChannel.EMAIL ) )
{
recipients.getEmailAddresses().addAll( recipientList );
}
}
return recipients;
}
private Set<ProgramNotificationTemplate> resolveTemplates( ProgramInstance programInstance, final NotificationTrigger trigger )
{
return programInstance.getProgram().getNotificationTemplates().stream()
.filter( t -> t.getNotificationTrigger() == trigger )
.collect( Collectors.toSet() );
}
private Set<ProgramNotificationTemplate> resolveTemplates( ProgramStageInstance programStageInstance, final NotificationTrigger trigger )
{
return programStageInstance.getProgramStage().getNotificationTemplates().stream()
.filter( t -> t.getNotificationTrigger() == trigger )
.collect( Collectors.toSet() );
}
private DhisMessage createDhisMessage( ProgramStageInstance psi, ProgramNotificationTemplate template )
{
DhisMessage dhisMessage = new DhisMessage();
dhisMessage.message = programStageNotificationRenderer.render( psi, template );
dhisMessage.recipients = resolveDhisMessageRecipients( template, null, psi );
return dhisMessage;
}
private DhisMessage createDhisMessage( ProgramInstance pi, ProgramNotificationTemplate template )
{
DhisMessage dhisMessage = new DhisMessage();
dhisMessage.message = programNotificationRenderer.render( pi, template );
dhisMessage.recipients = resolveDhisMessageRecipients( template, pi, null );
return dhisMessage;
}
private void sendDhisMessages( Set<DhisMessage> messages )
{
messages.forEach( m ->
messageService.sendMessage(
new MessageConversationParams.Builder(m.recipients, null, m.message.getSubject(), m.message.getMessage(), MessageType.SYSTEM )
.withForceNotification( true )
.build()
)
);
}
private void sendProgramMessages( Set<ProgramMessage> messages )
{
if ( messages.isEmpty() )
{
return;
}
log.debug( String.format( "Dispatching %d ProgramMessages", messages.size() ) );
BatchResponseStatus status = programMessageService.sendMessages( Lists.newArrayList( messages ) );
log.debug( String.format( "Resulting status from ProgramMessageService:\n %s", status.toString() ) );
}
private void sendAll( MessageBatch messageBatch )
{
sendDhisMessages( messageBatch.dhisMessages );
sendProgramMessages( messageBatch.programMessages );
}
// Internal classes
private static class DhisMessage
{
NotificationMessage message;
Set<User> recipients;
}
private static class MessageBatch
{
Set<DhisMessage> dhisMessages = Sets.newHashSet();
Set<ProgramMessage> programMessages = Sets.newHashSet();
MessageBatch( MessageBatch ...batches )
{
for ( MessageBatch batch : batches )
{
dhisMessages.addAll( batch.dhisMessages );
programMessages.addAll( batch.programMessages );
}
}
int messageCount()
{
return dhisMessages.size() + programMessages.size();
}
}
}
|
package org.innovateuk.ifs.user.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.user.resource.ProfileRole;
import org.innovateuk.ifs.user.resource.RoleProfileState;
import org.innovateuk.ifs.user.resource.RoleProfileStatusResource;
import org.innovateuk.ifs.user.transactional.RoleProfileStatusService;
import org.junit.Test;
import org.mockito.Mock;
import javax.ws.rs.core.MediaType;
import java.util.List;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.documentation.RoleProfileStatusResourceDocs.roleProfileStatusResourceFields;
import static org.innovateuk.ifs.user.builder.RoleProfileStatusResourceBuilder.newRoleProfileStatusResource;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class RoleProfileStatusControllerDocumentation extends BaseControllerMockMVCTest<RoleProfileStatusController> {
@Mock
private RoleProfileStatusService roleProfileStatusService;
@Override
protected RoleProfileStatusController supplyControllerUnderTest() {
return new RoleProfileStatusController();
}
@Test
public void findByUserId() throws Exception {
long userId = 1L;
List<RoleProfileStatusResource> roleProfileStatusResources = newRoleProfileStatusResource()
.withUserId(userId)
.withRoleProfileState(RoleProfileState.UNAVAILABLE)
.withProfileRole(ProfileRole.ASSESSOR)
.withDescription("Description")
.build(1);
when(roleProfileStatusService.findByUserId(userId)).thenReturn(serviceSuccess(roleProfileStatusResources));
mockMvc.perform(get("/user/{userId}/role-profile-status", userId)
.header("IFS_AUTH_TOKEN", "123abc"))
.andExpect(status().isOk())
.andDo(document("roleProfileStatus/{method-name}",
pathParameters(
parameterWithName("userId").description("Id of the user")
),
responseFields(fieldWithPath("[]").description("List of Project Users the user is allowed to see"))
.andWithPrefix("[].", roleProfileStatusResourceFields)
));
}
@Test
public void findByUserIdAndProfileRole() throws Exception {
long userId = 1L;
ProfileRole profileRole = ProfileRole.ASSESSOR;
RoleProfileStatusResource roleProfileStatusResource = newRoleProfileStatusResource().withUserId(userId).build();
when(roleProfileStatusService.findByUserIdAndProfileRole(userId, profileRole)).thenReturn(serviceSuccess(roleProfileStatusResource));
mockMvc.perform(get("/user/{userId}/role-profile-status/{profileRole}", userId, profileRole)
.header("IFS_AUTH_TOKEN", "123abc"))
.andExpect(status().isOk())
.andDo(document("roleProfileStatus/{method-name}",
pathParameters(
parameterWithName("userId").description("Id of the user"),
parameterWithName("profileRole").description("role of the user")
),
responseFields(roleProfileStatusResourceFields)
));
}
@Test
public void updateUserStatus() throws Exception {
long userId = 1L;
RoleProfileStatusResource roleProfileStatusResource = newRoleProfileStatusResource()
.withUserId(userId)
.withRoleProfileState(RoleProfileState.UNAVAILABLE)
.withProfileRole(ProfileRole.ASSESSOR)
.withDescription("Description")
.build();
when(roleProfileStatusService.updateUserStatus(anyLong(), any(RoleProfileStatusResource.class))).thenReturn(serviceSuccess());
mockMvc.perform(put("/user/{userId}/role-profile-status", userId)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(roleProfileStatusResource)))
.andExpect(status().isOk())
.andDo(document("roleProfileStatus/{method-name}",
pathParameters(
parameterWithName("userId").description("Id of the user"))));
}
}
|
package nl.mpi.arbil.data;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collection;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.regex.Pattern;
import javax.swing.ImageIcon;
import nl.mpi.arbil.ArbilIcons;
import nl.mpi.arbil.clarin.HandleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MetadataFormat {
private final static Logger logger = LoggerFactory.getLogger(MetadataFormat.class);
public static final int DEEP_CHECK_BYTES_TO_READ = 1024;
private static final Pattern ROOT_ELEMENT_PATTERN = Pattern.compile("<[\\S]*");
static class FormatType {
private FileType fileType;
private String suffixString;
private String metadataStartXpath;
private ImageIcon imageIcon;
public FormatType(String suffixString, String metadataStartXpath, ImageIcon imageIcon, FileType fileType) {
this.fileType = fileType;
this.suffixString = suffixString;
this.metadataStartXpath = metadataStartXpath;
this.imageIcon = imageIcon;
}
}
public enum FileType {
IMDI,
CMDI,
KMDI,
FILE,
DIRECTORY,
CHILD,
UNKNOWN
}
private final static Collection<FormatType> knownFormats = new CopyOnWriteArraySet<FormatType>(Arrays.asList(new FormatType[]{
new FormatType(".imdi", ".METATRANSCRIPT", null, FileType.IMDI),
// todo: the filter strings used by the cmdi templates and metadata loading process should be reading the metadataStartXpath from here instead
new FormatType(".cmdi", ".CMD.Components", ArbilIcons.clarinIcon, FileType.CMDI),
// Generic XML
new FormatType(".xml", "", ArbilIcons.clarinIcon, FileType.FILE), // Clarin icon is not really appropriate
// OAI-PMH, Open Archives Initiative Protocol for Metadata Harvesting
new FormatType(".xml", ".OAI-PMH.GetRecord.record.metadata.olac:olac", ArbilIcons.clarinIcon, FileType.FILE), // Clarin icon is not really appropriate
// KMDI, Kinship metadata
new FormatType(".kmdi", ".Kinnate.CustomData", ArbilIcons.kinOathIcon, FileType.KMDI),
// TLA test results
new FormatType(".trx", "", ArbilIcons.clarinIcon, FileType.CMDI)})); // Clarin icon is not really appropriate
// private static MetadataFormat singleInstance = null;
// static synchronized public MetadataFormat getSingleInstance() {
//// logger.debug("LinorgWindowManager getSingleInstance");
// if (singleInstance == null) {
// singleInstance = new MetadataFormat();
// return singleInstance;
public FileType shallowCheck(URI targetUri) {
// final URI targetUri = new HandleUtils().resolveHandle(inputUri);
String urlString = targetUri.toString();
if (isStringChildNode(urlString)) {
return FileType.CHILD;
}
File localFile = getFile(targetUri);
if (localFile != null && localFile.isDirectory()) {
return FileType.DIRECTORY;
}
for (FormatType formatType : knownFormats) {
if (urlString.endsWith(formatType.suffixString)) {
return formatType.fileType;
}
}
if (localFile != null && localFile.isFile()) {
return FileType.FILE;
}
if (urlString.lastIndexOf(".") > urlString.length() - 6) {
// if the file name has a suffix and has passed through the known metadata suffixes then we assume it is a file and dont bother reading the remote file
logger.debug("Presuming the URI points to non metadata based on its suffix: {}", urlString);
return FileType.FILE;
}
// the type is currently unknown and if a full load is requested will be deep checked before hand
return FileType.UNKNOWN;
}
public FileType deepCheck(URI targetUri) {
final FileType shallowCheckResult = shallowCheck(targetUri);
if (shallowCheckResult != FileType.UNKNOWN) {
logger.debug("Shallow check was decisive: {}", shallowCheckResult);
return shallowCheckResult;
}
logger.debug("Deep checking {}", targetUri);
try {
final URI resolveHandle = new HandleUtils().resolveHandle(targetUri);
final URLConnection uRLConnection = resolveHandle.toURL().openConnection();
if (uRLConnection instanceof HttpURLConnection) {
// For HTTP connections, we want to follow redirects
((HttpURLConnection) uRLConnection).setInstanceFollowRedirects(true);
}
// calling httpConnection.connect(); does not help us here, we need to get the input stream
// only then can we get the redirected URL but we must get it via httpConnection.getURL()
// because the original connection and its location header that could have been retrieved
// by httpConnection.getHeaderField("Location"); has been discarded and
// replaced by a new connection.
final InputStream inputStream = uRLConnection.getInputStream();
logger.debug("Connected to {}", uRLConnection.getURL());
try {
// Connection url might be different since a connection has been established which may have resulted in a redirect
final URL connectionUrl = uRLConnection.getURL();
if (connectionUrl != null) {
final FileType redirectedShallowCheckResult = shallowCheck(connectionUrl.toURI());
if (redirectedShallowCheckResult != FileType.UNKNOWN) {
logger.debug("Shallow check on URL {} was decisive: {}", connectionUrl, shallowCheckResult);
return redirectedShallowCheckResult;
}
}
} catch (URISyntaxException exception) {
logger.error("Could not read redirected URI: {}", exception.getMessage());
}
// There is no point checking uRLConnection.getContentType();
// because we dont have a useful mime type here, it could
// be application/xml or text/xml or text/plain etc.
// so there is no reliable way to test this content type
// without enforcing serverside content types
final Scanner scanner = new Scanner(inputStream);
String found;
while (null != (found = scanner.findWithinHorizon(ROOT_ELEMENT_PATTERN, DEEP_CHECK_BYTES_TO_READ))) {
if ("<?xml".equals(found)) {
continue;
} else if ("<!--".equals(found)) {
continue;
}
for (FormatType formatType : knownFormats) {
if (formatType.metadataStartXpath != null && formatType.metadataStartXpath.length() > 0) {
final String foundTag = found.substring(1);
if (formatType.metadataStartXpath.startsWith(foundTag, 1)) {
scanner.close();
inputStream.close();
return formatType.fileType;
}
}
}
logger.debug("found: {}", found);
// We have scanned beyond root node, moving on
break;
}
scanner.close();
inputStream.close();
} catch (IOException exception) {
logger.warn("Could not get remote file type for {}", targetUri);
logger.info("Could not get remote file type, returning FileType.UNKNOWN", exception);
return FileType.UNKNOWN;
}
return FileType.FILE;
}
public static boolean isPathImdi(String urlString) {
for (FormatType formatType : knownFormats) {
if (urlString.endsWith(formatType.suffixString)) {
return formatType.fileType == FileType.IMDI;
}
}
return false;
}
public static boolean isPathCmdi(String urlString) {
for (FormatType formatType : knownFormats) {
if (urlString.endsWith(formatType.suffixString)) {
return formatType.fileType == FileType.CMDI;
}
}
return false;
}
public static ImageIcon getFormatIcon(FileType fileType) {
for (FormatType formatType : knownFormats) {
if (formatType.fileType == fileType) {
return formatType.imageIcon;
}
}
return null;
}
public static String getMetadataStartPath(String urlString) {
for (FormatType formatType : knownFormats) {
if (urlString.endsWith(formatType.suffixString)) {
return formatType.metadataStartXpath;
}
}
return null;
}
public boolean isMetaDataNode(FileType fileType) {
return (MetadataFormat.FileType.CHILD == fileType
|| MetadataFormat.FileType.IMDI == fileType
|| MetadataFormat.FileType.CMDI == fileType
|| MetadataFormat.FileType.KMDI == fileType);
}
static public boolean isPathMetadata(String urlString) {
return isPathImdi(urlString) || isPathCmdi(urlString); // change made for clarin
}
static public boolean isStringChildNode(String urlString) {
// todo: this seems not to cause any issues but might it mistake a file for a child node?
return urlString.contains("#."); // anything with a fragment is a sub node //urlString.contains("#.METATRANSCRIPT") || urlString.contains("#.CMD"); // change made for clarin
}
public static File getFile(URI nodeUri) throws IllegalArgumentException {
final String scheme = nodeUri.getScheme();
if (scheme == null) {
throw new IllegalArgumentException("Expecting an absolute URI, instead was " + nodeUri);
}
if (scheme.toLowerCase().equals("file")) {
return new File(URI.create(nodeUri.toString().split("#")[0] /* fragment removed */));
}
return null;
}
}
|
package org.eclipse.birt.report.model.adapter.oda.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.report.model.adapter.oda.IODADesignFactory;
import org.eclipse.birt.report.model.adapter.oda.IReportParameterAdapter;
import org.eclipse.birt.report.model.adapter.oda.ODADesignFactory;
import org.eclipse.birt.report.model.adapter.oda.util.ParameterValueUtil;
import org.eclipse.birt.report.model.api.CommandStack;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.ExpressionType;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSetParameterHandle;
import org.eclipse.birt.report.model.api.ParameterGroupHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SelectionChoiceHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.OdaDataSetParameter;
import org.eclipse.birt.report.model.api.elements.structures.SelectionChoice;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.birt.report.model.elements.interfaces.IScalarParameterModel;
import org.eclipse.datatools.connectivity.oda.design.DataElementAttributes;
import org.eclipse.datatools.connectivity.oda.design.DataElementUIHints;
import org.eclipse.datatools.connectivity.oda.design.DataSetDesign;
import org.eclipse.datatools.connectivity.oda.design.DataSetParameters;
import org.eclipse.datatools.connectivity.oda.design.DynamicValuesQuery;
import org.eclipse.datatools.connectivity.oda.design.ElementNullability;
import org.eclipse.datatools.connectivity.oda.design.InputElementAttributes;
import org.eclipse.datatools.connectivity.oda.design.InputElementUIHints;
import org.eclipse.datatools.connectivity.oda.design.InputParameterAttributes;
import org.eclipse.datatools.connectivity.oda.design.InputParameterUIHints;
import org.eclipse.datatools.connectivity.oda.design.InputPromptControlStyle;
import org.eclipse.datatools.connectivity.oda.design.ParameterDefinition;
import org.eclipse.datatools.connectivity.oda.design.ScalarValueChoices;
import org.eclipse.datatools.connectivity.oda.design.ScalarValueDefinition;
import org.eclipse.datatools.connectivity.oda.design.StaticValues;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.util.EcoreUtil;
/**
* Converts values between a report parameter and ODA Design Session Request.
*
*/
public class ReportParameterAdapter implements IReportParameterAdapter
{
/**
* Deprecated allowNull property.
*
* @deprecated
*/
private static final String ALLOW_NULL_PROP_NAME = IScalarParameterModel.ALLOW_NULL_PROP;
/**
* Deprecated allowBlank property.
*
* @deprecated
*/
private static final String ALLOW_BLANK_PROP_NAME = IScalarParameterModel.ALLOW_BLANK_PROP;
private final IODADesignFactory designFactory;
/**
* Default constructor.
*/
public ReportParameterAdapter( )
{
designFactory = ODADesignFactory.getFactory( );
}
/**
* Checks whether the given report parameter is updated. This method checks
* values of report parameters and values in data set design.
* <p>
* If any input argument is null or the matched ODA parameter definition
* cannot be found, return <code>true</code>.
*
* @param reportParam
* the report parameter
* @param odaParam
* the ODA parameter definition
* @param newDataType
* the data type
*
* @return <code>true</code> if the report paramter is updated or has no
* parameter definition in the data set design. Otherwise
* <code>false</code>.
*/
boolean isUpdatedReportParameter( ScalarParameterHandle reportParam,
ParameterDefinition odaParam, String newDataType )
{
if ( reportParam == null || odaParam == null )
return true;
DataElementAttributes dataAttrs = odaParam.getAttributes( );
Boolean odaAllowNull = getROMNullability( dataAttrs.getNullability( ) );
boolean allowNull = getReportParamAllowMumble( reportParam,
ALLOW_NULL_PROP_NAME );
if ( odaAllowNull != null && allowNull != odaAllowNull.booleanValue( ) )
return false;
if ( !DesignChoiceConstants.PARAM_TYPE_ANY
.equalsIgnoreCase( newDataType ) )
{
if ( !CompareUtil
.isEquals( newDataType, reportParam.getDataType( ) ) )
return false;
}
DataElementUIHints dataUiHints = dataAttrs.getUiHints( );
if ( dataUiHints != null )
{
String newPromptText = dataUiHints.getDisplayName( );
String newHelpText = dataUiHints.getDescription( );
if ( !CompareUtil.isEquals( newPromptText, reportParam
.getPromptText( ) ) )
return false;
if ( !CompareUtil
.isEquals( newHelpText, reportParam.getHelpText( ) ) )
return false;
}
InputParameterAttributes paramAttrs = odaParam.getInputAttributes( );
InputParameterAttributes tmpParamDefn = null;
DataSetDesign tmpDataSet = null;
if ( paramAttrs != null )
{
tmpParamDefn = (InputParameterAttributes) EcoreUtil
.copy( paramAttrs );
DynamicValuesQuery tmpDynamicQuery = tmpParamDefn
.getElementAttributes( ).getDynamicValueChoices( );
if ( tmpDynamicQuery != null )
{
tmpDataSet = tmpDynamicQuery.getDataSetDesign( );
tmpDynamicQuery.setDataSetDesign( null );
}
if ( tmpParamDefn.getUiHints( ) != null )
{
tmpParamDefn.setUiHints( null );
}
}
else
tmpParamDefn = designFactory.createInputParameterAttributes( );
InputParameterAttributes tmpParamDefn1 = designFactory
.createInputParameterAttributes( );
updateInputElementAttrs( tmpParamDefn1, reportParam, null );
if ( tmpParamDefn1.getUiHints( ) != null )
{
tmpParamDefn1.setUiHints( null );
}
DynamicValuesQuery tmpDynamicQuery1 = tmpParamDefn1
.getElementAttributes( ).getDynamicValueChoices( );
DataSetDesign tmpDataSet1 = null;
if ( tmpDynamicQuery1 != null )
{
tmpDataSet1 = tmpDynamicQuery1.getDataSetDesign( );
tmpDynamicQuery1.setDataSetDesign( null );
}
if ( !EcoreUtil.equals( tmpDataSet, tmpDataSet1 ) )
return false;
return EcoreUtil.equals( tmpParamDefn, tmpParamDefn1 );
}
/**
* Updates allowNull property for the given data set parameter definition.
*
* @param romParamDefn
* the data set parameter definition.
* @param nullability
* the ODA object indicates nullability.
* @return <code>true</code> if is nullable. <code>false</code> if not
* nullable.
*/
static Boolean getROMNullability( ElementNullability nullability )
{
if ( nullability == null )
return null;
switch ( nullability.getValue( ) )
{
case ElementNullability.NULLABLE :
return Boolean.TRUE;
case ElementNullability.NOT_NULLABLE :
return Boolean.FALSE;
case ElementNullability.UNKNOWN :
return null;
}
return null;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.adapter.oda.IReportParameterAdapter#
* updateLinkedReportParameter
* (org.eclipse.birt.report.model.api.ScalarParameterHandle,
* org.eclipse.birt.report.model.api.OdaDataSetParameterHandle,
* org.eclipse.datatools.connectivity.oda.design.DataSetDesign)
*/
public void updateLinkedReportParameter( ScalarParameterHandle reportParam,
OdaDataSetParameterHandle dataSetParam, DataSetDesign dataSetDesign )
throws SemanticException
{
if ( reportParam == null || dataSetParam == null )
return;
ParameterDefinition matchedParam = null;
String dataType = null;
OdaDataSetHandle setHandle = (OdaDataSetHandle) dataSetParam
.getElementHandle( );
if ( dataSetDesign != null )
{
matchedParam = getValidParameterDefinition( dataSetParam,
dataSetDesign.getParameters( ) );
dataType = DataSetParameterAdapter.getROMDataType( dataSetDesign
.getOdaExtensionDataSourceId( ), dataSetDesign
.getOdaExtensionDataSetId( ),
(OdaDataSetParameter) dataSetParam.getStructure( ),
setHandle == null ? null : setHandle.parametersIterator( ) );
}
CommandStack cmdStack = reportParam.getModuleHandle( )
.getCommandStack( );
cmdStack.startTrans( null );
try
{
if ( matchedParam != null )
updateLinkedReportParameter( reportParam, matchedParam, null,
dataType, (OdaDataSetHandle) dataSetParam
.getElementHandle( ) );
updateLinkedReportParameterFromROMParameter( reportParam,
dataSetParam );
}
catch ( SemanticException e )
{
cmdStack.rollback( );
throw e;
}
cmdStack.commit( );
}
/**
* Updates values in report parameter by given ROM data set parameter.
*
* @param reportParam
* the report parameter
* @param dataSetParam
* the data set parameter
* @throws SemanticException
*/
private void updateLinkedReportParameterFromROMParameter(
ScalarParameterHandle reportParam,
OdaDataSetParameterHandle dataSetParam ) throws SemanticException
{
assert reportParam != null;
if ( dataSetParam == null )
return;
// should not convert report parameter name here.
String dataType = dataSetParam.getParameterDataType( );
if ( !StringUtil.isBlank( dataType ) )
{
if ( !DesignChoiceConstants.PARAM_TYPE_ANY
.equalsIgnoreCase( dataType ) )
{
reportParam.setDataType( dataType );
}
else
{
reportParam
.setDataType( DesignChoiceConstants.PARAM_TYPE_STRING );
}
}
String defaultValue = dataSetParam.getDefaultValue( );
String paramName = dataSetParam.getParamName( );
if ( !StringUtil.isBlank( defaultValue )
&& StringUtil.isBlank( paramName ) )
{
setROMDefaultValue( reportParam, defaultValue );
}
if ( StringUtil.isBlank( paramName ) )
{
dataSetParam.setParamName( reportParam.getName( ) );
}
}
/**
* Sets the default value for ROM data set parameter. Should add quotes for
* the value if the data type is string.
*
* @param setParam
* the ROM data set parameter
* @param literalValue
* the value
*/
private void setROMDefaultValue( ScalarParameterHandle setParam,
String value ) throws SemanticException
{
String literalValue = value;
if ( literalValue != null )
{
boolean match = ExpressionUtil
.isScalarParamReference( literalValue );
if ( match )
return;
}
if ( DataSetParameterAdapter.BIRT_JS_EXPR
.equalsIgnoreCase( literalValue ) )
{
return;
}
if ( DataSetParameterAdapter.needsQuoteDelimiters( setParam
.getDataType( ) ) )
{
if ( ParameterValueUtil.isQuoted( value ) )
{
literalValue = ParameterValueUtil.toLiteralValue( value );
}
else
return;
}
List<Expression> newValues = new ArrayList<Expression>( );
newValues.add( new Expression( literalValue, ExpressionType.CONSTANT ) );
setParam.setDefaultValueList( newValues );
}
/**
* Refreshes property values of the given report parameter by the given
* parameter definition and cached parameter definition. If values in cached
* parameter definition is null or values in cached parameter definition are
* not equal to values in parameter defnition, update values in given report
* parameter.
*
* @param reportParam
* the report parameter
* @param paramDefn
* the ODA parameter definition
* @param cachedParamDefn
* the cached ODA parameter definition in designerValues
* @param dataType
* the updated data type
* @param setHandle
* the ROM data set that has the corresponding data set parameter
* @throws SemanticException
* if value in the data set design is invalid
*/
void updateLinkedReportParameter( ScalarParameterHandle reportParam,
ParameterDefinition paramDefn, ParameterDefinition cachedParamDefn,
String dataType, OdaDataSetHandle setHandle )
throws SemanticException
{
if ( paramDefn == null )
return;
if ( isUpdatedReportParameter( reportParam, paramDefn, dataType ) )
{
return;
}
CommandStack cmdStack = reportParam.getModuleHandle( )
.getCommandStack( );
try
{
cmdStack.startTrans( null );
// any type is not support in report parameter data type.
if ( dataType == null )
{
if ( !DesignChoiceConstants.PARAM_TYPE_ANY
.equalsIgnoreCase( dataType ) )
{
reportParam.setDataType( dataType );
}
else
{
reportParam
.setDataType( DesignChoiceConstants.PARAM_TYPE_STRING );
}
}
updateDataElementAttrsToReportParam( paramDefn.getAttributes( ),
cachedParamDefn == null ? null : cachedParamDefn
.getAttributes( ), reportParam );
updateInputParameterAttrsToReportParam( paramDefn
.getInputAttributes( ), cachedParamDefn == null
? null
: cachedParamDefn.getInputAttributes( ), reportParam,
setHandle );
}
catch ( SemanticException e )
{
cmdStack.rollback( );
throw e;
}
cmdStack.commit( );
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.adapter.oda.IReportParameterAdapter#
* updateLinkedReportParameter
* (org.eclipse.birt.report.model.api.ScalarParameterHandle,
* org.eclipse.birt.report.model.api.OdaDataSetParameterHandle)
*/
public void updateLinkedReportParameter( ScalarParameterHandle reportParam,
OdaDataSetParameterHandle dataSetParam ) throws SemanticException
{
if ( reportParam == null || dataSetParam == null )
return;
updateLinkedReportParameterFromROMParameter( reportParam, dataSetParam );
}
/**
* Returns the matched ODA data set parameter by the given ROM data set
* parameter and data set design.
*
* @param param
* the ROM data set parameter
* @param dataSetDesign
* the oda data set design
* @return the matched ODA parameter defintion
*/
private static ParameterDefinition getValidParameterDefinition(
OdaDataSetParameterHandle param, DataSetParameters odaParams )
{
if ( param == null || odaParams == null )
return null;
if ( odaParams.getParameterDefinitions( ).isEmpty( ) )
return null;
ParameterDefinition matchedParam = DataSetParameterAdapter
.findParameterDefinition( odaParams, param.getNativeName( ),
param.getPosition( ) );
return matchedParam;
}
/**
* Updates values in DataElementAttributes to the given report parameter.
*
* @param dataAttrs
* the latest data element attributes
* @param cachedDataAttrs
* the cached data element attributes
* @param reportParam
* the report parameter
* @throws SemanticException
*/
private void updateDataElementAttrsToReportParam(
DataElementAttributes dataAttrs,
DataElementAttributes cachedDataAttrs,
ScalarParameterHandle reportParam ) throws SemanticException
{
if ( dataAttrs == null )
return;
boolean allowsNull = dataAttrs.allowsNull( );
if ( cachedDataAttrs == null
|| cachedDataAttrs.allowsNull( ) != allowsNull )
setReportParamIsRequired( reportParam, ALLOW_NULL_PROP_NAME,
dataAttrs.allowsNull( ) );
// reportParam.setAllowNull( dataAttrs.allowsNull( ) );
DataElementUIHints dataUiHints = dataAttrs.getUiHints( );
DataElementUIHints cachedDataUiHints = ( cachedDataAttrs == null
? null
: cachedDataAttrs.getUiHints( ) );
if ( dataUiHints != null )
{
String displayName = dataUiHints.getDisplayName( );
String cachedDisplayName = cachedDataUiHints == null
? null
: cachedDataUiHints.getDisplayName( );
if ( cachedDisplayName == null
|| !cachedDisplayName.equals( displayName ) )
reportParam.setPromptText( displayName );
String description = dataUiHints.getDescription( );
String cachedDescription = cachedDataUiHints == null
? null
: cachedDataUiHints.getDescription( );
if ( cachedDescription == null
|| !cachedDescription.equals( description ) )
reportParam.setHelpText( description );
}
}
/**
* Updates values in InputParameterAttributes to the given report parameter.
*
* @param dataAttrs
* the latest input parameter attributes
* @param cachedDataAttrs
* the cached input parameter attributes
* @param reportParam
* the report parameter
* @param setHandle
* the ROM data set that has the corresponding data set parameter
* @throws SemanticException
*/
private void updateInputParameterAttrsToReportParam(
InputParameterAttributes inputParamAttrs,
InputParameterAttributes cachedInputParamAttrs,
ScalarParameterHandle reportParam, OdaDataSetHandle setHandle )
throws SemanticException
{
if ( inputParamAttrs == null )
return;
InputParameterUIHints paramUiHints = inputParamAttrs.getUiHints( );
if ( paramUiHints != null
&& reportParam.getContainer( ) instanceof ParameterGroupHandle )
{
ParameterGroupHandle paramGroup = (ParameterGroupHandle) reportParam
.getContainer( );
InputParameterUIHints cachedParamUiHints = cachedInputParamAttrs == null
? null
: cachedInputParamAttrs.getUiHints( );
String cachedGroupPromptDisplayName = cachedParamUiHints == null
? null
: cachedParamUiHints.getGroupPromptDisplayName( );
String groupPromptDisplayName = paramUiHints
.getGroupPromptDisplayName( );
if ( cachedGroupPromptDisplayName == null
|| !cachedGroupPromptDisplayName
.equals( groupPromptDisplayName ) )
paramGroup.setDisplayName( paramUiHints
.getGroupPromptDisplayName( ) );
}
updateInputElementAttrsToReportParam( inputParamAttrs
.getElementAttributes( ), cachedInputParamAttrs == null
? null
: cachedInputParamAttrs.getElementAttributes( ), reportParam,
setHandle );
}
/**
* Updates values in InputElementAttributes to the given report parameter.
*
* @param dataAttrs
* the latest input element attributes
* @param cachedDataAttrs
* the cached input element attributes
* @param reportParam
* the report parameter
* @param setHandle
* the ROM data set that has the corresponding data set parameter
* @throws SemanticException
*/
private void updateInputElementAttrsToReportParam(
InputElementAttributes elementAttrs,
InputElementAttributes cachedElementAttrs,
ScalarParameterHandle reportParam, OdaDataSetHandle setHandle )
throws SemanticException
{
if ( elementAttrs == null )
return;
// update default values.
StaticValues defaultValues = elementAttrs.getDefaultValues( );
StaticValues cachedDefaultValues = cachedElementAttrs == null
? null
: cachedElementAttrs.getDefaultValues( );
if ( new EcoreUtil.EqualityHelper( ).equals( cachedDefaultValues,
defaultValues ) == false )
{
List<String> newValues = null;
if ( defaultValues != null )
{
newValues = new ArrayList<String>( );
List<Object> tmpValues = defaultValues.getValues( );
for ( int i = 0; i < tmpValues.size( ); i++ )
{
String tmpValue = (String) tmpValues.get( i );
// only update when the value is not internal value.
if ( !DataSetParameterAdapter.BIRT_JS_EXPR
.equals( tmpValue ) )
newValues.add( tmpValue );
}
}
reportParam.setDefaultValueList( newValues );
}
// update isOptional value
Boolean isOptional = Boolean.valueOf( elementAttrs.isOptional( ) );
Boolean cachedIsOptional = cachedElementAttrs == null ? null : Boolean
.valueOf( cachedElementAttrs.isOptional( ) );
if ( !CompareUtil.isEquals( cachedIsOptional, isOptional ) )
setReportParamIsRequired( reportParam, ALLOW_BLANK_PROP_NAME,
isOptional.booleanValue( ) );
// reportParam.setAllowBlank( isOptional.booleanValue( ) );
// update conceal value
Boolean masksValue = Boolean.valueOf( elementAttrs.isMasksValue( ) );
Boolean cachedMasksValues = cachedElementAttrs == null ? null : Boolean
.valueOf( cachedElementAttrs.isMasksValue( ) );
if ( !CompareUtil.isEquals( cachedMasksValues, masksValue ) )
reportParam.setConcealValue( masksValue.booleanValue( ) );
updateROMSelectionList( elementAttrs.getStaticValueChoices( ),
cachedElementAttrs == null ? null : cachedElementAttrs
.getStaticValueChoices( ), reportParam );
DynamicValuesQuery valueQuery = elementAttrs.getDynamicValueChoices( );
updateROMDyanmicList( valueQuery, cachedElementAttrs == null
? null
: cachedElementAttrs.getDynamicValueChoices( ), reportParam,
setHandle );
// for both dynamic and static parameter, the flag is in
// DynamicValuesQuery
DynamicValuesQuery cachedValueQuery = cachedElementAttrs == null
? null
: cachedElementAttrs.getDynamicValueChoices( );
if ( valueQuery == null && cachedValueQuery == null )
return;
// please note that new dynamic values query's isEnabled flag is true
if ( valueQuery == null )
valueQuery = designFactory.createDynamicValuesQuery( );
boolean isEnabled = valueQuery.isEnabled( );
boolean cachedIsEnabled = cachedValueQuery == null
? false
: cachedValueQuery.isEnabled( );
if ( ( cachedValueQuery == null || cachedIsEnabled != isEnabled )
&& isEnabled )
reportParam
.setValueType( DesignChoiceConstants.PARAM_VALUE_TYPE_DYNAMIC );
else if ( ( cachedValueQuery == null || cachedIsEnabled != isEnabled )
&& !isEnabled )
reportParam
.setValueType( DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC );
InputElementUIHints uiHints = elementAttrs.getUiHints( );
if ( uiHints != null )
{
InputElementUIHints cachedUiHints = cachedElementAttrs == null
? null
: cachedElementAttrs.getUiHints( );
InputPromptControlStyle style = uiHints.getPromptStyle( );
InputPromptControlStyle cachedStyle = cachedUiHints == null
? null
: cachedUiHints.getPromptStyle( );
if ( cachedStyle == null
|| ( style != null && cachedStyle.getValue( ) != style
.getValue( ) ) )
reportParam.setControlType( style == null
? null
: newROMControlType( style.getValue( ) ) );
}
}
/**
* Returns ROM defined control type by given ODA defined prompt style.
*
* @param promptStyle
* the ODA defined prompt style
* @return the ROM defined control type
*/
private static String newROMControlType( int promptStyle )
{
switch ( promptStyle )
{
case InputPromptControlStyle.CHECK_BOX :
return DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX;
case InputPromptControlStyle.SELECTABLE_LIST :
case InputPromptControlStyle.SELECTABLE_LIST_WITH_TEXT_FIELD :
return DesignChoiceConstants.PARAM_CONTROL_LIST_BOX;
case InputPromptControlStyle.RADIO_BUTTON :
return DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON;
case InputPromptControlStyle.TEXT_FIELD :
return DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX;
}
return null;
}
/**
* Updates values in ScalarValueChoices to the given report parameter.
*
* @param dataAttrs
* the latest scalar values
* @param cachedDataAttrs
* the cached scalar value
* @param reportParam
* the report parameter
* @throws SemanticException
*/
private void updateROMSelectionList( ScalarValueChoices staticChoices,
ScalarValueChoices cachedStaticChoices,
ScalarParameterHandle paramHandle ) throws SemanticException
{
if ( staticChoices == null )
return;
String newChoiceStr = DesignObjectSerializer
.toExternalForm( staticChoices );
String latestChoiceStr = DesignObjectSerializer
.toExternalForm( cachedStaticChoices );
if ( latestChoiceStr != null && latestChoiceStr.equals( newChoiceStr ) )
return;
List retList = new ArrayList( );
EList choiceList = staticChoices.getScalarValues( );
for ( int i = 0; i < choiceList.size( ); i++ )
{
ScalarValueDefinition valueDefn = (ScalarValueDefinition) choiceList
.get( i );
SelectionChoice choice = StructureFactory.createSelectionChoice( );
choice.setValue( valueDefn.getValue( ) );
choice.setLabel( valueDefn.getDisplayName( ) );
retList.add( choice );
}
PropertyHandle propHandle = paramHandle
.getPropertyHandle( ScalarParameterHandle.SELECTION_LIST_PROP );
propHandle.clearValue( );
for ( int i = 0; i < retList.size( ); i++ )
{
propHandle.addItem( retList.get( i ) );
}
}
/**
* Updates values in DynamicValuesQuery to the given report parameter.
*
* @param dataAttrs
* the latest dynamic values
* @param cachedDataAttrs
* the cached dynamic values
* @param reportParam
* the report parameter
* @throws SemanticException
*/
private void updateROMDyanmicList( DynamicValuesQuery valueQuery,
DynamicValuesQuery cachedValueQuery,
ScalarParameterHandle reportParam, OdaDataSetHandle setHandle )
throws SemanticException
{
if ( valueQuery == null )
return;
String value = valueQuery.getDataSetDesign( ).getName( );
String cachedValue = cachedValueQuery == null ? null : cachedValueQuery
.getDataSetDesign( ).getName( );
if ( cachedValue == null || !cachedValue.equals( value ) )
{
reportParam.setDataSetName( value );
// update the data set instance. To avoid recursivly convert,
// compare set handle instances.
ModuleHandle module = setHandle.getModuleHandle( );
DataSetHandle target = module.findDataSet( value );
if ( target instanceof OdaDataSetHandle && target != setHandle )
new ModelOdaAdapter( ).updateDataSetHandle( valueQuery
.getDataSetDesign( ), (OdaDataSetHandle) target, false );
// if there is no corresponding data set, creates a new one.
if ( target == null )
{
OdaDataSetHandle nestedDataSet = new ModelOdaAdapter( )
.createDataSetHandle( valueQuery.getDataSetDesign( ),
module );
module.getDataSets( ).add( nestedDataSet );
}
}
value = valueQuery.getValueColumn( );
cachedValue = cachedValueQuery == null ? null : cachedValueQuery
.getValueColumn( );
if ( cachedValue == null || !cachedValue.equals( value ) )
reportParam.setValueExpr( value );
value = valueQuery.getDisplayNameColumn( );
cachedValue = cachedValueQuery == null ? null : cachedValueQuery
.getDisplayNameColumn( );
if ( cachedValue == null || !cachedValue.equals( value ) )
reportParam.setLabelExpr( value );
}
/**
* Creates an ParameterDefinition with the given report parameter.
*
* @param paramDefn
* the ROM report parameter.
* @param paramHandle
* the report parameter
* @param dataSetDesign
* the data set design
* @return the created ParameterDefinition
*/
ParameterDefinition updateParameterDefinitionFromReportParam(
ParameterDefinition paramDefn, ScalarParameterHandle paramHandle,
DataSetDesign dataSetDesign )
{
assert paramHandle != null;
if ( paramDefn == null )
return null;
paramDefn.setAttributes( updateDataElementAttrs( paramDefn
.getAttributes( ), paramHandle ) );
paramDefn.setInputAttributes( updateInputElementAttrs( paramDefn
.getInputAttributes( ), paramHandle, dataSetDesign ) );
return paramDefn;
}
/**
* Creates an DataElementAttributes with the given ROM report parameter.
*
* @param paramHandle
* the ROM report parameter.
* @return the created DataElementAttributes
*/
private DataElementAttributes updateDataElementAttrs(
DataElementAttributes dataAttrs, ScalarParameterHandle paramHandle )
{
DataElementAttributes retDataAttrs = dataAttrs;
if ( retDataAttrs == null )
retDataAttrs = designFactory.createDataElementAttributes( );
// retDataAttrs.setNullability( DataSetParameterAdapter
// .newElementNullability( paramHandle.allowNll( ) ) );
retDataAttrs.setNullability( DataSetParameterAdapter
.newElementNullability( getReportParamAllowMumble( paramHandle,
ALLOW_NULL_PROP_NAME ) ) );
DataElementUIHints uiHints = designFactory.createDataElementUIHints( );
uiHints.setDisplayName( paramHandle.getPromptText( ) );
uiHints.setDescription( paramHandle.getHelpText( ) );
retDataAttrs.setUiHints( uiHints );
return retDataAttrs;
}
/**
* Creates a ODA InputParameterAttributes with the given ROM report
* parameter.
*
* @param paramHandle
* the ROM report parameter.
* @param dataSetDesign
*
* @return the created <code>InputParameterAttributes</code>.
*/
private InputParameterAttributes updateInputElementAttrs(
InputParameterAttributes inputParamAttrs,
ScalarParameterHandle paramHandle, DataSetDesign dataSetDesign )
{
InputParameterAttributes retInputParamAttrs = inputParamAttrs;
if ( inputParamAttrs == null )
retInputParamAttrs = designFactory.createInputParameterAttributes( );
InputElementAttributes inputAttrs = retInputParamAttrs
.getElementAttributes( );
if ( inputAttrs == null )
inputAttrs = designFactory.createInputElementAttributes( );
StaticValues newValues = null;
List<Expression> tmpValues = paramHandle.getDefaultValueList( );
if ( tmpValues != null )
{
for ( int i = 0; i < tmpValues.size( ); i++ )
{
if ( newValues == null )
newValues = designFactory.createStaticValues( );
newValues.add( tmpValues.get( i ).getStringExpression( ) );
}
}
inputAttrs.setDefaultValues( newValues );
// inputAttrs.setOptional( paramHandle.allowBlank( ) );
inputAttrs.setOptional( getReportParamAllowMumble( paramHandle,
ALLOW_BLANK_PROP_NAME ) );
inputAttrs.setMasksValue( paramHandle.isConcealValue( ) );
ScalarValueChoices staticChoices = null;
Iterator selectionList = paramHandle.choiceIterator( );
while ( selectionList.hasNext( ) )
{
if ( staticChoices == null )
staticChoices = designFactory.createScalarValueChoices( );
SelectionChoiceHandle choice = (SelectionChoiceHandle) selectionList
.next( );
ScalarValueDefinition valueDefn = designFactory
.createScalarValueDefinition( );
valueDefn.setValue( choice.getValue( ) );
valueDefn.setDisplayName( choice.getLabel( ) );
staticChoices.getScalarValues( ).add( valueDefn );
}
inputAttrs.setStaticValueChoices( staticChoices );
DataSetHandle setHandle = paramHandle.getDataSet( );
String valueExpr = paramHandle.getValueExpr( );
String labelExpr = paramHandle.getLabelExpr( );
if ( setHandle instanceof OdaDataSetHandle && valueExpr != null )
{
DynamicValuesQuery valueQuery = designFactory
.createDynamicValuesQuery( );
if ( dataSetDesign != null )
{
DataSetDesign targetDataSetDesign = (DataSetDesign) EcoreUtil
.copy( dataSetDesign );
if ( !setHandle.getName( ).equals( dataSetDesign.getName( ) ) )
targetDataSetDesign = new ModelOdaAdapter( )
.createDataSetDesign( (OdaDataSetHandle) setHandle );
valueQuery.setDataSetDesign( targetDataSetDesign );
}
else
{
DataSetDesign targetDataSetDesign = new ModelOdaAdapter( )
.createDataSetDesign( (OdaDataSetHandle) setHandle );
valueQuery.setDataSetDesign( targetDataSetDesign );
}
valueQuery.setDisplayNameColumn( labelExpr );
valueQuery.setValueColumn( valueExpr );
boolean isEnabled = DesignChoiceConstants.PARAM_VALUE_TYPE_DYNAMIC
.equalsIgnoreCase( paramHandle.getValueType( ) );
valueQuery.setEnabled( isEnabled );
inputAttrs.setDynamicValueChoices( valueQuery );
}
InputElementUIHints uiHints = designFactory.createInputElementUIHints( );
uiHints.setPromptStyle( newPromptStyle( paramHandle.getControlType( ),
paramHandle.isMustMatch( ) ) );
inputAttrs.setUiHints( uiHints );
if ( paramHandle.getContainer( ) instanceof ParameterGroupHandle )
{
ParameterGroupHandle groupHandle = (ParameterGroupHandle) paramHandle
.getContainer( );
InputParameterUIHints paramUiHints = designFactory
.createInputParameterUIHints( );
paramUiHints.setGroupPromptDisplayName( groupHandle
.getDisplayName( ) );
retInputParamAttrs.setUiHints( paramUiHints );
}
retInputParamAttrs.setElementAttributes( inputAttrs );
return retInputParamAttrs;
}
/**
* Returns the prompty style with the given ROM defined parameter type.
*
* @param romType
* the ROM defined parameter type
* @param mustMatch
* <code>true</code> if means list box, <code>false</code> means
* combo box.
* @return the new InputPromptControlStyle
*/
private static InputPromptControlStyle newPromptStyle( String romType,
boolean mustMatch )
{
if ( romType == null )
return null;
int type = -1;
if ( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX
.equalsIgnoreCase( romType ) )
type = InputPromptControlStyle.CHECK_BOX;
else if ( DesignChoiceConstants.PARAM_CONTROL_LIST_BOX
.equalsIgnoreCase( romType ) )
{
if ( mustMatch )
type = InputPromptControlStyle.SELECTABLE_LIST;
else
type = InputPromptControlStyle.SELECTABLE_LIST_WITH_TEXT_FIELD;
}
else if ( DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON
.equalsIgnoreCase( romType ) )
type = InputPromptControlStyle.RADIO_BUTTON;
else if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX
.equalsIgnoreCase( romType ) )
type = InputPromptControlStyle.TEXT_FIELD;
return InputPromptControlStyle.get( type );
}
/**
* Returns the boolean value of allowMumble properties. Only support
* "allowNull" and "allowBlank" properties.
* <p>
* "allowMumble" properties has been removed ROM. However, to do conversion,
* still need to know their values.
*
* @param param
* the parameter
* @param propName
* either "allowNull" or "allowBlank".
* @return <code>true</code> if the parameter allows the value. Otherwise
* <code>false</code>.
*/
private boolean getReportParamAllowMumble( ScalarParameterHandle param,
String propName )
{
if ( ALLOW_NULL_PROP_NAME.equalsIgnoreCase( propName ) )
return param.allowNull( );
else if ( ALLOW_BLANK_PROP_NAME.equalsIgnoreCase( propName ) )
return param.allowBlank( );
else
{
assert false;
return false;
}
}
/**
* Returns the boolean value of allowMumble properties. Only support
* "allowNull" and "allowBlank" properties.
* <p>
* "allowMumble" properties has been removed ROM. However, to do conversion,
* still need to know their values.
*
* @param param
* the parameter
* @param obsoletePropName
* either "allowNull" or "allowBlank".
*/
private void setReportParamIsRequired( ScalarParameterHandle param,
String obsoletePropName, boolean value ) throws SemanticException
{
if ( ALLOW_NULL_PROP_NAME.equalsIgnoreCase( obsoletePropName ) )
param.setAllowNull( value );
else if ( ALLOW_BLANK_PROP_NAME.equalsIgnoreCase( obsoletePropName ) )
param.setAllowBlank( value );
else
{
assert false;
}
}
}
|
package net.leolink.android.twitter4a;
import net.leolink.android.twitter4a.utils.Constants;
import net.leolink.android.twitter4a.widget.LoginDialog;
import net.leolink.android.twitter4a.widget.Spinner;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Window;
import android.webkit.CookieManager;
public abstract class Twitter4A {
public final static String TAG = "twitter4a";
// twitter4j's objects
private Twitter mTwitter;
private RequestToken mTwitterRequestToken;
private AccessToken mTwitterAccessToken;
private User mTwitterUser;
// twitter4a's objects
private String mConsumerKey;
private String mConsumerSecret;
private Activity mContext;
private boolean isLoggedIn = false;
private boolean isLoggingIn = false;
// Constructor
public Twitter4A(Activity context, String consumerKey,
String consumerSecret) {
mContext = context;
mConsumerKey = consumerKey;
mConsumerSecret = consumerSecret;
}
public void login() {
if (!isLoggingIn) {
// run an AsyncTask to get authentication URL, then open login dialog
new AsyncTask<Void, String, Void>() {
@Override
protected Void doInBackground(Void... voids) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(mConsumerKey);
builder.setOAuthConsumerSecret(mConsumerSecret);
twitter4j.conf.Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
mTwitter = factory.getInstance();
try {
mTwitterRequestToken = mTwitter.getOAuthRequestToken(Constants.TWITTER_CALLBACK_PREFIX);
publishProgress(mTwitterRequestToken.getAuthenticationURL());
} catch (TwitterException e) {
e.printStackTrace();
// call loginFailedCallback
loginFailedCallback();
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
// open LoginDialog to let user login to Twitter
if (!mContext.isFinishing())
new LoginDialog(mContext, Twitter4A.this, values[0]).show();
}
}.execute();
// Prevent calling login() function consecutively which leads to
// multiple LoginDialogs are opened at the same time
isLoggingIn = true;
}
}
// get data after login successfully
public void handleSuccessfulLogin(String uri) {
final Uri mUri = Uri.parse(uri);
final String verifier = mUri.getQueryParameter(Constants.URL_TWITTER_OAUTH_VERIFIER);
// Because this task need to using network which cannot be run on UI
// thread since Android 3.0 (maybe equivalent to API 11), so I need to
// use AsyncTask here!
new AsyncTask<Void, Void, Void>() {
private Spinner spinner;
protected void onPreExecute() {
spinner = new Spinner(mContext);
spinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
spinner.setCancelable(true);
spinner.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
mTwitterAccessToken = mTwitter.getOAuthAccessToken(mTwitterRequestToken, verifier);
mTwitterUser = mTwitter.showUser(mTwitterAccessToken.getUserId());
} catch (TwitterException e) {
e.printStackTrace();
// call loginFailedCallback
loginFailedCallback();
}
return null;
}
protected void onPostExecute(Void result) {
if (spinner.isShowing()) {
// dismiss the spinner
spinner.dismiss();
// if everything is okay, set isLoggedIn = true
isLoggedIn = true;
// call the callback
loginCallback();
} else { // if spinner is explicitly cancelled by user
// remove everything
mTwitter = null;
mTwitterAccessToken = null;
mTwitterRequestToken = null;
mTwitterUser = null;
// call loginFailedCallback
loginFailedCallback();
}
}
}.execute();
}
// logging out
public void logout() {
// remove all Twitter4J objects
mTwitter = null;
mTwitterAccessToken = null;
mTwitterRequestToken = null;
mTwitterUser = null;
isLoggedIn = false;
// inform programmers :)
Log.d(TAG, "Logged out successfully!");
// call the logout call back
this.logoutCallback();
}
// this method is called after login successfully
protected abstract void loginCallback();
// this method is called after logout successfully
protected abstract void logoutCallback();
// this method is called when login progress couldn't succeed for some reasons
public void loginFailedCallback() {
Log.e(TAG, "Login failed!");
}
public void setLoggingIn(boolean isLoggingIn) {
this.isLoggingIn = isLoggingIn;
}
// Get Twitter4J's objects -> For people who want to more than just a login
/**
* @return Twitter object of Twitter4J library
*/
public Twitter getTwitter4J() {
return mTwitter;
}
/**
* @return AccessToken object of Twitter4J library
*/
public AccessToken getTwitter4JAccessToken() {
return mTwitterAccessToken;
}
/**
* @return User object of Twitter4J library
*/
public User getTwitter4JUser() {
return mTwitterUser;
}
/**
* @return null if not logged in yet, otherwise return token of the current session
*/
public String getToken() {
if (mTwitterAccessToken != null)
return mTwitterAccessToken.getToken();
else
return null;
}
/**
* @return null if not logged in yet, otherwise return secret token of the current session
*/
public String getTokenSecret() {
if (mTwitterAccessToken != null)
return mTwitterAccessToken.getTokenSecret();
else
return null;
}
// Get basic user data -> For people who just want a login to get some basic data
/**
* @return return current login state
*/
public boolean isLoggedIn() {
return isLoggedIn;
}
/**
* @return userID of the current logged in user
*/
public long getUserID() {
if (mTwitterUser != null)
return mTwitterUser.getId();
else
return 0;
}
/**
* @return user name of the current logged in user
*/
public String getUsername() {
if (mTwitterUser != null)
return mTwitterUser.getName();
else
return null;
}
/**
* @return original profile picture URL of the user of the current logged in user
*/
public String getProfilePicURL() {
if (mTwitterUser != null)
return mTwitterUser.getOriginalProfileImageURL();
else
return null;
}
}
|
package com.versionone.common.sdk;
import com.versionone.apiclient.Asset;
import com.versionone.apiclient.Attribute;
import com.versionone.apiclient.IAttributeDefinition;
import com.versionone.apiclient.MetaException;
/**
* This class represents one Task in the VersionOne system
* @author jerry
*/
public class Task {
private static final String ID_NUMBER_PROPERTY = "Number";
private static final String NAME_PROPERTY = "Name";
private static final String PARENT_NAME_PROPERTY = "Parent.Name";
private static final String DETAIL_ESTIMATE_PROPERTY = "DetailEstimate";
private static final String TO_DO_PROPERTY = "ToDo";
private static final String STATUS_ID_PROPERTY = "Status";
private static final String DONE_PROPERTY = "Actuals.Value.@Sum";
private static final float INITIAL_EFFORT = -1;
private static final String TASK_PREFIX = "Task.";
IAttributeDefinition _nameDefinition;
IAttributeDefinition _estimateDefinition;
IAttributeDefinition _todoDefinition;
IAttributeDefinition _statusDefinition;
Asset _asset;
Float _effortValue = new Float(INITIAL_EFFORT);
/**
* Create
* @param asset - Task asset
* @throws MetaException
*/
Task(Asset asset) throws MetaException {
_asset = asset;
_nameDefinition = _asset.getAssetType().getAttributeDefinition(NAME_PROPERTY);
_estimateDefinition = _asset.getAssetType().getAttributeDefinition(DETAIL_ESTIMATE_PROPERTY);
_todoDefinition = _asset.getAssetType().getAttributeDefinition(TO_DO_PROPERTY);
_statusDefinition = _asset.getAssetType().getAttributeDefinition(STATUS_ID_PROPERTY);
}
public String getStoryName() throws Exception {
return getValue(PARENT_NAME_PROPERTY);
}
public String getToken() throws Exception {
return _asset.getOid().getToken();
}
public String getName() throws Exception {
return getValue(NAME_PROPERTY);
}
public void setName(String value) throws Exception {
_asset.setAttributeValue(_nameDefinition, value);
}
public String getID() throws Exception {
return getValue(ID_NUMBER_PROPERTY);
}
/**
* Detail Estimate
* @return value of estimate or -1 if the attribute is blank
* @throws Exception
*/
public float getEstimate() throws Exception {
return getFloatValue(_estimateDefinition);
}
public void setEstimate(float value) throws Exception {
if(0 > value)
throw new IllegalArgumentException("Estimate cannot be negative");
_asset.setAttributeValue(_estimateDefinition, value);
}
/**
* Remaining work
* @return value of estimate or -1 if the attribute is blank
* @throws Exception
*/
public float getToDo() throws Exception {
return getFloatValue(_todoDefinition);
}
public void setToDo(float value) throws Exception {
if(0 > value)
throw new IllegalArgumentException("ToDo cannot be negative");
_asset.setAttributeValue(_todoDefinition, value);
}
/**
* Object identifier (token) of current status
* @return status token
* @throws Exception
*/
public String getStatus() throws Exception {
Attribute attrib = _asset.getAttribute(_statusDefinition);
return attrib.getValue().toString();
}
/**
* Set the Status value
* @param value - the OID for the desired status value
* @throws Exception
*/
public void setStatus(String value) throws Exception {
_asset.setAttributeValue(_statusDefinition, value);
}
/**
* How much work has been done
* @return
* @throws Exception
*/
public String getDone() throws Exception {
return getValue(DONE_PROPERTY);
}
/**
* Effort on this task
* @return value of estimate or -1 if the attribute is blank
*/
public float getEffort() {
return _effortValue;
}
public void setEffort(float value) throws Exception {
_effortValue = value;
}
/**
* Has this instance been modified?
* @return true if a change was made
*/
public boolean isDirty() {
return (_asset.hasChanged()) || (INITIAL_EFFORT != _effortValue.floatValue());
}
/**
* Get the value of an attribute
* @param key - name of attribute
* @return value
* @throws Exception
*/
String getValue(String key) throws Exception {
if(_asset.getAttributes().containsKey(TASK_PREFIX + key)) {
Object value = _asset.getAttributes().get(TASK_PREFIX + key).getValue();
if(null == value) {
return "";
}
return value.toString();
}
// if this was a 'real' sdk, then you'd go back to the server and retrieve the attribute
return "";
}
/**
* Return the float value of an attribute definition
* @param attribute
* @return value of attribute or -1 if the attribute does not exist
* @throws Exception
*/
float getFloatValue(IAttributeDefinition attribute) throws Exception {
float rc = -1;
Attribute attrib = _asset.getAttribute(attribute);
if(null != attrib) {
Float value = ((Float)attrib.getValue());
if(null != value)
rc = value.floatValue();
}
return rc;
}
}
|
package org.pac4j.jwt.profile;
import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWEHeader;
import com.nimbusds.jose.JWEObject;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.DirectEncrypter;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.PlainJWT;
import com.nimbusds.jwt.SignedJWT;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.jwt.JwtConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Map;
/**
* Generates a JWT token from a user profile.
*
* @author Jerome Leleu
* @since 1.8.0
*/
public class JwtGenerator<U extends CommonProfile> {
public static final String INTERNAL_ROLES = "$int_roles";
public static final String INTERNAL_PERMISSIONS = "$int_perms";
protected final Logger logger = LoggerFactory.getLogger(getClass());
private String signingSecret;
private String encryptionSecret;
private JWSAlgorithm jwsAlgorithm = JWSAlgorithm.HS256;
private JWEAlgorithm jweAlgorithm = JWEAlgorithm.DIR;
private EncryptionMethod encryptionMethod = EncryptionMethod.A256GCM;
public JwtGenerator(final String secret) {
this(secret, true);
}
public JwtGenerator(final String secret, final boolean encrypted) {
this.signingSecret = secret;
if (encrypted) {
this.encryptionSecret = secret;
logger.warn("Using the same key for signing and encryption may lead to security vulnerabilities. Consider using different keys");
}
}
/**
* Initializes the generator that will create JWT tokens that is signed and optionally encrypted.
*
* @param signingSecret The signingSecret. Must be at least 256 bits long and not {@code null}
* @param encryptionSecret The encryptionSecret. Must be at least 256 bits long and not {@code null} if you want encryption
* @since 1.8.2
*/
public JwtGenerator(final String signingSecret, final String encryptionSecret) {
this.signingSecret = signingSecret;
this.encryptionSecret = encryptionSecret;
}
/**
* Generates a JWT from a user profile.
*
* @param profile the given user profile
* @return the created JWT
*/
public String generate(final U profile) {
return generate(profile, null, this.jwsAlgorithm);
}
/**
* Generates a JWT from a user profile.
*
* @param profile the given user profile
* @param signer the given user profile
* @param jwsAlgorithm the signing algorithm
* @return the created JWT
*/
public String generate(final U profile, final JWSSigner signer, final JWSAlgorithm jwsAlgorithm) {
verifyProfile(profile);
try {
final JWTClaimsSet claims = buildJwtClaimsSet(profile);
if (CommonHelper.isNotBlank(this.signingSecret)) {
CommonHelper.assertNotNull("jwsAlgorithm", jwsAlgorithm);
final SignedJWT signedJWT = signJwt(claims, signer, jwsAlgorithm);
if (CommonHelper.isNotBlank(this.encryptionSecret)) {
CommonHelper.assertNotNull("jweAlgorithm", jweAlgorithm);
CommonHelper.assertNotNull("encryptionMethod", encryptionMethod);
return encryptJwt(signedJWT);
}
return signedJWT.serialize();
}
return new PlainJWT(claims).serialize();
} catch (final Exception e) {
throw new TechnicalException("Cannot generate JWT", e);
}
}
protected String encryptJwt(final SignedJWT signedJWT) throws Exception {
// Create JWE object with signed JWT as payload
final JWEObject jweObject = new JWEObject(
new JWEHeader.Builder(jweAlgorithm, encryptionMethod).contentType("JWT").build(),
new Payload(signedJWT));
// Perform encryption
jweObject.encrypt(new DirectEncrypter(this.encryptionSecret.getBytes("UTF-8")));
// Serialise to JWE compact form
return jweObject.serialize();
}
protected SignedJWT signJwt(final JWTClaimsSet claims, JWSSigner signer, JWSAlgorithm jwsAlgorithm) throws JOSEException {
if (signer == null) {
// Create HMAC signer
signer = new MACSigner(this.signingSecret);
}
final SignedJWT signedJWT = new SignedJWT(new JWSHeader(jwsAlgorithm), claims);
// Apply the HMAC
signedJWT.sign(signer);
return signedJWT;
}
protected JWTClaimsSet buildJwtClaimsSet(final U profile) {
// Build claims
final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder()
.subject(profile.getTypedId())
.issueTime(new Date());
// add attributes
final Map<String, Object> attributes = profile.getAttributes();
for (final Map.Entry<String, Object> entry : attributes.entrySet()) {
builder.claim(entry.getKey(), entry.getValue());
}
builder.claim(INTERNAL_ROLES, profile.getRoles());
builder.claim(INTERNAL_PERMISSIONS, profile.getPermissions());
// claims
return builder.build();
}
private void verifyProfile(final U profile) {
CommonHelper.assertNotNull("profile", profile);
CommonHelper.assertNull("profile.sub", profile.getAttribute(JwtConstants.SUBJECT));
CommonHelper.assertNull("profile.iat", profile.getAttribute(JwtConstants.ISSUE_TIME));
CommonHelper.assertNull(INTERNAL_ROLES, profile.getAttribute(INTERNAL_ROLES));
CommonHelper.assertNull(INTERNAL_PERMISSIONS, profile.getAttribute(INTERNAL_PERMISSIONS));
}
public String getSigningSecret() {
return signingSecret;
}
public void setSigningSecret(final String signingSecret) {
this.signingSecret = signingSecret;
}
public String getEncryptionSecret() {
return encryptionSecret;
}
public void setEncryptionSecret(final String encryptionSecret) {
this.encryptionSecret = encryptionSecret;
}
public JWSAlgorithm getJwsAlgorithm() {
return jwsAlgorithm;
}
/**
* Only the HS256, HS384 and HS512 are currently supported.
*
* @param jwsAlgorithm the signing algorithm
*/
public void setJwsAlgorithm(final JWSAlgorithm jwsAlgorithm) {
this.jwsAlgorithm = jwsAlgorithm;
}
public JWEAlgorithm getJweAlgorithm() {
return jweAlgorithm;
}
public void setJweAlgorithm(final JWEAlgorithm jweAlgorithm) {
this.jweAlgorithm = jweAlgorithm;
}
public EncryptionMethod getEncryptionMethod() {
return encryptionMethod;
}
public void setEncryptionMethod(final EncryptionMethod encryptionMethod) {
this.encryptionMethod = encryptionMethod;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.