answer stringlengths 17 10.2M |
|---|
package org.jaulp.wicket.base.util.properties;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.jaulp.locale.PropertiesKeysListResolver;
import net.sourceforge.jaulp.locale.ResourceBundleKey;
import org.apache.wicket.Component;
import org.jaulp.wicket.base.util.resource.ResourceModelFactory;
/**
* The Class ComponentPropertiesKeysListResolver creates a list with the properties keys
* from the given list with the given prefix and optionally a suffix. This class
* is usefull for get Properties that have a properties key prefix for instance:
* properties key prefix='infringement.list.entry' and the properties key prefix='label'.
* The values list contains:
* a ResourceBundleKey object with the key '1' and with parameters '7'
* and a second ResourceBundleKey object with the key '2' with no parameters.
* The properties file could look something like this:
* infringement.list.entry.1.label = foo {0}
* infringement.list.entry.2.label = bar
*/
public class ComponentPropertiesKeysListResolver extends
PropertiesKeysListResolver<ResourceBundleKey> {
/** The relative component used for lookups. */
private Component component;
/**
* Instantiates a new properties list view renderer.
*
* @param propertiesKeyPrefix
* the properties key prefix
* @param component
* the component
* @param values
* the values
*/
public ComponentPropertiesKeysListResolver(String propertiesKeyPrefix,
Component component, List<ResourceBundleKey> values) {
this(propertiesKeyPrefix, null, component, values);
}
/**
* Instantiates a new properties list view renderer.
*
* @param propertiesKeyPrefix
* the properties key prefix
* @param propertiesKeySuffix
* the properties key suffix
* @param component
* the component
* @param values
* the values
*/
public ComponentPropertiesKeysListResolver(String propertiesKeyPrefix,
String propertiesKeySuffix, Component component,
List<ResourceBundleKey> values) {
super(propertiesKeyPrefix, propertiesKeySuffix, values);
this.component = component;
}
/**
* Gets the display value.
*
* @param resourceBundleKey
* the {@link ResourceBundleKey} object
* @return the display value
*/
public String getDisplayValue(final ResourceBundleKey resourceBundleKey) {
return ResourceModelFactory.newResourceModel(
getPropertiesKey(resourceBundleKey.getKey()),
resourceBundleKey.getParameters(),
component,
resourceBundleKey.getDefaultValue())
.getObject();
}
/**
* Gets the display values with the full properties keys as a List of {@link ResourceBundleKey}.
*
* @return the display values
*/
public List<ResourceBundleKey> getDisplayValues() {
List<ResourceBundleKey> rbk = new ArrayList<ResourceBundleKey>();
for(ResourceBundleKey key : getValues()) {
ResourceBundleKey clone = (ResourceBundleKey) key.clone();
clone.setKey(getPropertiesKey(key.getKey()));
rbk.add(clone);
}
return rbk;
}
} |
package de.ddb.pdc.metadata;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
class RDFItem {
@JsonProperty("ProvidedCHO")
private Map<String, Object> providedCHO;
@JsonProperty("Agent")
private Object agents;
@JsonProperty("Aggregation")
private Map<String, Object> aggregation;
/**
* @return a 4 digit int if a issued year is found or -1
*/
public int getPublishYear() {
try {
String publishedYear = (String) providedCHO.get("issued");
if (publishedYear == null) {
// The item is missing the publishing date.
return -1;
}
return getDateAsInt(publishedYear,"\\d{4}");
} catch (NumberFormatException e) {
return -1;
}
}
private int getDateAsInt(String date, String regex) {
return Integer.parseInt(MetadataUtils.useRegex(date, regex));
}
/**
* @return institution from the dataProvider item of aggregation
*/
public String getInstitution() {
List<Object> dataProvider = (ArrayList<Object>) aggregation
.get("dataProvider");
if (dataProvider == null || dataProvider.size() == 0) {
return null;
}
return dataProvider.get(0).toString();
}
/**
* @return list of all author ids
*/
public List<String> getAuthorIds() {
List<String> authorIds = new ArrayList<>();
List<Map> agents = getAgents();
if (agents != null) {
for (Map agent : getAgents()) {
String about = agent.get("@about").toString();
if (about.startsWith("http://d-nb.info/")) {
authorIds.add(about);
}
}
}
return authorIds;
}
/**
* @return list of all agents item in rdf item
*/
private List<Map> getAgents() {
if (agents == null) {
return null;
}
if (agents instanceof List) {
// Multiple agents
return (List) agents;
} else {
// A single agent
List<Map> agentList = new ArrayList<>();
agentList.add((Map) agents);
return agentList;
}
}
} |
/*
* @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.layout;
import org.gridlab.gridsphere.core.persistence.castor.descriptor.Description;
import org.gridlab.gridsphere.layout.event.PortletComponentEvent;
import org.gridlab.gridsphere.layout.event.PortletTabEvent;
import org.gridlab.gridsphere.layout.event.impl.PortletTabEventImpl;
import org.gridlab.gridsphere.portlet.PortletRequest;
import org.gridlab.gridsphere.portlet.PortletResponse;
import org.gridlab.gridsphere.portlet.PortletURI;
import org.gridlab.gridsphere.portlet.impl.SportletProperties;
import org.gridlab.gridsphere.portletcontainer.GridSphereEvent;
import java.io.Serializable;
import java.util.*;
/**
* A <code>PortletTab</code> represents the visual tab graphical interface and is contained
* by a {@link PortletTabbedPane}. A tab contains a title and any additional
* portlet component, such as another tabbed pane if a double level
* tabbed pane is desired.
*/
public class PortletTab extends BasePortletComponent implements Serializable, Cloneable, Comparator {
public static final int DEFAULT_USERTAB_ORDER = 20;
private String title = "?";
private List titles = new ArrayList();
private transient boolean selected = false;
private String url = null;
private PortletComponent portletComponent = null;
private int tabOrder = 50;
//protected StringBuffer tab = new StringBuffer();
/**
* Constructs an instance of PortletTab
*/
public PortletTab() {
}
/**
* Constructs an instance of PortletTab with the supplied title and
* portlet component.
*
* @param titles the titles of the portlet tab
* @param portletComponent any portlet component to represent beneath the tab
*/
public PortletTab(List titles, PortletComponent portletComponent) {
this.titles = titles;
this.portletComponent = portletComponent;
}
public int getTabOrder() {
return tabOrder;
}
public void setTabOrder(int tabOrder) {
this.tabOrder = tabOrder;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
/**
* Returns the portlet tab title
*
* @return the portlet tab title
*/
public List getTitles() {
return titles;
}
/**
* Sets the portlet tab title
*
* @param titles the portlet tab title
*/
public void setTitles(List titles) {
this.titles = titles;
}
/**
* Returns the portlet tab title
*
* @return the portlet tab title
*/
public String getTitle() {
return title;
}
/**
* Sets the portlet tab title
*
* @param title the portlet tab title
*/
public void setTitle(String title) {
this.title = title;
}
public String getTitle(String lang) {
if (lang == null) throw new IllegalArgumentException("lang is NULL");
Iterator it = titles.iterator();
String defTitle = title;
while (it.hasNext()) {
Description t = (Description) it.next();
if (t.getLang() == null) t.setLang(Locale.ENGLISH.getLanguage());
if (lang.equals(t.getLang())) return t.getText();
if (t.getLang().regionMatches(0, lang, 0, 2)) return t.getText();
if (t.getLang().equals(Locale.ENGLISH.getLanguage())) defTitle = t.getText();
}
return defTitle;
}
public void setTitle(String lang, String title) {
Iterator it = titles.iterator();
boolean found = false;
if (lang == null) throw new IllegalArgumentException("lang is NULL");
if (title == null) throw new IllegalArgumentException("title is NULL");
while (it.hasNext()) {
Description t = (Description) it.next();
if (lang.equalsIgnoreCase(t.getLang())) {
found = true;
t.setText(title);
}
}
if (!found) {
Description t = new Description();
t.setLang(lang);
t.setText(title);
titles.add(t);
}
}
/**
* Creates the portlet tab title links that are rendered by the
* {@link PortletTabbedPane}
*
* @param event the gridsphere event
*/
public String createTabTitleLink(GridSphereEvent event) {
if (url != null) return url;
PortletResponse res = event.getPortletResponse();
PortletURI portletURI = res.createURI();
portletURI.addParameter(SportletProperties.COMPONENT_ID, componentIDStr);
return portletURI.toString();
}
/**
* Sets the selected flag used in determining if this tab is selected and
* should be rendered
*
* @param selected the selected flag is true if this tag is currently selected
*/
public void setSelected(boolean selected) {
this.selected = selected;
}
/**
* Returns the selected flag used in determining if this tab is selected and
* hence rendered
*
* @return true if the tab is selected, false otherwise
*/
public boolean isSelected() {
return selected;
}
/**
* Sets the concrete portlet component contained by the portlet tab
*
* @param portletComponent a concrete portlet component instance
*/
public void setPortletComponent(PortletComponent portletComponent) {
this.portletComponent = portletComponent;
}
/**
* Returns the concrete portlet component contained by the portlet tab
*
* @return the concrete portlet component instance conatined by this tab
*/
public PortletComponent getPortletComponent() {
return portletComponent;
}
public void removePortletComponent() {
this.portletComponent = null;
}
/**
* Initializes the portlet tab. Since the components are isolated
* after Castor unmarshalls from XML, the ordering is determined by a
* passed in List containing the previous portlet components in the tree.
*
* @param list a list of component identifiers
* @return a list of updated component identifiers
* @see ComponentIdentifier
*/
public List init(PortletRequest req, List list) {
list = super.init(req, list);
ComponentIdentifier compId = new ComponentIdentifier();
compId.setPortletComponent(this);
compId.setComponentID(list.size());
compId.setComponentLabel(label);
compId.setClassName(this.getClass().getName());
list.add(compId);
portletComponent.setTheme(theme);
portletComponent.setRenderKit(renderKit);
list = portletComponent.init(req, list);
portletComponent.addComponentListener(this);
portletComponent.setParentComponent(this);
return list;
}
public void remove(PortletComponent pc, PortletRequest req) {
portletComponent = null;
parent.remove(this, req);
}
/**
* Performs an action on this portlet tab component
*
* @param event a gridsphere event
*/
public void actionPerformed(GridSphereEvent event) {
super.actionPerformed(event);
PortletComponentEvent compEvt = event.getLastRenderEvent();
PortletTabEvent tabEvent = new PortletTabEventImpl(this, event.getPortletRequest(), PortletTabEvent.TabAction.TAB_SELECTED, COMPONENT_ID);
List l = Collections.synchronizedList(listeners);
synchronized (l) {
Iterator it = l.iterator();
PortletComponent comp;
while (it.hasNext()) {
comp = (PortletComponent) it.next();
event.addNewRenderEvent(tabEvent);
comp.actionPerformed(event);
}
}
}
/**
* Renders the portlet tab component
*
* @param event a gridsphere event
*/
public void doRender(GridSphereEvent event) {
super.doRender(event);
List userRoles = event.getPortletRequest().getRoles();
StringBuffer tab = new StringBuffer();
if (roleString.equals("") || (userRoles.contains(roleString))) {
portletComponent.doRender(event);
tab.append(portletComponent.getBufferedOutput(event.getPortletRequest()));
}
event.getPortletRequest().setAttribute(SportletProperties.RENDER_OUTPUT + componentIDStr, tab);
}
public int compare(Object left, Object right) {
int leftID = ((PortletTab) left).getTabOrder();
int rightID = ((PortletTab) right).getTabOrder();
int result;
if (leftID < rightID) {
result = -1;
} else if (leftID > rightID) {
result = 1;
} else {
result = 0;
}
return result;
}
public boolean equals(Object object) {
if (object != null && (object.getClass().equals(this.getClass()))) {
PortletTab portletTab = (PortletTab) object;
return (tabOrder == portletTab.getTabOrder());
}
return false;
}
public Object clone() throws CloneNotSupportedException {
PortletTab t = (PortletTab) super.clone();
t.tabOrder = this.tabOrder;
t.url = this.url;
t.portletComponent = (this.portletComponent == null) ? null : (PortletComponent) this.portletComponent.clone();
t.selected = this.selected;
List stitles = Collections.synchronizedList(titles);
synchronized (stitles) {
t.titles = new ArrayList(stitles.size());
for (int i = 0; i < stitles.size(); i++) {
Description title = (Description) stitles.get(i);
t.titles.add(title.clone());
}
}
return t;
}
} |
package com.bbn.kbp.events2014.scorer.observers.breakdowns;
import com.bbn.bue.common.collections.MultimapUtils;
import com.bbn.bue.common.diff.ProvenancedConfusionMatrix;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.bue.common.symbols.SymbolUtils;
import com.bbn.kbp.events2014.TypeRoleFillerRealis;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Ordering;
import java.util.Map;
public final class BreakdownFunctions {
public static final Function<TypeRoleFillerRealis,Symbol> TypeDotRole = new Function<TypeRoleFillerRealis, Symbol> () {
@Override
public Symbol apply(TypeRoleFillerRealis input) {
return Symbol.from(input.type().toString() + "." + input.role().toString());
}
};
/**
* Will identify genres for ACE and pilot documents. Ideally this would be refactored to read the mappings from
* a file.
*/
public static final Function<TypeRoleFillerRealis,Symbol> Genre = new GenreFunction();
private static class GenreFunction implements Function<TypeRoleFillerRealis, Symbol> {
@Override
public Symbol apply(TypeRoleFillerRealis input) {
final String docid = input.docID().toString();
for (final Map.Entry<String, Symbol> classifier : prefixToGenre.entrySet()) {
if (docid.startsWith(classifier.getKey())) {
return classifier.getValue();
}
}
return UNKNOWN;
}
private static final Symbol UNKNOWN = Symbol.from("Unknown");
private static final Symbol NW = Symbol.from("Newswire");
private static final Symbol DF = Symbol.from("Forum");
private static final Symbol BLOG = Symbol.from("Blog");
private static final Symbol SPEECH = Symbol.from("Speech");
private static final Symbol BC = Symbol.from("Broadcast conversation");
private static final Symbol BN = Symbol.from("Broadast News");
private static final Map<String, Symbol> prefixToGenre = MultimapUtils.copyAsMap(
ImmutableMultimap.<Symbol, String>builder()
.putAll(BC, "CNN_CF", "CNN_IP")
.putAll(BN, "CNN_", "CNNHL")
.putAll(DF, "bolt", "marce", "alt.", "aus.cars", "Austin-Grad", "misc.",
"rec.", "seattle.", "soc.", "talk.", "uk.")
.putAll(NW, "APW", "AFP", "CNA", "NYT", "WPB", "XIN")
.putAll(BLOG, "AGGRESSIVEVOICEDAILY", "BACONSREBELLION",
"FLOPPING_ACES", "GETTINGPOLITICAL", "HEALINGIRAQ", "MARKBACKER", "OIADVANTAGE", "TTRACY")
.putAll(SPEECH, "fsh_")
.build()
.inverse());
};
public static final Map<String, Function<TypeRoleFillerRealis, Symbol>> StandardBreakdowns = ImmutableMap.of(
"Type", TypeRoleFillerRealis.Type,
"Role", BreakdownFunctions.TypeDotRole,
"Genre", BreakdownFunctions.Genre,
"DocId", TypeRoleFillerRealis.DocID);
private BreakdownFunctions() {
throw new UnsupportedOperationException();
}
public static <ProvenanceType>
ImmutableMap<String, Map<Symbol, ProvenancedConfusionMatrix<ProvenanceType>>> computeBreakdowns(
ProvenancedConfusionMatrix<ProvenanceType> corpusConfusionMatrix,
Map<String, Function<? super ProvenanceType, Symbol>> breakdowns)
{
final ImmutableMap.Builder<String, Map<Symbol, ProvenancedConfusionMatrix<ProvenanceType>>> printModes =
ImmutableMap.builder();
for (final Map.Entry<String, Function<? super ProvenanceType, Symbol>> breakdownEntry : breakdowns.entrySet()) {
printModes.put(breakdownEntry.getKey(), corpusConfusionMatrix.breakdown(breakdownEntry.getValue(),
Ordering.from(new SymbolUtils.ByString())));
}
return printModes.build();
}
} |
package de.skuzzle.semantic;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public final class Version implements Comparable<Version>, Serializable {
/** Conforms to all Version implementations since 0.6.0 */
private static final long serialVersionUID = 6034927062401119911L;
private static final String[] EMPTY_ARRAY = new String[0];
/**
* Semantic Version Specification to which this class complies.
*
* @since 0.2.0
*/
public static final Version COMPLIANCE = Version.create(2, 0, 0);
/**
* This exception indicates that a version- or a part of a version string could not be
* parsed according to the semantic version specification.
*
* @author Simon Taddiken
*/
public static class VersionFormatException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates a new VersionFormatException with the given message.
*
* @param message The exception message.
*/
private VersionFormatException(String message) {
super(message);
}
}
public static final Comparator<Version> NATURAL_ORDER = Version::compare;
public static final Comparator<Version> WITH_BUILD_META_DATA_ORDER = Version::compareWithBuildMetaData;
private static final int TO_STRING_ESTIMATE = 16;
// state machine states for parsing a version string
private static final int STATE_MAJOR_INIT = 0;
private static final int STATE_MAJOR_LEADING_ZERO = 1;
private static final int STATE_MAJOR_DEFAULT = 2;
private static final int STATE_MINOR_INIT = 3;
private static final int STATE_MINOR_LEADING_ZERO = 4;
private static final int STATE_MINOR_DEFAULT = 5;
private static final int STATE_PATCH_INIT = 6;
private static final int STATE_PATCH_LEADING_ZERO = 7;
private static final int STATE_PATCH_DEFAULT = 8;
private static final int STATE_PRERELEASE_INIT = 9;
private static final int STATE_BUILDMD_INIT = 10;
private static final int STATE_PART_INIT = 0;
private static final int STATE_PART_LEADING_ZERO = 1;
private static final int STATE_PART_NUMERIC = 2;
private static final int STATE_PART_DEFAULT = 3;
private static final int DECIMAL = 10;
private static final int EOS = -1;
private static final int FAILURE = -2;
private final int major;
private final int minor;
private final int patch;
private final String[] preReleaseParts;
private final String[] buildMetaDataParts;
// Since 1.1.0
// these fields are only necessary for deserializing previous versions
// see #readResolve method
@Deprecated
private String preRelease;
@Deprecated
private String buildMetaData;
// store hash code once it has been calculated
private static final int NOT_YET_CALCULATED = 2;
private static final int HASH_PRIME = 31;
private volatile int hash = NOT_YET_CALCULATED;
private Version(int major, int minor, int patch, String[] preRelease,
String[] buildMd) {
checkParams(major, minor, patch);
this.major = major;
this.minor = minor;
this.patch = patch;
this.preReleaseParts = preRelease;
this.buildMetaDataParts = buildMd;
}
private static Version parse(String s, boolean verifyOnly) {
/*
* Since 1.1.0:
*
* This huge and ugly inline parsing replaces the prior regex because it is way
* faster. Besides that it also does provide better error messages in case a
* String could not be parsed correctly. Condition and mutation coverage is
* extremely high to ensure correctness.
*/
// note: getting the char array once is faster than calling charAt multiple times
final char[] stream = s.toCharArray();
int major = 0;
int minor = 0;
int patch = 0;
int state = STATE_MAJOR_INIT;
List<String> preRelease = null;
List<String> buildMd = null;
loop: for (int i = 0; i <= stream.length; ++i) {
final int c = i < stream.length ? stream[i] : EOS;
switch (state) {
// Parse major part
case STATE_MAJOR_INIT:
if (c == '0') {
state = STATE_MAJOR_LEADING_ZERO;
} else if (c >= '1' && c <= '9') {
major = major * DECIMAL + Character.digit(c, DECIMAL);
state = STATE_MAJOR_DEFAULT;
} else if (verifyOnly) {
return null;
} else {
throw unexpectedChar(s, c);
}
break;
case STATE_MAJOR_LEADING_ZERO:
if (c == '.') {
// single 0 is allowed
state = STATE_MINOR_INIT;
} else if (c >= '0' && c <= '9') {
if (verifyOnly) {
return null;
}
throw illegalLeadingChar(s, '0', "major");
} else if (verifyOnly) {
return null;
} else {
throw unexpectedChar(s, c);
}
break;
case STATE_MAJOR_DEFAULT:
if (c >= '0' && c <= '9') {
major = major * DECIMAL + Character.digit(c, DECIMAL);
} else if (c == '.') {
state = STATE_MINOR_INIT;
} else if (verifyOnly) {
return null;
} else {
throw unexpectedChar(s, c);
}
break;
// parse minor part
case STATE_MINOR_INIT:
if (c == '0') {
state = STATE_MINOR_LEADING_ZERO;
} else if (c >= '1' && c <= '9') {
minor = minor * DECIMAL + Character.digit(c, DECIMAL);
state = STATE_MINOR_DEFAULT;
} else if (verifyOnly) {
return null;
} else {
throw unexpectedChar(s, c);
}
break;
case STATE_MINOR_LEADING_ZERO:
if (c == '.') {
// single 0 is allowed
state = STATE_PATCH_INIT;
} else if (c >= '0' && c <= '9') {
if (verifyOnly) {
return null;
}
throw illegalLeadingChar(s, '0', "minor");
} else if (verifyOnly) {
return null;
} else {
throw unexpectedChar(s, c);
}
break;
case STATE_MINOR_DEFAULT:
if (c >= '0' && c <= '9') {
minor = minor * DECIMAL + Character.digit(c, DECIMAL);
} else if (c == '.') {
state = STATE_PATCH_INIT;
} else if (verifyOnly) {
return null;
} else {
throw unexpectedChar(s, c);
}
break;
// parse patch part
case STATE_PATCH_INIT:
if (c == '0') {
state = STATE_PATCH_LEADING_ZERO;
} else if (c >= '1' && c <= '9') {
patch = patch * DECIMAL + Character.digit(c, DECIMAL);
state = STATE_PATCH_DEFAULT;
} else if (verifyOnly) {
return null;
} else {
throw unexpectedChar(s, c);
}
break;
case STATE_PATCH_LEADING_ZERO:
if (c == '-') {
// single 0 is allowed
state = STATE_PRERELEASE_INIT;
} else if (c == '+') {
state = STATE_BUILDMD_INIT;
} else if (c == EOS) {
break loop;
} else if (c >= '0' && c <= '9') {
if (verifyOnly) {
return null;
}
throw illegalLeadingChar(s, '0', "patch");
} else if (verifyOnly) {
return null;
} else {
throw unexpectedChar(s, c);
}
break;
case STATE_PATCH_DEFAULT:
if (c >= '0' && c <= '9') {
patch = patch * DECIMAL + Character.digit(c, DECIMAL);
} else if (c == '-') {
state = STATE_PRERELEASE_INIT;
} else if (c == '+') {
state = STATE_BUILDMD_INIT;
} else if (c != EOS) {
// eos is allowed here
if (verifyOnly) {
return null;
}
throw unexpectedChar(s, c);
}
break;
case STATE_PRERELEASE_INIT:
preRelease = verifyOnly ? null : new ArrayList<String>();
i = parseID(stream, s, i, verifyOnly, false, true, preRelease,
"pre-release");
if (i == FAILURE) {
// implies verifyOnly == true, otherwise exception would have been
// thrown
return null;
}
final int c1 = i < stream.length ? stream[i] : EOS;
if (c1 == '+') {
state = STATE_BUILDMD_INIT;
} else {
break loop;
}
break;
case STATE_BUILDMD_INIT:
buildMd = verifyOnly ? null : new ArrayList<String>();
i = parseID(stream, s, i, verifyOnly, true, false, buildMd,
"build-meta-data");
if (i == FAILURE) {
// implies verifyOnly == true, otherwise exception would have been
// thrown
return null;
}
break loop;
default:
throw new IllegalStateException("Illegal state: " + state);
}
}
final String[] prerelease = preRelease == null ? EMPTY_ARRAY
: preRelease.toArray(new String[preRelease.size()]);
final String[] buildmetadata = buildMd == null ? EMPTY_ARRAY
: buildMd.toArray(new String[buildMd.size()]);
return new Version(major, minor, patch, prerelease, buildmetadata);
}
private static int parseID(char[] stream, String full, int start, boolean verifyOnly,
boolean allowLeading0, boolean preRelease, List<String> parts,
String partName) {
assert verifyOnly || parts != null;
final StringBuilder b = verifyOnly
? null
: new StringBuilder(stream.length - start);
int i = start;
while (i <= stream.length) {
i = parseIDPart(stream, full, i, verifyOnly, allowLeading0, preRelease, true,
b, partName);
if (i == FAILURE) {
// implies verifyOnly == true, otherwise exception would have been thrown
return FAILURE;
} else if (!verifyOnly) {
parts.add(b.toString());
}
final int c = i < stream.length ? stream[i] : EOS;
if (c == '.') {
// keep looping
++i;
} else {
// identifier is done (hit EOS or '+')
return i;
}
}
throw new IllegalStateException();
}
private static int parseIDPart(char[] stream, String full, int start,
boolean verifyOnly,
boolean allowLeading0, boolean preRelease, boolean allowDot,
StringBuilder b, String partName) {
if (b != null) {
b.setLength(0);
}
int state = STATE_PART_INIT;
for (int i = start; i <= stream.length; ++i) {
final int c = i < stream.length ? stream[i] : EOS;
switch (state) {
case STATE_PART_INIT:
if (c == '0' && !allowLeading0) {
state = STATE_PART_LEADING_ZERO;
if (b != null) {
b.append('0');
}
} else if (c == '-' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
|| c >= '0' && c <= '9') {
if (b != null) {
b.appendCodePoint(c);
}
state = STATE_PART_DEFAULT;
} else if (c == '.') {
if (verifyOnly) {
return FAILURE;
}
throw unexpectedChar(full, -1);
} else {
if (verifyOnly) {
return FAILURE;
}
throw unexpectedChar(full, c);
}
break;
case STATE_PART_LEADING_ZERO:
// when in this state we consumed a single '0'
if (c == '-' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (b != null) {
b.appendCodePoint(c);
}
state = STATE_PART_DEFAULT;
} else if (c >= '0' && c <= '9') {
if (b != null) {
b.appendCodePoint(c);
}
state = STATE_PART_NUMERIC;
} else if (c == '.' && allowDot || c == EOS || c == '+' && preRelease) {
// if we are parsing a pre release part it can be terminated by a
// '+' in case a build meta data follows
// here, this part consist of a single '0'
return i;
} else if (verifyOnly) {
return FAILURE;
} else {
throw unexpectedChar(full, c);
}
break;
case STATE_PART_NUMERIC:
// when in this state, the part began with a '0' and we only consumed
// numeric chars so far
if (c == '-' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (b != null) {
b.appendCodePoint(c);
}
state = STATE_PART_DEFAULT;
} else if (c >= '0' && c <= '9') {
if (b != null) {
b.appendCodePoint(c);
}
} else if (c == '.' || c == EOS || c == '+' && preRelease) {
// if we are parsing a pre release part it can be terminated by a
// '+' in case a build meta data follows
if (verifyOnly) {
return FAILURE;
}
throw illegalLeadingChar(full, '0', partName);
} else if (verifyOnly) {
return FAILURE;
} else {
throw unexpectedChar(full, c);
}
break;
case STATE_PART_DEFAULT:
if (c == '-' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
|| c >= '0' && c <= '9') {
if (b != null) {
b.appendCodePoint(c);
}
} else if (c == '.' && allowDot || c == EOS || c == '+' && preRelease) {
// if we are parsing a pre release part it can be terminated by a
// '+' in case a build meta data follows
return i;
} else if (verifyOnly) {
return FAILURE;
} else {
throw unexpectedChar(full, c);
}
break;
}
}
throw new IllegalStateException();
}
private static VersionFormatException illegalLeadingChar(String v, int c,
String part) {
return new VersionFormatException(
String.format("Illegal leading char '%c' in %s part of %s", c, part, v));
}
private static VersionFormatException unexpectedChar(String v, int c) {
if (c == -1) {
return new VersionFormatException(String.format(
"Incomplete version part in %s", v));
}
return new VersionFormatException(
String.format("Unexpected char in %s: %c", v, c));
}
public Version withMajor(int newMajor) {
return new Version(newMajor, this.minor, this.patch, this.preReleaseParts,
this.buildMetaDataParts);
}
public Version withMinor(int newMinor) {
return new Version(this.major, newMinor, this.patch, this.preReleaseParts,
this.buildMetaDataParts);
}
public Version withPatch(int newPatch) {
return new Version(this.major, this.minor, newPatch, this.preReleaseParts,
this.buildMetaDataParts);
}
public Version withPreRelease(String newPreRelease) {
require(newPreRelease != null, "newPreRelease is null");
final String[] newPreReleaseParts = parsePreRelease(newPreRelease);
return new Version(this.major, this.minor, this.patch, newPreReleaseParts,
this.buildMetaDataParts);
}
public Version withPreRelease(String[] newPreRelease) {
require(newPreRelease != null, "newPreRelease is null");
final String joined = join(newPreRelease);
final String[] newPreReleaseParts = parsePreRelease(joined);
return new Version(this.major, this.minor, this.patch, newPreReleaseParts,
this.buildMetaDataParts);
}
public Version withBuildMetaData(String newBuildMetaData) {
require(newBuildMetaData != null, "newBuildMetaData is null");
final String[] newBuildMdParts = parseBuildMd(newBuildMetaData);
return new Version(this.major, this.minor, this.patch, this.preReleaseParts,
newBuildMdParts);
}
public Version withBuildMetaData(String[] newBuildMetaData) {
require(newBuildMetaData != null, "newBuildMetaData is null");
final String joined = join(newBuildMetaData);
final String[] newBuildMdParts = parseBuildMd(joined);
return new Version(this.major, this.minor, this.patch, this.preReleaseParts,
newBuildMdParts);
}
private String[] verifyAndCopyArray(String parts[], boolean allowLeading0) {
final String[] result = new String[parts.length];
for (int i = 0; i < parts.length; ++i) {
final String part = parts[i];
require(part != null, "version part is null");
if (part.isEmpty()) {
throw new VersionFormatException(
"Incomplete version part in " + join(parts));
}
result[i] = part;
// note: pass "pre-release" because this string will not be used when parsing
// build-meta-data
parseIDPart(part.toCharArray(), part, 0, false, allowLeading0, false, false,
null, "pre-release");
}
return result;
}
/**
* Drops both the pre-release and the build meta data from this version.
*
* @return The nearest stable version.
* @since 2.1.0
*/
public Version toStable() {
return new Version(this.major, this.minor, this.patch, EMPTY_ARRAY, EMPTY_ARRAY);
}
/**
* Given this Version, returns the next major Version. That is, the major part is
* incremented by 1 and the remaining parts are set to 0. This also drops the
* pre-release and build-meta-data.
*
* @return The incremented version.
* @see #nextMajor(String)
* @see #nextMajor(String[])
* @since 1.2.0
*/
public Version nextMajor() {
return new Version(this.major + 1, 0, 0, EMPTY_ARRAY, EMPTY_ARRAY);
}
public Version nextMajor(String newPrelease) {
require(newPrelease != null, "newPreRelease is null");
final String[] preReleaseParts = parsePreRelease(newPrelease);
return new Version(this.major + 1, 0, 0, preReleaseParts, EMPTY_ARRAY);
}
public Version nextMajor(String[] newPrelease) {
require(newPrelease != null, "newPreRelease is null");
final String[] newPreReleaseParts = verifyAndCopyArray(newPrelease, false);
return new Version(this.major + 1, 0, 0, newPreReleaseParts, EMPTY_ARRAY);
}
/**
* Given this version, returns the next minor version. That is, the major part remains
* the same, the minor version is incremented and all other parts are reset/dropped.
*
* @return The incremented version.
* @see #nextMinor(String)
* @see #nextMinor(String[])
* @since 1.2.0
*/
public Version nextMinor() {
return new Version(this.major, this.minor + 1, 0, EMPTY_ARRAY, EMPTY_ARRAY);
}
public Version nextMinor(String newPrelease) {
require(newPrelease != null, "newPreRelease is null");
final String[] preReleaseParts = parsePreRelease(newPrelease);
return new Version(this.major, this.minor + 1, 0, preReleaseParts, EMPTY_ARRAY);
}
public Version nextMinor(String[] newPrelease) {
require(newPrelease != null, "newPreRelease is null");
final String[] newPreReleaseParts = verifyAndCopyArray(newPrelease, false);
return new Version(this.major, this.minor + 1, 0, newPreReleaseParts,
EMPTY_ARRAY);
}
/**
* Given this version, returns the next patch version. That is, the major and minor
* parts remain the same, the patch version is incremented and all other parts are
* reset/dropped.
*
* @return The incremented version.
* @see #nextPatch(String)
* @see #nextPatch(String[])
* @since 1.2.0
*/
public Version nextPatch() {
return new Version(this.major, this.minor, this.patch + 1, EMPTY_ARRAY,
EMPTY_ARRAY);
}
public Version nextPatch(String newPrelease) {
require(newPrelease != null, "newPreRelease is null");
final String[] preReleaseParts = parsePreRelease(newPrelease);
return new Version(this.major, this.minor, this.patch + 1, preReleaseParts,
EMPTY_ARRAY);
}
public Version nextPatch(String[] newPrelease) {
require(newPrelease != null, "newPreRelease is null");
final String[] newPreReleaseParts = verifyAndCopyArray(newPrelease, false);
return new Version(this.major, this.minor, this.patch + 1, newPreReleaseParts,
EMPTY_ARRAY);
}
/**
* Derives a new Version instance from this one by only incrementing the pre-release
* identifier. The build-meta-data will be dropped, all other fields remain the same.
*
* <p>
* The incrementation of the pre-release identifier behaves as follows:
*
* <ul>
* <li>In case the identifier is currently empty, it becomes "1" in the result.</li>
* <li>If the identifier's last part is numeric, that last part will be incremented in
* the result.</li>
* <li>If the last part is not numeric, the identifier is interpreted as
* {@code identifier.0} which becomes {@code identifier.1} after increment.
* </ul>
* Examples:
*
* <table>
* <tr>
* <th>Version</th>
* <th>After increment</th>
* </tr>
* <tr>
* <td>1.2.3</td>
* <td>1.2.3-1</td>
* </tr>
* <tr>
* <td>1.2.3+build.meta.data</td>
* <td>1.2.3-1</td>
* </tr>
* <tr>
* <td>1.2.3-foo</td>
* <td>1.2.3-foo.1</td>
* </tr>
* <tr>
* <td>1.2.3-foo.1</td>
* <td>1.2.3-foo.2</td>
* </tr>
* </table>
*
* @return The incremented Version.
* @since 1.2.0
*/
public Version nextPreRelease() {
final String[] newPreReleaseParts = incrementIdentifier(this.preReleaseParts);
return new Version(this.major, this.minor, this.patch, newPreReleaseParts,
EMPTY_ARRAY);
}
/**
* Derives a new Version instance from this one by only incrementing the
* build-meta-data identifier. All other fields remain the same.
*
* <p>
* The incrementation of the build-meta-data identifier behaves as follows:
*
* <ul>
* <li>In case the identifier is currently empty, it becomes "1" in the result.</li>
* <li>If the identifier's last part is numeric, that last part will be incremented in
* the result. <b>Leading 0's will be removed</b>.</li>
* <li>If the last part is not numeric, the identifier is interpreted as
* {@code identifier.0} which becomes {@code identifier.1} after increment.
* </ul>
* Examples:
*
* <table>
* <tr>
* <th>Version</th>
* <th>After increment</th>
* </tr>
* <tr>
* <td>1.2.3</td>
* <td>1.2.3+1</td>
* </tr>
* <tr>
* <td>1.2.3-pre.release</td>
* <td>1.2.3-pre.release+1</td>
* </tr>
* <tr>
* <td>1.2.3+foo</td>
* <td>1.2.3+foo.1</td>
* </tr>
* <tr>
* <td>1.2.3+foo.1</td>
* <td>1.2.3+foo.2</td>
* </tr>
* </table>
*
* @return The incremented Version.
* @since 1.2.0
*/
public Version nextBuildMetaData() {
final String[] newBuildMetaData = incrementIdentifier(this.buildMetaDataParts);
return new Version(this.major, this.minor, this.patch, this.preReleaseParts,
newBuildMetaData);
}
private String[] incrementIdentifier(String[] parts) {
if (parts.length == 0) {
return new String[] { "1" };
}
final int lastIdx = parts.length - 1;
final String lastPart = parts[lastIdx];
int num = isNumeric(lastPart);
int newLength = parts.length;
if (num >= 0) {
num += 1;
} else {
newLength += 1;
num = 1;
}
final String[] result = Arrays.copyOf(parts, newLength);
result[newLength - 1] = String.valueOf(num);
return result;
}
/**
* Tries to parse the given String as a semantic version and returns whether the
* String is properly formatted according to the semantic version specification.
*
* <p>
* Note: this method does not throw an exception upon <code>null</code> input, but
* returns <code>false</code> instead.
*
*
* @param version The String to check.
* @return Whether the given String is formatted as a semantic version.
* @since 0.5.0
*/
public static boolean isValidVersion(String version) {
return version != null && !version.isEmpty() && parse(version, true) != null;
}
/**
* Returns whether the given String is a valid pre-release identifier. That is, this
* method returns <code>true</code> if, and only if the {@code preRelease} parameter
* is either the empty string or properly formatted as a pre-release identifier
* according to the semantic version specification.
*
* <p>
* Note: this method does not throw an exception upon <code>null</code> input, but
* returns <code>false</code> instead.
*
* @param preRelease The String to check.
* @return Whether the given String is a valid pre-release identifier.
* @since 0.5.0
*/
public static boolean isValidPreRelease(String preRelease) {
if (preRelease == null) {
return false;
} else if (preRelease.isEmpty()) {
return true;
}
return parseID(preRelease.toCharArray(), preRelease, 0, true, false, false, null,
"") != FAILURE;
}
/**
* Returns whether the given String is a valid build meta data identifier. That is,
* this method returns <code>true</code> if, and only if the {@code buildMetaData}
* parameter is either the empty string or properly formatted as a build meta data
* identifier according to the semantic version specification.
*
* <p>
* Note: this method does not throw an exception upon <code>null</code> input, but
* returns <code>false</code> instead.
*
*
* @param buildMetaData The String to check.
* @return Whether the given String is a valid build meta data identifier.
* @since 0.5.0
*/
public static boolean isValidBuildMetaData(String buildMetaData) {
if (buildMetaData == null) {
return false;
} else if (buildMetaData.isEmpty()) {
return true;
}
return parseID(buildMetaData.toCharArray(), buildMetaData, 0, true, true, false,
null, "") != FAILURE;
}
public static Version max(Version v1, Version v2) {
require(v1 != null, "v1 is null");
require(v2 != null, "v2 is null");
return compare(v1, v2, false) < 0
? v2
: v1;
}
public static Version min(Version v1, Version v2) {
require(v1 != null, "v1 is null");
require(v2 != null, "v2 is null");
return compare(v1, v2, false) <= 0
? v1
: v2;
}
public static int compare(Version v1, Version v2) {
// throw NPE to comply with Comparable specification
if (v1 == null) {
throw new NullPointerException("v1 is null");
} else if (v2 == null) {
throw new NullPointerException("v2 is null");
}
return compare(v1, v2, false);
}
/**
* Compares two Versions with additionally considering the build meta data field if
* all other parts are equal. Note: This is <em>not</em> part of the semantic version
* specification.
*
* <p>
* Comparison of the build meta data parts happens exactly as for pre release
* identifiers. Considering of build meta data first kicks in if both versions are
* equal when using their natural order.
*
*
* <p>
* This method fulfills the general contract for Java's {@link Comparator Comparators}
* and {@link Comparable Comparables}.
*
*
* @param v1 The first version for comparison.
* @param v2 The second version for comparison.
* @return A value below 0 iff {@code v1 < v2}, a value above 0 iff
* {@code v1 > v2</tt> and 0 iff <tt>v1 = v2}.
* @throws NullPointerException If either parameter is null.
* @since 0.3.0
*/
public static int compareWithBuildMetaData(Version v1, Version v2) {
// throw NPE to comply with Comparable specification
if (v1 == null) {
throw new NullPointerException("v1 is null");
} else if (v2 == null) {
throw new NullPointerException("v2 is null");
}
return compare(v1, v2, true);
}
private static int compare(Version v1, Version v2,
boolean withBuildMetaData) {
int result = 0;
if (v1 != v2) {
final int mc, mm, mp, pr, md;
if ((mc = compareInt(v1.major, v2.major)) != 0) {
result = mc;
} else if ((mm = compareInt(v1.minor, v2.minor)) != 0) {
result = mm;
} else if ((mp = compareInt(v1.patch, v2.patch)) != 0) {
result = mp;
} else if ((pr = comparePreRelease(v1, v2)) != 0) {
result = pr;
} else if (withBuildMetaData && ((md = compareBuildMetaData(v1, v2)) != 0)) {
result = md;
}
}
return result;
}
private static int compareInt(int a, int b) {
return a - b;
}
private static int comparePreRelease(Version v1, Version v2) {
return compareLiterals(v1.preReleaseParts, v2.preReleaseParts);
}
private static int compareBuildMetaData(Version v1, Version v2) {
return compareLiterals(v1.buildMetaDataParts, v2.buildMetaDataParts);
}
private static int compareLiterals(String[] v1Literal, String[] v2Literal) {
final int result;
if (v1Literal.length > 0 && v2Literal.length > 0) {
// compare pre release parts
result = compareIdentifiers(v1Literal, v2Literal);
} else if (v1Literal.length > 0) {
// other is greater, because it is no pre release
result = -1;
} else if (v2Literal.length > 0) {
// this is greater because other is no pre release
result = 1;
} else {
result = 0;
}
return result;
}
private static int compareIdentifiers(String[] parts1, String[] parts2) {
final int min = Math.min(parts1.length, parts2.length);
for (int i = 0; i < min; ++i) {
final int r = compareIdentifierParts(parts1[i], parts2[i]);
if (r != 0) {
// versions differ in part i
return r;
}
}
// all id's are equal, so compare amount of id's
return compareInt(parts1.length, parts2.length);
}
private static int compareIdentifierParts(String p1, String p2) {
final int num1 = isNumeric(p1);
final int num2 = isNumeric(p2);
final int result;
if (num1 < 0 && num2 < 0) {
// both are not numerical -> compare lexically
result = p1.compareTo(p2);
} else if (num1 >= 0 && num2 >= 0) {
// both are numerical
result = compareInt(num1, num2);
} else if (num1 >= 0) {
// only part1 is numerical -> p2 is greater
result = -1;
} else {
// only part2 is numerical -> p1 is greater
result = 1;
}
return result;
}
/**
* Determines whether s is a positive number. If it is, the number is returned,
* otherwise the result is -1.
*
* @param s The String to check.
* @return The positive number (incl. 0) if s a number, or -1 if it is not.
*/
private static int isNumeric(String s) {
final char[] chars = s.toCharArray();
int num = 0;
// note: this method does not account for leading zeroes as could occur in build
// meta data parts. Leading zeroes are thus simply ignored when parsing the
// number.
for (int i = 0; i < chars.length; ++i) {
final char c = chars[i];
if (c >= '0' && c <= '9') {
num = num * DECIMAL + Character.digit(c, DECIMAL);
} else {
return -1;
}
}
return num;
}
private static String[] parsePreRelease(String preRelease) {
if (preRelease != null && !preRelease.isEmpty()) {
final List<String> parts = new ArrayList<String>();
parseID(preRelease.toCharArray(), preRelease, 0, false, false, false, parts,
"pre-release");
return parts.toArray(new String[parts.size()]);
}
return EMPTY_ARRAY;
}
private static String[] parseBuildMd(String buildMetaData) {
if (buildMetaData != null && !buildMetaData.isEmpty()) {
final List<String> parts = new ArrayList<String>();
parseID(buildMetaData.toCharArray(), buildMetaData, 0, false, true, false,
parts, "build-meta-data");
return parts.toArray(new String[parts.size()]);
}
return EMPTY_ARRAY;
}
private static final Version createInternal(int major, int minor, int patch,
String preRelease, String buildMetaData) {
final String[] preReleaseParts = parsePreRelease(preRelease);
final String[] buildMdParts = parseBuildMd(buildMetaData);
return new Version(major, minor, patch, preReleaseParts, buildMdParts);
}
/**
* Creates a new Version from the provided components. Neither value of
* {@code major, minor} or {@code patch} must be lower than 0 and at least one must be
* greater than zero. {@code preRelease} or {@code buildMetaData} may be the empty
* String. In this case, the created {@code Version} will have no pre release resp.
* build meta data field. If those parameters are not empty, they must conform to the
* semantic version specification.
*
* @param major The major version.
* @param minor The minor version.
* @param patch The patch version.
* @param preRelease The pre release version or the empty string.
* @param buildMetaData The build meta data field or the empty string.
* @return The version instance.
* @throws VersionFormatException If {@code preRelease} or {@code buildMetaData} does
* not conform to the semantic version specification.
*/
public static final Version create(int major, int minor, int patch,
String preRelease,
String buildMetaData) {
require(preRelease != null, "preRelease is null");
require(buildMetaData != null, "buildMetaData is null");
return createInternal(major, minor, patch, preRelease, buildMetaData);
}
/**
* Creates a new Version from the provided components. The version's build meta data
* field will be empty. Neither value of {@code major, minor} or {@code patch} must be
* lower than 0 and at least one must be greater than zero. {@code preRelease} may be
* the empty String. In this case, the created version will have no pre release field.
* If it is not empty, it must conform to the specifications of the semantic version.
*
* @param major The major version.
* @param minor The minor version.
* @param patch The patch version.
* @param preRelease The pre release version or the empty string.
* @return The version instance.
* @throws VersionFormatException If {@code preRelease} is not empty and does not
* conform to the semantic versioning specification
*/
public static final Version create(int major, int minor, int patch,
String preRelease) {
return create(major, minor, patch, preRelease, "");
}
/**
* Creates a new Version from the three provided components. The version's pre release
* and build meta data fields will be empty. Neither value must be lower than 0 and at
* least one must be greater than zero.
*
* @param major The major version.
* @param minor The minor version.
* @param patch The patch version.
* @return The version instance.
*/
public static final Version create(int major, int minor, int patch) {
return new Version(major, minor, patch, EMPTY_ARRAY, EMPTY_ARRAY);
}
/**
* Creates a new Version from the two provided components, leaving the patch version
* 0. The version's pre release and build meta data fields will be empty. Neither
* value must be lower than 0 and at least one must be greater than zero.
*
* @param major The major version.
* @param minor The minor version.
* @return The version instance.
* @since 2.1.0
*/
public static final Version create(int major, int minor) {
return new Version(major, minor, 0, EMPTY_ARRAY, EMPTY_ARRAY);
}
/**
* Creates a new Version with the provided major version, leaving the minor and patch
* version 0. The version's pre release and build meta data fields will be empty. The
* major value must be lower than or equal to 0.
*
* @param major The major version.
* @return The version instance.
* @since 2.1.0
*/
public static final Version create(int major) {
return new Version(major, 0, 0, EMPTY_ARRAY, EMPTY_ARRAY);
}
private static void checkParams(int major, int minor, int patch) {
require(major >= 0, "major < 0");
require(minor >= 0, "minor < 0");
require(patch >= 0, "patch < 0");
require(major != 0 || minor != 0 || patch != 0, "all parts are 0");
}
private static void require(boolean condition, String message) {
if (!condition) {
throw new IllegalArgumentException(message);
}
}
public static final Version parseVersion(String versionString) {
require(versionString != null, "versionString is null");
return parse(versionString, false);
}
/**
* Tries to parse the provided String as a semantic version. If
* {@code allowPreRelease} is <code>false</code>, the String must have neither a
* pre-release nor a build meta data part. Thus the given String must have the format
* {@code X.Y.Z} where at least one part must be greater than zero.
*
* <p>
* If {@code allowPreRelease} is <code>true</code>, the String is parsed according to
* the normal semantic version specification.
*
*
* @param versionString The String to parse.
* @param allowPreRelease Whether pre-release and build meta data field are allowed.
* @return The parsed version.
* @throws VersionFormatException If the String is no valid version
* @since 0.4.0
*/
public static Version parseVersion(String versionString,
boolean allowPreRelease) {
final Version version = parseVersion(versionString);
if (!allowPreRelease && (version.isPreRelease() || version.hasBuildMetaData())) {
throw new VersionFormatException(String.format(
"Version string '%s' is expected to have no pre-release or "
+ "build meta data part",
versionString));
}
return version;
}
public Version min(Version other) {
return min(this, other);
}
public Version max(Version other) {
return max(this, other);
}
/**
* Gets this version's major number.
*
* @return The major version.
*/
public int getMajor() {
return this.major;
}
/**
* Gets this version's minor number.
*
* @return The minor version.
*/
public int getMinor() {
return this.minor;
}
/**
* Gets this version's path number.
*
* @return The patch number.
*/
public int getPatch() {
return this.patch;
}
/**
* Gets the pre release identifier parts of this version as array. Modifying the
* resulting array will have no influence on the internal state of this object.
*
* @return Pre release version as array. Array is empty if this version has no pre
* release part.
*/
public String[] getPreReleaseParts() {
if (this.preReleaseParts.length == 0) {
return EMPTY_ARRAY;
}
return Arrays.copyOf(this.preReleaseParts, this.preReleaseParts.length);
}
/**
* Gets the pre release identifier of this version. If this version has no such
* identifier, an empty string is returned.
*
* <p>
* Note: This method will always reconstruct a new String by joining the single
* identifier parts.
*
*
* @return This version's pre release identifier or an empty String if this version
* has no such identifier.
*/
public String getPreRelease() {
return join(this.preReleaseParts);
}
/**
* Gets this version's build meta data. If this version has no build meta data, the
* returned string is empty.
*
* <p>
* Note: This method will always reconstruct a new String by joining the single
* identifier parts.
*
*
* @return The build meta data or an empty String if this version has no build meta
* data.
*/
public String getBuildMetaData() {
return join(this.buildMetaDataParts);
}
private static String join(String[] parts) {
if (parts.length == 0) {
return "";
}
final StringBuilder b = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
final String part = parts[i];
b.append(part);
if (i < parts.length - 1) {
b.append(".");
}
}
return b.toString();
}
/**
* Gets the build meta data identifier parts of this version as array. Modifying the
* resulting array will have no influence on the internal state of this object.
*
* @return Build meta data as array. Array is empty if this version has no build meta
* data part.
*/
public String[] getBuildMetaDataParts() {
if (this.buildMetaDataParts.length == 0) {
return EMPTY_ARRAY;
}
return Arrays.copyOf(this.buildMetaDataParts, this.buildMetaDataParts.length);
}
/**
* Determines whether this version is still under initial development.
*
* @return <code>true</code> iff this version's major part is zero.
*/
public boolean isInitialDevelopment() {
return this.major == 0;
}
/**
* Whether this is a 'stable' version. That is, it has no pre-release identifier.
*
* @return <code>true</code> iff {@link #getPreRelease()} is empty.
* @see #isPreRelease()
* @since 2.1.0
*/
public boolean isStable() {
return this.preReleaseParts.length == 0;
}
/**
* Determines whether this is a pre release version.
*
* @return <code>true</code> iff {@link #getPreRelease()} is not empty.
* @see #isStable()
*/
public boolean isPreRelease() {
return this.preReleaseParts.length > 0;
}
/**
* Determines whether this version has a build meta data field.
*
* @return <code>true</code> iff {@link #getBuildMetaData()} is not empty.
*/
public boolean hasBuildMetaData() {
return this.buildMetaDataParts.length > 0;
}
/**
* Creates a String representation of this version by joining its parts together as by
* the semantic version specification.
*
* @return The version as a String.
*/
@Override
public String toString() {
final StringBuilder b = new StringBuilder(TO_STRING_ESTIMATE);
b.append(this.major).append(".")
.append(this.minor).append(".")
.append(this.patch);
if (isPreRelease()) {
b.append("-").append(getPreRelease());
}
if (hasBuildMetaData()) {
b.append("+").append(getBuildMetaData());
}
return b.toString();
}
/**
* The hash code for a version instance is computed from the fields {@link #getMajor()
* major}, {@link #getMinor() minor}, {@link #getPatch() patch} and
* {@link #getPreRelease() pre-release}.
*
* @return A hash code for this object.
*/
@Override
public int hashCode() {
final int h = this.hash;
if (h == NOT_YET_CALCULATED) {
this.hash = calculateHashCode();
}
return this.hash;
}
private int calculateHashCode() {
int h = HASH_PRIME + this.major;
h = HASH_PRIME * h + this.minor;
h = HASH_PRIME * h + this.patch;
h = HASH_PRIME * h + Arrays.hashCode(this.preReleaseParts);
return h;
}
/**
* Determines whether this version is equal to the passed object. This is the case if
* the passed object is an instance of Version and this version
* {@link #compareTo(Version) compared} to the provided one yields 0. Thus, this
* method ignores the {@link #getBuildMetaData()} field.
*
* @param obj the object to compare with.
* @return <code>true</code> iff {@code obj} is an instance of {@code Version} and
* {@code this.compareTo((Version) obj) == 0}
* @see #compareTo(Version)
*/
@Override
public boolean equals(Object obj) {
return testEquality(obj, false);
}
/**
* Determines whether this version is equal to the passed object (as determined by
* {@link #equals(Object)} and additionally considers the build meta data part of both
* versions for equality.
*
* @param obj The object to compare with.
* @return <code>true</code> iff {@code this.equals(obj)} and
* {@code this.getBuildMetaData().equals(((Version) obj).getBuildMetaData())}
* @since 0.4.0
*/
public boolean equalsWithBuildMetaData(Object obj) {
return testEquality(obj, true);
}
private boolean testEquality(Object obj, boolean includeBuildMd) {
return obj == this || obj instanceof Version
&& compare(this, (Version) obj, includeBuildMd) == 0;
}
/**
* Compares this version to the provided one, following the <em>semantic
* versioning</em> specification. See {@link #compare(Version, Version)} for more
* information.
*
* @param other The version to compare to.
* @return A value lower than 0 if this < other, a value greater than 0 if this
* > other and 0 if this == other. The absolute value of the result has no
* semantical interpretation.
*/
@Override
public int compareTo(Version other) {
return compare(this, other);
}
/**
* Compares this version to the provided one. Unlike the {@link #compareTo(Version)}
* method, this one additionally considers the build meta data field of both versions,
* if all other parts are equal. Note: This is <em>not</em> part of the semantic
* version specification.
*
* <p>
* Comparison of the build meta data parts happens exactly as for pre release
* identifiers. Considering of build meta data first kicks in if both versions are
* equal when using their natural order.
*
*
* @param other The version to compare to.
* @return A value lower than 0 if this < other, a value greater than 0 if this
* > other and 0 if this == other. The absolute value of the result has no
* semantical interpretation.
* @since 0.3.0
*/
public int compareToWithBuildMetaData(Version other) {
return compareWithBuildMetaData(this, other);
}
/**
* Returns a new Version where all identifiers are converted to upper case letters.
*
* @return A new version with upper case identifiers.
* @since 1.1.0
*/
public Version toUpperCase() {
return new Version(this.major, this.minor, this.patch,
copyCase(this.preReleaseParts, true),
copyCase(this.buildMetaDataParts, true));
}
/**
* Returns a new Version where all identifiers are converted to lower case letters.
*
* @return A new version with lower case identifiers.
* @since 1.1.0
*/
public Version toLowerCase() {
return new Version(this.major, this.minor, this.patch,
copyCase(this.preReleaseParts, false),
copyCase(this.buildMetaDataParts, false));
}
private static String[] copyCase(String[] source, boolean toUpper) {
final String[] result = new String[source.length];
for (int i = 0; i < source.length; i++) {
final String string = source[i];
result[i] = toUpper ? string.toUpperCase() : string.toLowerCase();
}
return result;
}
public boolean isGreaterThan(Version other) {
require(other != null, "other must no be null");
return compareTo(other) > 0;
}
public boolean isGreaterThanOrEqualTo(Version other) {
require(other != null, "other must no be null");
return compareTo(other) >= 0;
}
public boolean isLowerThan(Version other) {
require(other != null, "other must no be null");
return compareTo(other) < 0;
}
public boolean isLowerThanOrEqualTo(Version other) {
require(other != null, "other must no be null");
return compareTo(other) <= 0;
}
/**
* Handles proper deserialization of objects serialized with a version prior to 1.1.0
*
* @return the deserialized object.
* @throws ObjectStreamException If deserialization fails.
* @since 1.1.0
*/
private Object readResolve() throws ObjectStreamException {
if (this.preRelease != null || this.buildMetaData != null) {
return createInternal(this.major, this.minor, this.patch,
this.preRelease,
this.buildMetaData);
}
return this;
}
} |
package org.gridsphere.servlets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gridsphere.layout.PortletLayoutEngine;
import org.gridsphere.portlet.impl.SportletProperties;
import org.gridsphere.portlet.service.spi.PortletServiceFactory;
import org.gridsphere.services.core.registry.PortletManagerService;
import org.gridsphere.services.core.persistence.PersistenceManagerService;
import org.gridsphere.services.core.persistence.PersistenceManagerRdbms;
import org.gridsphere.services.core.security.role.PortletRole;
import org.gridsphere.services.core.security.role.RoleManagerService;
import org.gridsphere.services.core.portal.PortalConfigService;
import org.hibernate.StaleObjectStateException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.File;
import java.util.StringTokenizer;
import java.util.Enumeration;
/**
* GridSphereFilter is used for first time portal initialization including portlets
*/
public class GridSphereFilter implements Filter {
private static Boolean firstDoGet = Boolean.TRUE;
private Log log = LogFactory.getLog(GridSphereFilter.class);
private RoleManagerService roleService = null;
private ServletContext context = null;
public void init(FilterConfig filterConfig) {
context = filterConfig.getServletContext();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
log.info("START");
if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
//PersistenceManagerService pms = null;
// If first time being called, instantiate all portlets
if (firstDoGet.equals(Boolean.TRUE)) {
// check if database file exists
String release = SportletProperties.getInstance().getProperty("gridsphere.release");
int idx = release.lastIndexOf(" ");
String gsversion = release.substring(idx+1);
//System.err.println("gsversion=" + gsversion);
String dbpath = context.getRealPath("/WEB-INF/CustomPortal/database/GS_" + gsversion);
File dbfile = new File(dbpath);
if (!dbfile.exists()) {
request.setAttribute("setup", "true");
RequestDispatcher rd = request.getRequestDispatcher("/setup");
rd.forward(request, response);
return;
}
PersistenceManagerService pms = (PersistenceManagerService)PortletServiceFactory.createPortletService(PersistenceManagerService.class, true);
PersistenceManagerRdbms pm = null;
boolean noAdmin = true;
try {
log.info("Starting a database transaction");
pm = pms.createGridSphereRdbms();
pm.beginTransaction();
roleService = (RoleManagerService) PortletServiceFactory.createPortletService(RoleManagerService.class, true);
noAdmin = roleService.getUsersInRole(PortletRole.ADMIN).isEmpty();
pm.endTransaction();
} catch (StaleObjectStateException staleEx) {
log.error("This interceptor does not implement optimistic concurrency control!");
log.error("Your application will not work until you add compensation actions!");
} catch (Throwable ex) {
ex.printStackTrace();
pm.endTransaction();
try {
pm.rollbackTransaction();
} catch (Throwable rbEx) {
log.error("Could not rollback transaction after exception!", rbEx);
}
}
if (noAdmin) {
request.setAttribute("setup", "true");
RequestDispatcher rd = request.getRequestDispatcher("/setup");
rd.forward(request, response);
return;
}
System.err.println("Initializing portlets!!!");
log.info("Initializing portlets");
try {
// initialize all portlets
PortletManagerService portletManager = (PortletManagerService)PortletServiceFactory.createPortletService(PortletManagerService.class, true);
portletManager.initAllPortletWebApplications(req, res);
firstDoGet = Boolean.FALSE;
} catch (Exception e) {
log.error("GridSphere initialization failed!", e);
RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp");
req.setAttribute("error", e);
rd.forward(req, res);
return;
}
}
String pathInfo = req.getPathInfo();
StringBuffer requestURL = req.getRequestURL();
String requestURI = req.getRequestURI();
String query = req.getQueryString();
log.info("\ncontext path = " + req.getContextPath() + " servlet path=" + req.getServletPath());
log.info("\n pathInfo= " + pathInfo + " query= " + query);
log.info(" requestURL= " + requestURL + " requestURI= " + requestURI + "\n");
String extraInfo = "";
// use the servlet path to determine where to forward
// expect servlet path = /servletpath/XXXX
String path = req.getServletPath();
int start = path.indexOf("/", 1);
if ((start > 0) && (path.length()-1) > start) {
String parsePath = path.substring(start+1);
//System.err.println(parsePath);
extraInfo = "?";
StringTokenizer st = new StringTokenizer(parsePath, "/");
if (st.hasMoreTokens()) {
String layoutId = (String)st.nextElement();
extraInfo += SportletProperties.LAYOUT_PAGE_PARAM + "=" + layoutId;
}
if (st.hasMoreTokens()) {
String cid = (String)st.nextElement();
extraInfo += "&" + SportletProperties.COMPONENT_ID+ "=" + cid;
}
if (st.hasMoreTokens()) {
String action = (String)st.nextElement();
extraInfo += "&" + SportletProperties.DEFAULT_PORTLET_ACTION + "=" + action;
}
if (query != null) {
extraInfo += "&" + query;
}
//String ctxPath = "/" + configService.getProperty("gridsphere.context");
}
//chain.doFilter(request, response);
String ctxPath = "/gs";
log.info("forwarded URL: " + ctxPath + extraInfo);
context.getRequestDispatcher(ctxPath + extraInfo).forward(req, res);
log.info("END");
}
}
} |
package edu.sdsu.its.fit_welcome;
import com.opencsv.CSVWriter;
import edu.sdsu.its.fit_welcome.Models.Event;
import edu.sdsu.its.fit_welcome.Models.Quote;
import edu.sdsu.its.fit_welcome.Models.Staff;
import edu.sdsu.its.fit_welcome.Models.User;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@SuppressWarnings({"SqlNoDataSourceInspection", "SqlResolve"})
public class DB {
private static final String db_url = Param.getParam("fit_welcome", "db-url");
private static final String db_user = Param.getParam("fit_welcome", "db-user");
private static final String db_password = Param.getParam("fit_welcome", "db-password");
private static final Logger Log = Logger.getLogger(DB.class);
/**
* Create and return a new DB Connection
* Don't forget to close the connection!
*
* @return {@link Connection} DB Connection
*/
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(db_url, db_user, db_password);
} catch (Exception e) {
Log.fatal("Problem Initializing DB Connection", e);
System.exit(69);
}
return conn;
}
private static void executeStatement(final String sql) {
new Thread() {
@Override
public void run() {
Statement statement = null;
Connection connection = getConnection();
try {
statement = connection.createStatement();
Log.info(String.format("Executing SQL Statement - \"%s\"", sql));
statement.execute(sql);
} catch (SQLException e) {
Log.error("Problem Executing Statement \"" + sql + "\"", e);
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
}
}.start();
}
private static File queryToCSV(final String sql, final String fileName) throws IOException {
Connection connection = getConnection();
Statement statement = null;
CSVWriter writer = null;
File file = null;
try {
statement = connection.createStatement();
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
file = new File(System.getProperty("java.io.tmpdir") + "/" + fileName + ".csv");
writer = new CSVWriter(new FileWriter(file));
writer.writeAll(resultSet, true);
resultSet.close();
} catch (SQLException e) {
Log.error("Problem Querying DB", e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
Log.warn("Problem Closing Data Dump File");
}
}
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return file;
}
private static String sanitize(final String input) {
return input.replace("'", "");
}
/**
* Get User for the specified ID
*
* @param id {@link int} User's ID (Commonly their RedID)
* @return {@link User} User
*/
public static User getUser(final int id) {
Connection connection = getConnection();
Statement statement = null;
User user = null;
try {
statement = connection.createStatement();
final String sql = "SELECT * FROM bbusers WHERE id = " + id + ";";
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
user = new User(id, resultSet.getString("first_name"), resultSet.getString("last_name"), resultSet.getString("email"));
}
resultSet.close();
} catch (SQLException e) {
Log.error("Problem querying DB for UserID", e);
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return user;
}
/**
* Get User for the specified email
*
* @param email {@link String} User's email
* @return {@link User} User
*/
public static User getUser(final String email) {
Connection connection = getConnection();
Statement statement = null;
User user = null;
try {
statement = connection.createStatement();
final String sql = "SELECT * FROM bbusers WHERE email = '" + email + "';";
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
user = new User(resultSet.getInt("id"), resultSet.getString("first_name"), resultSet.getString("last_name"), resultSet.getString("email"));
}
resultSet.close();
} catch (SQLException e) {
Log.error("Problem querying DB for UserID", e);
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return user;
}
/**
* Get Staff User based on ID
*
* @param id {@link int} User's ID (Commonly their RedID)
* @return {@link Staff} Staff
*/
public static Staff getStaff(final int id) {
Connection connection = getConnection();
Statement statement = null;
Staff staff = null;
try {
statement = connection.createStatement();
final String sql = "SELECT * FROM staff WHERE id = " + id + ";";
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
staff = new Staff(id, resultSet.getString("first_name"), resultSet.getString("last_name"),
resultSet.getString("email"), resultSet.getBoolean("clockable"), resultSet.getBoolean("admin"), resultSet.getBoolean("instructional_designer"));
}
resultSet.close();
} catch (SQLException e) {
Log.error("Problem querying DB for UserID", e);
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return staff;
}
/**
* Get all Staff Users. Restrictions can be imposed with the restrictions param.
* Use restrictions with care as they are un sanitized and not checked.
*
* @param restriction {@link String} Restriction of which users should be included. Uses SQL format
* ex. "WHERE admin = 1"
* Use empty string to get all staff users.
* @return {@link Staff[]} All staff users who meet the supplied criteria.
*/
public static Staff[] getAllStaff(final String restriction) {
Connection connection = getConnection();
Statement statement = null;
Staff[] staff = null;
try {
statement = connection.createStatement();
final String sql = "SELECT * FROM staff " + restriction + ";";
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
final List<Staff> staffList = new ArrayList<>();
while (resultSet.next()) {
staffList.add(new Staff(resultSet.getInt("id"), resultSet.getString("first_name"), resultSet.getString("last_name"),
resultSet.getString("email"), resultSet.getBoolean("clockable"), resultSet.getBoolean("admin"), resultSet.getBoolean("instructional_designer")));
}
Collections.sort(staffList, (staff1, staff2) -> staff1.lastName.compareToIgnoreCase(staff2.lastName));
staff = new Staff[staffList.size()];
for (int s = 0; s < staffList.size(); s++) {
staff[s] = staffList.get(s);
}
resultSet.close();
} catch (SQLException e) {
Log.error("Problem querying DB for Staff List", e);
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return staff;
}
/**
* Log FIT Center Event
*
* @param id {@link int} Users's ID
* @param action {@link String} User's Goal
* @param params {@link String} Notes/Specifications for User's visit
*/
public static void logEvent(final String timestamp, final int id, final String action, final String params) {
final String sql = String.format("INSERT INTO events(TIMESTAMP, redid, action, params) VALUE ('%s', %d, '%s', '%s')", timestamp, id, sanitize(action), sanitize(params));
executeStatement(sql);
}
/**
* Get all Quotes from the DB
*
* @return {@link Quote[]} All Quotes
*/
public static Quote[] getQuotes() {
Connection connection = getConnection();
Statement statement = null;
Quote[] quotes = null;
try {
statement = connection.createStatement();
final String sql = "SELECT * FROM quotes;";
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
final List<Quote> quoteList = new ArrayList<>();
while (resultSet.next()) {
quoteList.add(new Quote(resultSet.getString("text"), resultSet.getString("author")));
}
quotes = new Quote[quoteList.size()];
for (int q = 0; q < quoteList.size(); q++) {
quotes[q] = quoteList.get(q);
}
} catch (SQLException e) {
Log.error("Problem Adding Action to DB", e);
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return quotes;
}
/**
* Clock In the User
*
* @param id {@link int} User's ID
* @param time {@link String} Current Time in SQL format
* 'now()' can be used, but is not recommended because Statements are Threaded.
*/
public static void clockIn(final int id, final String time) {
final String sql = String.format("INSERT INTO clock VALUES (%d, %s, DEFAULT );", id, time);
executeStatement(sql);
}
/**
* Clock Out the User
*
* @param id {@link int} User's ID
* @param time {@link String} Current Time in SQL format
* 'now()' can be used, but is not recommended because Statements are Threaded.
*/
public static void clockOut(final int id, final String time) {
final String sql = String.format("UPDATE clock SET time_out = %s WHERE id = %d AND time_out = '0000-00-00 00:00:00';\n", time, id);
executeStatement(sql);
}
/**
* @param id {@link int} Staff ID
* @return True if Clocked IN, False if Clocked OUT
*/
public static boolean clockStatus(final int id) {
Connection connection = getConnection();
Statement statement = null;
boolean status = false;
try {
statement = connection.createStatement();
final String sql = String.format("SELECT * FROM clock WHERE id = %d AND time_out = '0000-00-00 00:00:00';", id);
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
status = resultSet.next();
} catch (SQLException e) {
Log.error("Problem Adding Action to DB", e);
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return status;
}
/**
* Export all Events to a CSV.
*
* @param start {@link String} Start Date (Inclusive). Use HTML-Date (2015-12-23) format.
* @param end {@link String} Start Date (Inclusive). Use HTML-Date (2015-12-23) format.
* @param fileName {@link String} File Name for the Report. Do NOT include .csv
* @return {@link File} File object for the Report CSV
*/
public static File exportEvents(final String start, final String end, final String fileName) {
final String sql = "SELECT *\n" +
"FROM events\n" +
"WHERE\n" +
" TIMESTAMP BETWEEN STR_TO_DATE('" + start + "', '%Y-%m-%d') AND\n" +
" DATE_ADD(STR_TO_DATE('" + end + "', '%Y-%m-%d'), INTERVAL 1 DAY)\n" +
"ORDER BY TIMESTAMP ASC;";
try {
return queryToCSV(sql, fileName);
} catch (IOException e) {
Log.error("Problem Saving Events to CSV", e);
return null;
}
}
/**
* Export all ClockIO pairs for a User.
* - Used to generate Timesheets
*
* @param id {@link int} ID of user whose Clock In/Outs should be queried.
* @param start {@link String} Start Date (Inclusive). Use HTML-Date (2015-12-23) format.
* @param end {@link String} Start Date (Inclusive). Use HTML-Date (2015-12-23) format.
* @return {@link Clock.ClockIO[]} All ClockIn/Out pairs for the slected user during the specified interval
*/
public static Clock.ClockIO[] exportClockIOs(final int id, final String start, final String end) {
final String sql = "SELECT *\n" +
"FROM clock\n" +
"WHERE\n" +
" id = " + Integer.toString(id) + " AND\n" +
" time_in BETWEEN STR_TO_DATE('" + start + "', '%Y-%m-%d') AND\n" +
" DATE_ADD(STR_TO_DATE('" + end + "', '%Y-%m-%d'), INTERVAL 1 DAY)\n" +
"ORDER BY time_in ASC;";
Connection connection = getConnection();
Statement statement = null;
Clock.ClockIO[] rarray = null;
try {
statement = connection.createStatement();
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
List<Clock.ClockIO> clockIOs = new ArrayList<Clock.ClockIO>();
while (resultSet.next()) {
clockIOs.add(new Clock.ClockIO(DateTime.parse(resultSet.getString("time_in"), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.0")),
DateTime.parse(resultSet.getString("time_out"), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.0"))));
}
rarray = new Clock.ClockIO[clockIOs.size()];
for (int e = 0; e < clockIOs.size(); e++) {
rarray[e] = clockIOs.get(e);
}
} catch (SQLException e) {
Log.error("Problem retreating Clock entries from DB");
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return rarray;
}
/**
* Create a new Staff User
*
* @param staff {@link Staff} New User to Create
* @return {@link} If user was created successfully. False if the ID already exists.
*/
public static boolean createNewStaff(final Staff staff) {
if (getStaff(staff.id) != null) {
// If a staff member with that record already exists for that ID, thrown an error.
Log.warn("Cannot create new Staff user, a record with that ID already exists.");
return false;
}
final String sql = String.format("INSERT INTO staff VALUE (%d, '%s', '%s', '%s', %d, %d, %d);",
staff.id, sanitize(staff.firstName), sanitize(staff.lastName), sanitize(staff.email), staff.clockable ? 1 : 0, staff.admin ? 1 : 0, staff.instructional_designer ? 1 : 0);
executeStatement(sql);
return true;
}
/**
* Set the Don't Email flag for the User in the User List
*
* @param email {@link String} Email to Unsubscribe
*/
public static void unsubscribe(final String email) {
final String sql = "UPDATE bbusers\n" +
"SET send_emails = 0\n" +
"WHERE email = '" + email + "';";
Log.info(String.format("Unsubscribing user with email: %s from FollowUp List", email));
executeStatement(sql);
}
/**
* Unset the Don't Email flag for the User in the User List
*
* @param email {@link String } Email to Resubscribe
*/
public static void subscribe(final String email) {
final String sql = "UPDATE bbusers\n" +
"SET send_emails = 1\n" +
"WHERE email = '" + email + "';";
Log.info(String.format("Subscribing user with email: %s to FollowUp List", email));
executeStatement(sql);
}
/**
* Get the number of Events
*
* @return {@link int} Largest event id
*/
public static int numEvents() {
final String sql = "SELECT MAX(ID) FROM events;";
Connection connection = getConnection();
Statement statement = null;
int max = 0;
try {
statement = connection.createStatement();
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
max = resultSet.getInt(1);
}
} catch (SQLException e) {
Log.error("Problem retrieving Event entries from DB");
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return max;
}
/**
* Get all Events Today Since X Event ID
*
* @param last {@link int} Last eventID fetched - get all since
* @return {@link List} list of all Events since the provided event
*/
public static List<Event> getEventsSince(final int last) {
final String sql = "SELECT * FROM events WHERE ID > " + last + " AND TIMESTAMP >= CURDATE() ORDER BY TIMESTAMP ASC;";
Connection connection = getConnection();
Statement statement = null;
List<Event> events = new ArrayList<>();
try {
statement = connection.createStatement();
Log.info(String.format("Executing SQL Query - \"%s\"", sql));
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
final int redID = resultSet.getInt("redid");
final User user = User.getUser(redID);
final Staff staff = user != null ? null : Staff.getStaff(redID);
events.add(new Event(resultSet.getInt("ID"), user != null ? user : staff, new DateTime(resultSet.getTimestamp("TIMESTAMP")), resultSet.getString("action"), resultSet.getString("params")));
}
} catch (SQLException e) {
Log.error("Problem retrieving Event entries from DB");
} finally {
if (statement != null) {
try {
statement.close();
connection.close();
} catch (SQLException e) {
Log.warn("Problem Closing Statement", e);
}
}
}
return events;
}
} |
package com.cloud.network.firewall;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.commands.ListFirewallRulesCmd;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventVO;
import com.cloud.event.dao.EventDao;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.IPAddressVO;
import com.cloud.network.IpAddress;
import com.cloud.network.Network;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkManager;
import com.cloud.network.dao.FirewallRulesCidrsDao;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.rules.FirewallManager;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.FirewallRule.State;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.UserContext;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
@Local(value = { FirewallService.class, FirewallManager.class })
public class FirewallManagerImpl implements FirewallService, FirewallManager, Manager{
private static final Logger s_logger = Logger.getLogger(FirewallManagerImpl.class);
String _name;
@Inject
FirewallRulesDao _firewallDao;
@Inject
IPAddressDao _ipAddressDao;
@Inject
EventDao _eventDao;
@Inject
DomainDao _domainDao;
@Inject
FirewallRulesCidrsDao _firewallCidrsDao;
@Inject
AccountManager _accountMgr;
@Inject
NetworkManager _networkMgr;
@Inject
UsageEventDao _usageEventDao;
@Inject
ConfigurationDao _configDao;
private boolean _elbEnabled=false;
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
String elbEnabledString = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key());
_elbEnabled = Boolean.parseBoolean(elbEnabledString);
return true;
}
@Override
public FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException {
Account caller = UserContext.current().getCaller();
return createFirewallRule(rule.getSourceIpAddressId(), caller, rule.getXid(), rule.getSourcePortStart() ,rule.getSourcePortEnd(), rule.getProtocol(), rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType());
}
@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_OPEN, eventDescription = "creating firewll rule", create = true)
public FirewallRule createFirewallRule(long ipAddrId, Account caller, String xId, Integer portStart,Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType) throws NetworkRuleConflictException{
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
// Validate ip address
if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system");
} else if (ipAddress.isOneToOneNat()) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " has static nat enabled");
}
validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall);
//icmp code and icmp type can't be passed in for any other protocol rather than icmp
if (!protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (icmpCode != null || icmpType != null)) {
throw new InvalidParameterValueException("Can specify icmpCode and icmpType for ICMP protocol only");
}
if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (portStart != null || portEnd != null)) {
throw new InvalidParameterValueException("Can't specify start/end port when protocol is ICMP");
}
Long networkId = ipAddress.getAssociatedWithNetworkId();
Long accountId = ipAddress.getAccountId();
Long domainId = ipAddress.getDomainId();
Transaction txn = Transaction.currentTxn();
txn.start();
FirewallRuleVO newRule = new FirewallRuleVO (xId, ipAddrId, portStart, portEnd, protocol.toLowerCase(), networkId, accountId, domainId, Purpose.Firewall, sourceCidrList, icmpCode, icmpType);
newRule = _firewallDao.persist(newRule);
detectRulesConflict(newRule, ipAddress);
if (!_firewallDao.setStateToAdd(newRule)) {
throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
}
UserContext.current().setEventDetails("Rule Id: " + newRule.getId());
txn.commit();
return newRule;
}
@Override
public List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd) {
Account caller = UserContext.current().getCaller();
Long ipId = cmd.getIpAddressId();
Long id = cmd.getId();
String path = null;
Pair<String, Long> accountDomainPair = _accountMgr.finalizeAccountDomainForList(caller, cmd.getAccountName(), cmd.getDomainId());
String accountName = accountDomainPair.first();
Long domainId = accountDomainPair.second();
if (ipId != null) {
IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for firewall rules yet");
}
_accountMgr.checkAccess(caller, ipAddressVO);
}
if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
Domain domain = _accountMgr.getDomain(caller.getDomainId());
path = domain.getPath();
}
Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
sb.and("id", sb.entity().getId(), Op.EQ);
sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), Op.EQ);
sb.and("domainId", sb.entity().getDomainId(), Op.EQ);
sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
if (path != null) {
// for domain admin we should show only subdomains information
SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
SearchCriteria<FirewallRuleVO> sc = sb.create();
if (id != null) {
sc.setParameters("id", id);
}
if (ipId != null) {
sc.setParameters("ip", ipId);
}
if (domainId != null) {
sc.setParameters("domainId", domainId);
if (accountName != null) {
Account account = _accountMgr.getActiveAccount(accountName, domainId);
sc.setParameters("accountId", account.getId());
}
}
sc.setParameters("purpose", Purpose.Firewall);
if (path != null) {
sc.setJoinParameters("domainSearch", "path", path + "%");
}
return _firewallDao.search(sc, filter);
}
@Override
public void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException {
assert newRule.getSourceIpAddressId() == ipAddress.getId() : "You passed in an ip address that doesn't match the address in the new rule";
List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurposeAndNotRevoked(newRule.getSourceIpAddressId(), null);
assert (rules.size() >= 1) : "For network rules, we now always first persist the rule and then check for network conflicts so we should at least have one rule at this point.";
for (FirewallRuleVO rule : rules) {
if (rule.getId() == newRule.getId()) {
continue; // Skips my own rule.
}
if (rule.getPurpose() == Purpose.StaticNat && newRule.getPurpose() != Purpose.StaticNat) {
throw new NetworkRuleConflictException("There is 1 to 1 Nat rule specified for the ip address id=" + newRule.getSourceIpAddressId());
} else if (rule.getPurpose() != Purpose.StaticNat && newRule.getPurpose() == Purpose.StaticNat) {
throw new NetworkRuleConflictException("There is already firewall rule specified for the ip address id=" + newRule.getSourceIpAddressId());
}
if (rule.getNetworkId() != newRule.getNetworkId() && rule.getState() != State.Revoke) {
throw new NetworkRuleConflictException("New rule is for a different network than what's specified in rule " + rule.getXid());
}
boolean allowFirewall = ((rule.getPurpose() == Purpose.Firewall || newRule.getPurpose() == Purpose.Firewall) && newRule.getPurpose() != rule.getPurpose());
boolean notNullPorts = (newRule.getSourcePortStart() != null && newRule.getSourcePortEnd() != null && rule.getSourcePortStart() != null && rule.getSourcePortEnd() != null);
if (!allowFirewall && notNullPorts && ((rule.getSourcePortStart() <= newRule.getSourcePortStart() && rule.getSourcePortEnd() >= newRule.getSourcePortStart())
|| (rule.getSourcePortStart() <= newRule.getSourcePortEnd() && rule.getSourcePortEnd() >= newRule.getSourcePortEnd())
|| (newRule.getSourcePortStart() <= rule.getSourcePortStart() && newRule.getSourcePortEnd() >= rule.getSourcePortStart())
|| (newRule.getSourcePortStart() <= rule.getSourcePortEnd() && newRule.getSourcePortEnd() >= rule.getSourcePortEnd()))) {
// we allow port forwarding rules with the same parameters but different protocols
boolean allowPf = (rule.getPurpose() == Purpose.PortForwarding && newRule.getPurpose() == Purpose.PortForwarding && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol()));
boolean allowStaticNat = (rule.getPurpose() == Purpose.StaticNat && newRule.getPurpose() == Purpose.StaticNat && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol()));
if (!(allowPf || allowStaticNat || allowFirewall)) {
throw new NetworkRuleConflictException("The range specified, " + newRule.getSourcePortStart() + "-" + newRule.getSourcePortEnd() + ", conflicts with rule " + rule.getId()
+ " which has " + rule.getSourcePortStart() + "-" + rule.getSourcePortEnd());
}
}
if (newRule.getProtocol().equalsIgnoreCase(NetUtils.ICMP_PROTO) && newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())) {
if (newRule.getIcmpCode().longValue() == rule.getIcmpCode().longValue() && newRule.getIcmpType().longValue() == rule.getIcmpType().longValue() && newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())) {
throw new InvalidParameterValueException("New rule conflicts with existing rule id=" + rule.getId());
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("No network rule conflicts detected for " + newRule + " against " + (rules.size() - 1) + " existing rules");
}
}
@Override
public void validateFirewallRule(Account caller, IPAddressVO ipAddress, Integer portStart, Integer portEnd, String proto, Purpose purpose) {
// Validate ip address
_accountMgr.checkAccess(caller, ipAddress);
Long networkId = ipAddress.getAssociatedWithNetworkId();
if (networkId == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule ; ip id=" + ipAddress.getId() + " is not associated with any network");
}
Network network = _networkMgr.getNetwork(networkId);
assert network != null : "Can't create port forwarding rule as network associated with public ip address is null...how is it possible?";
if (portStart != null && !NetUtils.isValidPort(portStart)) {
throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart);
}
if (portEnd != null && !NetUtils.isValidPort(portEnd)) {
throw new InvalidParameterValueException("Public port range is an invalid value: " + portEnd);
}
// start port can't be bigger than end port
if (portStart != null && portEnd != null && portStart > portEnd) {
throw new InvalidParameterValueException("Start port can't be bigger than end port");
}
// Verify that the network guru supports the protocol specified
Map<Network.Capability, String> protocolCapabilities = null;
if (purpose == Purpose.LoadBalancing) {
if (!_elbEnabled) {
protocolCapabilities = _networkMgr.getServiceCapabilities(network.getDataCenterId(), network.getNetworkOfferingId(), Service.Lb);
}
} else {
protocolCapabilities = _networkMgr.getServiceCapabilities(network.getDataCenterId(), network.getNetworkOfferingId(), Service.Firewall);
}
if (protocolCapabilities != null) {
String supportedProtocols = protocolCapabilities.get(Capability.SupportedProtocols).toLowerCase();
if (!supportedProtocols.contains(proto.toLowerCase())) {
throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId());
} else if (proto.equalsIgnoreCase(NetUtils.ICMP_PROTO) && purpose != Purpose.Firewall) {
throw new InvalidParameterValueException("Protocol " + proto + " is currently supported only for rules with purpose " + Purpose.Firewall);
}
}
}
@Override
public boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError) throws ResourceUnavailableException {
if (!_networkMgr.applyRules(rules, continueOnError)) {
s_logger.warn("Rules are not completely applied");
return false;
} else {
for (FirewallRule rule : rules) {
if (rule.getState() == FirewallRule.State.Revoke) {
_firewallDao.remove(rule.getId());
} else if (rule.getState() == FirewallRule.State.Add) {
FirewallRuleVO ruleVO = _firewallDao.findById(rule.getId());
ruleVO.setState(FirewallRule.State.Active);
_firewallDao.update(ruleVO.getId(), ruleVO);
}
}
return true;
}
}
@Override
public boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException {
List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall);
return applyFirewallRules(rules, false, caller);
}
@Override
public boolean applyFirewallRules(List<FirewallRuleVO> rules, boolean continueOnError, Account caller) {
if (rules.size() == 0) {
s_logger.debug("There are no firewall rules to apply for ip id=" + rules);
return true;
}
for (FirewallRuleVO rule: rules){
// load cidrs if any
rule.setSourceCidrList(_firewallCidrsDao.getSourceCidrs(rule.getId()));
}
if (caller != null) {
_accountMgr.checkAccess(caller, rules.toArray(new FirewallRuleVO[rules.size()]));
}
try {
if (!applyRules(rules, continueOnError)) {
return false;
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to apply firewall rules due to ", ex);
return false;
}
return true;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
public boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId) {
FirewallRuleVO rule = _firewallDao.findById(ruleId);
if (rule == null || rule.getPurpose() != Purpose.Firewall) {
throw new InvalidParameterValueException("Unable to find " + ruleId + " having purpose " + Purpose.Firewall);
}
_accountMgr.checkAccess(caller, rule);
revokeRule(rule, caller, userId, false);
boolean success = false;
if (apply) {
List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(rule.getSourceIpAddressId(), Purpose.Firewall);
return applyFirewallRules(rules, false, caller);
} else {
success = true;
}
return success;
}
@Override
public boolean revokeFirewallRule(long ruleId, boolean apply) {
Account caller = UserContext.current().getCaller();
long userId = UserContext.current().getCallerUserId();
return revokeFirewallRule(ruleId, apply, caller, userId);
}
@Override
@DB
public void revokeRule(FirewallRuleVO rule, Account caller, long userId, boolean needUsageEvent) {
if (caller != null) {
_accountMgr.checkAccess(caller, rule);
}
Transaction txn = Transaction.currentTxn();
boolean generateUsageEvent = false;
txn.start();
if (rule.getState() == State.Staged) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule);
}
_firewallDao.remove(rule.getId());
generateUsageEvent = true;
} else if (rule.getState() == State.Add || rule.getState() == State.Active) {
rule.setState(State.Revoke);
_firewallDao.update(rule.getId(), rule);
generateUsageEvent = true;
}
if (generateUsageEvent && needUsageEvent) {
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(), null);
_usageEventDao.persist(usageEvent);
}
txn.commit();
}
@Override
public FirewallRule getFirewallRule(long ruleId) {
return _firewallDao.findById(ruleId);
}
@Override
public boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException {
List<FirewallRule> rules = new ArrayList<FirewallRule>();
List<FirewallRuleVO> fwRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.Firewall);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + fwRules.size() + " firewall rules for ip id=" + ipId);
}
for (FirewallRuleVO rule : fwRules) {
// Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no need to send them one by one
revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM);
}
// now send everything to the backend
List<FirewallRuleVO> rulesToApply = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall);
applyFirewallRules(rulesToApply, true, caller);
// Now we check again in case more rules have been inserted.
rules.addAll(_firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.Firewall));
if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully released firewall rules for ip id=" + ipId + " and # of rules now = " + rules.size());
}
return rules.size() == 0;
}
@Override
public FirewallRule createRuleForAllCidrs(long ipAddrId, Account caller, Integer startPort, Integer endPort, String protocol, Integer icmpCode, Integer icmpType) throws NetworkRuleConflictException{
//If firwallRule for this port range already exists, return it
List<FirewallRuleVO> rules = _firewallDao.listByIpPurposeAndProtocolAndNotRevoked(ipAddrId, startPort, endPort, protocol, Purpose.Firewall);
if (!rules.isEmpty()) {
return rules.get(0);
}
List<String> oneCidr = new ArrayList<String>();
oneCidr.add(NetUtils.ALL_CIDRS);
return createFirewallRule(ipAddrId, caller, null, startPort, endPort, protocol, oneCidr, icmpCode, icmpType);
}
@Override
public boolean revokeAllFirewallRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException {
List<FirewallRule> rules = new ArrayList<FirewallRule>();
List<FirewallRuleVO> fwRules = _firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.Firewall);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + fwRules.size() + " firewall rules for network id=" + networkId);
}
for (FirewallRuleVO rule : fwRules) {
// Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no need to send them one by one
revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM);
}
// now send everything to the backend
List<FirewallRuleVO> rulesToApply = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.Firewall);
applyFirewallRules(rulesToApply, true, caller);
// Now we check again in case more rules have been inserted.
rules.addAll(_firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.Firewall));
if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully released firewall rules for network id=" + networkId + " and # of rules now = " + rules.size());
}
return rules.size() == 0;
}
} |
package org.java_websocket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.spi.AbstractSelectableChannel;
import org.java_websocket.WebSocket.Role;
public class SocketChannelIOHelper {
public static boolean read(final ByteBuffer buf, WebSocketImpl ws, ByteChannel channel) throws IOException {
buf.clear();
int read = channel.read(buf);
buf.flip();
if(read == -1) {
ws.eot();
return false;
}
return read != 0;
}
/**
* @see WrappedByteChannel#readMore(ByteBuffer)
* @return returns whether there is more data left which can be obtained via {@link #readMore(ByteBuffer, WebSocketImpl, WrappedByteChannel)}
**/
public static boolean readMore(final ByteBuffer buf, WebSocketImpl ws, WrappedByteChannel channel) throws IOException {
buf.clear();
int read = channel.readMore(buf);
buf.flip();
if(read == -1) {
ws.eot();
return false;
}
return channel.isNeedRead();
}
/** Returns whether the whole outQueue has been flushed */
public static boolean batch(WebSocketImpl ws, ByteChannel sockchannel) throws IOException {
ByteBuffer buffer = ws.outQueue.peek();
WrappedByteChannel c = null;
if(buffer == null) {
if(sockchannel instanceof WrappedByteChannel) {
c = (WrappedByteChannel)sockchannel;
if(c.isNeedWrite()) {
c.writeMore();
}
}
} else {
do {
sockchannel.write(buffer);
if(buffer.remaining() > 0) {
return false;
} else {
ws.outQueue.poll();
buffer = ws.outQueue.peek();
}
} while(buffer != null);
}
if(ws != null &&
ws.outQueue.isEmpty() &&
ws.isFlushAndClose() &&
ws.getDraft() != null &&
ws.getDraft().getRole() != null &&
ws.getDraft().getRole() == Role.SERVER) {
synchronized(ws) {
ws.closeConnection();
}
}
return c != null ? !((WrappedByteChannel)sockchannel).isNeedWrite() : true;
}
} |
package com.matthewtamlin.spyglass.library.call_handler_adapters;
import android.content.res.TypedArray;
import com.matthewtamlin.java_utilities.testing.Tested;
import com.matthewtamlin.spyglass.library.call_handler_annotations.SpecificFlagHandler;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
/**
* Adapter for interfacing with Specific Flag Handler annotations.
*/
@Tested(testMethod = "automated")
public class SpecificFlagHandlerAdapter implements CallHandlerAdapter<SpecificFlagHandler> {
@Override
public boolean shouldCallMethod(final SpecificFlagHandler annotation, final TypedArray attrs) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
checkNotNull(attrs, "Argument \'attrs\' cannot be null.");
if (arrayContainsValue(attrs, annotation.attributeId())) {
final int handledFlags = annotation.handledFlags();
final int foundFlags = attrs.getInt(annotation.attributeId(), 0);
// Return true if at least one flag bit matches
return (foundFlags & handledFlags) > 0;
} else {
return false;
}
}
/**
* Determines whether the supplied set of attributes contains an integer value for the
* supplied attribute.
*
* @param attrs
* a set of attribute to check, not null
* @param attrId
* the resource ID of the attribute to check for
*
* @return true if a value exists, false otherwise
*/
private static boolean arrayContainsValue(final TypedArray attrs, final int attrId) {
// Compare two different results to see if the default is consistently returned
final int reading1 = attrs.getInt(attrId, 0);
final int reading2 = attrs.getInt(attrId, 1);
return !((reading1 == 0) && (reading2 == 1));
}
} |
package ee.shy.core.diff;
import ee.shy.core.Tree;
import ee.shy.core.TreeItem;
import ee.shy.storage.DataStorage;
import java.io.IOException;
import java.util.*;
/**
* Class to get the differences between two tree objects.
*/
public class TreeDiffer implements Differ<Tree> {
/**
* Storage object to get stored items according to their hash values.
*/
private final DataStorage storage;
/**
* Differ used for individual Tree items.
*/
private final TreeItemDiffer treeItemDiffer;
/**
* Construct a new {@link TreeDiffer} with given {@link DataStorage} object.
* @param storage storage to use
*/
public TreeDiffer(DataStorage storage) {
this.storage = storage;
treeItemDiffer = new TreeItemDiffer(this);
}
@Override
public List<String> diff(Tree original, Tree revised) throws IOException {
return diff("", original, revised);
}
@Override
public List<String> diff(String prefixPath, Tree original, Tree revised) throws IOException {
List<String> diffStrings = new ArrayList<>();
Map<String, TreeItem> originalItems = original.getItems();
Map<String, TreeItem> revisedItems = revised.getItems();
Set<String> unionTreeKeySet = new HashSet<>();
unionTreeKeySet.addAll(originalItems.keySet());
unionTreeKeySet.addAll(revisedItems.keySet());
for (String name : unionTreeKeySet) {
TreeItem originalItem = originalItems.get(name);
TreeItem revisedItem = revisedItems.get(name);
List<String> currentDiffStrings = treeItemDiffer.diff(prefixPath + "/" + name, originalItem, revisedItem);
diffStrings.addAll(currentDiffStrings);
if (!currentDiffStrings.isEmpty())
diffStrings.add("");
}
if (!diffStrings.isEmpty())
diffStrings.remove(diffStrings.size() - 1);
return diffStrings;
}
public DataStorage getStorage() {
return storage;
}
} |
package com.cloud.configure;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.file.filters.AbstractFileListFilter;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.ftp.filters.FtpSimplePatternFileListFilter;
import org.springframework.integration.ftp.inbound.FtpInboundFileSynchronizer;
import org.springframework.integration.ftp.inbound.FtpInboundFileSynchronizingMessageSource;
import org.springframework.integration.ftp.session.DefaultFtpSessionFactory;
import org.springframework.messaging.MessageHandler;
import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class FtpConfiguration {
@Autowired
private ServerConfig config;
@Bean
public SessionFactory<FTPFile> ftpFileSessionFactory() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost("localhost");
sf.setPort(config.getPort());
sf.setUsername(config.getUserId());
sf.setPassword(config.getPassword());
return new CachingSessionFactory<>(sf);
}
@Bean
public FtpInboundFileSynchronizer ftpInboundFileSynchronizer() {
FtpInboundFileSynchronizer fileSynchronizer = new FtpInboundFileSynchronizer(ftpFileSessionFactory());
// TODO : file remove will use trash system
fileSynchronizer.setDeleteRemoteFiles(false);
fileSynchronizer.setFilter(new FtpSimplePatternFileListFilter("*.*"));
fileSynchronizer.setRemoteDirectory("/");
return fileSynchronizer;
}
@Bean
@InboundChannelAdapter(channel="PrivateFtpChannel")
public MessageSource<File> ftpMessageSource() {
FtpInboundFileSynchronizingMessageSource source =
new FtpInboundFileSynchronizingMessageSource(ftpInboundFileSynchronizer());
source.setLocalDirectory(new File(config.getSyncDirectory()));
source.setAutoCreateLocalDirectory(true);
source.setLocalFilter(new DocPhotoFileListFilter());
return source;
}
// TODO : Custom integrate channel
@Bean
@ServiceActivator(inputChannel = "PrivateFtpChannel")
public MessageHandler handler() {
return message -> {
System.out.println(message.getPayload());
};
}
/**
* allow files only document or photo
*/
class DocPhotoFileListFilter extends AbstractFileListFilter<File> {
private Set<String> allowExtensions = null;
@Override
protected boolean accept(File file) {
if(allowExtensions == null) {
// create immutable set
allowExtensions = Collections.unmodifiableSet(new HashSet<>(config.getAllowExtensions()));
}
return allowExtensions.contains(FilenameUtils.getExtension(file.getName()));
}
}
} |
package main.java.elegit;
import main.java.elegit.treefx.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* The controller class for the commit trees. Handles mouse interaction, cell selection/highlighting,
* as well as updating the views when necessary
*/
public class CommitTreeController{
// The list of all models controlled by this controller
public static List<CommitTreeModel> allCommitTreeModels = new ArrayList<>();
// The id of the currently selected cell
private static String selectedCellID = null;
// The session controller if this controller needs to access other models/views
public static SessionController sessionController;
/**
* Takes in the cell that was clicked on, and selects it using selectCommit
* @param cell the cell that was clicked
*/
public static void handleMouseClicked(Cell cell){
String id = cell.getCellId();
if(id.equals(selectedCellID)){
sessionController.clearSelectedCommit();
}else{
sessionController.selectCommit(id);
}
selectCommitInGraph(id);
}
/**
* Handles mouse clicks that didn't happen on a cell. Deselects any
* selected commit
*/
public static void handleMouseClicked(){
resetSelection();
}
/**
* Takes in the cell that was moused over, and highlights it using highlightCommit
* @param cell the cell generated the mouseover event
* @param isOverCell whether the mouse is entering or exiting the cell
*/
public static void handleMouseover(Cell cell, boolean isOverCell){
highlightCommitInGraph(cell.getCellId(), isOverCell);
}
/**
* If the commit with the given id is not selected, select it and deselect the previously
* selected commit if necessary. If the current id is already selected, deselect it.
* Loops through all tracked CommitTreeModels and updates their corresponding views.
* @param commitID the id of the commit to select/deselect
*/
private static void selectCommitInGraph(String commitID){
boolean isDeselecting = commitID.equals(selectedCellID);
for(CommitTreeModel model : allCommitTreeModels){
if(model.treeGraph == null) continue;
TreeGraphModel m = model.treeGraph.treeGraphModel;
if(selectedCellID == null){
selectCommitInGraph(commitID, m, true);
}else{
selectCommitInGraph(selectedCellID, m, false);
if(!isDeselecting){
selectCommitInGraph(commitID, m, true);
}
}
}
if(isDeselecting){
selectedCellID = null;
}else{
selectedCellID = commitID;
}
// Edge.allVisible.set(selectedCellID == null);
}
/**
* Highlight the commit with the given id in every tracked CommitTreeModel and corresponding
* view. If the given id is selected, do nothing.
* @param commitID the id of the commit to select
* @param isOverCell whether to highlight or un-highlight the corresponding cells
*/
private static void highlightCommitInGraph(String commitID, boolean isOverCell){
for(CommitTreeModel model : allCommitTreeModels){
if(model.treeGraph == null) continue;
TreeGraphModel m = model.treeGraph.treeGraphModel;
if(!isSelected(commitID)){
Highlighter.highlightCell(commitID, selectedCellID, m, isOverCell);
Highlighter.updateCellEdges(commitID, selectedCellID, m, isOverCell);
}
}
}
/**
* Helper method that uses the Highlighter class to appropriately color the selected
* commit and its edges
* @param commitID the commit to select
* @param model the model wherein the corresponding cell should be highlighted
* @param enable whether to select or deselect the cell
*/
private static void selectCommitInGraph(String commitID, TreeGraphModel model, boolean enable){
Highlighter.highlightSelectedCell(commitID, model, enable);
if(enable){
Highlighter.updateCellEdges(commitID, commitID, model, true);
}else{
Highlighter.updateCellEdges(commitID, null, model, false);
}
}
/**
* Deselects the currently selected commit, if there is one
*/
public static void resetSelection(){
if(selectedCellID != null){
selectCommitInGraph(selectedCellID);
}
sessionController.clearSelectedCommit();
}
/**
* Checks to see if the given id is currently selected
* @param cellID the id to check
* @return true if it is selected, false otherwise
*/
private static boolean isSelected(String cellID){
return selectedCellID != null && selectedCellID.equals(cellID);
}
/**
* Initializes the view corresponding to the given CommitTreeModel. Updates
* all tracked CommitTreeModels with branch heads and missing commits,
* but does not update their view
* @param commitTreeModel the model whose view should be updated
*/
public static void init(CommitTreeModel commitTreeModel){
RepoHelper repo = commitTreeModel.sessionModel.getCurrentRepoHelper();
List<String> commitIDs = repo.getAllCommitIDs();
for(CommitTreeModel model : allCommitTreeModels){
if(model.treeGraph != null){
for(String id : commitIDs){
if(!model.containsID(id)){
model.addInvisibleCommit(id);
}
}
model.treeGraph.update();
}
}
commitTreeModel.resetBranchHeads(false);
List<BranchHelper> modelBranches = commitTreeModel.getBranches();
if(modelBranches != null){
for(BranchHelper branch : modelBranches){
if(!commitTreeModel.sessionModel.getCurrentRepoHelper().isBranchTracked(branch)){
commitTreeModel.setCommitAsUntrackedBranch(branch.getHead().getId());
}else{
commitTreeModel.setCommitAsTrackedBranch(branch.getHead().getId());
}
}
}
commitTreeModel.view.displayTreeGraph(commitTreeModel.treeGraph, commitTreeModel.sessionModel.getCurrentRepoHelper().getHead());
}
/**
* Updates the views corresponding to all tracked CommitTreeModels after updating them
* with branch heads and any missing commits
* @param repo the repo from which the list of all commits is pulled
*/
public static void update(RepoHelper repo) throws IOException{
List<String> commitIDs = repo.getAllCommitIDs();
for(CommitTreeModel model : allCommitTreeModels){
if(model.treeGraph != null){
for(String id : commitIDs){
if(!model.containsID(id)){
model.addInvisibleCommit(id);
}
}
model.resetBranchHeads(true);
List<BranchHelper> modelBranches = model.getBranches();
if(modelBranches == null) continue;
for(BranchHelper branch : modelBranches){
if(!model.sessionModel.getCurrentRepoHelper().isBranchTracked(branch)){
model.setCommitAsUntrackedBranch(branch.getHeadId());
}else{
model.setCommitAsTrackedBranch(branch.getHeadId());
}
}
model.treeGraph.update();
model.view.displayTreeGraph(model.treeGraph, null);
}
}
}
/**
* Uses the Highlighter class to emphasize and scroll to the cell corresponding
* to the given commit in every view corresponding to a tracked CommitTreeModel
* @param commit the commit to focus
*/
public static void focusCommitInGraph(CommitHelper commit){
if(commit == null) return;
for(CommitTreeModel model : allCommitTreeModels){
if(model.treeGraph != null && model.treeGraph.treeGraphModel.containsID(commit.getId())){
Cell c = model.treeGraph.treeGraphModel.cellMap.get(commit.getId());
Highlighter.emphasizeCell(c);
}
}
}
/**
* Uses the Highlighter class to emphasize and scroll to the cell corresponding
* to the cell with the given ID in every view corresponding to a tracked CommitTreeModel
* @param commitID the ID of the commit to focus
*/
public static void focusCommitInGraph(String commitID){
if(commitID == null) return;
for(CommitTreeModel model : allCommitTreeModels){
if(model.treeGraph != null && model.treeGraph.treeGraphModel.containsID(commitID)){
Cell c = model.treeGraph.treeGraphModel.cellMap.get(commitID);
Highlighter.emphasizeCell(c);
}
}
}
} |
//WIP WIP WIP
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.commons.codec.digest.DigestUtils;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis;
import org.myrobotlab.service.data.AudioData;
import org.myrobotlab.service.interfaces.AudioListener;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.slf4j.Logger;
public class MicrosoftLocalTTS extends AbstractSpeechSynthesis implements AudioListener {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(MicrosoftLocalTTS.class);
transient Integer voice=0;
transient String voiceName;
transient List<Integer> voices;
private String ttsFolder = "tts";
private String ttsExecutable = ttsFolder+"/tts.exe";
boolean ttsExecutableExist;
// this is a peer service.
transient AudioFile audioFile = null;
transient Map<Integer,String> voiceMap = new HashMap<Integer,String>();
Stack<String> audioFiles = new Stack<String>();
transient HashMap<AudioData, String> utterances = new HashMap<AudioData, String>();
String lang="en";
public MicrosoftLocalTTS(String n) {
super(n);
}
@Override
public List<String> getVoices() {
ArrayList<String> args = new ArrayList<String>();
args.add("-V");
String cmd = Runtime.execute(System.getProperty("user.dir")+"\\"+ttsExecutable,"-V");
String[] lines = cmd.split(System.getProperty("line.separator"));
List <String> voiceList = (List<String>) Arrays.asList(lines);
for (int i = 0; i < voiceList.size() && i<10; i++) {
// error(voiceList.get(i).substring(0,2));
if (voiceList.get(i).substring(0,1).matches("\\d+"))
{
voiceMap.put(i,voiceList.get(i).substring(2,voiceList.get(i).length()));
log.info("voice : "+voiceMap.get(i)+" index : "+i);
}
}
return voiceList;
}
@Override
public boolean setVoice(String voice) {
getVoices();
Integer voiceId=Integer.parseInt(voice);
if (voiceMap.containsKey(voiceId)) {
this.voiceName = voiceMap.get(voiceId);
this.voice = voiceId;
log.info("setting voice to {}", voice, "( ", voiceName, " ) ");
return true;
}
error("could not set voice to {}", voice);
return false;
}
@Override
public void setLanguage(String l) {
log.info("not used");
}
@Override
public String getLanguage() {
return lang;
}
public byte[] cacheFile(String toSpeak) throws IOException {
byte[] mp3File = null;
String localFileName = getLocalFileName(this, toSpeak, "mp3");
if (voiceName==null)
{
setVoice(voice.toString());
}
if (!audioFile.cacheContains(localFileName)) {
log.info("retrieving speech from locals - {}", localFileName, voiceName);
String command = System.getProperty("user.dir")+"\\"+ttsExecutable+" -f 9 -v "+voice+" -t -o tts//output \""+toSpeak+"\"";
File f = new File(System.getProperty("user.dir")+"\\"+ttsFolder+"\\output0.mp3");
f.delete();
String cmd = Runtime.execute("cmd.exe", "/c", command);
if (!f.exists())
{
log.error(ttsExecutable+" caused an error : "+cmd);
}
else
{
mp3File = FileIO.toByteArray(f);
audioFile.cache(localFileName, mp3File, toSpeak);
f.delete();
}
} else {
log.info("using local cached file");
mp3File = FileIO.toByteArray(new File(AudioFile.globalFileCacheDir + File.separator + getLocalFileName(this, toSpeak, "mp3")));
}
return mp3File;
}
@Override
public AudioData speak(String toSpeak) throws Exception {
cacheFile(toSpeak);
AudioData audioData = audioFile.playCachedFile(getLocalFileName(this, toSpeak, "mp3"));
utterances.put(audioData, toSpeak);
return audioData;
}
@Override
public String publishStartSpeaking(String utterance) {
log.info("publishStartSpeaking {}", utterance);
return utterance;
}
@Override
public String publishEndSpeaking(String utterance) {
log.info("publishEndSpeaking {}", utterance);
return utterance;
}
@Override
public void onAudioStart(AudioData data) {
log.info("onAudioStart {} {}", getName(), data.toString());
// filters on only our speech
if (utterances.containsKey(data)) {
String utterance = utterances.get(data);
invoke("publishStartSpeaking", utterance);
}
}
@Override
public void onAudioEnd(AudioData data) {
log.info("onAudioEnd {} {}", getName(), data.toString());
// filters on only our speech
if (utterances.containsKey(data)) {
String utterance = utterances.get(data);
invoke("publishEndSpeaking", utterance);
utterances.remove(data);
}
}
@Override
public boolean speakBlocking(String toSpeak) throws Exception {
cacheFile(toSpeak);
invoke("publishStartSpeaking", toSpeak);
audioFile.playBlocking(AudioFile.globalFileCacheDir + File.separator + getLocalFileName(this, toSpeak, "mp3"));
invoke("publishEndSpeaking", toSpeak);
return false;
}
@Override
public void setVolume(float volume) {
audioFile.setVolume(volume);
}
@Override
public float getVolume() {
return audioFile.getVolume();
}
@Override
public void interrupt() {
// TODO Auto-generated method stub
}
@Override
public String getVoice() {
return voice.toString();
}
@Override
public String getLocalFileName(SpeechSynthesis provider, String toSpeak, String audioFileType) throws UnsupportedEncodingException {
// TODO: make this a base class sort of thing.
// having - AudioFile.globalFileCacheDir exposed like this is a bad idea ..
// AudioFile should just globallyCache - the details of that cache should not be exposed :(
return provider.getClass().getSimpleName() + File.separator + URLEncoder.encode(provider.getVoice(), "UTF-8") + File.separator + DigestUtils.md5Hex(toSpeak) + "."
+ audioFileType;
}
// can this be defaulted ?
@Override
public void addEar(SpeechRecognizer ear) {
// TODO Auto-generated method stub
}
@Override
public void onRequestConfirmation(String text) {
// TODO Auto-generated method stub
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(MicrosoftLocalTTS.class.getCanonicalName());
meta.addDescription("used as a general template");
meta.setAvailable(true); // false if you do not want it viewable in a
// gui
// add dependency if necessary
meta.addPeer("audioFile", "AudioFile", "audioFile");
meta.addCategory("speech");
meta.addDependency("org.apache.commons.httpclient", "4.5.2");
meta.addDependency("tts.microsoftspeech", "1.0");
return meta;
}
@Override
public void startService() {
super.startService();
audioFile = (AudioFile) startPeer("audioFile");
audioFile.startService();
subscribe(audioFile.getName(), "publishAudioStart");
subscribe(audioFile.getName(), "publishAudioEnd");
// attach a listener when the audio file ends playing.
audioFile.addListener("finishedPlaying", this.getName(), "publishEndSpeaking");
File f = new File(System.getProperty("user.dir")+"\\"+ttsExecutable);
ttsExecutableExist=true;
if(!f.exists()) {
error("Missing : "+System.getProperty("user.dir")+"\\"+ttsExecutable);
ttsExecutableExist=false;
}
}
public static void main(String[] args) throws Exception {
LoggingFactory.init(Level.INFO);
MicrosoftLocalTTS microsoftLocalTTS = (MicrosoftLocalTTS) Runtime.start("microsoftLocalTTS", "MicrosoftLocalTTS");
microsoftLocalTTS.getVoices();
microsoftLocalTTS.setVoice("1");
microsoftLocalTTS.speakBlocking("local tts");
microsoftLocalTTS.speak("test");
}
@Override
public List<String> getLanguages() {
// TODO Auto-generated method stub
return null;
}
} |
package eme.model;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import eme.parser.JavaProjectParser;
/**
* Base class for an intermediate model.
* @author Timur Saglam
*/
public class IntermediateModel {
private static final Logger logger = LogManager.getLogger(JavaProjectParser.class.getName());
private final Set<ExtractedPackage> packages;
private final String projectName;
private ExtractedPackage rootElement;
private final Set<ExtractedType> types;
/**
* Basic constructor.
* @param projectName is the name of the project the model was extracted from.
*/
public IntermediateModel(String projectName) {
packages = new LinkedHashSet<ExtractedPackage>();
types = new LinkedHashSet<ExtractedType>();
this.projectName = projectName;
}
/**
* Adds a new package to the intermediate model if it is not already added.
* @param newPackage is the new package to add.
*/
public void add(ExtractedPackage newPackage) {
if (packages.add(newPackage)) {
if (rootElement == null) { // if it is the first package
rootElement = newPackage; // add as root
newPackage.setAsRoot(); // mark as root
} else {
getPackage(newPackage.getParentName()).add(newPackage);
}
}
}
/**
* Adds a new type to the intermediate model if it is not already added. Finds parent package
* automatically.
* @param type is the new type to add.
*/
public void add(ExtractedType type) {
addTo(type, getPackage(type.getParentName()));
}
/**
* Adds a new type to the intermediate model and to a specific parent package if it is not
* already added.
* @param type is the new type to add.
* @param parent is the parent package.
*/
public void addTo(ExtractedType type, ExtractedPackage parent) {
if (types.add(type)) { // add class to list of classes.
parent.add(type);
}
}
/**
* Returns the package of the intermediate model whose full name matches the given full name.
* @param fullName is the given full name.
* @return the package with the matching name.
* @throws RuntimeException if the package is not found. This means this method cannot be used
* to check whether there is a certain package in the model. It is explicitly used to find an
* existing package.
*/
public ExtractedPackage getPackage(String fullName) {
for (ExtractedPackage aPackage : packages) { // for all packages
if (aPackage.getFullName().equals(fullName)) { // if parent
return aPackage; // can only have on parent
}
}
throw new RuntimeException("Could not find package " + fullName);
}
/**
* Getter for the name of the project.
* @return the name.
*/
public String getProjectName() {
return projectName;
}
/**
* Getter for the root package of the model.
* @return the root package.
*/
public ExtractedPackage getRoot() {
return rootElement;
}
/**
* Returns the type of the intermediate model whose full name matches the given full name.
* @param fullName is the given full name.
* @return the type with the matching name, or null if no matching type is found.
*/
public ExtractedType getType(String fullName) {
for (ExtractedType type : types) { // for all packages
if (type.getFullName().equals(fullName)) { // if parent
return type; // can only have on parent
}
}
return null;
}
/**
* Prints the model.
*/
public void print() {
logger.info(toString());
logger.info(" with packages " + packages.toString());
logger.info(" with types " + types.toString());
// TODO (LOW) keep up to date.
}
@Override
public String toString() {
return projectName + "IntermediateModel[Packages=" + packages.size() + ", Types=" + types.size() + "]";
// TODO (LOW) keep up to date.
}
} |
package hudson.model;
import hudson.DescriptorExtensionList;
import hudson.Util;
import hudson.Extension;
import hudson.views.BuildButtonColumn;
import hudson.views.JobColumn;
import hudson.views.LastDurationColumn;
import hudson.views.LastFailureColumn;
import hudson.views.LastSuccessColumn;
import hudson.views.ListViewColumn;
import hudson.views.ListViewColumnDescriptor;
import hudson.views.StatusColumn;
import hudson.views.WeatherColumn;
import hudson.views.StatusColumn.DescriptorImpl;
import hudson.model.Descriptor.FormException;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.triggers.Messages;
import hudson.triggers.SCMTrigger.SCMTriggerCause;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.model.Cause.UserCause;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.ServletException;
/**
* Displays {@link Job}s in a flat list view.
*
* @author Kohsuke Kawaguchi
*/
public class OneAndOneView extends View implements Saveable {
/**
* List of job names. This is what gets serialized.
*/
/* package */final SortedSet<String> jobNames = new TreeSet<String>(
CaseInsensitiveComparator.INSTANCE);
private DescribableList<ListViewColumn, Descriptor<ListViewColumn>> columns;
/**
* Include regex string.
*/
private String includeRegex;
/**
* Compiled include pattern from the includeRegex string.
*/
private transient Pattern includePattern;
private String showType;
public String getShowType() {
return showType;
}
private static final String TYPEALL = "ALL";
private static final String TYPESUCCESS = "Successes";
private static final String TYPEFAILURE = "Failures";
private static final String TYPEUNSTABLE = "Unstables";
private static final String TYPEDISABLED = "Disabled";
private static final String TYPETESTERRORS = "TestErrors";
public String getTYPEALL() {
return TYPEALL;
}
public String getTYPESUCCESS() {
return TYPESUCCESS;
}
public String getTYPEFAILURE() {
return TYPEFAILURE;
}
public String getTYPEUNSTABLE() {
return TYPEUNSTABLE;
}
public String getTYPEDISABLED() {
return TYPEDISABLED;
}
public String getTYPETESTERRORS() {
return TYPETESTERRORS;
}
private String viewType;
public String getViewType() {
return viewType;
}
public static final String VIEWTYPEGLOBAL = "Global";
public static final String VIEWTYPEADMIN = "Admin";
public static final String VIEWTYPEUSER = "User";
public String getVIEWTYPEGLOBAL() {
return VIEWTYPEGLOBAL;
}
public String getVIEWTYPEADMIN() {
return VIEWTYPEADMIN;
}
public String getVIEWTYPEUSER() {
return VIEWTYPEUSER;
}
private String viewUserName;
public String getViewUserName() {
if (viewUserName == null)
viewUserName = "";
return viewUserName;
}
@DataBoundConstructor
public OneAndOneView(String name) {
super(name);
initColumns();
}
public OneAndOneView(String name, ViewGroup owner) {
this(name);
this.owner = owner;
}
public void save() throws IOException {
// persistence is a part of the owner.
// due to the initialization timing issue, it can be null when this method is called.
if (owner!=null)
owner.save();
}
private Object readResolve() {
if (includeRegex != null)
includePattern = Pattern.compile(includeRegex);
initColumns();
return this;
}
protected void initColumns() {
if (columns != null) {
// already persisted
return;
}
// OK, set up default list of columns:
// create all instances
ArrayList<ListViewColumn> r = new ArrayList<ListViewColumn>();
DescriptorExtensionList<ListViewColumn, Descriptor<ListViewColumn>> all = ListViewColumn.all();
ArrayList<Descriptor<ListViewColumn>> left = new ArrayList<Descriptor<ListViewColumn>>(all);
for (Class<? extends ListViewColumn> d: DEFAULT_COLUMNS) {
Descriptor<ListViewColumn> des = all.find(d);
if (des != null) {
try {
r.add(des.newInstance(null, null));
left.remove(des);
} catch (FormException e) {
LOGGER.log(Level.WARNING, "Failed to instantiate "+des.clazz,e);
}
}
}
for (Descriptor<ListViewColumn> d : left)
try {
if (d instanceof ListViewColumnDescriptor) {
ListViewColumnDescriptor ld = (ListViewColumnDescriptor) d;
if (!ld.shownByDefault()) continue; // skip this
}
ListViewColumn lvc = d.newInstance(null, null);
if (!lvc.shownByDefault()) continue; // skip this
r.add(lvc);
} catch (FormException e) {
LOGGER.log(Level.WARNING, "Failed to instantiate "+d.clazz,e);
}
columns = new DescribableList<ListViewColumn, Descriptor<ListViewColumn>>(this,r);
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* @see Hudson#getActions()
*/
public List<Action> getActions() {
return Hudson.getInstance().getActions();
}
public Iterable<ListViewColumn> getColumns() {
return columns;
}
/**
* Returns a read-only view of all {@link Job}s in this view.
*
* <p>
* This method returns a separate copy each time to avoid concurrent
* modification issue.
*/
public synchronized List<TopLevelItem> getItems() {
SortedSet<String> names = new TreeSet<String>(jobNames);
if (includePattern != null) {
for (TopLevelItem item : Hudson.getInstance().getItems()) {
String itemName = item.getName();
if (includePattern.matcher(itemName).matches()) {
names.add(itemName);
}
}
}
for (Iterator<String> iterator = names.iterator(); iterator.hasNext();) {
String name = iterator.next();
Result result = Result.NOT_BUILT;
AbstractTestResultAction testResultAction = null;
if (Hudson.getInstance().getItem(name) instanceof AbstractProject){
if (((AbstractProject<?, ?>) Hudson.getInstance().getItem(name))
.getLastBuild() != null) {
testResultAction = ((AbstractProject<?, ?>) Hudson
.getInstance().getItem(name)).getLastBuild()
.getTestResultAction();
result = ((AbstractProject<?, ?>) Hudson.getInstance().getItem(
name)).getLastBuild().getResult();
}
boolean isDisabled = ((AbstractProject<?, ?>) Hudson.getInstance()
.getItem(name)).isDisabled();
int failedTestCount = 0;
if (testResultAction != null)
failedTestCount = testResultAction.getFailCount();
if (showType != null) {
if ((showType.equals(TYPEFAILURE))
&& ((result != Result.FAILURE) || isDisabled)) {
iterator.remove();
} else if ((showType.equals(TYPESUCCESS))
&& ((result != Result.SUCCESS) || isDisabled)) {
iterator.remove();
} else if ((showType.equals(TYPEUNSTABLE))
&& ((result != Result.UNSTABLE) || isDisabled)) {
iterator.remove();
} else if ((showType.equals(TYPEDISABLED)) && (!isDisabled)) {
iterator.remove();
} else if ((showType.equals(TYPETESTERRORS))
&& (failedTestCount == 0)) {
iterator.remove();
}
}
}
else{
iterator.remove();
}
}
List<TopLevelItem> items = new ArrayList<TopLevelItem>(names.size());
for (String name : names) {
TopLevelItem item = Hudson.getInstance().getItem(name);
if (item != null)
items.add(item);
}
return items;
}
public boolean contains(TopLevelItem item) {
return jobNames.contains(item.getName());
}
public String getIncludeRegex() {
return includeRegex;
}
public Item doCreateItem(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
Item item = Hudson.getInstance().doCreateItem(req, rsp);
if (item != null) {
jobNames.add(item.getName());
owner.save();
}
return item;
}
@Override
public synchronized void onJobRenamed(Item item, String oldName,
String newName) {
if (jobNames.remove(oldName) && newName != null)
jobNames.add(newName);
}
/**
* Build all jobs of this view.
*
* @throws ServletException
*/
public synchronized void doBuild(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
for (TopLevelItem item : this.getItems()) {
((AbstractProject<?, ?>) item).scheduleBuild(new UserCause());
}
rsp.sendRedirect(".");
}
/**
* Handles the configuration submission.
*
* Load view-specific properties here.
*/
@Override
protected void submit(StaplerRequest req) throws IOException, ServletException,
FormException {
jobNames.clear();
for (TopLevelItem item : Hudson.getInstance().getItems()) {
if (req.getParameter(item.getName()) != null)
jobNames.add(item.getName());
}
if (req.getParameter("showType") != null)
showType = req.getParameter("showType");
else
showType = TYPEALL;
if (req.getParameter("viewType") != null)
viewType = req.getParameter("viewType");
else
viewType = VIEWTYPEGLOBAL;
if (req.getParameter("viewUserName") != null)
viewUserName = req.getParameter("viewUserName");
else
viewUserName = "";
if (req.getParameter("useincluderegex") != null) {
includeRegex = Util.nullify(req.getParameter("includeRegex"));
includePattern = Pattern.compile(includeRegex);
} else {
includeRegex = null;
includePattern = null;
}
if (columns == null) {
columns = new DescribableList<ListViewColumn, Descriptor<ListViewColumn>>(
Saveable.NOOP);
}
columns.rebuildHetero(req, req.getSubmittedForm(), Hudson.getInstance()
.getDescriptorList(ListViewColumn.class), "columns");
}
@Extension
public static final class DescriptorImpl extends ViewDescriptor {
public String getDisplayName() {
return "1&1 View";
}
/**
* Checks if the include regular expression is valid.
*/
public FormValidation doCheckIncludeRegex(@QueryParameter String value)
throws IOException, ServletException, InterruptedException {
String v = Util.fixEmpty(value);
if (v != null) {
try {
Pattern.compile(v);
} catch (PatternSyntaxException pse) {
return FormValidation.error(pse.getMessage());
}
}
return FormValidation.ok();
}
}
public static List<ListViewColumn> getDefaultColumns() {
ArrayList<ListViewColumn> r = new ArrayList<ListViewColumn>();
DescriptorExtensionList<ListViewColumn, Descriptor<ListViewColumn>> all = ListViewColumn.all();
for (Class<? extends ListViewColumn> t : DEFAULT_COLUMNS) {
Descriptor<ListViewColumn> d = all.find(t);
if (d != null) {
try {
r.add (d.newInstance(null, null));
} catch (FormException e) {
LOGGER.log(Level.WARNING, "Failed to instantiate "+d.clazz,e);
}
}
}
return Collections.unmodifiableList(r);
}
public static class ViewCause extends Cause {
@Override
public String getShortDescription() {
if (Hudson.getAuthentication().getName() != null) {
return Hudson.getAuthentication().getName()
+ " triggered this build via complete view build of ";
//+ "View"
} else {
return "Unknown triggered this build via complete view build of ";
//+ getDisplayName();
}
}
@Override
public boolean equals(Object o) {
return o instanceof ViewCause;
}
@Override
public int hashCode() {
return 7;
}
}
private static final Logger LOGGER = Logger.getLogger(ListView.class.getName());
/**
* Traditional column layout before the {@link ListViewColumn} becomes extensible.
*/
private static final List<Class<? extends ListViewColumn>> DEFAULT_COLUMNS = Arrays.asList(
StatusColumn.class,
WeatherColumn.class,
BuildButtonColumn.class,
JobColumn.class,
LastSuccessColumn.class,
LastFailureColumn.class,
LastDurationColumn.class
);
} |
package org.jboss.as.server.deployment;
/**
* An enumeration of the phases of a deployment unit's processing cycle.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public enum Phase {
/* == TEMPLATE ==
* Upon entry, this phase performs the following actions:
* <ul>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
/**
* This phase creates the initial root structure. Depending on the service for this phase will ensure that the
* deployment unit's initial root structure is available and accessible.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li>
* <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments:
* <ul>
* <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* </ul>
* <p>
*/
STRUCTURE(null),
/**
* This phase assembles information from the root structure to prepare for adding and processing additional external
* structure, such as from class path entries and other similar mechanisms.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li>
* <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li>
* <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li>
* </ul>
* <p>
*/
PARSE(null),
/**
* In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>Any additional external structure is mounted during {@link #XXX}</li>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
DEPENDENCIES(null),
CONFIGURE_MODULE(null),
POST_MODULE(null),
INSTALL(null),
CLEANUP(null),
;
/**
* This is the key for the attachment to use as the phase's "value". The attachment is taken from
* the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified.
*/
private final AttachmentKey<?> phaseKey;
private Phase(final AttachmentKey<?> key) {
phaseKey = key;
}
/**
* Get the next phase, or {@code null} if none.
*
* @return the next phase, or {@code null} if there is none
*/
public Phase next() {
final int ord = ordinal() + 1;
final Phase[] phases = Phase.values();
return ord == phases.length ? null : phases[ord];
}
/**
* Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value
* of this phase.
*
* @return the key
*/
public AttachmentKey<?> getPhaseKey() {
return phaseKey;
}
// STRUCTURE
public static final int STRUCTURE_MOUNT = 0x0000;
public static final int STRUCTURE_MANIFEST = 0x0100;
public static final int STRUCTURE_OSGI_MANIFEST = 0x0200;
public static final int STRUCTURE_RAR = 0x0300;
public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0400;
public static final int STRUCTURE_WAR = 0x0500;
public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0600;
public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0700;
public static final int STRUCTURE_EAR_JBOSS_APP_XML_PARSE = 0x0800;
public static final int STRUCTURE_EAR = 0x0900;
public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x0A00;
public static final int STRUCTURE_ANNOTATION_INDEX = 0x0B00;
public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x0C00;
public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x0C01;
public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x0D00;
public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x0E00;
public static final int STRUCTURE_SUB_DEPLOYMENT = 0x0F00;
public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1000;
public static final int STRUCTURE_EE_MODULE_INIT = 0x1100;
// PARSE
public static final int PARSE_EE_MODULE_NAME = 0x0100;
public static final int PARSE_STRUCTURE_DESCRIPTOR = 0x0200;
public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0300;
public static final int PARSE_EAR_LIB_CLASS_PATH = 0x0400;
public static final int PARSE_ADDITIONAL_MODULES = 0x0500;
public static final int PARSE_CLASS_PATH = 0x0600;
public static final int PARSE_EXTENSION_LIST = 0x0700;
public static final int PARSE_EXTENSION_NAME = 0x0800;
public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900;
public static final int PARSE_OSGI_PROPERTIES = 0x0A00;
public static final int PARSE_WEB_DEPLOYMENT = 0x0B00;
public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00;
public static final int PARSE_ANNOTATION_WAR = 0x0D00;
public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00;
public static final int PARSE_TLD_DEPLOYMENT = 0x0F00;
public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000;
// create and attach EJB metadata for EJB deployments
public static final int PARSE_EJB_DEPLOYMENT = 0x1100;
public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200;
public static final int PARSE_EJB_MDB_DD = 0x1300;
public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x1301;
// create and attach the component description out of EJB annotations
public static final int PARSE_EJB_ANNOTATION = 0x1400;
public static final int PARSE_MESSAGE_DRIVEN_ANNOTATION = 0x1500;
public static final int PARSE_EJB_TRANSACTION_MANAGEMENT = 0x1600;
public static final int PARSE_EJB_BUSINESS_VIEW_ANNOTATION = 0x1700;
public static final int PARSE_EJB_STARTUP_ANNOTATION = 0x1800;
public static final int PARSE_EJB_CONCURRENCY_MANAGEMENT_ANNOTATION = 0x1900;
public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901;
// should be after ConcurrencyManagement annotation processor
public static final int PARSE_EJB_LOCK_ANNOTATION = 0x1A00;
// should be after ConcurrencyManagement annotation processor
public static final int PARSE_EJB_ACCESS_TIMEOUT_ANNOTATION = 0x1B00;
// should be after all views are known
public static final int PARSE_EJB_TRANSACTION_ATTR_ANNOTATION = 0x1C00;
public static final int PARSE_EJB_RESOURCE_ADAPTER_ANNOTATION = 0x1D00;
public static final int PARSE_EJB_ASYNCHRONOUS_ANNOTATION = 0x1E00;
public static final int PARSE_WEB_COMPONENTS = 0x1F00;
public static final int PARSE_WEB_MERGE_METADATA = 0x2000;
public static final int PARSE_RA_DEPLOYMENT = 0x2100;
public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200;
public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300;
public static final int PARSE_MC_BEAN_DEPLOYMENT = 0x2400;
public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500;
public static final int PARSE_RESOURCE_ADAPTERS = 0x2600;
public static final int PARSE_DATA_SOURCES = 0x2700;
public static final int PARSE_ARQUILLIAN_RUNWITH = 0x2800;
public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900;
public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00;
public static final int PARSE_WELD_DEPLOYMENT = 0x2B00;
public static final int PARSE_WEBSERVICES_XML = 0x2C00;
public static final int PARSE_DATA_SOURCE_DEFINITION = 0x2D00;
public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00;
public static final int PARSE_PERSISTENCE_UNIT = 0x2F00;
public static final int PARSE_PERSISTENCE_ANNOTATION = 0x3000;
public static final int PARSE_INTERCEPTORS_ANNOTATION = 0x3100;
public static final int PARSE_LIEFCYCLE_ANNOTATION = 0x3200;
public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300;
public static final int PARSE_RESOURCE_INJECTION_ANNOTATION = 0x3400;
// should be after all components are known
public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x3500;
public static final int PARSE_WEB_SERVICE_INJECTION_ANNOTATION = 0x3600;
// DEPENDENCIES
public static final int DEPENDENCIES_MODULE = 0x0100;
public static final int DEPENDENCIES_DS = 0x0200;
public static final int DEPENDENCIES_RAR_CONFIG = 0x0300;
public static final int DEPENDENCIES_MANAGED_BEAN = 0x0400;
public static final int DEPENDENCIES_SAR_MODULE = 0x0500;
public static final int DEPENDENCIES_WAR_MODULE = 0x0600;
public static final int DEPENDENCIES_ARQUILLIAN = 0x0700;
public static final int DEPENDENCIES_CLASS_PATH = 0x0800;
public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900;
public static final int DEPENDENCIES_WELD = 0x0A00;
public static final int DEPENDENCIES_NAMING = 0x0B00;
public static final int DEPENDENCIES_WS = 0x0C00;
public static final int DEPENDENCIES_JAXRS = 0x0D00;
public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00;
// Sets up appropriate module dependencies for EJB deployments
public static final int DEPENDENCIES_EJB = 0x0F00;
public static final int DEPENDENCIES_JPA = 0x1000;
// CONFIGURE_MODULE
public static final int CONFIGURE_MODULE_SPEC = 0x0100;
// POST_MODULE
public static final int POST_MODULE_WELD_WEB_INTEGRATION = 0x0100;
public static final int POST_MODULE_INSTALL_EXTENSION = 0x0200;
public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0300;
public static final int POST_MODULE_EAR_DEPENDENCY = 0x0400;
public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0500;
public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0600;
// should come before ejb jndi bindings processor
public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x0700;
public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x0800;
public static final int POST_MODULE_EJB_MODULE_CONFIGURATION = 0x0801;
public static final int POST_INITIALIZE_IN_ORDER = 0x0900;
// INSTALL
public static final int INSTALL_EAR_AGGREGATE_COMPONENT_INDEX = 0x0000;
public static final int INSTALL_REFLECTION_INDEX = 0x0100;
public static final int INSTALL_JAXRS_SCANNING = 0x0200;
public static final int INSTALL_APP_CONTEXT = 0x0300;
public static final int INSTALL_MODULE_CONTEXT = 0x0400;
public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500;
public static final int INSTALL_OSGI_DEPLOYMENT = 0x0600;
public static final int INSTALL_WAR_METADATA = 0x0700; //this needs to be removed, however WSDeploymentActivator still uses it
public static final int INSTALL_RA_DEPLOYMENT = 0x0800;
public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900;
public static final int INSTALL_MC_BEAN_DEPLOYMENT = 0x0A00;
public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00;
public static final int INSTALL_EE_COMP_LAZY_BINDING_SOURCE_HANDLER = 0x0C00;
public static final int INSTALL_WS_LAZY_BINDING_SOURCE_HANDLER = 0x0D00;
public static final int INSTALL_ENV_ENTRY = 0x0E00;
public static final int INSTALL_EJB_REF = 0x0F00;
public static final int INSTALL_PERSISTENCE_REF = 0x1000;
public static final int INSTALL_EE_MODULE_CONFIG = 0x1100;
public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200;
public static final int INSTALL_EE_COMPONENT = 0x1230;
public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300;
public static final int INSTALL_JAXRS_COMPONENT = 0x1400;
public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500;
public static final int INSTALL_JSF_ANNOTATIONS = 0x1600;
public static final int INSTALL_ARQUILLIAN_DEPLOYMENT = 0x1700;
public static final int INSTALL_JDBC_DRIVER = 0x1800;
public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900;
public static final int INSTALL_PERSISTENCE_PROVIDER = 0x1A00;
public static final int INSTALL_PERSISTENTUNIT = 0x1A50;
public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00;
public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00;
public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00;
// CLEANUP
public static final int CLEANUP_REFLECTION_INDEX = 0x0100;
} |
package org.opencms.xml.types;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsRuntimeException;
import org.opencms.main.OpenCms;
import org.opencms.relations.CmsLink;
import org.opencms.relations.CmsLinkUpdateUtil;
import org.opencms.relations.CmsRelationType;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.page.CmsXmlPage;
import java.util.Locale;
import org.dom4j.Attribute;
import org.dom4j.Element;
/**
* Describes the XML content type "OpenCmsVfsFile".<p>
*
* This type allows links to internal VFS resources only.<p>
*
* @author Michael Moossen
*
* @version $Revision: 1.6 $
*
* @since 7.0.0
*/
public class CmsXmlVfsFileValue extends A_CmsXmlContentValue {
/** Value to mark that no link is defined, "none". */
public static final String NO_LINK = "none";
/** The name of this type as used in the XML schema. */
public static final String TYPE_NAME = "OpenCmsVfsFile";
/** The vfs link type constant. */
public static final String TYPE_VFS_LINK = "vfsLink";
/** The schema definition String is located in a text for easier editing. */
private static String m_schemaDefinition;
/** The String value of the element node. */
private String m_stringValue;
/**
* Creates a new, empty schema type descriptor of type "OpenCmsVfsFile".<p>
*/
public CmsXmlVfsFileValue() {
// empty constructor is required for class registration
}
/**
* Creates a new XML content value of type "OpenCmsVfsFile".<p>
*
* @param document the XML content instance this value belongs to
* @param element the XML element that contains this value
* @param locale the locale this value is created for
* @param type the type instance to create the value for
*/
public CmsXmlVfsFileValue(I_CmsXmlDocument document, Element element, Locale locale, I_CmsXmlSchemaType type) {
super(document, element, locale, type);
}
/**
* Creates a new schema type descriptor for the type "OpenCmsVfsFile".<p>
*
* @param name the name of the XML node containing the value according to the XML schema
* @param minOccurs minimum number of occurrences of this type according to the XML schema
* @param maxOccurs maximum number of occurrences of this type according to the XML schema
*/
public CmsXmlVfsFileValue(String name, String minOccurs, String maxOccurs) {
super(name, minOccurs, maxOccurs);
}
/**
* Fills the given element with a {@link CmsXmlVfsFileValue} for the given resource.<p>
*
* @param element the element to fill
* @param resource the resource to use
* @param type the relation type to use
*/
public static void fillResource(Element element, CmsResource resource, CmsRelationType type) {
CmsLink link = new CmsLink(
CmsXmlVfsFileValue.TYPE_VFS_LINK,
type,
resource.getStructureId(),
resource.getRootPath(),
true);
// update xml node
CmsLinkUpdateUtil.updateXmlForVfsFile(link, element.addElement(CmsXmlPage.NODE_LINK));
}
/**
* @see org.opencms.xml.types.A_CmsXmlContentValue#createValue(I_CmsXmlDocument, org.dom4j.Element, Locale)
*/
public I_CmsXmlContentValue createValue(I_CmsXmlDocument document, Element element, Locale locale) {
return new CmsXmlVfsFileValue(document, element, locale, this);
}
/**
* @see org.opencms.xml.types.I_CmsXmlSchemaType#generateXml(org.opencms.file.CmsObject, org.opencms.xml.I_CmsXmlDocument, org.dom4j.Element, java.util.Locale)
*/
@Override
public Element generateXml(CmsObject cms, I_CmsXmlDocument document, Element root, Locale locale) {
Element element = root.addElement(getName());
// get the default value from the content handler
String defaultValue = document.getContentDefinition().getContentHandler().getDefault(cms, this, locale);
if (defaultValue != null) {
I_CmsXmlContentValue value = createValue(document, element, locale);
value.setStringValue(cms, defaultValue);
}
return element;
}
/**
* Returns the link object represented by this XML content value.<p>
*
* @param cms the cms context, can be <code>null</code> but in this case no link check is performed
*
* @return the link object represented by this XML content value
*/
public CmsLink getLink(CmsObject cms) {
Element linkElement = m_element.element(CmsXmlPage.NODE_LINK);
if (linkElement == null) {
String uri = m_element.getText();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(uri)) {
setStringValue(cms, uri);
}
linkElement = m_element.element(CmsXmlPage.NODE_LINK);
if (linkElement == null) {
return null;
}
}
CmsLinkUpdateUtil.updateType(linkElement, getContentDefinition().getContentHandler().getRelationType(getPath()));
CmsLink link = new CmsLink(linkElement);
link.checkConsistency(cms);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(link.getTarget())) {
return null;
}
return link;
}
/**
* @see org.opencms.xml.types.I_CmsXmlContentValue#getPlainText(org.opencms.file.CmsObject)
*/
@Override
public String getPlainText(CmsObject cms) {
return getStringValue(cms);
}
/**
* @see org.opencms.xml.types.I_CmsXmlSchemaType#getSchemaDefinition()
*/
public String getSchemaDefinition() {
// the schema definition is located in a separate file for easier editing
if (m_schemaDefinition == null) {
m_schemaDefinition = readSchemaDefinition("org/opencms/xml/types/XmlVfsFileValue.xsd");
}
return m_schemaDefinition;
}
/**
* @see org.opencms.xml.types.I_CmsXmlContentValue#getStringValue(CmsObject)
*/
public String getStringValue(CmsObject cms) throws CmsRuntimeException {
if (m_stringValue == null) {
m_stringValue = createStringValue(cms);
}
return m_stringValue;
}
/**
* @see org.opencms.xml.types.A_CmsXmlContentValue#getTypeName()
*/
public String getTypeName() {
return TYPE_NAME;
}
/**
* @see org.opencms.xml.types.A_CmsXmlContentValue#isSearchable()
*/
@Override
public boolean isSearchable() {
// there is no point in searching link values
return false;
}
/**
* @see org.opencms.xml.types.A_CmsXmlContentValue#newInstance(java.lang.String, java.lang.String, java.lang.String)
*/
public I_CmsXmlSchemaType newInstance(String name, String minOccurs, String maxOccurs) {
return new CmsXmlVfsFileValue(name, minOccurs, maxOccurs);
}
/**
* @see org.opencms.xml.types.A_CmsXmlContentValue#setStringValue(org.opencms.file.CmsObject, java.lang.String)
*/
public void setStringValue(CmsObject cms, String value) throws CmsIllegalArgumentException {
m_element.clearContent();
// ensure the String value is re-calculated next time it's needed
m_stringValue = null;
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
// no valid value given
return;
}
String path = value;
if (cms != null) {
String siteRoot = OpenCms.getSiteManager().getSiteRoot(value);
String oldSite = cms.getRequestContext().getSiteRoot();
try {
if (siteRoot != null) {
// only switch the site if needed
cms.getRequestContext().setSiteRoot(siteRoot);
// remove the site root, because the link manager call will append it anyway
path = cms.getRequestContext().removeSiteRoot(value);
}
// remove parameters, if not the link manager call might fail
String query = "";
int pos = path.indexOf(CmsRequestUtil.URL_DELIMITER);
int anchorPos = path.indexOf('
if ((pos == -1) || ((anchorPos > -1) && (pos > anchorPos))) {
pos = anchorPos;
}
if (pos > -1) {
query = path.substring(pos);
path = path.substring(0, pos);
}
// get the root path
path = OpenCms.getLinkManager().getRootPath(cms, path);
if (path == null) {
path = value;
} else {
// append parameters again
path += query;
}
} finally {
if (siteRoot != null) {
cms.getRequestContext().setSiteRoot(oldSite);
}
}
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(path)) {
return;
}
CmsRelationType type = getContentDefinition().getContentHandler().getRelationType(getPath());
CmsLink link = new CmsLink(TYPE_VFS_LINK, type, path, true);
// link management check
link.checkConsistency(cms);
// update xml node
CmsLinkUpdateUtil.updateXmlForVfsFile(link, m_element.addElement(CmsXmlPage.NODE_LINK));
}
/**
* Creates the String value for this vfs file value element.<p>
*
* @param cms the cms context
*
* @return the String value for this vfs file value element
*/
private String createStringValue(CmsObject cms) {
Attribute enabled = m_element.attribute(CmsXmlPage.ATTRIBUTE_ENABLED);
String content = "";
if ((enabled == null) || Boolean.valueOf(enabled.getText()).booleanValue()) {
CmsLink link = getLink(cms);
if (link != null) {
content = link.getUri();
if (cms != null) {
content = cms.getRequestContext().removeSiteRoot(link.getUri());
}
}
}
return content;
}
} |
package es.pcv.game.elements;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Rectangle2D;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;
import javax.swing.JFrame;
import es.pcv.core.render.ObjectIcon;
import es.pcv.core.render.Point2D;
import es.pcv.core.updater.elements.Collisionable;
import es.pcv.core.updater.elements.Element;
import es.pcv.game.Game;
import es.pcv.game.configuration.Config;
public class Player implements Element {
Semaphore fireS = new Semaphore(1);
Point2D position = new Point2D(0.5f, 0);
Point2D velocity = new Point2D(0.005f, -0.005f);
Point2D size = new Point2D(0.05f, 0.05f);
float vbull = 0.05f;
Color c = new Color(255, 255, 0);
Point last_mouse_position;
ObjectIcon icon = new ObjectIcon("bad1.png",4,3);
int movYImg = 0;
int movXImg = 0;
int mov=0;
int imgFija=1;
boolean fire = false;
JFrame jp;
final long RELOAD_CD = 50;
long reload = 0;
public Player(JFrame jp) {
this.jp = jp;
ply = new Polygon(
new int[] { Math.round((position.getX() + size.getX()) * Config.size.getX()),
Math.round((position.getX() - size.getX()) * Config.size.getX()),
Math.round((position.getX() - size.getX()) * Config.size.getX()),
Math.round((position.getX() + size.getX()) * Config.size.getX()) },
new int[] { Math.round((position.getY() - size.getY()) * Config.size.getY()),
Math.round((position.getY() - size.getY()) * Config.size.getY()),
Math.round((position.getY() + size.getY()) * Config.size.getY()),
Math.round((position.getY() + size.getY()) * Config.size.getY()) },
4);
KeyListener kl = new KeyListener() {
private final Set<Integer> pressed = new HashSet<Integer>();
public void keyTyped(KeyEvent e) {}
public synchronized void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_W){
movYImg=0;
imgFija=10;
}
if(e.getKeyCode()==KeyEvent.VK_A){
movXImg=0;
imgFija=4;
}
if(e.getKeyCode()==KeyEvent.VK_S){
movYImg=0;
imgFija=1;
}
if(e.getKeyCode()==KeyEvent.VK_D){
movXImg=0;
imgFija=7;
}
pressed.remove(e.getKeyCode());
}
public synchronized void keyPressed(KeyEvent e) {
pressed.add(e.getKeyCode());
if (pressed.size() > 0) {
if (pressed.contains(KeyEvent.VK_W)) {
movYImg=1;
position.addY(velocity.getY());
}
if (pressed.contains(KeyEvent.VK_A)) {
movXImg=-1;
position.addX(-velocity.getX());
}
if (pressed.contains(KeyEvent.VK_S)) {
movYImg=-1;
position.addY(-velocity.getY());
}
if (pressed.contains(KeyEvent.VK_D)) {
movXImg=1;
position.addX(velocity.getX());
}
if (position.getX() > 1) {
position.setX(1);
}
if (position.getY() > 1) {
position.setY(1);
}
if (position.getX() < 0) {
position.setX(0);
}
if (position.getY() < 0) {
position.setY(0);
}
}
}
};
// 1 boton inquierdo, 2 central y 3 derecho
MouseListener ml = new MouseListener() {
public void mouseReleased(MouseEvent e) {
if (e.getButton() == 1) {
finishFire();
}
}
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1) {
startFire();
}
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
};
jp.addMouseListener(ml);
jp.addKeyListener(kl);
}
public synchronized void update() {
if (isFire() && (System.currentTimeMillis() - reload) > RELOAD_CD) {
Point last = jp.getMousePosition();
if (last != null) {
last_mouse_position = last;
}
// Calculate fire direction
float fx = (float) last_mouse_position.getX() / Config.size.getX() - position.getX();
float fy = (float) last_mouse_position.getY() / Config.size.getY() - position.getY();
float aux = Math.abs(fy) + Math.abs(fx);
fx = (fx / aux);
fy = (fy / aux);
// Calculate offset
float ox = size.getX() * fx;
float oy = size.getY() * fy;
System.out.println(fx + "_" + fy);
Bull b = new Bull(position.getX() + ox, position.getY() + oy, vbull * fx, vbull * fy);
Game.getGame().render.add(b);
Game.getGame().updater.add(b);
reload = System.currentTimeMillis();
}
}
public void startFire() {
try {
fireS.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fire = true;
fireS.release();
}
public void finishFire() {
try {
fireS.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fire = false;
fireS.release();
}
public boolean isFire() {
try {
fireS.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean r = fire;
fireS.release();
return r;
}
Polygon ply;
public void draw(Graphics g) {
ply = new Polygon(
new int[] { Math.round((position.getX() + size.getX()) * Config.size.getX()),
Math.round((position.getX() - size.getX()) * Config.size.getX()),
Math.round((position.getX() - size.getX()) * Config.size.getX()),
Math.round((position.getX() + size.getX()) * Config.size.getX()) },
new int[] { Math.round((position.getY() - size.getY()) * Config.size.getY()),
Math.round((position.getY() - size.getY()) * Config.size.getY()),
Math.round((position.getY() + size.getY()) * Config.size.getY()),
Math.round((position.getY() + size.getY()) * Config.size.getY()) },
4);
g.setColor(c);
int img=0;
if(movXImg==0&&movYImg==0){
img=imgFija;
}
else if(movXImg==-1){
img=3+mov;
mov++;
if(mov==3){
mov=0;
}
}
else if(movXImg==1){
img=6+mov;
mov++;
if(mov==3){
mov=0;
}
}
else if(movYImg==-1){
img=0+mov;
mov++;
if(mov==3){
mov=0;
}
}
else if(movYImg==1){
img=9+mov;
mov++;
if(mov==3){
mov=0;
}
}
g.drawImage(icon.getImage(img), Math.round((position.getX() - size.getX()) * Config.size.getX()),
Math.round((position.getY() - size.getY()) * Config.size.getY()),Math.round(size.getX()*Config.size.getX())*2,
Math.round(size.getY()*Config.size.getY())*2, null);
}
public boolean isDead() {
return false;
}
public boolean kill() {
return false;
}
public boolean isCollision(Collisionable c) {
return c.getCollisionBox().intersects(ply.getBounds2D());
}
public void collision(Collisionable col) {
c = new Color((int) Math.round(Math.random() * 255), (int) Math.round(Math.random() * 255),
(int) Math.round(Math.random() * 255));
}
public Rectangle2D getCollisionBox() {
return ply.getBounds2D();
}
} |
package org.spine3.base;
import com.google.common.base.Converter;
/**
* An object converting from A to B and reverse.
*
* @author Alexander Yevsyukov
*/
@SuppressWarnings("AbstractMethodOverridesAbstractMethod")
public abstract class Stringifier<A, B> extends Converter<A, B> {
} |
package org.jboss.as.server.deployment;
/**
* An enumeration of the phases of a deployment unit's processing cycle.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public enum Phase {
/* == TEMPLATE ==
* Upon entry, this phase performs the following actions:
* <ul>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
/**
* This phase creates the initial root structure. Depending on the service for this phase will ensure that the
* deployment unit's initial root structure is available and accessible.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li>
* <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments:
* <ul>
* <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* </ul>
* <p>
*/
STRUCTURE(null),
/**
* This phase assembles information from the root structure to prepare for adding and processing additional external
* structure, such as from class path entries and other similar mechanisms.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li>
* <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li>
* <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li>
* </ul>
* <p>
*/
PARSE(null),
/**
* In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>Any additional external structure is mounted during {@link #XXX}</li>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
DEPENDENCIES(null),
CONFIGURE_MODULE(null),
POST_MODULE(null),
INSTALL(null),
CLEANUP(null),
;
/**
* This is the key for the attachment to use as the phase's "value". The attachment is taken from
* the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified.
*/
private final AttachmentKey<?> phaseKey;
private Phase(final AttachmentKey<?> key) {
phaseKey = key;
}
/**
* Get the next phase, or {@code null} if none.
*
* @return the next phase, or {@code null} if there is none
*/
public Phase next() {
final int ord = ordinal() + 1;
final Phase[] phases = Phase.values();
return ord == phases.length ? null : phases[ord];
}
/**
* Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value
* of this phase.
*
* @return the key
*/
public AttachmentKey<?> getPhaseKey() {
return phaseKey;
}
// STRUCTURE
public static final int STRUCTURE_MOUNT = 0x0000;
public static final int STRUCTURE_MANIFEST = 0x0100;
public static final int STRUCTURE_OSGI_MANIFEST = 0x0200;
public static final int STRUCTURE_RAR = 0x0300;
public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0400;
public static final int STRUCTURE_WAR = 0x0500;
public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0600;
public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0700;
public static final int STRUCTURE_EAR_JBOSS_APP_XML_PARSE = 0x0800;
public static final int STRUCTURE_EAR = 0x0900;
public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x0A00;
public static final int STRUCTURE_ANNOTATION_INDEX = 0x0B00;
public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x0C00;
public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x0C01;
public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x0D00;
public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x0E00;
public static final int STRUCTURE_SUB_DEPLOYMENT = 0x0F00;
public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1000;
public static final int STRUCTURE_EE_MODULE_INIT = 0x1100;
// PARSE
public static final int PARSE_EE_MODULE_NAME = 0x0100;
public static final int PARSE_STRUCTURE_DESCRIPTOR = 0x0200;
public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0300;
public static final int PARSE_EAR_LIB_CLASS_PATH = 0x0400;
public static final int PARSE_ADDITIONAL_MODULES = 0x0500;
public static final int PARSE_CLASS_PATH = 0x0600;
public static final int PARSE_EXTENSION_LIST = 0x0700;
public static final int PARSE_EXTENSION_NAME = 0x0800;
public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900;
public static final int PARSE_OSGI_PROPERTIES = 0x0A00;
public static final int PARSE_WEB_DEPLOYMENT = 0x0B00;
public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00;
public static final int PARSE_ANNOTATION_WAR = 0x0D00;
public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00;
public static final int PARSE_TLD_DEPLOYMENT = 0x0F00;
public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000;
// create and attach EJB metadata for EJB deployments
public static final int PARSE_EJB_DEPLOYMENT = 0x1100;
public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200;
public static final int PARSE_EJB_MDB_DD = 0x1300;
public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x1301;
// create and attach the component description out of EJB annotations
public static final int PARSE_EJB_ANNOTATION = 0x1400;
public static final int PARSE_MESSAGE_DRIVEN_ANNOTATION = 0x1500;
public static final int PARSE_EJB_TRANSACTION_MANAGEMENT = 0x1600;
public static final int PARSE_EJB_BUSINESS_VIEW_ANNOTATION = 0x1700;
public static final int PARSE_EJB_STARTUP_ANNOTATION = 0x1800;
public static final int PARSE_EJB_CONCURRENCY_MANAGEMENT_ANNOTATION = 0x1900;
public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901;
// should be after ConcurrencyManagement annotation processor
public static final int PARSE_EJB_LOCK_ANNOTATION = 0x1A00;
// should be after ConcurrencyManagement annotation processor
public static final int PARSE_EJB_ACCESS_TIMEOUT_ANNOTATION = 0x1B00;
// should be after all views are known
public static final int PARSE_EJB_TRANSACTION_ATTR_ANNOTATION = 0x1C00;
public static final int PARSE_EJB_RESOURCE_ADAPTER_ANNOTATION = 0x1D00;
public static final int PARSE_EJB_ASYNCHRONOUS_ANNOTATION = 0x1E00;
public static final int PARSE_WEB_COMPONENTS = 0x1F00;
public static final int PARSE_WEB_MERGE_METADATA = 0x2000;
public static final int PARSE_RA_DEPLOYMENT = 0x2100;
public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200;
public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300;
public static final int PARSE_MC_BEAN_DEPLOYMENT = 0x2400;
public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500;
public static final int PARSE_RESOURCE_ADAPTERS = 0x2600;
public static final int PARSE_DATA_SOURCES = 0x2700;
public static final int PARSE_ARQUILLIAN_RUNWITH = 0x2800;
public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900;
public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00;
public static final int PARSE_WELD_DEPLOYMENT = 0x2B00;
public static final int PARSE_WELD_WEB_INTEGRATION = 0x2B10;
public static final int PARSE_WELD_COMPONENT_INTEGRATION = 0x2B20;
public static final int PARSE_WEBSERVICES_XML = 0x2C00;
public static final int PARSE_DATA_SOURCE_DEFINITION = 0x2D00;
public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00;
public static final int PARSE_PERSISTENCE_UNIT = 0x2F00;
public static final int PARSE_PERSISTENCE_ANNOTATION = 0x3000;
public static final int PARSE_INTERCEPTORS_ANNOTATION = 0x3100;
public static final int PARSE_LIEFCYCLE_ANNOTATION = 0x3200;
public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300;
public static final int PARSE_RESOURCE_INJECTION_ANNOTATION = 0x3400;
public static final int PARSE_WELD_EJB_INTERCEPTORS_INTEGRATION = 0x3500;
// should be after all components are known
public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x3500;
public static final int PARSE_WEB_SERVICE_INJECTION_ANNOTATION = 0x3600;
// DEPENDENCIES
public static final int DEPENDENCIES_MODULE = 0x0100;
public static final int DEPENDENCIES_DS = 0x0200;
public static final int DEPENDENCIES_RAR_CONFIG = 0x0300;
public static final int DEPENDENCIES_MANAGED_BEAN = 0x0400;
public static final int DEPENDENCIES_SAR_MODULE = 0x0500;
public static final int DEPENDENCIES_WAR_MODULE = 0x0600;
public static final int DEPENDENCIES_ARQUILLIAN = 0x0700;
public static final int DEPENDENCIES_CLASS_PATH = 0x0800;
public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900;
public static final int DEPENDENCIES_WELD = 0x0A00;
public static final int DEPENDENCIES_NAMING = 0x0B00;
public static final int DEPENDENCIES_WS = 0x0C00;
public static final int DEPENDENCIES_JAXRS = 0x0D00;
public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00;
// Sets up appropriate module dependencies for EJB deployments
public static final int DEPENDENCIES_EJB = 0x0F00;
public static final int DEPENDENCIES_JPA = 0x1000;
// CONFIGURE_MODULE
public static final int CONFIGURE_MODULE_SPEC = 0x0100;
// POST_MODULE
public static final int POST_MODULE_INSTALL_EXTENSION = 0x0200;
public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0300;
public static final int POST_MODULE_EAR_DEPENDENCY = 0x0400;
public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0500;
public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0600;
// should come before ejb jndi bindings processor
public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x0700;
public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x0800;
public static final int POST_MODULE_EJB_MODULE_CONFIGURATION = 0x0801;
public static final int POST_INITIALIZE_IN_ORDER = 0x0900;
// INSTALL
public static final int INSTALL_EAR_AGGREGATE_COMPONENT_INDEX = 0x0000;
public static final int INSTALL_REFLECTION_INDEX = 0x0100;
public static final int INSTALL_JAXRS_SCANNING = 0x0200;
public static final int INSTALL_APP_CONTEXT = 0x0300;
public static final int INSTALL_MODULE_CONTEXT = 0x0400;
public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500;
public static final int INSTALL_OSGI_DEPLOYMENT = 0x0600;
public static final int INSTALL_WAR_METADATA = 0x0700; //this needs to be removed, however WSDeploymentActivator still uses it
public static final int INSTALL_RA_DEPLOYMENT = 0x0800;
public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900;
public static final int INSTALL_MC_BEAN_DEPLOYMENT = 0x0A00;
public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00;
public static final int INSTALL_EE_COMP_LAZY_BINDING_SOURCE_HANDLER = 0x0C00;
public static final int INSTALL_WS_LAZY_BINDING_SOURCE_HANDLER = 0x0D00;
public static final int INSTALL_ENV_ENTRY = 0x0E00;
public static final int INSTALL_EJB_REF = 0x0F00;
public static final int INSTALL_PERSISTENCE_REF = 0x1000;
public static final int INSTALL_EE_MODULE_CONFIG = 0x1100;
public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200;
public static final int INSTALL_EE_COMPONENT = 0x1230;
public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300;
public static final int INSTALL_JAXRS_COMPONENT = 0x1400;
public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500;
public static final int INSTALL_JSF_ANNOTATIONS = 0x1600;
public static final int INSTALL_ARQUILLIAN_DEPLOYMENT = 0x1700;
public static final int INSTALL_JDBC_DRIVER = 0x1800;
public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900;
public static final int INSTALL_PERSISTENCE_PROVIDER = 0x1A00;
public static final int INSTALL_PERSISTENTUNIT = 0x1A50;
public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00;
public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00;
public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00;
// CLEANUP
public static final int CLEANUP_REFLECTION_INDEX = 0x0100;
} |
package org.pentaho.di.trans.steps.sort;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
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;
/**
* Sort the rows in the input-streams based on certain criteria
*
* @author Matt
* @since 29-apr-2003
*/
public class SortRows extends BaseStep implements StepInterface
{
private SortRowsMeta meta;
private SortRowsData data;
public SortRows(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
meta=(SortRowsMeta)getStepMeta().getStepMetaInterface();
data=(SortRowsData)stepDataInterface;
}
private boolean addBuffer(RowMetaInterface rowMeta, Object[] r) throws KettleException
{
if (r!=null)
{
// Do we need to convert binary string keys?
for (int i=0;i<data.fieldnrs.length;i++)
{
if (data.convertKeysToNative[i])
{
int index = data.fieldnrs[i];
r[index] = rowMeta.getValueMeta(index).convertBinaryStringToNativeType((byte[]) r[index]);
}
}
// Save row
data.buffer.add( r );
}
if (data.files.size()==0 && r==null) // No more records: sort buffer
{
quickSort(data.buffer);
}
// Check the free memory every 1000 rows...
data.freeCounter++;
if (data.sortSize<=0 && data.freeCounter>=1000)
{
data.freeMemoryPct = Const.getPercentageFreeMemory();
data.freeCounter=0;
if (log.isDetailed())
{
data.memoryReporting++;
if (data.memoryReporting>=10)
{
logDetailed("Available memory : "+data.freeMemoryPct+"%");
data.memoryReporting=0;
}
}
}
boolean doSort = data.buffer.size()==data.sortSize; // Buffer is full: sort & dump to disk
doSort |= data.files.size()>0 && r==null && data.buffer.size()>0; // No more records: join from disk
doSort |= data.freeMemoryPctLimit>0 && data.freeMemoryPct<data.freeMemoryPctLimit && data.buffer.size()>=data.minSortSize;
// time to sort the buffer and write the data to disk...
if ( doSort )
{
// First sort the rows in buffer[]
quickSort(data.buffer);
// Then write them to disk...
DataOutputStream dos;
GZIPOutputStream gzos;
int p;
Object[] previousRow = null;
try
{
FileObject fileObject=KettleVFS.createTempFile(meta.getPrefix(), ".tmp", environmentSubstitute(meta.getDirectory()), getTransMeta());
data.files.add(fileObject); // Remember the files!
OutputStream outputStream = KettleVFS.getOutputStream(fileObject,false);
if (data.compressFiles)
{
gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
dos=new DataOutputStream(gzos);
}
else
{
dos = new DataOutputStream(new BufferedOutputStream(outputStream, 500000));
gzos = null;
}
// Just write the data, nothing else
if (meta.isOnlyPassingUniqueRows())
{
int index=0;
while (index<data.buffer.size())
{
Object[] row = data.buffer.get(index);
if (previousRow!=null)
{
int result = data.outputRowMeta.compare(row, previousRow, data.fieldnrs);
if (result==0)
{
data.buffer.remove(index); // remove this duplicate element as requested
if (log.isRowLevel()) logRowlevel("Duplicate row removed: "+data.outputRowMeta.getString(row));
}
else
{
index++;
}
}
else
{
index++;
}
previousRow = row;
}
}
// How many records do we have left?
data.bufferSizes.add( data.buffer.size() );
for (p=0;p<data.buffer.size();p++)
{
data.outputRowMeta.writeData(dos, data.buffer.get(p));
}
if (data.sortSize<0)
{
if (data.buffer.size()>data.minSortSize)
{
data.minSortSize=data.buffer.size(); // if we did it once, we can do it again.
// Memory usage goes up over time, even with garbage collection
// We need pointers, file handles, etc.
// As such, we're going to lower the min sort size a bit
data.minSortSize = (int)Math.round((double)data.minSortSize * 0.90);
}
}
// Clear the list
data.buffer.clear();
// Close temp-file
dos.close(); // close data stream
if (gzos != null)
{
gzos.close(); // close gzip stream
}
outputStream.close(); // close file stream
// How much memory do we have left?
data.freeMemoryPct = Const.getPercentageFreeMemory();
data.freeCounter=0;
if (data.sortSize<=0)
{
if (log.isDetailed()) logDetailed("Available memory : "+data.freeMemoryPct+"%");
}
}
catch(Exception e)
{
throw new KettleException("Error processing temp-file!", e);
}
data.getBufferIndex=0;
}
return true;
}
private Object[] getBuffer() throws KettleValueException
{
Object[] retval;
// Open all files at once and read one row from each file...
if (data.files.size()>0 && ( data.dis.size()==0 || data.fis.size()==0 ))
{
if(log.isBasic()) logBasic("Opening "+data.files.size()+" tmp-files...");
try
{
for (int f=0;f<data.files.size() && !isStopped();f++)
{
FileObject fileObject = (FileObject)data.files.get(f);
String filename = KettleVFS.getFilename(fileObject);
if (log.isDetailed()) logDetailed("Opening tmp-file: ["+filename+"]");
InputStream fi=KettleVFS.getInputStream(fileObject);
DataInputStream di;
data.fis.add(fi);
if (data.compressFiles)
{
GZIPInputStream gzfi = new GZIPInputStream(new BufferedInputStream(fi));
di =new DataInputStream(gzfi);
data.gzis.add(gzfi);
}
else
{
di=new DataInputStream(new BufferedInputStream(fi, 50000));
}
data.dis.add(di);
// How long is the buffer?
int buffersize=data.bufferSizes.get(f);
if (log.isDetailed()) logDetailed("["+filename+"] expecting "+buffersize+" rows...");
if (buffersize>0)
{
Object[] row = (Object [])data.outputRowMeta.readData(di);
data.rowbuffer.add( row ); // new row from input stream
data.tempRows.add( new RowTempFile(row,f) );
}
}
// Sort the data row buffer
Collections.sort(data.tempRows, data.comparator);
}
catch(Exception e)
{
logError("Error reading back tmp-files : "+e.toString());
logError(Const.getStackTracker(e));
}
}
if (data.files.size()==0)
{
if (data.getBufferIndex<data.buffer.size())
{
retval=(Object[])data.buffer.get(data.getBufferIndex);
data.getBufferIndex++;
}
else
{
retval=null;
}
}
else
{
if (data.rowbuffer.size()==0)
{
retval=null;
}
else
{
// We now have "filenr" rows waiting: which one is the smallest?
if (log.isRowLevel())
{
for (int i=0;i<data.rowbuffer.size() && !isStopped();i++)
{
Object[] b = (Object[])data.rowbuffer.get(i);
logRowlevel("--BR#"+i+": "+data.outputRowMeta.getString(b));
}
}
RowTempFile rowTempFile = data.tempRows.remove(0);
retval = rowTempFile.row;
int smallest = rowTempFile.fileNumber;
// now get another Row for position smallest
FileObject file = (FileObject)data.files.get(smallest);
DataInputStream di = (DataInputStream)data.dis.get(smallest);
InputStream fi = (InputStream)data.fis.get(smallest);
GZIPInputStream gzfi = (data.compressFiles) ? (GZIPInputStream)data.gzis.get(smallest) : null;
try
{
Object[] row2 = (Object [])data.outputRowMeta.readData(di);
RowTempFile extra = new RowTempFile(row2, smallest);
int index = Collections.binarySearch(data.tempRows, extra, data.comparator);
if (index < 0)
{
data.tempRows.add(index*(-1) - 1, extra);
}
else
{
data.tempRows.add(index, extra);
}
}
catch(KettleFileException fe) // empty file or EOF mostly
{
try
{
di.close();
fi.close();
if (gzfi != null) gzfi.close();
file.delete();
}
catch(IOException e)
{
logError("Unable to close/delete file #"+smallest+" --> "+file.toString());
setErrors(1);
stopAll();
return null;
}
data.files.remove(smallest);
data.dis.remove(smallest);
data.fis.remove(smallest);
if (gzfi != null) data.gzis.remove(smallest);
// Also update all file numbers in in data.tempRows if they are larger than smallest.
for (RowTempFile rtf : data.tempRows)
{
if (rtf.fileNumber>smallest) rtf.fileNumber
}
}
catch (SocketTimeoutException e)
{
throw new KettleValueException(e); // should never happen on local files
}
}
}
return retval;
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
boolean err=true;
int i;
Object[] r=getRow(); // get row from rowset, wait for our turn, indicate busy!
// initialize
if (first && r!=null)
{
first=false;
data.convertKeysToNative = new boolean[meta.getFieldName().length];
data.fieldnrs=new int[meta.getFieldName().length];
for (i=0;i<meta.getFieldName().length;i++)
{
data.fieldnrs[i]=getInputRowMeta().indexOfValue( meta.getFieldName()[i] );
if (data.fieldnrs[i]<0)
{
logError("Sort field ["+meta.getFieldName()[i]+"] not found!");
setOutputDone();
return false;
}
data.convertKeysToNative[i] = getInputRowMeta().getValueMeta(data.fieldnrs[i]).isStorageBinaryString();
}
// Metadata
data.outputRowMeta = getInputRowMeta().clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
}
err=addBuffer(getInputRowMeta(), r);
if (!err)
{
setOutputDone(); // signal receiver we're finished.
return false;
}
if (r==null) // no more input to be expected...
{
// Now we can start the output!
r=getBuffer();
Object[] previousRow = null;
while (r!=null && !isStopped())
{
if (log.isRowLevel()) logRowlevel("Read row: "+getInputRowMeta().getString(r));
// Do another verification pass for unique rows...
if (meta.isOnlyPassingUniqueRows())
{
if (previousRow!=null)
{
// See if this row is the same as the previous one as far as the keys are concerned.
// If so, we don't put forward this row.
int result = data.outputRowMeta.compare(r, previousRow, data.fieldnrs);
if (result!=0)
{
putRow(data.outputRowMeta, r); // copy row to possible alternate rowset(s).
}
}
else
{
putRow(data.outputRowMeta, r); // copy row to possible alternate rowset(s).
}
previousRow = r;
}
else
{
putRow(data.outputRowMeta, r); // copy row to possible alternate rowset(s).
}
r=getBuffer();
}
setOutputDone(); // signal receiver we're finished.
return false;
}
if (checkFeedback(getLinesRead()))
{
if(log.isBasic()) logBasic("Linenr "+getLinesRead());
}
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(SortRowsMeta)smi;
data=(SortRowsData)sdi;
if (super.init(smi, sdi))
{
data.sortSize = Const.toInt(environmentSubstitute(meta.getSortSize()), -1);
data.freeMemoryPctLimit = Const.toInt(meta.getFreeMemoryLimit(), -1);
if (data.sortSize<=0 && data.freeMemoryPctLimit<=0)
{
// Prefer the memory limit as it should never fail
data.freeMemoryPctLimit = 25;
}
if (data.sortSize>0)
{
data.buffer = new ArrayList<Object[]>(data.sortSize);
}
else
{
data.buffer = new ArrayList<Object[]>(5000);
}
data.compressFiles = getBooleanValueOfVariable(meta.getCompressFilesVariable(), meta.getCompressFiles());
data.comparator = new Comparator<RowTempFile>(){
public int compare(RowTempFile o1, RowTempFile o2)
{
try
{
return data.outputRowMeta.compare(o1.row, o2.row, data.fieldnrs);
}
catch(KettleValueException e)
{
logError("Error comparing rows: "+e.toString());
return 0;
}
}
};
// Add init code here.
if (data.sortSize>0)
{
data.rowbuffer=new ArrayList<Object[]>(data.sortSize);
}
else
{
data.rowbuffer=new ArrayList<Object[]>();
}
data.tempRows = new ArrayList<RowTempFile>();
data.minSortSize = 5000;
return true;
}
return false;
}
@Override
public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
// Clean out the sort buffer
data.buffer = null;
data.rowbuffer = null;
super.dispose(smi, sdi);
}
/**
* Sort the entire vector, if it is not empty.
*/
public void quickSort(List<Object[]> elements)
{
if (log.isDetailed()) logDetailed("Starting quickSort algorithm...");
if (elements.size()>0)
{
Collections.sort(elements, new Comparator<Object[]>()
{
public int compare(Object[] o1, Object[] o2)
{
Object[] r1 = (Object[]) o1;
Object[] r2 = (Object[]) o2;
try
{
return data.outputRowMeta.compare(r1, r2, data.fieldnrs);
}
catch(KettleValueException e)
{
logError("Error comparing rows: "+e.toString());
return 0;
}
}
}
);
long nrConversions = 0L;
for (ValueMetaInterface valueMeta : data.outputRowMeta.getValueMetaList())
{
nrConversions+=valueMeta.getNumberOfBinaryStringConversions();
valueMeta.setNumberOfBinaryStringConversions(0L);
}
if(log.isDetailed()) logDetailed("The number of binary string to data type conversions done in this sort block is "+nrConversions);
}
if (log.isDetailed()) logDetailed("QuickSort algorithm has finished.");
}
} |
package eu.goodlike.resty;
import com.google.common.base.Function;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import eu.goodlike.neat.Null;
import eu.goodlike.resty.http.steps.BodyTypeStep;
import eu.goodlike.resty.http.steps.QueryParamStep;
import eu.goodlike.resty.url.DynamicURL;
import java.util.Arrays;
import java.util.List;
/**
* <pre>
* Loading cache wrapper for endpoint creation
*
* Rather than having to manually store the endpoints, you can use this cache; first, set up a seed, which will
* be an universal prefix for all endpoints, i.e.
* DynamicURL apiPrefix = DynamicURL.builder().HTTPS().IP(api.twitch.tv).withPath("kraken");
* Endpoints twitchApi = Endpoints.of(apiPrefix);
* then call:
* DynamicURL channelEndpoint = twitchApi.at("/channels/:channel");
* or directly:
* twitchApi.GET("/channels/some_channel");
*
* Cache uses softValues(), so memory should be fine
* </pre>
*/
public final class Endpoints {
/**
* @return the seed of these Endpoints
*/
public DynamicURL at() {
return seed;
}
public DynamicURL at(String... path) {
Null.checkAlone(path).ifAny("Path array cannot be null");
return at(Arrays.asList(path));
}
public DynamicURL at(List<String> path) {
return urlCache.getUnchecked(path);
}
/**
* @return seed.GET()
*/
public QueryParamStep GET() {
return seed.GET();
}
public QueryParamStep GET(String... path) {
return at(path).GET();
}
public QueryParamStep GET(List<String> path) {
return at(path).GET();
}
/**
* @return seed.POST()
*/
public BodyTypeStep POST() {
return seed.POST();
}
public BodyTypeStep POST(String... path) {
return at(path).POST();
}
public BodyTypeStep POST(List<String> path) {
return at(path).POST();
}
/**
* @return seed.PUT()
*/
public BodyTypeStep PUT() {
return seed.PUT();
}
public BodyTypeStep PUT(String... path) {
return at(path).PUT();
}
public BodyTypeStep PUT(List<String> path) {
return at(path).PUT();
}
/**
* @return seed.DELETE()
*/
public BodyTypeStep DELETE() {
return seed.DELETE();
}
public BodyTypeStep DELETE(String... path) {
return at(path).DELETE();
}
public BodyTypeStep DELETE(List<String> path) {
return at(path).DELETE();
}
// CONSTRUCTORS
public static Endpoints of(String seedUrl) {
return new Endpoints(DynamicURL.of(seedUrl));
}
/**
* Constructs a cache of DynamicURLs, which uses the seed as basis and appends paths to it when needed
* @throws NullPointerException if seed is null
*/
public static Endpoints of(DynamicURL seed) {
return new Endpoints(seed);
}
public Endpoints(DynamicURL seed) {
Null.check(seed).ifAny("Seed URL cannot be null");
this.seed = seed;
Function<List<String>, DynamicURL> loadingFunction = seed::appendPath;
this.urlCache = CacheBuilder.newBuilder()
.softValues()
.build(CacheLoader.from(loadingFunction));
}
// PRIVATE
private final DynamicURL seed;
private final LoadingCache<List<String>, DynamicURL> urlCache;
} |
package org.voovan.tools.log;
import org.voovan.tools.TEnv;
import org.voovan.tools.TFile;
import org.voovan.tools.TObject;
import org.voovan.tools.TString;
public class Logger {
private static Formater formater = Formater.newInstance();
private static boolean enable = true;
/**
*
*
* @return true:,false
*/
public static boolean isEnable() {
return enable;
}
/**
*
* @param enable true:,false
*/
public static void setEnable(boolean enable) {
Logger.enable = enable;
}
public static void stopLoggerThread(){
}
/**
*
* @param logLevel
* @return true: , false:
*/
public static boolean isLogLevel(String logLevel){
if(formater.getLogLevel().contains("ALL")){
return true;
}
if(formater.getLogLevel().contains(logLevel)){
return true;
}else{
return false;
}
}
public static void custom(String logLevel, Object msg, Throwable e) {
if(!Logger.isEnable()){
return;
}
try {
msg = buildMessage(msg, e);
Message message = Message.newInstance(logLevel, msg.toString());
formater.writeFormatedLog(message);
} catch (Exception oe) {
simple("Logger system error:"+oe.getMessage()+"\r\n");
simple(TEnv.getStackElementsMessage(oe.getStackTrace()));
simple("Output message is: " + msg);
}
}
public static void custom(String logLevel, Object msg) {
custom(logLevel, msg, null);
}
public static void custom(String logLevel, Exception e) {
custom(logLevel, null, e);
}
public static void customf(String logLevel, String msg, Throwable e, Object ... args){
if(!Logger.isEnable()){
return;
}
custom(logLevel, TString.tokenReplace(msg, args), e);
}
public static void customf(String logLevel, String msg, Object ... args) {
customf(logLevel, msg, args, null);
}
public static void info(Object msg) {
custom("INFO", msg);
}
public static void infof(String msg, Object ... args){
customf("INFO", msg, args);
}
public static void fremawork(Object msg) {
custom("FRAMEWORK", msg);
}
public static void fremaworkf(String msg, Object ... args){
customf("FRAMEWORK", msg, args);
}
public static void sql(Object msg) {
custom("SQL", msg);
}
public static void sqlf(String msg, Object ... args){
customf("SQL", msg, args);
}
public static void debug(Object msg) {
custom("DEBUG", msg);
}
public static void debugf(String msg, Object ... args){
customf("DEBUG", msg, args);
}
public static void warn(Object msg) {
custom("WARN", msg);
}
public static void warnf(String msg, Object ... args){
customf("WARN", msg, args);
}
public static void warn(Exception e) {
custom("WARN", null, e);
}
public static void warn(Object msg, Throwable e) {
custom("WARN", msg, e);
}
public static void warnf(String msg, Throwable e, Object ... args){
customf("WARN", msg, e, args);
}
public static void error(Object msg) {
custom("ERROR", msg);
}
public static void errorf(String msg, Object ... args){
customf("ERROR", msg, args);
}
public static void error(Exception e) {
custom("ERROR", e);
}
public static void error(Object msg, Throwable e) {
custom("ERROR", msg, e);
}
public static void errorf(String msg, Throwable e, Object ... args){
customf("ERROR", msg, e, args);
}
public static void fatal(Object msg) {
custom("FATAL", msg);
}
public static void fatalf(String msg, Object ... args){
customf("FATAL", msg, args);
}
public static void fatal(Throwable e) {
custom("FATAL", e);
}
public static void fatal(Object msg, Throwable e) {
custom("FATAL", msg, e);
}
public static void fatalf(String msg, Throwable e, Object ... args){
customf("FATAL", msg, e, args);
}
public static void simple(Object msg) {
custom("SIMPLE", msg);
}
public static void simplef(String msg, Object ... args){
customf("SIMPLE", msg, args);
}
/**
*
* @param msg
* @param exception
* @return
*/
private static String buildMessage(Object msg, Throwable exception){
msg = TObject.nullDefault(msg, "");
String stackMessage = "";
if (exception == null) {
return msg.toString();
}
do{
stackMessage = stackMessage + exception.getClass().getCanonicalName() + ": " +
exception.getMessage() + TFile.getLineSeparator() +
TString.indent(TEnv.getStackElementsMessage(exception.getStackTrace()),8) +
TFile.getLineSeparator();
exception = exception.getCause();
} while(exception!=null);
return (msg.toString().isEmpty() ? "" : (msg + " => ")) + stackMessage;
}
/**
*
* @param msg
* @return
*/
private static String buildMessage(Object msg){
return buildMessage(msg, null);
}
} |
package org.jboss.as.server.deployment;
/**
* An enumeration of the phases of a deployment unit's processing cycle.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public enum Phase {
/* == TEMPLATE ==
* Upon entry, this phase performs the following actions:
* <ul>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
/**
* This phase creates the initial root structure. Depending on the service for this phase will ensure that the
* deployment unit's initial root structure is available and accessible.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li>
* <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments:
* <ul>
* <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* </ul>
* <p>
*/
STRUCTURE(null),
/**
* This phase assembles information from the root structure to prepare for adding and processing additional external
* structure, such as from class path entries and other similar mechanisms.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li>
* <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li>
* <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li>
* </ul>
* <p>
*/
PARSE(null),
/**
* In this phase parsing of deployment metadata is complete and the component may be registered with the subsystem.
* This is prior to working out the components dependency and equivalent to the OSGi INSTALL life cycle.
*/
REGISTER(null),
/**
* In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>Any additional external structure is mounted during {@link #XXX}</li>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
DEPENDENCIES(null),
CONFIGURE_MODULE(null),
/**
* Processors that need to start/complete before the deployment classloader is used to load application classes,
* belong in the FIRST_MODULE_USE phase.
*/
FIRST_MODULE_USE(null),
POST_MODULE(null),
INSTALL(null),
CLEANUP(null),
;
/**
* This is the key for the attachment to use as the phase's "value". The attachment is taken from
* the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified.
*/
private final AttachmentKey<?> phaseKey;
private Phase(final AttachmentKey<?> key) {
phaseKey = key;
}
/**
* Get the next phase, or {@code null} if none.
*
* @return the next phase, or {@code null} if there is none
*/
public Phase next() {
final int ord = ordinal() + 1;
final Phase[] phases = Phase.values();
return ord == phases.length ? null : phases[ord];
}
/**
* Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value
* of this phase.
*
* @return the key
*/
public AttachmentKey<?> getPhaseKey() {
return phaseKey;
}
// STRUCTURE
public static final int STRUCTURE_EXPLODED_MOUNT = 0x0100;
public static final int STRUCTURE_MOUNT = 0x0200;
public static final int STRUCTURE_MANIFEST = 0x0300;
public static final int STRUCTURE_OSGI_MANIFEST = 0x0400;
public static final int STRUCTURE_OSGI_PROPERTIES = 0x0410;
public static final int STRUCTURE_OSGI_WEBBUNDLE = 0x0420;
public static final int STRUCTURE_OSGI_METADATA = 0x0430;
public static final int STRUCTURE_REMOUNT_EXPLODED = 0x0450;
public static final int STRUCTURE_EE_SPEC_DESC_PROPERTY_REPLACEMENT = 0x0500;
public static final int STRUCTURE_EE_JBOSS_DESC_PROPERTY_REPLACEMENT= 0x0550;
public static final int STRUCTURE_EE_DEPLOYMENT_PROPERTIES = 0x0560;
public static final int STRUCTURE_EE_DEPLOYMENT_PROPERTY_RESOLVER = 0x0561;
public static final int STRUCTURE_EE_VAULT_PROPERTY_RESOLVER = 0x0562;
public static final int STRUCTURE_EE_SYSTEM_PROPERTY_RESOLVER = 0x0563;
public static final int STRUCTURE_EE_PROPERTY_RESOLVER = 0x0564;
public static final int STRUCTURE_JDBC_DRIVER = 0x0600;
public static final int STRUCTURE_RAR = 0x0700;
public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0800;
public static final int STRUCTURE_WAR = 0x0900;
public static final int STRUCTURE_CONTENT_OVERRIDE = 0x0950;
public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0A00;
public static final int STRUCTURE_REGISTER_JBOSS_ALL_XML_PARSER = 0x0A10;
public static final int STRUCTURE_PARSE_JBOSS_ALL_XML = 0x0A20;
public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0B00;
public static final int STRUCTURE_JBOSS_EJB_CLIENT_XML_PARSE = 0x0C00;
public static final int STRUCTURE_EJB_EAR_APPLICATION_NAME = 0x0D00;
public static final int STRUCTURE_EAR = 0x0E00;
public static final int STRUCTURE_APP_CLIENT = 0x0F00;
public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x1000;
public static final int STRUCTURE_ANNOTATION_INDEX = 0x1100;
public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x1200;
public static final int STRUCTURE_APPLICATION_CLIENT_IN_EAR = 0x1300;
public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x1400;
public static final int STRUCTURE_BUNDLE_SUB_DEPLOYMENT = 0x1450;
public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x1500;
public static final int STRUCTURE_SAR = 0x1580;
public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x1600;
public static final int STRUCTURE_SUB_DEPLOYMENT = 0x1700;
public static final int STRUCTURE_JBOSS_DEPLOYMENT_STRUCTURE = 0x1800;
public static final int STRUCTURE_CLASS_PATH = 0x1900;
public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1A00;
public static final int STRUCTURE_EE_MODULE_INIT = 0x1B00;
public static final int STRUCTURE_EE_RESOURCE_INJECTION_REGISTRY = 0x1C00;
public static final int STRUCTURE_DEPLOYMENT_DEPENDENCIES = 0x1D00;
public static final int STRUCTURE_GLOBAL_MODULES = 0x1E00;
// PARSE
public static final int PARSE_EE_MODULE_NAME = 0x0100;
public static final int PARSE_EJB_DEFAULT_DISTINCT_NAME = 0x0110;
public static final int PARSE_EAR_SUBDEPLOYMENTS_ISOLATION_DEFAULT = 0x0200;
public static final int PARSE_DEPENDENCIES_MANIFEST = 0x0300;
public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0301;
public static final int PARSE_EXTENSION_LIST = 0x0700;
public static final int PARSE_EXTENSION_NAME = 0x0800;
public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900;
public static final int PARSE_WEB_DEPLOYMENT = 0x0B00;
public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00;
public static final int PARSE_JSF_VERSION = 0x0C50;
public static final int PARSE_JSF_SHARED_TLDS = 0x0C51;
public static final int PARSE_ANNOTATION_WAR = 0x0D00;
public static final int PARSE_ANNOTATION_EJB = 0x0D10;
public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00;
public static final int PARSE_TLD_DEPLOYMENT = 0x0F00;
public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000;
// create and attach EJB metadata for EJB deployments
public static final int PARSE_EJB_DEPLOYMENT = 0x1100;
public static final int PARSE_APP_CLIENT_XML = 0x1101;
public static final int PARSE_CREATE_COMPONENT_DESCRIPTIONS = 0x1150;
// described EJBs must be created after annotated EJBs
public static final int PARSE_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1152;
public static final int PARSE_CMP_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1153;
public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200;
// create and attach the component description out of EJB annotations
public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901;
public static final int PARSE_WELD_CONFIGURATION = 0x1C01;
public static final int PARSE_WEB_COMPONENTS = 0x1F00;
public static final int PARSE_WEB_MERGE_METADATA = 0x2000;
public static final int PARSE_OSGI_COMPONENTS = 0x2010;
public static final int PARSE_WEBSERVICES_CONTEXT_INJECTION = 0x2040;
public static final int PARSE_WEBSERVICES_LIBRARY_FILTER = 0x2045;
public static final int PARSE_WEBSERVICES_XML = 0x2050;
public static final int PARSE_JBOSS_WEBSERVICES_XML = 0x2051;
public static final int PARSE_JAXWS_EJB_INTEGRATION = 0x2052;
public static final int PARSE_JAXRPC_POJO_INTEGRATION = 0x2053;
public static final int PARSE_JAXRPC_EJB_INTEGRATION = 0x2054;
public static final int PARSE_JAXWS_HANDLER_CHAIN_ANNOTATION = 0x2055;
public static final int PARSE_WS_JMS_INTEGRATION = 0x2056;
public static final int PARSE_XTS_SOAP_HANDLERS = 0x2057;
public static final int PARSE_JAXWS_ENDPOINT_CREATE_COMPONENT_DESCRIPTIONS = 0x2058;
public static final int PARSE_XTS_COMPONENT_INTERCEPTORS = 0x2059;
public static final int PARSE_JAXWS_HANDLER_CREATE_COMPONENT_DESCRIPTIONS = 0x2060;
public static final int PARSE_RA_DEPLOYMENT = 0x2100;
public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200;
public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300;
public static final int PARSE_POJO_DEPLOYMENT = 0x2400;
public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500;
public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900;
public static final int PARSE_EE_ANNOTATIONS = 0x2901;
public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00;
public static final int PARSE_CDI_ANNOTATIONS = 0x2A10;
public static final int PARSE_CDI_BEAN_DEFINING_ANNOTATIONS = 0x2A80;
public static final int PARSE_WELD_DEPLOYMENT = 0x2B00;
public static final int PARSE_WELD_IMPLICIT_DEPLOYMENT_DETECTION = 0x2C00;
public static final int PARSE_DATA_SOURCE_DEFINITION_ANNOTATION = 0x2D00;
public static final int PARSE_MAIL_SESSION_DEFINITION_ANNOTATION = 0x2D01;
public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00;
public static final int PARSE_EJB_TIMERSERVICE_BINDING = 0x2E01;
public static final int PARSE_EJB_DEFAULT_SECURITY_DOMAIN = 0x2E02;
public static final int PARSE_PERSISTENCE_UNIT = 0x2F00;
public static final int PARSE_PERMISSIONS = 0x3100;
public static final int PARSE_LIFECYCLE_ANNOTATION = 0x3200;
public static final int PARSE_PASSIVATION_ANNOTATION = 0x3250;
public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300;
public static final int PARSE_AROUNDTIMEOUT_ANNOTATION = 0x3400;
public static final int PARSE_TIMEOUT_ANNOTATION = 0x3401;
public static final int PARSE_EJB_DD_INTERCEPTORS = 0x3500;
public static final int PARSE_EJB_SECURITY_ROLE_REF_DD = 0x3501;
public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x3600;
public static final int PARSE_DISTINCT_NAME = 0x3601;
public static final int PARSE_OSGI_DEPLOYMENT = 0x3700;
public static final int PARSE_OSGI_SUBSYSTEM_ACTIVATOR = 0x3800;
public static final int PARSE_WAB_CONTEXT_FACTORY = 0x3900;
// should be after all components are known
public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x4000;
public static final int PARSE_JACORB = 0x4100;
public static final int PARSE_TRANSACTION_ROLLBACK_ACTION = 0x4200;
public static final int PARSE_EAR_MESSAGE_DESTINATIONS = 0x4400;
public static final int PARSE_DSXML_DEPLOYMENT = 0x4500;
public static final int PARSE_MESSAGING_XML_RESOURCES = 0x4600;
public static final int PARSE_DESCRIPTOR_LIFECYCLE_METHOD_RESOLUTION = 0x4700;
public static final int PARSE_EE_CONCURRENT_DEFAULT_CONTEXT_SERVICE = 0x4800;
public static final int PARSE_EE_CONCURRENT_DEFAULT_MANAGED_THREAD_FACTORY = 0x4801;
public static final int PARSE_EE_CONCURRENT_DEFAULT_MANAGED_EXECUTOR_SERVICE = 0x4802;
public static final int PARSE_EE_CONCURRENT_DEFAULT_MANAGED_SCHEDULED_EXECUTOR_SERVICE = 0x4803;
// REGISTER
public static final int REGISTER_BUNDLE_INSTALL = 0x0100;
// DEPENDENCIES
public static final int DEPENDENCIES_EE_PERMISSIONS = 0x0100;
public static final int DEPENDENCIES_EJB_PERMISSIONS = 0x0110;
public static final int DEPENDENCIES_EJB = 0x0200;
public static final int DEPENDENCIES_MODULE = 0x0300;
public static final int DEPENDENCIES_RAR_CONFIG = 0x0400;
public static final int DEPENDENCIES_MANAGED_BEAN = 0x0500;
public static final int DEPENDENCIES_SAR_MODULE = 0x0600;
public static final int DEPENDENCIES_WAR_MODULE = 0x0700;
public static final int DEPENDENCIES_CLASS_PATH = 0x0800;
public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900;
public static final int DEPENDENCIES_WELD = 0x0A00;
public static final int DEPENDENCIES_SEAM = 0x0A01;
public static final int DEPENDENCIES_WS = 0x0C00;
public static final int DEPENDENCIES_SECURITY = 0x0C50;
public static final int DEPENDENCIES_JAXRS = 0x0D00;
public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00;
public static final int DEPENDENCIES_PERSISTENCE_ANNOTATION = 0x0F00;
public static final int DEPENDENCIES_JPA = 0x1000;
public static final int DEPENDENCIES_TRANSACTIONS = 0x1100;
public static final int DEPENDENCIES_XTS = 0x1110;
public static final int DEPENDENCIES_JDK = 0x1200;
public static final int DEPENDENCIES_JACORB = 0x1300;
public static final int DEPENDENCIES_JMS = 0x1400;
public static final int DEPENDENCIES_CMP = 0x1500;
public static final int DEPENDENCIES_JAXR = 0x1600;
public static final int DEPENDENCIES_DRIVERS = 0x1700;
public static final int DEPENDENCIES_JSF = 0x1800;
public static final int DEPENDENCIES_BUNDLE = 0x1900;
public static final int DEPENDENCIES_BUNDLE_CONTEXT_BINDING = 0x1A00;
//these must be last, and in this specific order
public static final int DEPENDENCIES_APPLICATION_CLIENT = 0x2000;
public static final int DEPENDENCIES_VISIBLE_MODULES = 0x2100;
public static final int DEPENDENCIES_EE_CLASS_DESCRIPTIONS = 0x2200;
// CONFIGURE_MODULE
public static final int CONFIGURE_RESOLVE_BUNDLE = 0x0100;
public static final int CONFIGURE_MODULE_SPEC = 0x0200;
public static final int CONFIGURE_DEFERRED_PHASE = 0x0300;
// FIRST_MODULE_USE
public static final int FIRST_MODULE_USE_PERSISTENCE_CLASS_FILE_TRANSFORMER = 0x0100; // need to be before POST_MODULE_REFLECTION_INDEX
// and anything that could load class definitions
public static final int FIRST_MODULE_USE_INTERCEPTORS = 0x0200;
public static final int FIRST_MODULE_USE_PERSISTENCE_PREPARE = 0x0300;
public static final int FIRST_MODULE_USE_DSXML_DEPLOYMENT = 0x0400;
public static final int FIRST_MODULE_USE_TRANSFORMER = 0x0500;
// POST_MODULE
public static final int POST_MODULE_INJECTION_ANNOTATION = 0x0100;
public static final int POST_MODULE_REFLECTION_INDEX = 0x0200;
public static final int POST_MODULE_WAB_FRAGMENTS = 0x0250;
public static final int POST_MODULE_JSF_MANAGED_BEANS = 0x0300;
public static final int POST_MODULE_INTERCEPTOR_ANNOTATIONS = 0x0301;
public static final int POST_MODULE_EJB_BUSINESS_VIEW_ANNOTATION = 0x0400;
public static final int POST_MODULE_EJB_HOME_MERGE = 0x0401;
public static final int POST_MODULE_EJB_DD_METHOD_RESOLUTION = 0x0402;
public static final int POST_MODULE_EJB_TIMER_METADATA_MERGE = 0x0506;
public static final int POST_MODULE_EJB_SLSB_POOL_NAME_MERGE = 0x0507;
public static final int POST_MODULE_EJB_MDB_POOL_NAME_MERGE = 0x0508;
public static final int POST_MODULE_EJB_ENTITY_POOL_NAME_MERGE = 0x0509;
public static final int POST_MODULE_EJB_USER_APP_SPECIFIC_CONTAINER_INTERCEPTORS = 0x050A;
public static final int POST_MODULE_EJB_DD_INTERCEPTORS = 0x0600;
public static final int POST_MODULE_EJB_TIMER_SERVICE = 0x0601;
public static final int POST_MODULE_EJB_TRANSACTION_MANAGEMENT = 0x0602;
public static final int POST_MODULE_EJB_TX_ATTR_MERGE = 0x0603;
public static final int POST_MODULE_EJB_CONCURRENCY_MANAGEMENT_MERGE= 0x0604;
public static final int POST_MODULE_EJB_CONCURRENCY_MERGE = 0x0605;
public static final int POST_MODULE_EJB_RUN_AS_MERGE = 0x0606;
public static final int POST_MODULE_EJB_RESOURCE_ADAPTER_MERGE = 0x0607;
public static final int POST_MODULE_EJB_REMOVE_METHOD = 0x0608;
public static final int POST_MODULE_EJB_STARTUP_MERGE = 0x0609;
public static final int POST_MODULE_EJB_SECURITY_DOMAIN = 0x060A;
public static final int POST_MODULE_EJB_ROLES = 0x060B;
public static final int POST_MODULE_METHOD_PERMISSIONS = 0x060C;
public static final int POST_MODULE_EJB_STATEFUL_TIMEOUT = 0x060D;
public static final int POST_MODULE_EJB_ASYNCHRONOUS_MERGE = 0x060E;
public static final int POST_MODULE_EJB_SESSION_SYNCHRONIZATION = 0x060F;
public static final int POST_MODULE_EJB_INIT_METHOD = 0x0610;
public static final int POST_MODULE_EJB_SESSION_BEAN = 0x0611;
public static final int POST_MODULE_EJB_SECURITY_PRINCIPAL_ROLE_MAPPING_MERGE = 0x0612;
public static final int POST_MODULE_EJB_SECURITY_MISSING_METHOD_PERMISSIONS = 0x0613;
public static final int POST_MODULE_EJB_CACHE = 0x0614;
public static final int POST_MODULE_EJB_CLUSTERED = 0x0615;
public static final int POST_MODULE_EJB_DELIVERY_ACTIVE_MERGE = 0x0616;
public static final int POST_MODULE_WELD_WEB_INTEGRATION = 0x0700;
public static final int POST_MODULE_WELD_COMPONENT_INTEGRATION = 0x0800;
public static final int POST_MODULE_INSTALL_EXTENSION = 0x0A00;
public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0B00;
public static final int POST_MODULE_EAR_DEPENDENCY = 0x0C00;
public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0D00;
public static final int POST_MODULE_WELD_EXTERNAL_BEAN_ARCHIVE = 0x0D50;
public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0E00;
public static final int POST_MODULE_XTS_PORTABLE_EXTENSIONS = 0x0E10;
public static final int POST_MODULE_JMS_CDI_EXTENSIONS = 0x0F00;
// should come before ejb jndi bindings processor
public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x1000;
public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x1100;
public static final int POST_MODULE_EJB_CLIENT_METADATA = 0x1102;
public static final int POST_MODULE_EJB_APPLICATION_EXCEPTIONS = 0x1200;
public static final int POST_INITIALIZE_IN_ORDER = 0x1300;
public static final int POST_MODULE_ENV_ENTRY = 0x1400;
public static final int POST_MODULE_EJB_REF = 0x1500;
public static final int POST_MODULE_PERSISTENCE_REF = 0x1600;
public static final int POST_MODULE_DATASOURCE_REF = 0x1700;
public static final int POST_MODULE_MAIL_SESSION_REF = 0x1701;
public static final int POST_MODULE_WS_REF_DESCRIPTOR = 0x1800;
public static final int POST_MODULE_WS_REF_ANNOTATION = 0x1801;
public static final int POST_MODULE_JAXRS_SCANNING = 0x1A00;
public static final int POST_MODULE_JAXRS_COMPONENT = 0x1B00;
public static final int POST_MODULE_JAXRS_CDI_INTEGRATION = 0x1C00;
public static final int POST_MODULE_RTS_PROVIDERS = 0x1D00;
public static final int POST_MODULE_LOCAL_HOME = 0x1E00;
public static final int POST_MODULE_APPLICATION_CLIENT_MANIFEST = 0x1F00;
public static final int POST_MODULE_APPLICATION_CLIENT_ACTIVE = 0x2000;
public static final int POST_MODULE_EJB_ORB_BIND = 0x2100;
public static final int POST_MODULE_CMP_PARSE = 0x2300;
public static final int POST_MODULE_CMP_ENTITY_METADATA = 0x2400;
public static final int POST_MODULE_CMP_STORE_MANAGER = 0x2500;
public static final int POST_MODULE_EJB_IIOP = 0x2600;
public static final int POST_MODULE_POJO = 0x2700;
public static final int POST_MODULE_IN_APP_CLIENT = 0x2780;
public static final int POST_MODULE_EE_INSTANCE_NAME = 0x2790;
public static final int POST_MODULE_NAMING_CONTEXT = 0x2800;
public static final int POST_MODULE_APP_NAMING_CONTEXT = 0x2900;
public static final int POST_MODULE_CACHED_CONNECTION_MANAGER = 0x2A00;
public static final int POST_MODULE_LOGGING_CONFIG = 0x2B00;
public static final int POST_MODULE_EL_EXPRESSION_FACTORY = 0x2C00;
public static final int POST_MODULE_SAR_SERVICE_COMPONENT = 0x2D00;
public static final int POST_MODULE_UNDERTOW_WEBSOCKETS = 0x2E00;
public static final int POST_MODULE_UNDERTOW_HANDLERS = 0x2F00;
public static final int POST_MODULE_EE_CONCURRENT_CONTEXT = 0x3000;
// INSTALL
public static final int INSTALL_JACC_POLICY = 0x0350;
public static final int INSTALL_COMPONENT_AGGREGATION = 0x0400;
public static final int INSTALL_RESOLVE_MESSAGE_DESTINATIONS = 0x0403;
public static final int INSTALL_EJB_CLIENT_CONTEXT = 0x0404;
public static final int INSTALL_EJB_JACC_PROCESSING = 0x1105;
public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500;
public static final int INSTALL_RESOLVER_MODULE = 0x0600;
public static final int INSTALL_RA_NATIVE = 0x0800;
public static final int INSTALL_RA_DEPLOYMENT = 0x0801;
public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900;
public static final int INSTALL_POJO_DEPLOYMENT = 0x0A00;
public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00;
public static final int INSTALL_EE_MODULE_CONFIG = 0x1101;
public static final int INSTALL_JMS_BINDINGS = 0x1150;
public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200;
public static final int INSTALL_DEPENDS_ON_ANNOTATION = 0x1210;
public static final int INSTALL_PERSISTENTUNIT = 0x1220;
public static final int INSTALL_EE_COMPONENT = 0x1230;
public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300;
public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500;
public static final int INSTALL_JSF_ANNOTATIONS = 0x1600;
public static final int INSTALL_JDBC_DRIVER = 0x1800;
public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900;
public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00;
public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00;
public static final int INSTALL_JNDI_DEPENDENCIES = 0x1C01;
public static final int INSTALL_CDI_VALIDATOR_FACTORY = 0x1C02;
public static final int INSTALL_WS_UNIVERSAL_META_DATA_MODEL = 0x1C10;
public static final int INSTALL_WS_DEPLOYMENT_ASPECTS = 0x1C11;
// IMPORTANT: WS integration installs deployment aspects dynamically
// so consider INSTALL 0x1C10 - 0x1CFF reserved for WS subsystem!
public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00;
public static final int INSTALL_WAB_DEPLOYMENT = 0x1E00;
public static final int INSTALL_DEPLOYMENT_REPOSITORY = 0x1F00;
public static final int INSTALL_EJB_MANAGEMENT_RESOURCES = 0x2000;
public static final int INSTALL_APPLICATION_CLIENT = 0x2010;
public static final int INSTALL_MESSAGING_XML_RESOURCES = 0x2030;
public static final int INSTALL_BUNDLE_ACTIVATE = 0x2040;
public static final int INSTALL_WAB_SERVLETCONTEXT_SERVICE = 0x2050;
public static final int INSTALL_PERSISTENCE_SERVICES = 0x2060;
public static final int INSTALL_DEPLOYMENT_COMPLETE_SERVICE = 0x2100;
// CLEANUP
public static final int CLEANUP_REFLECTION_INDEX = 0x0100;
public static final int CLEANUP_EE = 0x0200;
public static final int CLEANUP_EJB = 0x0300;
public static final int CLEANUP_ANNOTATION_INDEX = 0x0400;
} |
package fi.csc.chipster.rest;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import com.esotericsoftware.yamlbeans.YamlReader;
public class Config {
private static final String DB_URL_PREFIX = "db-url-";
private static final String URL_INT_PREFIX = "url-int-";
private static final String URL_EXT_PREFIX = "url-ext-";
private static final String URL_ADMIN_EXT_PREFIX = "url-admin-ext-";
private static final String URL_M2M_INT_PREFIX = "url-m2m-int-";
private static final String URL_BIND_PREFIX = "url-bind-";
private static final String URL_ADMIN_BIND_PREFIX = "url-admin-bind-";
private static final String URL_M2M_BIND_PREFIX = "url-m2m-bind-";
private static final String SERVICE_PASSWORD_PREFIX = "service-password-";
private static final String SSO_SERVICE_PASSWORD_PREFIX = "sso-service-password-";
private static final String ADMIN_USERNAME_PREFIX = "admin-username-";
private static final String VARIABLE_PREFIX = "variable-";
public static final String DEFAULT_CONF_PATH = "chipster-defaults.yaml";
public static final String KEY_CONF_PATH = "conf-path";
public static final String KEY_MONITORING_PASSWORD = "auth-monitoring-password";
public static final String KEY_SESSION_DB_NAME = "session-db-name";
public static final String KEY_SESSION_DB_HIBERNATE_SCHEMA = "session-db-hibernate-schema";
public static final String KEY_SESSION_DB_RESTRICT_SHARING_TO_EVERYONE = "session-db-restrict-sharing-to-everyone";
public static final String KEY_SESSION_DB_MAX_SHARE_COUNT = "session-db-max-share-count";
public static final String KEY_WEB_SERVER_WEB_ROOT_PATH = "web-server-web-root-path";
public static final String KEY_COMP_MAX_JOBS = "comp-max-jobs";
public static final String KEY_COMP_SCHEDULE_TIMEOUT = "comp-schedule-timeout";
public static final String KEY_COMP_OFFER_DELAY = "comp-offer-delay";
public static final String KEY_COMP_SWEEP_WORK_DIR = "comp-sweep-work-dir";
public static final String KEY_COMP_TIMEOUT_CHECK_INTERVAL = "comp-timeout-check-interval";
public static final String KEY_COMP_STATUS_INTERVAL = "comp-status-interval";
public static final String KEY_COMP_MODULE_FILTER_NAME = "comp-module-filter-name";
public static final String KEY_COMP_MODULE_FILTER_MODE = "comp-module-filter-mode";
public static final String KEY_COMP_RESOURCE_MONITORING_INTERVAL = "comp-resource-monitoring-interval";
public static final String KEY_COMP_JOB_TIMEOUT = "comp-job-timeout";
public static final String KEY_SCHEDULER_WAIT_TIMEOUT = "scheduler-wait-timeout";
public static final String KEY_SCHEDULER_WAIT_RUNNABLE_TIMEOUT = "scheduler-wait-runnable-timeout";
public static final String KEY_SCHEDULER_SCHEDULE_TIMEOUT = "scheduler-schedule-timeout";
public static final String KEY_SCHEDULER_HEARTBEAT_LOST_TIMEOUT = "scheduler-heartbeat-lost-timeout";
public static final String KEY_SCHEDULER_JOB_TIMER_INTERVAL = "scheduler-job-timer-interval";
public static final String KEY_FILE_BROKER_SHUTDOWN_TIMEOUT = "file-broker-shutdown-timeout";
public static final String KEY_SESSION_WORKER_SHUTDOWN_TIMEOUT = "file-broker-shutdown-timeout";
public static final String KEY_TOOLBOX_TOOLS_BIN_PATH = "toolbox-tools-bin-path";
public static final String KEY_AUTH_JAAS_PREFIX = "auth-jaas-prefix";
public static final String KEY_WEBSOCKET_IDLE_TIMEOUT = "websocket-idle-timeout";
public static final String KEY_WEBSOCKET_PING_INTERVAL = "websocket-ping-interval";
public static final String KEY_DB_FALLBACK = "db-fallback";
public static final String KEY_SESSION_WORKER_SMTP_HOST = "session-worker-smtp-host";
public static final String KEY_SESSION_WORKER_SMPT_USERNAME = "session-worker-smtp-username";
public static final String KEY_SESSION_WORKER_SMTP_TLS = "session-worker-smtp-tls";
public static final String KEY_SESSION_WORKER_SMTP_AUTH = "session-worker-smtp-auth";
public static final String KEY_SESSION_WORKER_SMTP_FROM = "session-worker-smtp-from";
public static final String KEY_SESSION_WORKER_SMTP_FROM_NAME = "session-worker-smtp-from-name";
public static final String KEY_SESSION_WORKER_SMTP_PORT = "session-worker-smtp-port";
public static final String KEY_SESSION_WORKER_SMTP_PASSWORD = "session-worker-smtp-password";
public static final String KEY_SESSION_WORKER_SUPPORT_EMAIL_PREFIX = "session-worker-support-email-";
public static final String KEY_SESSION_WORKER_SUPPORT_THROTTLE_PERIOD = "session-worker-support-throttle-period";
public static final String KEY_SESSION_WORKER_SUPPORT_THROTTLE_REQEUST_COUNT = "session-worker-support-throttle-request-count";
public static final String KEY_SESSION_WORKER_SUPPORT_SESSION_OWNER = "session-worker-support-session-owner";
public static final String KEY_SESSION_WORKER_SUPPORT_SESSION_DELETE_AFTER = "session-worker-support-session-delete-after";
private static HashMap<String, HashMap<String, String>> confFileCache = new HashMap<>();
private static String confFilePath = getFromFile(DEFAULT_CONF_PATH, KEY_CONF_PATH);
private static Logger logger;
@SuppressWarnings("unused")
private LoggerContext log4jContext;
public Config() {
configureLog4j();
}
public void configureLog4j() {
// send everything from java.util.logging (JUL) to log4j
String cn = "org.apache.logging.log4j.jul.LogManager";
System.setProperty("java.util.logging.manager", cn);
logger = LogManager.getLogger();
// check that the JUL logging manager was successfully changed
java.util.logging.LogManager lm = java.util.logging.LogManager.getLogManager();
if (!cn.equals(lm.getClass().getName())) {
try {
ClassLoader.getSystemClassLoader().loadClass(cn);
} catch (ClassNotFoundException cnfe) {
logger.warn("log4j-jul jar not found from the class path. Logging to can't be configured with log4j", cnfe);
}
logger.warn("JUL to log4j bridge couldn't be initialized, because Logger or LoggerManager was already created. Make sure the logger field of the startup class isn't static and call this mehtod before instantiating it.");
}
}
public static void setLoggingLevel(String logger, Level level) {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(logger);
loggerConfig.setLevel(level);
ctx.updateLoggers();
}
public static Level getLoggingLevel(String logger) {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(logger);
return loggerConfig.getLevel();
}
private HashMap<String, String> variableDefaults = getVariableDefaults();
private static boolean confFileWarnShown;
public String getString(String key) {
return getString(key, true, true, true);
}
/**
* Get config value of <key>-<role> if exists or <key> otherwise
*
* Makes it simpler to configure default values for e.g. db configs but allows
* individual configurations for each role when necessary.
*
* @param key
* @param role
* @return
*/
public String getString(String key, String role) {
if (hasKey(key + "-" + role)) {
return getString(key + "-" + role);
}
return getString(key);
}
/**
* Get config value of <key>-<role> if exists or <key> otherwise
*
* @param key
* @param role
* @return
*/
public boolean getBoolean(String key, String role) {
if (hasKey(key + "-" + role)) {
return getBoolean(key + "-" + role);
}
return getBoolean(key);
}
private HashMap<String, String> getVariableDefaults() {
return (HashMap<String, String>) readFile(DEFAULT_CONF_PATH).entrySet().stream()
.filter(entry -> entry.getKey().startsWith(VARIABLE_PREFIX))
.collect(Collectors.toMap(e -> e.getKey().replace(VARIABLE_PREFIX, ""), e -> e.getValue()));
}
public String getString(String key, boolean env, boolean file, boolean defaultValue) {
String value = null;
if (env) {
// only underscore is allowed in bash variables
value = System.getenv(key.replace("-", "_"));
}
if (value == null && file) {
value = getFromFile(confFilePath, key);
}
if (value == null && defaultValue) {
value = getDefault(key);
}
return value;
}
private static String getFromFile(String confFilePath, String key) {
return readFile(confFilePath).get(key);
}
private static HashMap<String, String> readFile(String confFilePath) {
if (!confFileCache.containsKey(confFilePath)) {
confFileCache.put(confFilePath, readFileUncached(confFilePath));
}
return confFileCache.get(confFilePath);
}
private static HashMap<String, String> readFileUncached(String confFilePath) {
HashMap<String, String> conf = new HashMap<>();
Reader streamReader = null;
try {
if (DEFAULT_CONF_PATH.equals(confFilePath)) {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(confFilePath);
streamReader = new InputStreamReader(is);
} else {
streamReader = new FileReader(confFilePath);
}
YamlReader reader = new YamlReader(streamReader);
Object object = reader.read();
if (object instanceof Map) {
@SuppressWarnings("rawtypes")
Map confFileMap = (Map) object;
for (Object key : confFileMap.keySet()) {
Object valueObj = confFileMap.get(key);
String value = valueObj != null ? valueObj.toString() : null;
conf.put(key.toString(), value);
}
} else if (object == null){
// empty config file
} else {
throw new RuntimeException("configuration file should be a yaml map, but it is " + object);
}
} catch (FileNotFoundException e) {
// show only once per JVM
if (!Config.confFileWarnShown) {
logger.warn("configuration file " + confFilePath + " not found");
Config.confFileWarnShown = true;
}
} catch (IOException e) {
// convert to runtime exception, because there is no point to continue
// (so no point to check exceptions either)
throw new RuntimeException("failed to read the config file " + confFilePath, e);
} finally {
try {
if (streamReader != null) {
streamReader.close();
}
} catch (IOException e) {
logger.warn(e);
}
}
return conf;
}
/**
* Each service has a configuration item for the password, which is created
* automatically and accessed with this method. The method will log a warning if
* the default password is used.
*
* @param username
* @return
* @throws IOException
*/
public String getPassword(String username) {
String key = getPasswordConfigKey(username);
if (isDefault(key)) {
logger.warn("default password for username " + username);
}
return getString(key);
}
public String getPasswordConfigKey(String username) {
return SERVICE_PASSWORD_PREFIX + username;
}
public String getSsoPassword(String username) {
String key = getSsoPasswordConfigKey(username);
// there are no sso accounts in the default config
if (hasDefault(key)) {
logger.warn("default password for username " + username);
}
return getString(key);
}
public String getSsoPasswordConfigKey(String username) {
return SSO_SERVICE_PASSWORD_PREFIX + username;
}
/**
* Collect all services that have a service password entry and their configured passwords
*
* Collecting the list of services straight from the config file makes it easier to add new services.
* The list of services is collected only from the default config file, because there should be no need
* to alter this list in configuration. Passwords have to be configurable
* so those are of course collected from all normal configuration locations.
*
* @return a map where keys are the service names and values are the service passwords
*/
public Map<String, String> getServicePasswords() {
List<String> services = readFile(DEFAULT_CONF_PATH).keySet().stream()
.filter(confKey -> confKey.startsWith(SERVICE_PASSWORD_PREFIX))
.map(confKey -> confKey.replace(SERVICE_PASSWORD_PREFIX, ""))
.collect(Collectors.toList());
return services.stream()
.collect(Collectors.toMap(service -> service, service -> getPassword(service)));
}
public Set<String> getAdminAccounts() {
HashMap<String, String> conf = readFile(DEFAULT_CONF_PATH);
conf.putAll(readFile(confFilePath));
return conf.entrySet().stream()
.filter(entry -> entry.getKey().startsWith(ADMIN_USERNAME_PREFIX))
.map(entry -> entry.getValue())
.collect(Collectors.toSet());
}
public Map<String, String> getSsoServicePasswords() {
HashMap<String, String> conf = readFile(DEFAULT_CONF_PATH);
// new sso services can be added in configuration
conf.putAll(readFile(confFilePath));
List<String> services = conf.keySet().stream()
.filter(confKey -> confKey.startsWith(SSO_SERVICE_PASSWORD_PREFIX))
.map(confKey -> confKey.replace(SSO_SERVICE_PASSWORD_PREFIX, ""))
.collect(Collectors.toList());
return services.stream()
.collect(Collectors.toMap(service -> service, service -> getSsoPassword(service)));
}
/**
* Services having an internal address
*
* @return a map where keys are the service names and values are their internal addresses
*/
public Map<String, String> getInternalServiceUrls() {
return getConfigEntriesFixed(URL_INT_PREFIX);
}
/**
* Services having an external address
*
* @return a map where keys are the service names and values are their external addresses
*/
public Map<String, String> getExternalServiceUrls() {
return getConfigEntries(URL_EXT_PREFIX);
}
/**
* Services having an admin address
*
* @return a map where keys are the service names and values are their admin addresses
*/
public Map<String, String> getAdminServiceUrls() {
return getConfigEntriesFixed(URL_ADMIN_EXT_PREFIX);
}
/**
* Services having a machine-to-machine address
*
* @return a map where keys are the service names and values are their m2m addresses
*/
public Map<String, String> getM2mServiceUrls() {
return getConfigEntriesFixed(URL_M2M_INT_PREFIX);
}
/**
* Get all config entries starting with the prefix
*
* The config keys are searched only from the default configuration, so the configuration file
* can only change the values, but not add new keys.
*
* @param prefix
* @return Map of entries. Keys without the prefix.
*/
private Map<String, String> getConfigEntriesFixed(String prefix) {
return readFile(DEFAULT_CONF_PATH).entrySet().stream()
.filter(entry -> entry.getKey().startsWith(prefix))
.collect(Collectors.toMap(e -> e.getKey().replace(prefix, ""), e -> getString(e.getKey())));
}
/**
* Get all config entries starting with the prefix
*
* New keys can be added also in the configuration.
*
* @param prefix
* @return Map of entries. Keys without the prefix.
*/
private Map<String, String> getConfigEntries(String prefix) {
HashMap<String, String> conf = readFile(DEFAULT_CONF_PATH);
// new sso services can be added in configuration
conf.putAll(readFile(confFilePath));
return conf.entrySet().stream()
.filter(entry -> entry.getKey().startsWith(prefix))
.collect(Collectors.toMap(e -> e.getKey().replace(prefix, ""), e -> getString(e.getKey())));
}
public String getBindUrl(String service) {
return getString(URL_BIND_PREFIX + service);
}
public String getAdminBindUrl(String service) {
return getString(URL_ADMIN_BIND_PREFIX + service);
}
public String getM2mBindUrl(String service) {
return getString(URL_M2M_BIND_PREFIX + service);
}
public String getDefault(String key) {
String template = getFromFile(DEFAULT_CONF_PATH, key);
if (template == null) {
throw new IllegalArgumentException("configuration key not found: " + key);
}
return replaceVariables(template);
}
public boolean hasDefault(String key) {
return readFile(DEFAULT_CONF_PATH).containsKey(key);
}
public boolean isDefault(String key) {
return getDefault(key).equals(getString(key));
}
private String replaceVariables(String template) {
for (String variableName : variableDefaults.keySet()) {
// if set in environment variable
String variableValue = System.getenv(variableName);
// use default
if (variableValue == null) {
variableValue = variableDefaults.get(variableName);
}
template = template.replaceAll(Pattern.quote("{{" + variableName + "}}"), variableValue);
}
return template;
}
public URI getURI(String key) {
return URI.create(getString(key));
}
public int getInt(String key) throws NumberFormatException {
return Integer.parseInt(getString(key));
}
public boolean getBoolean(String key) {
return "true".equalsIgnoreCase(getString(key));
}
public long getLong(String key) throws NumberFormatException {
return Long.parseLong(getString(key));
}
public String getVariableString(String key) {
return this.replaceVariables("{{" + key + "}}");
}
public int getVariableInt(String key) {
return Integer.parseInt(getVariableString(key));
}
public Set<String> getDbBackupRoles() {
return getConfigEntries(DB_URL_PREFIX).keySet();
}
public Map<String, String> getSupportEmails() {
return getConfigEntries(KEY_SESSION_WORKER_SUPPORT_EMAIL_PREFIX);
}
public boolean hasKey(String key) {
try {
getString(key);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
} |
package io.subutai.hub.share.dto.environment;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.subutai.hub.share.dto.PublicKeyContainer;
public class EnvironmentPeerDto
{
public enum PeerState
{
EXCHANGE_INFO,
RESERVE_NETWORK,
SETUP_TUNNEL,
BUILD_CONTAINER,
CONFIGURE_CONTAINER,
CONFIGURE_DOMAIN,
CHANGE_CONTAINER_STATE,
DELETE_PEER,
WAIT,
READY,
ERROR
}
private String peerId;
private EnvironmentInfoDto environmentInfo;
private String ownerId;
private PeerState requestState;
private Set<String> p2pSubnets = new HashSet<>();
private Set<Long> vnis = new HashSet<>();
private Set<String> containerSubnets = new HashSet<>();
private PublicKeyContainer publicKey;
private String interfaceName;
private String communityName;
private String tunnelAddress;
private String p2pSecretKey;
private Boolean setupTunnel;
private Set<EnvironmentPeerRHDto> rhs = new HashSet<>();
private String peerToken;
private String peerTokenId;
private String envOwnerToken;
private String envOwnerTokenId;
private String message;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Integer vlan;
public EnvironmentPeerDto()
{
}
public EnvironmentPeerDto( PeerState requestState )
{
this.requestState = requestState;
}
public String getPeerId()
{
return peerId;
}
public void setPeerId( final String peerId )
{
this.peerId = peerId;
}
public PeerState getState()
{
return requestState;
}
public void setState( final PeerState requestState )
{
this.requestState = requestState;
}
public EnvironmentInfoDto getEnvironmentInfo()
{
return environmentInfo;
}
public void setEnvironmentInfo( final EnvironmentInfoDto environmentInfo )
{
this.environmentInfo = environmentInfo;
}
public String getOwnerId()
{
return ownerId;
}
public void setOwnerId( final String ownerId )
{
this.ownerId = ownerId;
}
public Set<String> getP2pSubnets()
{
return p2pSubnets;
}
public void setP2pSubnets( final Set<String> p2pSubnets )
{
this.p2pSubnets = p2pSubnets;
}
public void addP2pSubnet( final String p2pSubnet )
{
this.p2pSubnets.add( p2pSubnet );
}
public void removeP2pSubnet( final String p2pSubnet )
{
this.p2pSubnets.remove( p2pSubnet );
}
public Set<Long> getVnis()
{
return vnis;
}
public void setVnis( final Set<Long> vnis )
{
this.vnis = vnis;
}
public void addVni( final Long vni )
{
this.vnis.add( vni );
}
public Set<String> getContainerSubnets()
{
return containerSubnets;
}
public void setContainerSubnets( final Set<String> containerSubnets )
{
this.containerSubnets = containerSubnets;
}
public void addContainerSubnet( final String containerSubnet )
{
this.containerSubnets.add( containerSubnet );
}
public PublicKeyContainer getPublicKey()
{
return publicKey;
}
public void setPublicKey( final PublicKeyContainer publicKey )
{
this.publicKey = publicKey;
}
public String getInterfaceName()
{
return interfaceName;
}
public void setInterfaceName( final String interfaceName )
{
this.interfaceName = interfaceName;
}
public String getCommunityName()
{
return communityName;
}
public void setCommunityName( final String communityName )
{
this.communityName = communityName;
}
public String getTunnelAddress()
{
return tunnelAddress;
}
public void setTunnelAddress( final String tunnelAddress )
{
this.tunnelAddress = tunnelAddress;
}
public String getP2pSecretKey()
{
return p2pSecretKey;
}
public void setP2pSecretKey( final String p2pSecretKey )
{
this.p2pSecretKey = p2pSecretKey;
}
public Boolean getSetupTunnel()
{
return setupTunnel;
}
public void setSetupTunnel( final Boolean setupTunnel )
{
this.setupTunnel = setupTunnel;
}
public Set<EnvironmentPeerRHDto> getRhs()
{
return rhs;
}
public void setRhs( final Set<EnvironmentPeerRHDto> rhs )
{
this.rhs = rhs;
}
public void addRH( final EnvironmentPeerRHDto rh )
{
this.rhs.add( rh );
}
public String getPeerToken()
{
return peerToken;
}
public void setPeerToken( final String peerToken )
{
this.peerToken = peerToken;
}
public String getEnvOwnerToken()
{
return envOwnerToken;
}
public void setEnvOwnerToken( final String envOwnerToken )
{
this.envOwnerToken = envOwnerToken;
}
public String getPeerTokenId()
{
return peerTokenId;
}
public void setPeerTokenId( final String peerTokenId )
{
this.peerTokenId = peerTokenId;
}
public String getEnvOwnerTokenId()
{
return envOwnerTokenId;
}
public void setEnvOwnerTokenId( final String envOwnerTokenId )
{
this.envOwnerTokenId = envOwnerTokenId;
}
public String getMessage()
{
return message;
}
public void setMessage( String message )
{
this.message = message;
}
public Integer getVlan()
{
return vlan;
}
public void setVlan( final Integer vlan )
{
this.vlan = vlan;
}
public void setError( String message )
{
setState( PeerState.ERROR );
setMessage( message );
}
} |
package org.spine3.server.command;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import io.grpc.stub.StreamObserver;
import org.spine3.annotations.Internal;
import org.spine3.base.Command;
import org.spine3.base.CommandId;
import org.spine3.base.Error;
import org.spine3.base.Errors;
import org.spine3.base.FailureThrowable;
import org.spine3.base.Identifiers;
import org.spine3.base.Response;
import org.spine3.base.Responses;
import org.spine3.envelope.CommandEnvelope;
import org.spine3.server.BoundedContext;
import org.spine3.server.Statuses;
import org.spine3.server.bus.Bus;
import org.spine3.server.failure.FailureBus;
import org.spine3.server.users.CurrentTenant;
import org.spine3.type.CommandClass;
import org.spine3.util.Environment;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.getRootCause;
import static org.spine3.base.CommandStatus.SCHEDULED;
import static org.spine3.base.Commands.isScheduled;
import static org.spine3.validate.Validate.isNotDefault;
/**
* Dispatches the incoming commands to the corresponding handler.
*
* @author Alexander Yevsyukov
* @author Mikhail Melnik
* @author Alexander Litus
* @author Alex Tymchenko
*/
public class CommandBus extends Bus<Command, CommandEnvelope, CommandClass, CommandDispatcher> {
private final Filter filter;
private final CommandStore commandStore;
private final CommandStatusService commandStatusService;
private final CommandScheduler scheduler;
private final Rescheduler rescheduler;
private final FailureBus failureBus;
private final Log log;
/**
* Is true, if the {@code BoundedContext} (to which this {@code CommandBus} belongs)
* is multi-tenant.
*
* <p>If the {@code CommandBus} is multi-tenant, the commands posted must have the
* {@code tenant_id} attribute defined.
*/
private boolean isMultitenant;
/**
* Determines whether the manual thread spawning is allowed within current runtime environment.
*
* <p>If set to {@code true}, {@code CommandBus} will be running some of internal processing in
* parallel to improve performance.
*/
private final boolean isThreadSpawnAllowed;
/**
* Creates new instance according to the passed {@link Builder}.
*/
private CommandBus(Builder builder) {
this(builder.getCommandStore(),
builder.getCommandScheduler(),
builder.getFailureBus(),
builder.log,
builder.isThreadSpawnAllowed());
}
/**
* Initializes the instance by rescheduling commands.
*/
private void rescheduleCommands() {
rescheduler.rescheduleCommands();
}
/**
* Creates a new {@link Builder} for the {@code CommandBus}.
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* Creates a new instance.
*
* @param commandStore a store to save commands
* @param scheduler a command scheduler
* @param failureBus a failure bus
* @param log a problem logger
* @param threadSpawnAllowed whether the current runtime environment allows manual thread spawn
*/
@SuppressWarnings("ThisEscapedInObjectConstruction") // is OK because helper instances only store the reference.
private CommandBus(CommandStore commandStore,
CommandScheduler scheduler,
FailureBus failureBus,
Log log,
boolean threadSpawnAllowed) {
this.commandStore = checkNotNull(commandStore);
this.commandStatusService = new CommandStatusService(commandStore);
this.scheduler = checkNotNull(scheduler);
this.failureBus = checkNotNull(failureBus);
this.log = checkNotNull(log);
this.isThreadSpawnAllowed = threadSpawnAllowed;
this.filter = new Filter(this);
this.rescheduler = new Rescheduler(this);
}
boolean isMultitenant() {
return isMultitenant;
}
boolean isThreadSpawnAllowed() {
return isThreadSpawnAllowed;
}
CommandStore commandStore() {
return commandStore;
}
Log problemLog() {
return log;
}
@VisibleForTesting
Rescheduler rescheduler() {
return rescheduler;
}
@VisibleForTesting
CommandScheduler scheduler() {
return scheduler;
}
@VisibleForTesting
FailureBus failureBus() {
return this.failureBus;
}
@Override
protected CommandDispatcherRegistry createRegistry() {
return new CommandDispatcherRegistry();
}
/**
* Obtains the view {@code Set} of commands that are known to this {@code CommandBus}.
*
* <p>This set is changed when command dispatchers or handlers are registered or un-registered.
*
* @return a set of classes of supported commands
*/
public Set<CommandClass> getRegisteredCommandClasses() {
return registry().getRegisteredMessageClasses();
}
/**
* Obtains the instance of the {@link CommandStatusService} associated with this command bus.
*/
CommandStatusService getCommandStatusService() {
return commandStatusService;
}
private Optional<CommandDispatcher> getDispatcher(CommandClass commandClass) {
return registry().getDispatcher(commandClass);
}
/**
* Directs the command to be dispatched.
*
* <p>If the command has scheduling attributes, it will be posted for execution by
* the configured scheduler according to values of those scheduling attributes.
*
* <p>If a command does not have a dispatcher, the error is
* {@linkplain StreamObserver#onError(Throwable) returned} with
* {@link UnsupportedCommandException} as the cause.
*
* @param command the command to be processed
* @param responseObserver the observer to return the result of the call
*/
@Override
public void post(Command command, StreamObserver<Response> responseObserver) {
checkNotNull(command);
checkNotNull(responseObserver);
checkArgument(isNotDefault(command));
final CommandEnvelope commandEnvelope = CommandEnvelope.of(command);
final CommandClass commandClass = commandEnvelope.getMessageClass();
final Optional<CommandDispatcher> dispatcher = getDispatcher(commandClass);
// If the command is not supported, return as error.
if (!dispatcher.isPresent()) {
handleDeadMessage(commandEnvelope, responseObserver);
return;
}
if (!filter.handleValidation(command, responseObserver)) {
return;
}
if (isScheduled(command)) {
scheduleAndStore(command, responseObserver);
return;
}
if (isMultitenant) {
CurrentTenant.set(command.getContext()
.getTenantId());
}
commandStore.store(command);
responseObserver.onNext(Responses.ok());
doPost(commandEnvelope, dispatcher.get());
responseObserver.onCompleted();
}
@Override
public void handleDeadMessage(CommandEnvelope message,
StreamObserver<Response> responseObserver) {
Command command = message.getCommand();
final CommandException unsupported = new UnsupportedCommandException(command);
commandStore.storeWithError(command, unsupported);
responseObserver.onError(Statuses.invalidArgumentWithCause(unsupported));
}
/**
* Passes a previously scheduled command to the corresponding dispatcher.
*/
void postPreviouslyScheduled(Command command) {
final CommandEnvelope commandEnvelope = CommandEnvelope.of(command);
final Optional<CommandDispatcher> dispatcher = getDispatcher(
commandEnvelope.getMessageClass()
);
if (!dispatcher.isPresent()) {
throw noDispatcherFound(commandEnvelope);
}
doPost(commandEnvelope, dispatcher.get());
}
private static IllegalStateException noDispatcherFound(CommandEnvelope commandEnvelope) {
final String idStr = Identifiers.idToString(commandEnvelope.getCommandId());
final String msg = String.format("No dispatcher found for the command (class: %s id: %s).",
commandEnvelope.getMessageClass(), idStr);
throw new IllegalStateException(msg);
}
private void scheduleAndStore(Command command, StreamObserver<Response> responseObserver) {
scheduler.schedule(command);
commandStore.store(command, SCHEDULED);
responseObserver.onNext(Responses.ok());
responseObserver.onCompleted();
}
/**
* Directs a command to be dispatched.
*/
void doPost(CommandEnvelope commandEnvelope, CommandDispatcher dispatcher) {
try {
dispatcher.dispatch(commandEnvelope);
setStatusOk(commandEnvelope);
} catch (RuntimeException e) {
final Throwable cause = getRootCause(e);
updateCommandStatus(commandEnvelope, cause);
}
}
private void setStatusOk(CommandEnvelope envelope) {
final CommandId commandId = envelope.getCommandId();
commandStatusService.setOk(commandId);
}
@SuppressWarnings("ChainOfInstanceofChecks") // OK for this rare case
private void updateCommandStatus(CommandEnvelope commandEnvelope, Throwable cause) {
if (cause instanceof FailureThrowable) {
final FailureThrowable failure = (FailureThrowable) cause;
log.failureHandling(failure,
commandEnvelope.getMessage(),
commandEnvelope.getCommandId());
commandStatusService.setToFailure(commandEnvelope.getCommandId(), failure);
failureBus.post(failure.toFailure());
} else if (cause instanceof Exception) {
final Exception exception = (Exception) cause;
log.errorHandling(exception,
commandEnvelope.getMessage(),
commandEnvelope.getCommandId());
commandStatusService.setToError(commandEnvelope.getCommandId(), exception);
} else {
log.errorHandlingUnknown(cause,
commandEnvelope.getMessage(),
commandEnvelope.getCommandId());
final Error error = Errors.fromThrowable(cause);
commandStatusService.setToError(commandEnvelope.getCommandId(), error);
}
}
/**
* Sets the multitenancy status of the {@link CommandBus}.
*
* <p>A {@link CommandBus} is multi-tenant if its {@link BoundedContext} is multi-tenant.
*/
@Internal
public void setMultitenant(boolean isMultitenant) {
this.isMultitenant = isMultitenant;
}
/**
* Closes the instance, preventing any for further posting of commands.
*
* <p>The following operations are performed:
* <ol>
* <li>All command dispatchers are un-registered.
* <li>{@code CommandStore} is closed.
* <li>{@code CommandScheduler} is shut down.
* </ol>
*
* @throws Exception if closing the {@code CommandStore} cases an exception
*/
@Override
public void close() throws Exception {
registry().unregisterAll();
commandStore.close();
scheduler.shutdown();
failureBus.close();
}
/**
* {@inheritDoc}
*
* <p>Overrides for return type covariance.
*/
@Override
protected CommandDispatcherRegistry registry() {
return (CommandDispatcherRegistry) super.registry();
}
/**
* The {@code Builder} for {@code CommandBus}.
*/
public static class Builder {
private CommandStore commandStore;
private Log log;
/**
* Optional field for the {@code CommandBus}.
*
* <p>If unset, the default {@link ExecutorCommandScheduler} implementation is used.
*/
private CommandScheduler commandScheduler;
/**
* If set to {@code true}, the {@code CommandBus} will be creating instances of
* {@link Thread} for operation.
*
* <p>However, some runtime environments, such as Google AppEngine Standard,
* do not allow manual thread
* spawning. In this case, this flag should be set to {@code false}.
*
* <p>The default value of this flag is set upon the best guess,
* based on current {@link Environment}.
*/
private boolean threadSpawnAllowed = detectThreadsAllowed();
/**
* If set the builder will not call {@link CommandBus#rescheduleCommands()}.
*
* <p>One of the applications of this flag is to disable rescheduling of commands in tests.
*/
private boolean autoReschedule;
private FailureBus failureBus;
/**
* Checks whether the manual {@link Thread} spawning is allowed within
* the current runtime environment.
*/
private static boolean detectThreadsAllowed() {
final boolean appEngine = Environment.getInstance()
.isAppEngine();
return !appEngine;
}
public CommandStore getCommandStore() {
return commandStore;
}
public CommandScheduler getCommandScheduler() {
return commandScheduler;
}
public FailureBus getFailureBus() {
return failureBus;
}
public Builder setCommandStore(CommandStore commandStore) {
checkNotNull(commandStore);
this.commandStore = commandStore;
return this;
}
public Builder setCommandScheduler(CommandScheduler commandScheduler) {
checkNotNull(commandScheduler);
this.commandScheduler = commandScheduler;
return this;
}
public Builder setFailureBus(FailureBus failureBus) {
checkNotNull(failureBus);
this.failureBus = failureBus;
return this;
}
public boolean isThreadSpawnAllowed() {
return threadSpawnAllowed;
}
public Builder setThreadSpawnAllowed(boolean threadSpawnAllowed) {
this.threadSpawnAllowed = threadSpawnAllowed;
return this;
}
@VisibleForTesting
Builder setLog(Log log) {
this.log = log;
return this;
}
@VisibleForTesting
Builder setAutoReschedule(boolean autoReschedule) {
this.autoReschedule = autoReschedule;
return this;
}
private Builder() {
// Do not allow creating builder instances directly.
}
/**
* Builds an instance of {@link CommandBus}.
*/
public CommandBus build() {
checkNotNull(commandStore, "CommandStore must be set");
if (commandScheduler == null) {
commandScheduler = new ExecutorCommandScheduler();
}
if (log == null) {
log = new Log();
}
if (failureBus == null) {
failureBus = FailureBus.newBuilder()
.build();
}
final CommandBus commandBus = new CommandBus(this);
if (commandScheduler.getCommandBus() == null) {
commandScheduler.setCommandBus(commandBus);
}
if (autoReschedule) {
commandBus.rescheduleCommands();
}
return commandBus;
}
}
} |
package filter.expression;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import backend.resource.*;
import filter.ParseException;
import util.Utility;
import backend.interfaces.IModel;
import filter.MetaQualifierInfo;
import filter.QualifierApplicationException;
public class Qualifier implements FilterExpression {
public static final Qualifier EMPTY = new Qualifier(QualifierType.EMPTY, "");
public static final Qualifier FALSE = new Qualifier(QualifierType.FALSE, "");
private final QualifierType type;
// Only one of these will be present at a time
private Optional<DateRange> dateRange = Optional.empty();
private Optional<String> content = Optional.empty();
private Optional<LocalDate> date = Optional.empty();
private Optional<NumberRange> numberRange = Optional.empty();
private Optional<Integer> number = Optional.empty();
private List<SortKey> sortKeys = new ArrayList<>();
// Copy constructor
public Qualifier(Qualifier other) {
this.type = other.getType();
if (other.getDateRange().isPresent()) {
this.dateRange = other.getDateRange();
} else if (other.getDate().isPresent()) {
this.date = other.getDate();
} else if (other.getContent().isPresent()) {
this.content = other.getContent();
} else if (other.getNumberRange().isPresent()) {
this.numberRange = other.getNumberRange();
} else if (other.getNumber().isPresent()) {
this.number = other.getNumber();
} else if (!other.sortKeys.isEmpty()) {
this.sortKeys = new ArrayList<>(other.sortKeys);
} else {
assert false : "Unrecognised content type! You may have forgotten to add it above";
}
}
public Qualifier(QualifierType type, String content) {
this.type = type;
this.content = Optional.of(content);
}
public Qualifier(QualifierType type, NumberRange numberRange) {
this.type = type;
this.numberRange = Optional.of(numberRange);
}
public Qualifier(QualifierType type, DateRange dateRange) {
this.type = type;
this.dateRange = Optional.of(dateRange);
}
public Qualifier(QualifierType type, LocalDate date) {
this.type = type;
this.date = Optional.of(date);
}
public Qualifier(QualifierType type, int number) {
this.type = type;
this.number = Optional.of(number);
}
public Qualifier(QualifierType type, List<SortKey> keys) {
this.type = type;
this.sortKeys = new ArrayList<>(keys);
}
public static FilterExpression replaceMilestoneAliases(IModel model, FilterExpression expr) {
List<String> repoIds = getMetaQualifierContent(expr, QualifierType.REPO).stream()
.map(String::toLowerCase)
.collect(Collectors.toList());
if (repoIds.isEmpty()) {
repoIds.add(model.getDefaultRepo().toLowerCase());
}
List<TurboMilestone> allMilestones = model.getMilestones().stream()
.filter(ms -> ms.getDueDate().isPresent())
.filter(ms -> repoIds.contains(ms.getRepoId().toLowerCase()))
.sorted((a, b) -> getMilestoneDueDateComparator().compare(a, b))
.collect(Collectors.toList());
boolean hasRelevantMilestone = allMilestones.stream().anyMatch(ms -> isRelevantMilestone(ms));
if (!hasRelevantMilestone) {
List<TurboMilestone> openMilestonesWithoutDueDate = model.getMilestones().stream()
.filter(ms -> !ms.getDueDate().isPresent())
.filter(ms -> repoIds.contains(ms.getRepoId().toLowerCase()))
.filter(ms -> ms.isOpen())
.collect(Collectors.toList());
if (openMilestonesWithoutDueDate.size() == 1) {
//milestones without due date can only be located at the end of the list
allMilestones.add(openMilestonesWithoutDueDate.get(0));
}
}
Optional<Integer> currentMilestoneIndex = getCurrentMilestoneIndex(allMilestones);
if (!currentMilestoneIndex.isPresent()) {
return expr;
}
return expr.map(q -> {
if (Qualifier.isMilestoneQualifier(q)) {
return q.convertMilestoneAliasQualifier(allMilestones, currentMilestoneIndex.get());
} else {
return q;
}
});
}
/**
* Helper function for testing a filter expression against an issue.
* Ensures that meta-qualifiers are taken care of.
* Should always be used over isSatisfiedBy.
*/
public static boolean process(IModel model, FilterExpression expr, TurboIssue issue) {
FilterExpression exprWithNormalQualifiers = expr.filter(Qualifier::shouldNotBeStripped);
List<Qualifier> metaQualifiers = expr.find(Qualifier::isMetaQualifier);
// Preprocessing for repo qualifier
boolean containsRepoQualifier = metaQualifiers.stream()
.map(Qualifier::getType)
.collect(Collectors.toList())
.contains(QualifierType.REPO);
if (!containsRepoQualifier) {
exprWithNormalQualifiers = new Conjunction(
new Qualifier(QualifierType.REPO, model.getDefaultRepo()),
exprWithNormalQualifiers);
}
return exprWithNormalQualifiers.isSatisfiedBy(model, issue, new MetaQualifierInfo(metaQualifiers));
}
private static Optional<Integer> getCurrentMilestoneIndex(List<TurboMilestone> allMilestones) {
if (allMilestones.isEmpty()) {
return Optional.empty();
}
int currentIndex = 0;
for (TurboMilestone checker : allMilestones) {
if (checker.isOpen() && isRelevantMilestone(checker)) {
return Optional.of(currentIndex);
}
currentIndex++;
}
// if no open milestone, set current as one after last milestone
// - this means that no such milestone, which will return no issue
return Optional.of(allMilestones.size());
}
private static boolean isRelevantMilestone(TurboMilestone milestone) {
boolean overdue = milestone.getDueDate().isPresent() &&
milestone.getDueDate().get().isBefore(LocalDate.now());
return !(overdue && milestone.getOpenIssues() == 0);
}
public static HashSet<String> getMetaQualifierContent(FilterExpression expr, QualifierType qualifierType) {
HashSet<String> contents = new HashSet<>();
List<Qualifier> panelMetaQualifiers = expr.find(Qualifier::isMetaQualifier);
panelMetaQualifiers.forEach(metaQualifier -> {
if (metaQualifier.getType().equals(qualifierType) && metaQualifier.getContent().isPresent()) {
contents.add(metaQualifier.getContent().get());
}
});
return contents;
}
private static LocalDateTime currentTime = null;
private static LocalDateTime getCurrentTime() {
if (currentTime == null) {
return LocalDateTime.now();
} else {
return currentTime;
}
}
/**
* For testing. Stubs the current time so time-related qualifiers work properly.
*/
public static void setCurrentTime(LocalDateTime dateTime) {
currentTime = dateTime;
}
@Override
public boolean isEmpty() {
return type == QualifierType.EMPTY;
}
public boolean isFalse() {
return type == QualifierType.FALSE;
}
@Override
public boolean isSatisfiedBy(IModel model, TurboIssue issue, MetaQualifierInfo info) {
assert type != null;
// The empty qualifier is satisfied by anything
if (isEmpty()) return true;
// The false qualifier is satisfied by nothing
if (isFalse()) return false;
switch (type) {
case ID:
return idSatisfies(issue);
case KEYWORD:
return keywordSatisfies(issue, info);
case TITLE:
return titleSatisfies(issue);
case DESCRIPTION:
return bodySatisfies(issue);
case MILESTONE:
return milestoneSatisfies(model, issue);
case LABEL:
return labelsSatisfy(model, issue);
case AUTHOR:
return authorSatisfies(issue);
case ASSIGNEE:
return assigneeSatisfies(model, issue);
case INVOLVES:
return involvesSatisfies(model, issue);
case TYPE:
return typeSatisfies(issue);
case STATE:
return stateSatisfies(issue);
case HAS:
return satisfiesHasConditions(issue);
case NO:
return satisfiesNoConditions(issue);
case IS:
return satisfiesIsConditions(issue);
case CREATED:
return satisfiesCreationDate(issue);
case UPDATED:
return satisfiesUpdatedHours(issue);
case REPO:
return satisfiesRepo(issue);
default:
assert false : "Missing case for " + type;
return false;
}
}
@Override
public void applyTo(TurboIssue issue, IModel model) throws QualifierApplicationException {
assert type != null && content != null;
// The empty qualifier should not be applied to anything
assert !isEmpty();
// The false qualifier should not be applied to anything
assert !isFalse();
switch (type) {
case TITLE:
case DESCRIPTION:
case KEYWORD:
throw new QualifierApplicationException("Unnecessary filter: issue text cannot be changed by dragging");
case ID:
throw new QualifierApplicationException("Unnecessary filter: id is immutable");
case CREATED:
throw new QualifierApplicationException("Unnecessary filter: cannot change issue creation date");
case HAS:
case NO:
case IS:
throw new QualifierApplicationException("Ambiguous filter: " + type);
case MILESTONE:
applyMilestone(issue, model);
break;
case LABEL:
applyLabel(issue, model);
break;
case ASSIGNEE:
applyAssignee(issue, model);
break;
case AUTHOR:
throw new QualifierApplicationException("Unnecessary filter: cannot change author of issue");
case INVOLVES:
throw new QualifierApplicationException("Ambiguous filter: cannot change users involved with issue");
case STATE:
applyState(issue);
break;
default:
assert false : "Missing case for " + type;
break;
}
}
@Override
public boolean canBeAppliedToIssue() {
return true;
}
@Override
public List<QualifierType> getQualifierTypes() {
return new ArrayList<>(Arrays.asList(type));
}
@Override
public FilterExpression filter(Predicate<Qualifier> pred) {
if (pred.test(this)) {
return new Qualifier(this);
} else {
return EMPTY;
}
}
@Override
public List<Qualifier> find(Predicate<Qualifier> pred) {
if (pred.test(this)) {
ArrayList<Qualifier> result = new ArrayList<>();
result.add(this);
return result;
} else {
return new ArrayList<>();
}
}
@Override
public FilterExpression map(Function<Qualifier, Qualifier> func) {
return func.apply(this);
}
/**
* This method is used to serialise qualifiers. Thus whatever form returned
* should be syntactically valid.
*/
@Override
public String toString() {
if (this.isEmpty()) {
return "";
} else if (content.isPresent()) {
String quotedContent = content.get();
if (quotedContent.contains(" ")) {
quotedContent = "\"" + quotedContent + "\"";
}
if (type == QualifierType.KEYWORD) {
return quotedContent;
} else {
return type + ":" + quotedContent;
}
} else if (date.isPresent()) {
return type + ":" + date.get().toString();
} else if (dateRange.isPresent()) {
return type + ":" + dateRange.get().toString();
} else if (!sortKeys.isEmpty()) {
return type + ":" + sortKeys.stream().map(SortKey::toString).collect(Collectors.joining(","));
} else if (numberRange.isPresent()) {
return type + ":" + numberRange.get().toString();
} else if (number.isPresent()) {
return type + ":" + number.get().toString();
} else {
assert false : "Should not happen";
return "";
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((dateRange == null) ? 0 : dateRange.hashCode());
result = prime * result + ((number == null) ? 0 : number.hashCode());
result = prime * result + ((numberRange == null) ? 0 : numberRange.hashCode());
result = prime * result + ((sortKeys == null) ? 0 : sortKeys.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Qualifier other = (Qualifier) obj;
return content.equals(other.content) &&
date.equals(other.date) &&
dateRange.equals(other.dateRange) &&
number.equals(other.number) &&
numberRange.equals(other.numberRange) &&
sortKeys.equals(other.sortKeys) &&
type.equals(other.type);
}
private static boolean shouldNotBeStripped(Qualifier q) {
return !shouldBeStripped(q);
}
private static boolean shouldBeStripped(Qualifier q) {
switch (q.getType()) {
case IN:
case SORT:
case COUNT:
return true;
default:
return false;
}
}
public static boolean isMetaQualifier(Qualifier q) {
switch (q.getType()) {
case SORT:
case IN:
case REPO:
case COUNT:
return true;
default:
return isUpdatedQualifier(q);
}
}
public static boolean isMilestoneQualifier(Qualifier q) {
switch (q.getType()) {
case MILESTONE:
return true;
default:
return false;
}
}
public static boolean isUpdatedQualifier(Qualifier q) {
switch (q.getType()) {
case UPDATED:
return true;
default:
return false;
}
}
public static boolean hasUpdatedQualifier(FilterExpression expr) {
return !expr.find(Qualifier::isUpdatedQualifier).isEmpty();
}
public Comparator<TurboIssue> getCompoundSortComparator(IModel model, boolean isSortableByNonSelfUpdates) {
if (sortKeys.isEmpty()) {
return (a, b) -> 0;
}
return (a, b) -> {
for (SortKey key : sortKeys) {
Comparator<TurboIssue> comparator =
getSortComparator(model, key.key, key.inverted, isSortableByNonSelfUpdates);
int result = comparator.compare(a, b);
if (result != 0) {
return result;
}
}
return 0;
};
}
public static Comparator<TurboIssue> getSortComparator(IModel model,
String key,
boolean inverted,
boolean isSortableByNonSelfUpdates) {
Comparator<TurboIssue> comparator = (a, b) -> 0;
boolean isLabelGroup = false;
switch (key) {
case "comments":
comparator = (a, b) -> a.getCommentCount() - b.getCommentCount();
break;
case "repo":
comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId());
break;
case "updated":
case "date":
comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt());
break;
case "nonSelfUpdate":
if (isSortableByNonSelfUpdates) {
comparator = (a, b) ->
a.getMetadata().getNonSelfUpdatedAt().compareTo(b.getMetadata().getNonSelfUpdatedAt());
} else {
comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt());
}
break;
case "assignee":
case "as":
comparator = (a, b) -> {
Optional<String> aAssignee = a.getAssignee();
Optional<String> bAssignee = b.getAssignee();
if (!aAssignee.isPresent() && !bAssignee.isPresent()) {
return 0;
} else if (!aAssignee.isPresent()) {
return 1;
} else if (!bAssignee.isPresent()) {
return -1;
} else {
return aAssignee.get().compareTo(bAssignee.get());
}
};
break;
case "milestone":
case "m":
comparator = (a, b) -> {
Optional<TurboMilestone> aMilestone = model.getMilestoneOfIssue(a);
Optional<TurboMilestone> bMilestone = model.getMilestoneOfIssue(b);
if (!aMilestone.isPresent() && !bMilestone.isPresent()) {
return 0;
} else if (!aMilestone.isPresent()) {
return 1;
} else if (!bMilestone.isPresent()) {
return -1;
} else {
Optional<LocalDate> aDueDate = aMilestone.get().getDueDate();
Optional<LocalDate> bDueDate = bMilestone.get().getDueDate();
if (!aDueDate.isPresent() && !bDueDate.isPresent()) {
return 0;
} else if (!aDueDate.isPresent()) {
return 1;
} else if (!bDueDate.isPresent()) {
return -1;
} else {
return -(getMilestoneDueDateComparator()
.compare(aMilestone.get(), bMilestone.get()));
}
}
};
break;
case "id":
comparator = (a, b) -> a.getId() - b.getId();
break;
case "state":
case "status":
case "s":
comparator = (a, b) -> Boolean.compare(b.isOpen(), a.isOpen());
break;
default:
// Doesn't match anything; assume it's a label group
isLabelGroup = true;
break;
}
if (isLabelGroup) {
// Has a different notion of inversion
return getLabelGroupComparator(model, key, inverted);
} else {
// Use default behaviour for inverting
if (!inverted) {
return comparator;
} else {
final Comparator<TurboIssue> finalComparator = comparator;
return (a, b) -> -finalComparator.compare(a, b);
}
}
}
public static Comparator<TurboIssue> getLabelGroupComparator(IModel model, String key, boolean inverted) {
// Strip trailing ., if any
final String group = key.replaceAll("\\.$", "");
return (a, b) -> {
// Matches labels belong to the given group
Predicate<TurboLabel> sameGroup = l ->
l.getGroup().isPresent() && l.getGroup().get().equals(group);
Comparator<TurboLabel> labelComparator = (x, y) -> x.getName().compareTo(y.getName());
List<TurboLabel> aLabels = model.getLabelsOfIssue(a, sameGroup);
List<TurboLabel> bLabels = model.getLabelsOfIssue(b, sameGroup);
Collections.sort(aLabels, labelComparator);
Collections.sort(bLabels, labelComparator);
// Put empty lists at the back
if (aLabels.isEmpty() && bLabels.isEmpty()) {
return 0;
} else if (aLabels.isEmpty()) {
// a is larger
return 1;
} else if (bLabels.isEmpty()) {
// b is larger
return -1;
}
// Compare lengths
int result = !inverted
? aLabels.size() - bLabels.size()
: bLabels.size() - aLabels.size();
if (result != 0) {
return result;
}
// Lexicographic label comparison
assert aLabels.size() == bLabels.size();
for (int i = 0; i < aLabels.size(); i++) {
result = !inverted
? labelComparator.compare(aLabels.get(i), bLabels.get(i))
: labelComparator.compare(bLabels.get(i), aLabels.get(i));
if (result != 0) {
return result;
}
}
return 0;
};
}
private boolean idSatisfies(TurboIssue issue) {
if (number.isPresent()) {
return issue.getId() == number.get();
} else if (numberRange.isPresent()) {
return numberRange.get().encloses(issue.getId());
}
return false;
}
private boolean satisfiesUpdatedHours(TurboIssue issue) {
NumberRange updatedRange;
if (numberRange.isPresent()) {
updatedRange = numberRange.get();
} else if (number.isPresent()) {
updatedRange = new NumberRange(null, number.get(), true);
} else {
return false;
}
LocalDateTime dateOfUpdate = issue.getUpdatedAt();
int hoursSinceUpdate = Utility.safeLongToInt(dateOfUpdate.until(getCurrentTime(), ChronoUnit.HOURS));
return updatedRange.encloses(hoursSinceUpdate);
}
private boolean satisfiesRepo(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getRepoId().equalsIgnoreCase(content.get());
}
private boolean satisfiesCreationDate(TurboIssue issue) {
LocalDate creationDate = issue.getCreatedAt().toLocalDate();
if (date.isPresent()) {
return creationDate.isEqual(date.get());
} else if (dateRange.isPresent()) {
return dateRange.get().encloses(creationDate);
} else {
return false;
}
}
private boolean satisfiesHasConditions(TurboIssue issue) {
if (!content.isPresent()) return false;
switch (content.get()) {
case "label":
case "labels":
return issue.getLabels().size() > 0;
case "milestone":
case "milestones":
case "m":
assert issue.getMilestone() != null;
return issue.getMilestone().isPresent();
case "assignee":
case "assignees":
case "as":
assert issue.getAssignee() != null;
return issue.getAssignee().isPresent();
default:
return false;
}
}
private boolean satisfiesNoConditions(TurboIssue issue) {
return content.isPresent() && !satisfiesHasConditions(issue);
}
private boolean satisfiesIsConditions(TurboIssue issue) {
if (!content.isPresent()) return false;
switch (content.get()) {
case "open":
case "closed":
return stateSatisfies(issue);
case "pr":
case "issue":
return typeSatisfies(issue);
case "merged":
return issue.isPullRequest() && !issue.isOpen();
case "unmerged":
return issue.isPullRequest() && issue.isOpen();
case "read":
return issue.isCurrentlyRead();
case "unread":
return !issue.isCurrentlyRead();
default:
return false;
}
}
private boolean stateSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String content = this.content.get().toLowerCase();
if (content.contains("open")) {
return issue.isOpen();
} else if (content.contains("closed")) {
return !issue.isOpen();
} else {
return false;
}
}
private boolean assigneeSatisfies(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
Optional<TurboUser> assignee = model.getAssigneeOfIssue(issue);
if (!assignee.isPresent()) return false;
String content = this.content.get().toLowerCase();
String login = assignee.get().getLoginName() == null ? "" : assignee.get().getLoginName().toLowerCase();
String name = assignee.get().getRealName() == null ? "" : assignee.get().getRealName().toLowerCase();
return login.contains(content) || name.contains(content);
}
private boolean authorSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String creator = issue.getCreator();
return creator.toLowerCase().contains(content.get().toLowerCase());
}
private boolean involvesSatisfies(IModel model, TurboIssue issue) {
return authorSatisfies(issue) || assigneeSatisfies(model, issue);
}
public static boolean labelMatches(String input, String candidate) {
// Make use of TurboLabel constructor to parse the input, avoiding duplication
TurboLabel inputLabel = new TurboLabel("", input.toLowerCase());
TurboLabel candidateLabel = new TurboLabel("", candidate.toLowerCase());
String group = "";
if (inputLabel.hasGroup()) {
group = inputLabel.getGroup().get();
}
String labelName = inputLabel.getName();
if (candidateLabel.hasGroup()) {
if (labelName.isEmpty()) {
// Check the group
if (candidateLabel.getGroup().get().contains(group)) {
return true;
}
} else {
if (candidateLabel.getGroup().get().contains(group)
&& candidateLabel.getName().contains(labelName)) {
return true;
}
}
} else {
// Check only the label name
if (group.isEmpty() && !labelName.isEmpty() && candidateLabel.getName().contains(labelName)) {
return true;
}
}
return false;
}
private boolean labelsSatisfy(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
// A qualifier matches an issue if the issue is associated with some subset of the
// labels that the qualifier expresses. It should only reject an issue if the issue
// does not contain any labels it expresses, and not if the issue contains some label
// it does not express.
for (TurboLabel label : model.getLabelsOfIssue(issue)) {
if (labelMatches(content.get(), label.getActualName())) {
return true;
}
}
return false;
}
private boolean milestoneSatisfies(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
Optional<TurboMilestone> milestone = model.getMilestoneOfIssue(issue);
if (!milestone.isPresent()) return false;
String contents = content.get().toLowerCase();
String title = milestone.get().getTitle().toLowerCase();
return title.contains(contents);
}
private boolean keywordSatisfies(TurboIssue issue, MetaQualifierInfo info) {
if (info.getIn().isPresent()) {
switch (info.getIn().get()) {
case "title":
return titleSatisfies(issue);
case "body":
case "desc":
case "description":
return bodySatisfies(issue);
default:
return false;
}
} else {
return titleSatisfies(issue) || bodySatisfies(issue);
}
}
private boolean bodySatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getDescription().toLowerCase().contains(content.get().toLowerCase());
}
private boolean titleSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getTitle().toLowerCase().contains(content.get().toLowerCase());
}
private boolean typeSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String content = this.content.get().toLowerCase();
switch (content) {
case "issue":
return !issue.isPullRequest();
case "pr":
case "pullrequest":
return issue.isPullRequest();
default:
return false;
}
}
private void applyMilestone(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Name of milestone to apply required");
}
// Find milestones containing partial title
List<TurboMilestone> milestones = model.getMilestones().stream()
.filter(m -> m.getTitle().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (milestones.isEmpty()) {
throw new QualifierApplicationException("Invalid milestone " + content.get());
} else if (milestones.size() == 1) {
issue.setMilestone(milestones.get(0));
return;
}
// Find milestones containing exact title
milestones = model.getMilestones().stream()
.filter(m -> m.getTitle().toLowerCase().equals(content.get().toLowerCase()))
.collect(Collectors.toList());
if (milestones.isEmpty()) {
throw new QualifierApplicationException("Invalid milestone " + content.get());
} else if (milestones.size() == 1) {
issue.setMilestone(milestones.get(0));
return;
}
throw new QualifierApplicationException(
"Ambiguous filter: can apply any of the following milestones: " + milestones.toString());
}
private void applyLabel(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Name of label to apply required");
}
// Find labels containing the label name
List<TurboLabel> labels = model.getLabels().stream()
.filter(l -> l.getActualName().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (labels.isEmpty()) {
throw new QualifierApplicationException("Invalid label " + content.get());
} else if (labels.size() == 1) {
issue.addLabel(labels.get(0));
return;
}
// Find labels with the exact label name
labels = model.getLabels().stream()
.filter(l -> l.getActualName().toLowerCase().equals(content.get().toLowerCase()))
.collect(Collectors.toList());
if (labels.isEmpty()) {
throw new QualifierApplicationException("Invalid label " + content.get());
} else if (labels.size() == 1) {
issue.addLabel(labels.get(0));
return;
}
throw new QualifierApplicationException(
"Ambiguous filter: can apply any of the following labels: " + labels.toString());
}
private void applyAssignee(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Name of assignee to apply required");
}
// Find assignees containing partial name
List<TurboUser> assignees = model.getUsers().stream()
.filter(c -> c.getLoginName().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (assignees.isEmpty()) {
throw new QualifierApplicationException("Invalid user " + content.get());
} else if (assignees.size() == 1) {
issue.setAssignee(assignees.get(0));
return;
}
// Find assignees containing partial name
assignees = model.getUsers().stream()
.filter(c -> c.getLoginName().toLowerCase().equals(content.get().toLowerCase()))
.collect(Collectors.toList());
if (assignees.isEmpty()) {
throw new QualifierApplicationException("Invalid user " + content.get());
} else if (assignees.size() == 1) {
issue.setAssignee(assignees.get(0));
return;
}
throw new QualifierApplicationException(
"Ambiguous filter: can apply any of the following assignees: " + assignees.toString());
}
private void applyState(TurboIssue issue) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("State to apply required");
}
if (content.get().toLowerCase().contains("open")) {
issue.setOpen(true);
} else if (content.get().toLowerCase().contains("closed")) {
issue.setOpen(false);
} else {
throw new QualifierApplicationException("Invalid state " + content.get());
}
}
public Optional<Integer> getNumber() {
return number;
}
public Optional<NumberRange> getNumberRange() {
return numberRange;
}
public Optional<DateRange> getDateRange() {
return dateRange;
}
public Optional<String> getContent() {
return content;
}
public Optional<LocalDate> getDate() {
return date;
}
public QualifierType getType() {
return type;
}
private Qualifier convertMilestoneAliasQualifier(List<TurboMilestone> allMilestones, int currentIndex) {
if (!content.isPresent()) {
return Qualifier.EMPTY;
}
String contents = content.get();
String alias = contents;
Pattern aliasPattern = Pattern.compile("(curr(?:ent)?)(?:(\\+|-)(\\d+))?$");
Matcher aliasMatcher = aliasPattern.matcher(alias);
if (!aliasMatcher.find()) {
return this;
}
int offset;
int newIndex = currentIndex;
if (aliasMatcher.group(2) != null && aliasMatcher.group(3) != null) {
offset = Integer.parseInt(aliasMatcher.group(3));
if (aliasMatcher.group(2).equals("+")) {
newIndex += offset;
} else {
newIndex -= offset;
}
}
// if out of milestone range, don't convert alias
if (newIndex >= allMilestones.size() || newIndex < 0) {
return Qualifier.FALSE;
}
contents = allMilestones.get(newIndex).getTitle().toLowerCase();
return new Qualifier(type, contents);
}
/**
* Condition: milestone must have due dates
*/
public static Comparator<TurboMilestone> getMilestoneDueDateComparator() {
return (a, b) -> {
assert a.getDueDate().isPresent();
assert b.getDueDate().isPresent();
LocalDate aDueDate = a.getDueDate().get();
LocalDate bDueDate = b.getDueDate().get();
return aDueDate.compareTo(bDueDate);
};
}
/**
* Determines the count value to be taken from the count qualifier. Throw a ParseException if count
* qualifier is not valid.
*
* @param issueList Issue list obtained after filtering and sorting.
* @param filterExpr The filter expression of the particular panel.
* @return The valid count value in the qualifier or the issueList.size() by default
*/
public static int determineCount(List<TurboIssue> issueList, FilterExpression filterExpr) {
List<Qualifier> countQualifiers = filterExpr.find(Qualifier::isMetaQualifier).stream()
.filter(q -> q.getType() == QualifierType.COUNT)
.collect(Collectors.toList());
if (countQualifiers.isEmpty()) {
return issueList.size();
} else if (countQualifiers.size() > 1) {
throw new ParseException("More than one count qualifier");
} else if (!countQualifiers.get(0).getNumber().isPresent()) {
throw new ParseException("Count qualifier should be a number greater than or equal to 0");
} else {
return countQualifiers.get(0).getNumber().get();
}
}
} |
package org.cache2k.impl;
import org.cache2k.BulkCacheSource;
import org.cache2k.CacheEntry;
import org.cache2k.CacheEntryProcessingException;
import org.cache2k.CacheEntryProcessor;
import org.cache2k.CacheException;
import org.cache2k.CacheManager;
import org.cache2k.CacheMisconfigurationException;
import org.cache2k.CacheWriter;
import org.cache2k.ClosableIterator;
import org.cache2k.EntryExpiryCalculator;
import org.cache2k.EntryProcessingResult;
import org.cache2k.ExceptionExpiryCalculator;
import org.cache2k.ExceptionPropagator;
import org.cache2k.ExperimentalBulkCacheSource;
import org.cache2k.Cache;
import org.cache2k.CacheConfig;
import org.cache2k.FetchCompletedListener;
import org.cache2k.RefreshController;
import org.cache2k.StorageConfiguration;
import org.cache2k.ValueWithExpiryTime;
import org.cache2k.impl.threading.Futures;
import org.cache2k.impl.threading.LimitedPooledExecutor;
import org.cache2k.impl.timer.GlobalTimerService;
import org.cache2k.impl.timer.TimerService;
import org.cache2k.impl.util.ThreadDump;
import org.cache2k.CacheSourceWithMetaInfo;
import org.cache2k.CacheSource;
import org.cache2k.PropagatedCacheException;
import org.cache2k.storage.PurgeableStorage;
import org.cache2k.storage.StorageEntry;
import org.cache2k.impl.util.Log;
import org.cache2k.impl.util.TunableConstants;
import org.cache2k.impl.util.TunableFactory;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.security.SecureRandom;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.cache2k.impl.util.Util.*;
/**
* Foundation for all cache variants. All common functionality is in here.
* For a (in-memory) cache we need three things: a fast hash table implementation, an
* LRU list (a simple double linked list), and a fast timer.
* The variants implement different eviction strategies.
*
* <p>Locking: The cache has a single structure lock obtained via {@link #lock} and also
* locks on each entry for operations on it. Though, mutation operations that happen on a
* single entry get serialized.
*
* @author Jens Wilke; created: 2013-07-09
*/
@SuppressWarnings({"unchecked", "SynchronizationOnLocalVariableOrMethodParameter"})
public abstract class BaseCache<E extends Entry, K, T>
implements Cache<K, T>, CanCheckIntegrity, Iterable<CacheEntry<K, T>>, StorageAdapter.Parent {
static final Random SEED_RANDOM = new Random(new SecureRandom().nextLong());
static int cacheCnt = 0;
protected static final Tunable TUNABLE = TunableFactory.get(Tunable.class);
/**
* Instance of expiry calculator that extracts the expiry time from the value.
*/
final static EntryExpiryCalculator<?, ValueWithExpiryTime> ENTRY_EXPIRY_CALCULATOR_FROM_VALUE = new
EntryExpiryCalculator<Object, ValueWithExpiryTime>() {
@Override
public long calculateExpiryTime(
Object _key, ValueWithExpiryTime _value, long _fetchTime,
CacheEntry<Object, ValueWithExpiryTime> _oldEntry) {
return _value.getCacheExpiryTime();
}
};
final static ExceptionPropagator DEFAULT_EXCEPTION_PROPAGATOR = new ExceptionPropagator() {
@Override
public void propagateException(String _additionalMessage, Throwable _originalException) {
throw new PropagatedCacheException(_additionalMessage, _originalException);
}
};
protected int hashSeed;
{
if (TUNABLE.disableHashRandomization) {
hashSeed = TUNABLE.hashSeed;
} else {
hashSeed = SEED_RANDOM.nextInt();
}
}
/** Maximum amount of elements in cache */
protected int maxSize = 5000;
protected String name;
protected CacheManagerImpl manager;
protected CacheSourceWithMetaInfo<K, T> source;
/** Statistics */
/** Time in milliseconds we keep an element */
protected long maxLinger = 10 * 60 * 1000;
protected long exceptionMaxLinger = 1 * 60 * 1000;
protected EntryExpiryCalculator<K, T> entryExpiryCalculator;
protected ExceptionExpiryCalculator<K> exceptionExpiryCalculator;
protected Info info;
protected long clearedTime = 0;
protected long startedTime;
protected long touchedTime;
protected int timerCancelCount = 0;
protected long keyMutationCount = 0;
protected long putCnt = 0;
protected long putButExpiredCnt = 0;
protected long putNewEntryCnt = 0;
protected long removedCnt = 0;
/** Number of entries removed by clear. */
protected long clearedCnt = 0;
protected long expiredKeptCnt = 0;
protected long expiredRemoveCnt = 0;
protected long evictedCnt = 0;
protected long refreshCnt = 0;
protected long suppressedExceptionCnt = 0;
protected long fetchExceptionCnt = 0;
/* that is a miss, but a hit was already counted. */
protected long peekHitNotFreshCnt = 0;
/* no heap hash hit */
protected long peekMissCnt = 0;
protected long fetchCnt = 0;
protected long fetchButHitCnt = 0;
protected long bulkGetCnt = 0;
protected long fetchMillis = 0;
protected long refreshHitCnt = 0;
protected long newEntryCnt = 0;
/**
* Entries created for processing via invoke, but no operation happened on it.
*/
protected long invokeNewEntryCnt = 0;
/**
* Loaded from storage, but the entry was not fresh and cannot be returned.
*/
protected long loadNonFreshCnt = 0;
/**
* Entry was loaded from storage and fresh.
*/
protected long loadHitCnt = 0;
/**
* Separate counter for loaded entries that needed a fetch.
*/
protected long loadNonFreshAndFetchedCnt;
protected long refreshSubmitFailedCnt = 0;
/**
* An exception that should not have happened and was not thrown to the
* application. Only used for the refresh thread yet.
*/
protected long internalExceptionCnt = 0;
/**
* Needed to correct the counter invariants, because during eviction the entry
* might be removed from the replacement list, but still in the hash.
*/
protected int evictedButInHashCnt = 0;
/**
* Storage did not contain the requested entry.
*/
protected long loadMissCnt = 0;
/**
* A newly inserted entry was removed by the eviction without the fetch to complete.
*/
protected long virginEvictCnt = 0;
protected int maximumBulkFetchSize = 100;
/**
* Structure lock of the cache. Every operation that needs a consistent structure
* of the cache or modifies it needs to synchronize on this. Since this is a global
* lock, locking on it should be avoided and any operation under the lock should be
* quick.
*/
protected final Object lock = new Object();
protected CacheRefreshThreadPool refreshPool;
protected Hash<E> mainHashCtrl;
protected E[] mainHash;
protected Hash<E> refreshHashCtrl;
protected E[] refreshHash;
protected ExperimentalBulkCacheSource<K, T> experimentalBulkCacheSource;
protected BulkCacheSource<K, T> bulkCacheSource;
protected Timer timer;
/** Stuff that we need to wait for before shutdown may complete */
protected Futures.WaitForAllFuture<?> shutdownWaitFuture;
protected boolean shutdownInitiated = false;
/**
* Flag during operation that indicates, that the cache is full and eviction needs
* to be done. Eviction is only allowed to happen after an entry is fetched, so
* at the end of an cache operation that increased the entry count we check whether
* something needs to be evicted.
*/
protected boolean evictionNeeded = false;
protected Class keyType;
protected Class valueType;
protected CacheWriter<K, T> writer;
protected ExceptionPropagator exceptionPropagator = DEFAULT_EXCEPTION_PROPAGATOR;
protected StorageAdapter storage;
protected TimerService timerService = GlobalTimerService.getInstance();
/**
* Stops creation of new entries when clear is ongoing.
*/
protected boolean waitForClear = false;
private int featureBits = 0;
private static final int SHARP_TIMEOUT_FEATURE = 1;
private static final int KEEP_AFTER_EXPIRED = 2;
private static final int SUPPRESS_EXCEPTIONS = 4;
private static final int NULL_VALUE_SUPPORT = 8;
protected final boolean hasSharpTimeout() {
return (featureBits & SHARP_TIMEOUT_FEATURE) > 0;
}
protected final boolean hasKeepAfterExpired() {
return (featureBits & KEEP_AFTER_EXPIRED) > 0;
}
protected final boolean hasNullValueSupport() {
return (featureBits & NULL_VALUE_SUPPORT) > 0;
}
protected final boolean hasSuppressExceptions() {
return (featureBits & SUPPRESS_EXCEPTIONS) > 0;
}
protected final void setFeatureBit(int _bitmask, boolean _flag) {
if (_flag) {
featureBits |= _bitmask;
} else {
featureBits &= ~_bitmask;
}
}
/**
* Enabling background refresh means also serving expired values.
*/
protected final boolean hasBackgroundRefreshAndServesExpiredValues() {
return refreshPool != null;
}
/**
* Returns name of the cache with manager name.
*/
protected String getCompleteName() {
if (manager != null) {
return manager.getName() + ":" + name;
}
return name;
}
/**
* Normally a cache itself logs nothing, so just construct when needed.
*/
protected Log getLog() {
return
Log.getLog(Cache.class.getName() + '/' + getCompleteName());
}
@Override
public void resetStorage(StorageAdapter _from, StorageAdapter to) {
synchronized (lock) {
storage = to;
}
}
/** called via reflection from CacheBuilder */
public void setCacheConfig(CacheConfig c) {
valueType = c.getValueType();
keyType = c.getKeyType();
if (name != null) {
throw new IllegalStateException("already configured");
}
setName(c.getName());
maxSize = c.getMaxSize();
if (c.getHeapEntryCapacity() >= 0) {
maxSize = c.getHeapEntryCapacity();
}
if (c.isBackgroundRefresh()) {
refreshPool = CacheRefreshThreadPool.getInstance();
}
long _expiryMillis = c.getExpiryMillis();
if (_expiryMillis == Long.MAX_VALUE || _expiryMillis < 0) {
maxLinger = -1;
} else if (_expiryMillis >= 0) {
maxLinger = _expiryMillis;
}
long _exceptionExpiryMillis = c.getExceptionExpiryMillis();
if (_exceptionExpiryMillis == -1) {
if (maxLinger == -1) {
exceptionMaxLinger = -1;
} else {
exceptionMaxLinger = maxLinger / 10;
}
} else {
exceptionMaxLinger = _exceptionExpiryMillis;
}
setFeatureBit(KEEP_AFTER_EXPIRED, c.isKeepDataAfterExpired());
setFeatureBit(SHARP_TIMEOUT_FEATURE, c.isSharpExpiry());
setFeatureBit(SUPPRESS_EXCEPTIONS, c.isSuppressExceptions());
/*
if (c.isPersistent()) {
storage = new PassingStorageAdapter();
}
-*/
List<StorageConfiguration> _stores = c.getStorageModules();
if (_stores.size() == 1) {
StorageConfiguration cfg = _stores.get(0);
if (cfg.getEntryCapacity() < 0) {
cfg.setEntryCapacity(c.getMaxSize());
}
storage = new PassingStorageAdapter(this, c, _stores.get(0));
} else if (_stores.size() > 1) {
throw new UnsupportedOperationException("no aggregation support yet");
}
if (ValueWithExpiryTime.class.isAssignableFrom(c.getValueType()) &&
entryExpiryCalculator == null) {
entryExpiryCalculator =
(EntryExpiryCalculator<K, T>)
ENTRY_EXPIRY_CALCULATOR_FROM_VALUE;
}
}
public void setEntryExpiryCalculator(EntryExpiryCalculator<K, T> v) {
entryExpiryCalculator = v;
}
public void setExceptionExpiryCalculator(ExceptionExpiryCalculator<K> v) {
exceptionExpiryCalculator = v;
}
/** called via reflection from CacheBuilder */
public void setRefreshController(final RefreshController<T> lc) {
entryExpiryCalculator = new EntryExpiryCalculator<K, T>() {
@Override
public long calculateExpiryTime(K _key, T _value, long _fetchTime, CacheEntry<K, T> _oldEntry) {
if (_oldEntry != null) {
return lc.calculateNextRefreshTime(_oldEntry.getValue(), _value, _oldEntry.getLastModification(), _fetchTime);
} else {
return lc.calculateNextRefreshTime(null, _value, 0L, _fetchTime);
}
}
};
}
public void setExceptionPropagator(ExceptionPropagator ep) {
exceptionPropagator = ep;
}
@SuppressWarnings("unused")
public void setSource(CacheSourceWithMetaInfo<K, T> eg) {
source = eg;
}
public void setWriter(CacheWriter<K, T> w) {
writer = w;
}
@SuppressWarnings("unused")
public void setSource(final CacheSource<K, T> g) {
if (g != null) {
source = new CacheSourceWithMetaInfo<K, T>() {
@Override
public T get(K key, long _currentTime, T _previousValue, long _timeLastFetched) throws Throwable {
return g.get(key);
}
};
}
}
@SuppressWarnings("unused")
public void setExperimentalBulkCacheSource(ExperimentalBulkCacheSource<K, T> g) {
experimentalBulkCacheSource = g;
if (source == null) {
source = new CacheSourceWithMetaInfo<K, T>() {
@Override
public T get(K key, long _currentTime, T _previousValue, long _timeLastFetched) throws Throwable {
K[] ka = (K[]) Array.newInstance(keyType, 1);
ka[0] = key;
T[] ra = (T[]) Array.newInstance(valueType, 1);
BitSet _fetched = new BitSet(1);
experimentalBulkCacheSource.getBulk(ka, ra, _fetched, 0, 1);
return ra[0];
}
};
}
}
public void setBulkCacheSource(BulkCacheSource<K, T> s) {
bulkCacheSource = s;
if (source == null) {
source = new CacheSourceWithMetaInfo<K, T>() {
@Override
public T get(final K key, final long _currentTime, final T _previousValue, final long _timeLastFetched) throws Throwable {
final CacheEntry<K, T> entry = new CacheEntry<K, T>() {
@Override
public K getKey() {
return key;
}
@Override
public T getValue() {
return _previousValue;
}
@Override
public Throwable getException() {
return null;
}
@Override
public long getLastModification() {
return _timeLastFetched;
}
};
List<CacheEntry<K, T>> _entryList = new AbstractList<CacheEntry<K, T>>() {
@Override
public CacheEntry<K, T> get(int index) {
return entry;
}
@Override
public int size() {
return 1;
}
};
return bulkCacheSource.getValues(_entryList, _currentTime).get(0);
}
};
}
}
/**
* Set the name and configure a logging, used within cache construction.
*/
public void setName(String n) {
if (n == null) {
n = this.getClass().getSimpleName() + "#" + cacheCnt++;
}
name = n;
}
/**
* Set the time in seconds after which the cache does an refresh of the
* element. -1 means the element will be hold forever.
* 0 means the element will not be cached at all.
*/
public void setExpirySeconds(int s) {
if (s < 0 || s == Integer.MAX_VALUE) {
maxLinger = -1;
return;
}
maxLinger = s * 1000;
}
public String getName() {
return name;
}
public void setCacheManager(CacheManagerImpl cm) {
manager = cm;
}
public StorageAdapter getStorage() { return storage; }
public Class<?> getKeyType() { return keyType; }
public Class<?> getValueType() { return valueType; }
/**
* Registers the cache in a global set for the clearAllCaches function and
* registers it with the resource monitor.
*/
public void init() {
synchronized (lock) {
if (name == null) {
name = "" + cacheCnt++;
}
if (storage == null && maxSize == 0) {
throw new IllegalArgumentException("maxElements must be >0");
}
if (storage != null) {
bulkCacheSource = null;
storage.open();
}
initializeHeapCache();
initTimer();
if (refreshPool != null &&
source == null) {
throw new CacheMisconfigurationException("backgroundRefresh, but no source");
}
if (refreshPool != null && timer == null) {
if (maxLinger == 0) {
getLog().warn("Background refresh is enabled, but elements are fetched always. Disable background refresh!");
} else {
getLog().warn("Background refresh is enabled, but elements are eternal. Disable background refresh!");
}
refreshPool.destroy();
refreshPool = null;
}
}
}
boolean isNeedingTimer() {
return
maxLinger > 0 || entryExpiryCalculator != null ||
exceptionMaxLinger > 0 || exceptionExpiryCalculator != null;
}
/**
* Either add a timer or remove the timer if needed or not needed.
*/
private void initTimer() {
if (isNeedingTimer()) {
if (timer == null) {
timer = new Timer(name, true);
}
} else {
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
/**
* Clear may be called during operation, e.g. to reset all the cache content. We must make sure
* that there is no ongoing operation when we send the clear to the storage. That is because the
* storage implementation has a guarantee that there is only one storage operation ongoing for
* one entry or key at any time. Clear, of course, affects all entries.
*/
private void processClearWithStorage() {
StorageClearTask t = new StorageClearTask();
boolean _untouchedHeapCache;
synchronized (lock) {
checkClosed();
waitForClear = true;
_untouchedHeapCache = touchedTime == clearedTime && getLocalSize() == 0;
if (!storage.checkStorageStillDisconnectedForClear()) {
t.allLocalEntries = iterateAllHeapEntries();
t.allLocalEntries.setStopOnClear(false);
}
t.storage = storage;
t.storage.disconnectStorageForClear();
}
try {
if (_untouchedHeapCache) {
FutureTask<Void> f = new FutureTask<Void>(t);
updateShutdownWaitFuture(f);
f.run();
} else {
updateShutdownWaitFuture(manager.getThreadPool().execute(t));
}
} catch (Exception ex) {
throw new CacheStorageException(ex);
}
synchronized (lock) {
if (isClosed()) { throw new CacheClosedException(); }
clearLocalCache();
waitForClear = false;
lock.notifyAll();
}
}
protected void updateShutdownWaitFuture(Future<?> f) {
synchronized (lock) {
if (shutdownWaitFuture == null || shutdownWaitFuture.isDone()) {
shutdownWaitFuture = new Futures.WaitForAllFuture(f);
} else {
shutdownWaitFuture.add((Future) f);
}
}
}
class StorageClearTask implements LimitedPooledExecutor.NeverRunInCallingTask<Void> {
ClosableConcurrentHashEntryIterator<Entry> allLocalEntries;
StorageAdapter storage;
@Override
public Void call() {
try {
if (allLocalEntries != null) {
waitForEntryOperations();
}
storage.clearAndReconnect();
storage = null;
return null;
} catch (Throwable t) {
if (allLocalEntries != null) {
allLocalEntries.close();
}
getLog().warn("clear exception, when signalling storage", t);
storage.disable(t);
throw new CacheStorageException(t);
}
}
private void waitForEntryOperations() {
Iterator<Entry> it = allLocalEntries;
while (it.hasNext()) {
Entry e = it.next();
synchronized (e) { }
}
}
}
protected void checkClosed() {
if (isClosed()) {
throw new CacheClosedException();
}
while (waitForClear) {
try {
lock.wait();
} catch (InterruptedException ignore) { }
}
}
public final void clear() {
if (storage != null) {
processClearWithStorage();
return;
}
synchronized (lock) {
checkClosed();
clearLocalCache();
}
}
protected final void clearLocalCache() {
iterateAllEntriesRemoveAndCancelTimer();
clearedCnt += getLocalSize();
initializeHeapCache();
clearedTime = System.currentTimeMillis();
touchedTime = clearedTime;
}
protected void iterateAllEntriesRemoveAndCancelTimer() {
Iterator<Entry> it = iterateAllHeapEntries();
int _count = 0;
while (it.hasNext()) {
Entry e = it.next();
e.removedFromList();
cancelExpiryTimer(e);
_count++;
}
}
protected void initializeHeapCache() {
if (mainHashCtrl != null) {
mainHashCtrl.cleared();
refreshHashCtrl.cleared();
}
mainHashCtrl = new Hash<E>();
refreshHashCtrl = new Hash<E>();
mainHash = mainHashCtrl.init((Class<E>) newEntry().getClass());
refreshHash = refreshHashCtrl.init((Class<E>) newEntry().getClass());
if (startedTime == 0) {
startedTime = System.currentTimeMillis();
}
if (timer != null) {
timer.cancel();
timer = null;
initTimer();
}
}
public void clearTimingStatistics() {
synchronized (lock) {
fetchCnt = 0;
fetchMillis = 0;
}
}
/**
* Preparation for shutdown. Cancel all pending timer jobs e.g. for
* expiry/refresh or flushing the storage.
*/
Future<Void> cancelTimerJobs() {
synchronized (lock) {
if (timer != null) {
timer.cancel();
}
Future<Void> _waitFuture = new Futures.BusyWaitFuture<Void>() {
@Override
public boolean isDone() {
synchronized (lock) {
return getFetchesInFlight() == 0;
}
}
};
if (storage != null) {
Future<Void> f = storage.cancelTimerJobs();
if (f != null) {
_waitFuture = new Futures.WaitForAllFuture(_waitFuture, f);
}
}
return _waitFuture;
}
}
public void purge() {
if (storage != null) {
storage.purge();
}
}
public void flush() {
if (storage != null) {
storage.flush();
}
}
@Override
public boolean isClosed() {
return shutdownInitiated;
}
@Override
public void destroy() {
close();
}
@Override
public void close() {
synchronized (lock) {
if (shutdownInitiated) {
return;
}
shutdownInitiated = true;
}
Future<Void> _await = cancelTimerJobs();
try {
_await.get(TUNABLE.waitForTimerJobsSeconds, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
int _fetchesInFlight;
synchronized (lock) {
_fetchesInFlight = getFetchesInFlight();
}
if (_fetchesInFlight > 0) {
getLog().warn(
"Fetches still in progress after " +
TUNABLE.waitForTimerJobsSeconds + " seconds. " +
"fetchesInFlight=" + _fetchesInFlight);
} else {
getLog().warn(
"timeout waiting for timer jobs termination" +
" (" + TUNABLE.waitForTimerJobsSeconds + " seconds)", ex);
getLog().warn("Thread dump:\n" + ThreadDump.generateThredDump());
}
getLog().warn("State: " + toString());
} catch (Exception ex) {
getLog().warn("exception waiting for timer jobs termination", ex);
}
synchronized (lock) {
mainHashCtrl.close();
refreshHashCtrl.close();
}
try {
Future<?> _future = shutdownWaitFuture;
if (_future != null) {
_future.get();
}
} catch (Exception ex) {
throw new CacheException(ex);
}
Future<Void> _waitForStorage = null;
if (storage != null) {
_waitForStorage = storage.shutdown();
}
if (_waitForStorage != null) {
try {
_waitForStorage.get();
} catch (Exception ex) {
StorageAdapter.rethrow("shutdown", ex);
}
}
synchronized (lock) {
storage = null;
}
synchronized (lock) {
if (timer != null) {
timer.cancel();
timer = null;
}
if (refreshPool != null) {
refreshPool.destroy();
refreshPool = null;
}
mainHash = refreshHash = null;
source = null;
if (manager != null) {
manager.cacheDestroyed(this);
manager = null;
}
}
}
@Override
public void removeAll() {
ClosableIterator<E> it;
if (storage == null) {
synchronized (lock) {
it = new IteratorFilterFresh((ClosableIterator<E>) iterateAllHeapEntries());
}
} else {
it = (ClosableIterator<E>) storage.iterateAll();
}
while (it.hasNext()) {
E e = it.next();
remove((K) e.getKey());
}
}
@Override
public ClosableIterator<CacheEntry<K, T>> iterator() {
if (storage == null) {
synchronized (lock) {
return new IteratorFilterEntry2Entry((ClosableIterator<E>) iterateAllHeapEntries(), true);
}
} else {
return new IteratorFilterEntry2Entry((ClosableIterator<E>) storage.iterateAll(), false);
}
}
/**
* Filter out non valid entries and wrap each entry with a cache
* entry object.
*/
class IteratorFilterEntry2Entry implements ClosableIterator<CacheEntry<K, T>> {
ClosableIterator<E> iterator;
E entry;
CacheEntry<K, T> lastEntry;
boolean filter = true;
IteratorFilterEntry2Entry(ClosableIterator<E> it) { iterator = it; }
IteratorFilterEntry2Entry(ClosableIterator<E> it, boolean _filter) {
iterator = it;
filter = _filter;
}
/**
* Between hasNext() and next() an entry may be evicted or expired.
* In practise we have to deliver a next entry if we return hasNext() with
* true, furthermore, there should be no big gap between the calls to
* hasNext() and next().
*/
@Override
public boolean hasNext() {
if (entry != null) {
return true;
}
if (iterator == null) {
return false;
}
while (iterator.hasNext()) {
E e = iterator.next();
if (filter) {
if (e.hasFreshData()) {
entry = e;
return true;
}
} else {
entry = e;
return true;
}
}
entry = null;
close();
return false;
}
@Override
public void close() {
if (iterator != null) {
iterator.close();
iterator = null;
}
}
@Override
public CacheEntry<K, T> next() {
if (entry == null && !hasNext()) {
throw new NoSuchElementException("not available");
}
recordHitLocked(entry);
lastEntry = returnEntry(entry);
entry = null;
return lastEntry;
}
@Override
public void remove() {
if (lastEntry == null) {
throw new IllegalStateException("hasNext() / next() not called or end of iteration reached");
}
BaseCache.this.remove((K) lastEntry.getKey());
}
}
/**
* Filter out non valid entries and wrap each entry with a cache
* entry object.
*/
class IteratorFilterFresh implements ClosableIterator<E> {
ClosableIterator<E> iterator;
E entry;
CacheEntry<K, T> lastEntry;
boolean filter = true;
IteratorFilterFresh(ClosableIterator<E> it) { iterator = it; }
/**
* Between hasNext() and next() an entry may be evicted or expired.
* In practise we have to deliver a next entry if we return hasNext() with
* true, furthermore, there should be no big gap between the calls to
* hasNext() and next().
*/
@Override
public boolean hasNext() {
if (entry != null) {
return true;
}
if (iterator == null) {
return false;
}
while (iterator.hasNext()) {
E e = iterator.next();
if (e.hasFreshData()) {
entry = e;
return true;
}
}
entry = null;
close();
return false;
}
@Override
public void close() {
if (iterator != null) {
iterator.close();
iterator = null;
}
}
@Override
public E next() {
if (entry == null && !hasNext()) {
throw new NoSuchElementException("not available");
}
E tmp = entry;
entry = null;
return tmp;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
protected static void removeFromList(final Entry e) {
e.prev.next = e.next;
e.next.prev = e.prev;
e.removedFromList();
}
protected static void insertInList(final Entry _head, final Entry e) {
e.prev = _head;
e.next = _head.next;
e.next.prev = e;
_head.next = e;
}
protected static final int getListEntryCount(final Entry _head) {
Entry e = _head.next;
int cnt = 0;
while (e != _head) {
cnt++;
if (e == null) {
return -cnt;
}
e = e.next;
}
return cnt;
}
protected static final <E extends Entry> void moveToFront(final E _head, final E e) {
removeFromList(e);
insertInList(_head, e);
}
protected static final <E extends Entry> E insertIntoTailCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.next = _head;
e.prev = _head.prev;
_head.prev = e;
e.prev.next = e;
return _head;
}
/**
* Insert X into A B C, yields: A X B C.
*/
protected static final <E extends Entry> E insertAfterHeadCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.prev = _head;
e.next = _head.next;
_head.next.prev = e;
_head.next = e;
return _head;
}
/** Insert element at the head of the list */
protected static final <E extends Entry> E insertIntoHeadCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.next = _head;
e.prev = _head.prev;
_head.prev.next = e;
_head.prev = e;
return e;
}
protected static <E extends Entry> E removeFromCyclicList(final E _head, E e) {
if (e.next == e) {
e.removedFromList();
return null;
}
Entry _eNext = e.next;
e.prev.next = _eNext;
e.next.prev = e.prev;
e.removedFromList();
return e == _head ? (E) _eNext : _head;
}
protected static Entry removeFromCyclicList(final Entry e) {
Entry _eNext = e.next;
e.prev.next = _eNext;
e.next.prev = e.prev;
e.removedFromList();
return _eNext == e ? null : _eNext;
}
protected static int getCyclicListEntryCount(Entry e) {
if (e == null) { return 0; }
final Entry _head = e;
int cnt = 0;
do {
cnt++;
e = e.next;
if (e == null) {
return -cnt;
}
} while (e != _head);
return cnt;
}
protected static boolean checkCyclicListIntegrity(Entry e) {
if (e == null) { return true; }
Entry _head = e;
do {
if (e.next == null) {
return false;
}
if (e.next.prev == null) {
return false;
}
if (e.next.prev != e) {
return false;
}
e = e.next;
} while (e != _head);
return true;
}
/**
* Record an entry hit.
*/
protected abstract void recordHit(E e);
/**
* New cache entry, put it in the replacement algorithm structure
*/
protected abstract void insertIntoReplacementList(E e);
/**
* Entry object factory. Return an entry of the proper entry subtype for
* the replacement/eviction algorithm.
*/
protected abstract E newEntry();
/**
* Find an entry that should be evicted. Called within structure lock.
* After doing some checks the cache will call {@link #removeEntryFromReplacementList(Entry)}
* if this entry will be really evicted. Pinned entries may be skipped. A
* good eviction algorithm returns another candidate on sequential calls, even
* if the candidate was not removed.
*
* <p/>Rationale: Within the structure lock we can check for an eviction candidate
* and may remove it from the list. However, we cannot process additional operations or
* events which affect the entry. For this, we need to acquire the lock on the entry
* first.
*/
protected abstract E findEvictionCandidate();
protected void removeEntryFromReplacementList(E e) {
removeFromList(e);
}
/**
* Check whether we have an entry in the ghost table
* remove it from ghost and insert it into the replacement list.
* null if nothing there. This may also do an optional eviction
* if the size limit of the cache is reached, because some replacement
* algorithms (ARC) do this together.
*/
protected E checkForGhost(K key, int hc) { return null; }
/**
* Implement unsynchronized lookup if it is supported by the eviction.
* If a null is returned the lookup is redone synchronized.
*/
protected E lookupEntryUnsynchronized(K key, int hc) { return null; }
protected E lookupEntryUnsynchronizedNoHitRecord(K key, int hc) { return null; }
protected void recordHitLocked(E e) {
synchronized (lock) {
recordHit(e);
}
}
@Override
public T get(K key) {
return (T) returnValue(getEntryInternal(key));
}
/**
* Wrap entry in a separate object instance. We can return the entry directly, however we lock on
* the entry object.
*/
protected CacheEntry<K, T> returnEntry(final Entry<E, K, T> e) {
if (e == null) {
return null;
}
synchronized (e) {
final K _key = e.getKey();
final T _value = e.getValue();
final Throwable _exception = e.getException();
final long _lastModification = e.getLastModification();
return returnCacheEntry(_key, _value, _exception, _lastModification);
}
}
public String getEntryState(K key) {
E e = getEntryInternal(key);
return generateEntryStateString(e);
}
private String generateEntryStateString(E e) {
synchronized (e) {
String _timerState = "n/a";
if (e.task != null) {
_timerState = "<unavailable>";
try {
Field f = TimerTask.class.getDeclaredField("state");
f.setAccessible(true);
int _state = f.getInt(e.task);
_timerState = _state + "";
} catch (Exception x) {
_timerState = x.toString();
}
}
return
"Entry{" + System.identityHashCode(e) + "}, " +
"keyIdentityHashCode=" + System.identityHashCode(e.key) + ", " +
"valueIdentityHashCode=" + System.identityHashCode(e.value) + ", " +
"keyHashCode" + e.key.hashCode() + ", " +
"keyModifiedHashCode=" + e.hashCode + ", " +
"keyMutation=" + (modifiedHash(e.key.hashCode()) != e.hashCode) + ", " +
"modified=" + e.getLastModification() + ", " +
"nextRefreshTime(with state)=" + e.nextRefreshTime + ", " +
"hasTimer=" + (e.task != null ? "true" : "false") + ", " +
"timerState=" + _timerState;
}
}
private CacheEntry<K, T> returnCacheEntry(final K _key, final T _value, final Throwable _exception, final long _lastModification) {
CacheEntry<K, T> ce = new CacheEntry<K, T>() {
@Override
public K getKey() {
return _key;
}
@Override
public T getValue() {
return _value;
}
@Override
public Throwable getException() {
return _exception;
}
@Override
public long getLastModification() {
return _lastModification;
}
@Override
public String toString() {
return "CacheEntry(" +
"key=" + getKey() +
((getException() != null) ? ", exception=" + getException() + ", " : ", value=" + getValue()) +
", updated=" + formatMillis(getLastModification());
}
};
return ce;
}
@Override
public CacheEntry<K, T> getEntry(K key) {
return returnEntry(getEntryInternal(key));
}
protected E getEntryInternal(K key) {
long _previousNextRefreshTime;
E e;
for (;;) {
e = lookupOrNewEntrySynchronized(key);
if (e.hasFreshData()) {
return e;
}
synchronized (e) {
e.waitForFetch();
if (e.hasFreshData()) {
return e;
}
if (e.isRemovedState()) {
continue;
}
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
finishFetch(e, fetch(e, _previousNextRefreshTime));
_finished = true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
evictEventually();
return e;
}
protected void finishFetch(E e, long _nextRefreshTime) {
synchronized (e) {
e.nextRefreshTime = stopStartTimer(_nextRefreshTime, e, System.currentTimeMillis());
e.notifyAll();
}
}
/** Always fetch the value from the source. That is a copy of getEntryInternal without fresh checks. */
protected void fetchAndReplace(K key) {
long _previousNextRefreshTime;
E e;
for (;;) {
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
finishFetch(e, fetch(e, _previousNextRefreshTime));
_finished = true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
evictEventually();
}
/**
* Insert the storage entry in the heap cache and return it. Used when storage entries
* are queried. We need to check whether the entry is present meanwhile, get the entry lock
* and maybe fetch it from the source. Doubles with {@link #getEntryInternal(Object)}
* except we do not need to retrieve the data from the storage again.
*
* @param _needsFetch if true the entry is fetched from CacheSource when expired.
* @return a cache entry is always returned, however, it may be outdated
*/
protected Entry insertEntryFromStorage(StorageEntry se, boolean _needsFetch) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupOrNewEntrySynchronized((K) se.getKey());
if (e.hasFreshData()) { return e; }
synchronized (e) {
if (!e.isDataValidState()) {
if (e.isRemovedState()) {
continue;
}
if (e.isFetchInProgress()) {
e.waitForFetch();
return e.hasFreshData() ? e : null;
}
e.startFetch();
}
}
boolean _fresh;
boolean _finished = false;
try {
long _nextRefresh = insertEntryFromStorage(se, e, _needsFetch);
_fresh = e.hasFreshData(System.currentTimeMillis(), _nextRefresh);
finishFetch(e, _nextRefresh);
_finished = true;
} finally {
e.ensureFetchAbort(_finished);
}
evictEventually();
return _fresh ? e : null;
}
}
/**
* Insert a cache entry for the given key and run action under the entry
* lock. If the cache entry has fresh data, we do not run the action.
* Called from storage. The entry referenced by the key is expired and
* will be purged.
*/
protected void lockAndRunForPurge(Object key, PurgeableStorage.PurgeAction _action) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
boolean _virgin;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
e = lookupOrNewEntrySynchronized((K) key);
if (e.hasFreshData()) { return; }
synchronized (e) {
e.waitForFetch();
if (e.isDataValidState()) {
return;
}
if (e.isRemovedState()) {
continue;
}
_virgin = e.isVirgin();
e.startFetch();
break;
}
}
boolean _finished = false;
try {
StorageEntry se = _action.checkAndPurge(key);
synchronized (e) {
if (_virgin) {
finishFetch(e, Entry.VIRGIN_STATE);
evictEntryFromHeap(e);
} else {
finishFetch(e, Entry.LOADED_NON_VALID);
evictEntryFromHeap(e);
}
}
_finished = true;
} finally {
e.ensureFetchAbort(_finished);
}
}
protected final void evictEventually() {
int _spinCount = TUNABLE.maximumEvictSpins;
E _previousCandidate = null;
while (evictionNeeded) {
if (_spinCount-- <= 0) { return; }
E e;
synchronized (lock) {
checkClosed();
if (getLocalSize() <= maxSize) {
evictionNeeded = false;
return;
}
e = findEvictionCandidate();
}
boolean _shouldStore;
synchronized (e) {
if (e.isRemovedState()) {
continue;
}
if (e.isPinned()) {
if (e != _previousCandidate) {
_previousCandidate = e;
continue;
} else {
return;
}
}
boolean _storeEvenImmediatelyExpired = hasKeepAfterExpired() && (e.isDataValidState() || e.isExpiredState() || e.nextRefreshTime == Entry.FETCH_NEXT_TIME_STATE);
_shouldStore =
(storage != null) && (_storeEvenImmediatelyExpired || e.hasFreshData());
if (_shouldStore) {
e.startFetch();
} else {
evictEntryFromHeap(e);
}
}
if (_shouldStore) {
try {
storage.evict(e);
} finally {
synchronized (e) {
finishFetch(e, Entry.FETCH_ABORT);
evictEntryFromHeap(e);
}
}
}
}
}
private void evictEntryFromHeap(E e) {
synchronized (lock) {
if (e.isRemovedFromReplacementList()) {
if (removeEntryFromHash(e)) {
evictedButInHashCnt
evictedCnt++;
}
} else {
if (removeEntry(e)) {
evictedCnt++;
}
}
evictionNeeded = getLocalSize() > maxSize;
}
e.notifyAll();
}
/**
* Remove the entry from the hash and the replacement list.
* There is a race condition to catch: The eviction may run
* in a parallel thread and may have already selected this
* entry.
*/
protected boolean removeEntry(E e) {
if (!e.isRemovedFromReplacementList()) {
removeEntryFromReplacementList(e);
}
return removeEntryFromHash(e);
}
@Override
public T peekAndPut(K key, T _value) {
final int hc = modifiedHash(key.hashCode());
boolean _hasFreshData = false;
E e;
long _previousNextRefreshTime;
for (;;) {
e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_hasFreshData = e.hasFreshData();
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
T _previousValue = null;
if (storage != null && e.isVirgin()) {
long t = fetchWithStorage(e, false, _previousNextRefreshTime);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
}
if (_hasFreshData) {
_previousValue = (T) e.getValue();
recordHitLocked(e);
} else {
synchronized (lock) {
peekMissCnt++;
}
}
long t = System.currentTimeMillis();
finishFetch(e, insertOnPut(e, _value, t, t, _previousNextRefreshTime));
_finished = true;
return _previousValue;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
@Override
public T peekAndReplace(K key, T _value) {
final int hc = modifiedHash(key.hashCode());
boolean _hasFreshData = false;
boolean _newEntry = false;
E e;
long _previousNextRefreshTime;
for (;;) {
e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null && storage != null) {
e = newEntry(key, hc);
_newEntry = true;
}
}
}
if (e == null) {
synchronized (lock) {
peekMissCnt++;
}
return null;
}
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_hasFreshData = e.hasFreshData();
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
if (storage != null && e.isVirgin()) {
long t = fetchWithStorage(e, false, _previousNextRefreshTime);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
}
long t = System.currentTimeMillis();
if (_hasFreshData) {
recordHitLocked(e);
T _previousValue = (T) e.getValue();
finishFetch(e, insertOnPut(e, _value, t, t, _previousNextRefreshTime));
_finished = true;
return _previousValue;
} else {
synchronized (lock) {
if (_newEntry) {
putNewEntryCnt++;
}
peekMissCnt++;
}
finishFetch(e, Entry.LOADED_NON_VALID);
_finished = true;
return null;
}
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
@Override
public boolean replace(K key, T _newValue) {
return replace(key, false, null, _newValue) == null;
}
@Override
public boolean replace(K key, T _oldValue, T _newValue) {
return replace(key, true, _oldValue, _newValue) == null;
}
public CacheEntry<K, T> replaceOrGet(K key, T _oldValue, T _newValue, CacheEntry<K, T> _dummyEntry) {
E e = replace(key, true, _oldValue, _newValue);
if (e == DUMMY_ENTRY_NO_REPLACE) {
return _dummyEntry;
} else if (e != null) {
return returnEntry(e);
}
return null;
}
final Entry DUMMY_ENTRY_NO_REPLACE = new Entry();
/**
* replace if value matches. if value not matches, return the existing entry or the dummy entry.
*/
protected E replace(K key, boolean _compare, T _oldValue, T _newValue) {
final int hc = modifiedHash(key.hashCode());
long _previousNextRefreshTime;
if (storage == null) {
E e = lookupEntrySynchronized(key);
if (e == null) {
synchronized (lock) {
peekMissCnt++;
}
return (E) DUMMY_ENTRY_NO_REPLACE;
}
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState() || !e.hasFreshData()) {
return (E) DUMMY_ENTRY_NO_REPLACE;
}
if (_compare && !e.equalsValue(_oldValue)) {
return e;
}
_previousNextRefreshTime = e.startFetch();
}
boolean _finished = false;
recordHitLocked(e);
try {
long t = System.currentTimeMillis();
finishFetch(e, insertOnPut(e, _newValue, t, t, _previousNextRefreshTime));
_finished = true;
return null;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
boolean _hasFreshData = false;
E e;
for (;;) {
e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
if (!e.hasFreshData()) {
return (E) DUMMY_ENTRY_NO_REPLACE;
}
if (_compare && !e.equalsValue(_oldValue)) {
return e;
}
_previousNextRefreshTime = e.startFetch();
break;
}
}
boolean _finished = false;
try {
if (e.isVirgin()) {
long t = fetchWithStorage(e, false, _previousNextRefreshTime);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
if (!_hasFreshData) {
finishFetch(e, t);
_finished = true;
return (E) DUMMY_ENTRY_NO_REPLACE;
}
if (_compare && !e.equalsValue(_oldValue)) {
finishFetch(e, t);
_finished = true;
return e;
}
}
long t = System.currentTimeMillis();
finishFetch(e, insertOnPut(e, _newValue, t, t, _previousNextRefreshTime));
_finished = true;
return null;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
/**
* Return the entry, if it is in the cache, without invoking the
* cache source.
*
* <p>The cache storage is asked whether the entry is present.
* If the entry is not present, this result is cached in the local
* cache.
*/
final protected E peekEntryInternal(K key) {
final int hc = modifiedHash(key.hashCode());
long _previousNextRefreshTime;
int _spinCount = TUNABLE.maximumEntryLockSpins;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
if (e == null && storage != null) {
e = newEntry(key, hc);
}
}
}
if (e == null) {
peekMissCnt++;
return null;
}
if (e.hasFreshData()) { return e; }
boolean _hasFreshData = false;
if (storage != null) {
boolean _needsLoad;
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
if (e.hasFreshData()) {
return e;
}
_previousNextRefreshTime = e.nextRefreshTime;
_needsLoad = conditionallyStartProcess(e);
}
if (_needsLoad) {
boolean _finished = false;
try {
long t = fetchWithStorage(e, false, _previousNextRefreshTime);
finishFetch(e, t);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
_finished = true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
}
evictEventually();
if (_hasFreshData) {
return e;
}
peekHitNotFreshCnt++;
return null;
}
}
@Override
public boolean contains(K key) {
if (storage == null) {
E e = lookupEntrySynchronizedNoHitRecord(key);
return e != null && e.hasFreshData();
}
E e = peekEntryInternal(key);
if (e != null) {
return true;
}
return false;
}
@Override
public T peek(K key) {
E e = peekEntryInternal(key);
if (e != null) {
return (T) returnValue(e);
}
return null;
}
@Override
public CacheEntry<K, T> peekEntry(K key) {
return returnEntry(peekEntryInternal(key));
}
@Override
public boolean putIfAbsent(K key, T value) {
long _previousNextRefreshTime;
long now;
if (storage == null) {
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
for (;;) {
if (_spinCount
throw new CacheLockSpinsExceededError();
}
e = lookupOrNewEntrySynchronizedNoHitRecord(key);
synchronized (e) {
if (e.isRemovedState()) {
continue;
}
now = System.currentTimeMillis();
if (e.hasFreshData(now)) {
return false;
}
synchronized (lock) {
if (!e.isVirgin()) {
recordHit(e);
peekHitNotFreshCnt++;
}
}
_previousNextRefreshTime = e.startFetch();
}
boolean _finished = false;
try {
finishFetch(e, insertOnPut(e, value, now, now, _previousNextRefreshTime));
_finished = true;
return true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
}
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e; long t;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
t = System.currentTimeMillis();
if (e.hasFreshData(t)) {
return false;
}
_previousNextRefreshTime = e.startFetch();
break;
}
}
if (e.isVirgin()) {
long _result = _previousNextRefreshTime = fetchWithStorage(e, false, _previousNextRefreshTime);
now = System.currentTimeMillis();
if (e.hasFreshData(now, _result)) {
finishFetch(e, _result);
return false;
}
e.nextRefreshTime = Entry.LOADED_NON_VALID_AND_PUT;
}
boolean _finished = false;
try {
finishFetch(e, insertOnPut(e, value, t, t, _previousNextRefreshTime));
_finished = true;
evictEventually();
return true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
}
@Override
public void put(K key, T value) {
long _previousNextRefreshTime;
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
for (;;) {
if (_spinCount-- <= 0) { throw new CacheLockSpinsExceededError(); }
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
if (e.isRemovedState()) {
continue;
}
if (e.isFetchInProgress()) {
e.waitForFetch();
continue;
} else {
_previousNextRefreshTime = e.startFetch();
break;
}
}
}
boolean _finished = false;
try {
long t = System.currentTimeMillis();
finishFetch(e, insertOnPut(e, value, t, t, _previousNextRefreshTime));
_finished = true;
} finally {
e.ensureFetchAbort(_finished, _previousNextRefreshTime);
}
evictEventually();
}
@Override
public boolean remove(K key, T _value) {
return removeWithFlag(key, true, _value);
}
public boolean removeWithFlag(K key) {
return removeWithFlag(key, false, null);
}
/**
* Remove the object mapped to a key from the cache.
*
* <p>Operation with storage: If there is no entry within the cache there may
* be one in the storage, so we need to send the remove to the storage. However,
* if a remove() and a get() is going on in parallel it may happen that the entry
* gets removed from the storage and added again by the tail part of get(). To
* keep the cache and the storage consistent it must be ensured that this thread
* is the only one working on the entry.
*/
public boolean removeWithFlag(K key, boolean _checkValue, T _value) {
if (!_checkValue) {
eventuallyCallWriterDelete(key);
}
if (storage == null) {
E e = lookupEntrySynchronized(key);
if (e != null) {
synchronized (e) {
e.waitForFetch();
if (!e.isRemovedState()) {
synchronized (lock) {
boolean f = e.hasFreshData();
if (_checkValue) {
if (!f || !e.equalsValue(_value)) {
return false;
}
eventuallyCallWriterDelete(key);
}
if (removeEntry(e)) {
removedCnt++;
return f;
}
return false;
}
}
}
}
return false;
}
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
boolean _hasFreshData;
for (;;) {
if (_spinCount
throw new CacheLockSpinsExceededError();
}
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_hasFreshData = e.hasFreshData();
e.startFetch();
break;
}
}
boolean _finished = false;
try {
long t;
if (!_hasFreshData && e.isVirgin()) {
t = fetchWithStorage(e, false, 0);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
if (_checkValue && _hasFreshData && !e.equalsValue(_value)) {
finishFetch(e, t);
_finished = true;
return false;
}
}
if (_checkValue && _hasFreshData && !e.equalsValue(_value)) {
_hasFreshData = false;
}
if (_hasFreshData) {
eventuallyCallWriterDelete(key);
storage.remove(key);
}
synchronized (e) {
finishFetch(e, Entry.LOADED_NON_VALID);
if (_hasFreshData) {
synchronized (lock) {
if (removeEntry(e)) {
removedCnt++;
}
}
}
}
_finished = true;
} finally {
e.ensureFetchAbort(_finished);
}
return _hasFreshData;
}
private void eventuallyCallWriterDelete(K key) {
if (writer != null) {
try {
writer.delete(key);
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new CacheException(ex);
}
}
}
@Override
public void remove(K key) {
removeWithFlag(key);
}
public T peekAndRemove(K key) {
eventuallyCallWriterDelete(key);
if (storage == null) {
E e = lookupEntrySynchronized(key);
if (e != null) {
synchronized (e) {
e.waitForFetch();
if (!e.isRemovedState()) {
synchronized (lock) {
T _value = null;
boolean f = e.hasFreshData();
if (f) {
_value = (T) e.getValue();
recordHit(e);
} else {
peekMissCnt++;
}
if (removeEntry(e)) {
removedCnt++;
}
return _value;
}
}
}
}
synchronized (lock) {
peekMissCnt++;
}
return null;
} // end if (storage == null) ....
int _spinCount = TUNABLE.maximumEntryLockSpins;
E e;
boolean _hasFreshData;
for (;;) {
if (_spinCount
throw new CacheLockSpinsExceededError();
}
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForFetch();
if (e.isRemovedState()) {
continue;
}
_hasFreshData = e.hasFreshData();
e.startFetch();
break;
}
}
boolean _finished = false;
T _value = null;
try {
long t;
if (!_hasFreshData && e.isVirgin()) {
t = fetchWithStorage(e, false, 0);
_hasFreshData = e.hasFreshData(System.currentTimeMillis(), t);
}
if (_hasFreshData) {
_value = (T) e.getValue();
storage.remove(key);
}
synchronized (e) {
finishFetch(e, Entry.LOADED_NON_VALID);
if (_hasFreshData) {
synchronized (lock) {
if (removeEntry(e)) {
removedCnt++;
}
}
}
}
_finished = true;
} finally {
e.ensureFetchAbort(_finished);
}
return _value;
}
@Override
public void prefetch(final K key) {
if (refreshPool == null ||
lookupEntrySynchronized(key) != null) {
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
get(key);
}
};
refreshPool.submit(r);
}
public void prefetch(final List<K> keys, final int _startIndex, final int _endIndexExclusive) {
if (keys.size() == 0 || _startIndex == _endIndexExclusive) {
return;
}
if (keys.size() <= _endIndexExclusive) {
throw new IndexOutOfBoundsException("end > size");
}
if (_startIndex > _endIndexExclusive) {
throw new IndexOutOfBoundsException("start > end");
}
if (_startIndex > 0) {
throw new IndexOutOfBoundsException("end < 0");
}
Set<K> ks = new AbstractSet<K>() {
@Override
public Iterator<K> iterator() {
return new Iterator<K>() {
int idx = _startIndex;
@Override
public boolean hasNext() {
return idx < _endIndexExclusive;
}
@Override
public K next() {
return keys.get(idx++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return _endIndexExclusive - _startIndex;
}
};
prefetch(ks);
}
@Override
public void fetchAll(Set<? extends K> _keys, boolean replaceExistingValues, FetchCompletedListener l) {
if (replaceExistingValues) {
for (K k : _keys) {
fetchAndReplace(k);
}
if (l != null) {
l.fetchCompleted();
}
} else {
prefetch(_keys, l);
}
}
@Override
public void prefetch(final Set<K> keys) {
prefetch(keys, null);
}
void prefetch(final Set<? extends K> keys, final FetchCompletedListener l) {
if (refreshPool == null) {
getAll(keys);
if (l != null) {
l.fetchCompleted();
}
return;
}
boolean _complete = true;
for (K k : keys) {
if (lookupEntryUnsynchronized(k, modifiedHash(k.hashCode())) == null) {
_complete = false; break;
}
}
if (_complete) {
if (l != null) {
l.fetchCompleted();
}
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
getAll(keys);
if (l != null) {
l.fetchCompleted();
}
}
};
refreshPool.submit(r);
}
/**
* Lookup or create a new entry. The new entry is created, because we need
* it for locking within the data fetch.
*/
protected E lookupOrNewEntrySynchronized(K key) {
int hc = modifiedHash(key.hashCode());
return lookupOrNewEntrySynchronized(key, hc);
}
protected E lookupOrNewEntrySynchronized(K key, int hc) {
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntry(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
return e;
}
protected E lookupOrNewEntrySynchronizedNoHitRecord(K key) {
int hc = modifiedHash(key.hashCode());
E e = lookupEntryUnsynchronizedNoHitRecord(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntryNoHitRecord(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
return e;
}
protected T returnValue(Entry<E, K,T> e) {
T v = e.value;
if (v instanceof ExceptionWrapper) {
ExceptionWrapper w = (ExceptionWrapper) v;
if (w.additionalExceptionMessage == null) {
synchronized (e) {
long t = e.getValueExpiryTime();
w.additionalExceptionMessage = "(expiry=" + (t > 0 ? formatMillis(t) : "none") + ") " + w.getException();
}
}
exceptionPropagator.propagateException(w.additionalExceptionMessage, w.getException());
}
return v;
}
protected E lookupEntrySynchronized(K key) {
int hc = modifiedHash(key.hashCode());
E e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntry(key, hc);
}
}
return e;
}
protected E lookupEntrySynchronizedNoHitRecord(K key) {
int hc = modifiedHash(key.hashCode());
E e = lookupEntryUnsynchronizedNoHitRecord(key, hc);
if (e == null) {
synchronized (lock) {
e = lookupEntryNoHitRecord(key, hc);
}
}
return e;
}
protected final E lookupEntry(K key, int hc) {
E e = Hash.lookup(mainHash, key, hc);
if (e != null) {
recordHit(e);
return e;
}
e = refreshHashCtrl.remove(refreshHash, key, hc);
if (e != null) {
refreshHitCnt++;
mainHash = mainHashCtrl.insert(mainHash, e);
recordHit(e);
return e;
}
return null;
}
protected final E lookupEntryNoHitRecord(K key, int hc) {
E e = Hash.lookup(mainHash, key, hc);
if (e != null) {
return e;
}
e = refreshHashCtrl.remove(refreshHash, key, hc);
if (e != null) {
refreshHitCnt++;
mainHash = mainHashCtrl.insert(mainHash, e);
return e;
}
return null;
}
/**
* Insert new entry in all structures (hash and replacement list). May evict an
* entry if the maximum capacity is reached.
*/
protected E newEntry(K key, int hc) {
if (getLocalSize() >= maxSize) {
evictionNeeded = true;
}
E e = checkForGhost(key, hc);
if (e == null) {
e = newEntry();
e.key = key;
e.hashCode = hc;
insertIntoReplacementList(e);
}
mainHash = mainHashCtrl.insert(mainHash, e);
newEntryCnt++;
return e;
}
/**
* Called when expiry of an entry happens. Remove it from the
* main cache, refresh cache and from the (lru) list. Also cancel the timer.
* Called under big lock.
*/
/**
* The entry is already removed from the replacement list. stop/reset timer, if needed.
* Called under big lock.
*/
private boolean removeEntryFromHash(E e) {
boolean f = mainHashCtrl.remove(mainHash, e) || refreshHashCtrl.remove(refreshHash, e);
checkForHashCodeChange(e);
cancelExpiryTimer(e);
if (e.isVirgin()) {
virginEvictCnt++;
}
e.setRemovedState();
return f;
}
protected final void cancelExpiryTimer(Entry e) {
if (e.task != null) {
e.task.cancel();
timerCancelCount++;
if (timerCancelCount >= 10000) {
timer.purge();
timerCancelCount = 0;
}
e.task = null;
}
}
/**
* Check whether the key was modified during the stay of the entry in the cache.
* We only need to check this when the entry is removed, since we expect that if
* the key has changed, the stored hash code in the cache will not match any more and
* the item is evicted very fast.
*/
private void checkForHashCodeChange(Entry e) {
if (modifiedHash(e.key.hashCode()) != e.hashCode && !e.isStale()) {
if (keyMutationCount == 0) {
getLog().warn("Key mismatch! Key hashcode changed! keyClass=" + e.key.getClass().getName());
String s;
try {
s = e.key.toString();
if (s != null) {
getLog().warn("Key mismatch! key.toString(): " + s);
}
} catch (Throwable t) {
getLog().warn("Key mismatch! key.toString() threw exception", t);
}
}
keyMutationCount++;
}
}
/**
* Time when the element should be fetched again from the underlying storage.
* If 0 then the object should not be cached at all. -1 means no expiry.
*
* @param _newObject might be a fetched value or an exception wrapped into the {@link ExceptionWrapper}
*/
static <K, T> long calcNextRefreshTime(
K _key, T _newObject, long now, Entry _entry,
EntryExpiryCalculator<K, T> ec, long _maxLinger,
ExceptionExpiryCalculator<K> _exceptionEc, long _exceptionMaxLinger) {
if (!(_newObject instanceof ExceptionWrapper)) {
if (_maxLinger == 0) {
return 0;
}
if (ec != null) {
long t = ec.calculateExpiryTime(_key, _newObject, now, _entry);
return limitExpiryToMaxLinger(now, _maxLinger, t);
}
if (_maxLinger > 0) {
return _maxLinger + now;
}
return -1;
}
if (_exceptionMaxLinger == 0) {
return 0;
}
if (_exceptionEc != null) {
ExceptionWrapper _wrapper = (ExceptionWrapper) _newObject;
long t = _exceptionEc.calculateExpiryTime(_key, _wrapper.getException(), now);
t = limitExpiryToMaxLinger(now, _exceptionMaxLinger, t);
return t;
}
if (_exceptionMaxLinger > 0) {
return _exceptionMaxLinger + now;
} else {
return _exceptionMaxLinger;
}
}
static long limitExpiryToMaxLinger(long now, long _maxLinger, long t) {
if (_maxLinger > 0) {
long _tMaximum = _maxLinger + now;
if (t > _tMaximum) {
return _tMaximum;
}
if (t < -1 && -t > _tMaximum) {
return -_tMaximum;
}
}
return t;
}
protected long calcNextRefreshTime(K _key, T _newObject, long now, Entry _entry) {
return calcNextRefreshTime(
_key, _newObject, now, _entry,
entryExpiryCalculator, maxLinger,
exceptionExpiryCalculator, exceptionMaxLinger);
}
protected long fetch(final E e, long _previousNextRefreshTime) {
if (storage != null) {
return fetchWithStorage(e, true, _previousNextRefreshTime);
} else {
return fetchFromSource(e, _previousNextRefreshTime);
}
}
protected boolean conditionallyStartProcess(E e) {
if (!e.isVirgin()) {
return false;
}
e.startFetch();
return true;
}
/**
*
* @param e
* @param _needsFetch true if value needs to be fetched from the cache source.
* This is false, when the we only need to peek for an value already mapped.
*/
protected long fetchWithStorage(E e, boolean _needsFetch, long _previousNextRefreshTime) {
if (!e.isVirgin()) {
if (_needsFetch) {
return fetchFromSource(e, _previousNextRefreshTime);
}
return Entry.LOADED_NON_VALID;
}
StorageEntry se = storage.get(e.key);
if (se == null) {
if (_needsFetch) {
synchronized (lock) {
loadMissCnt++;
}
return fetchFromSource(e, _previousNextRefreshTime);
}
synchronized (lock) {
touchedTime = System.currentTimeMillis();
loadNonFreshCnt++;
}
return Entry.LOADED_NON_VALID;
}
return insertEntryFromStorage(se, e, _needsFetch);
}
protected long insertEntryFromStorage(StorageEntry se, E e, boolean _needsFetch) {
e.setLastModificationFromStorage(se.getCreatedOrUpdated());
T _valueOrException = (T) se.getValueOrException();
long now = System.currentTimeMillis();
T v = (T) se.getValueOrException();
long _nextRefreshTime = maxLinger == 0 ? 0 : Long.MAX_VALUE;
long _expiryTimeFromStorage = se.getValueExpiryTime();
boolean _expired = _expiryTimeFromStorage != 0 && _expiryTimeFromStorage <= now;
if (!_expired && timer != null) {
_nextRefreshTime = calcNextRefreshTime((K) se.getKey(), v, se.getCreatedOrUpdated(), null);
_expired = _nextRefreshTime > Entry.EXPIRY_TIME_MIN && _nextRefreshTime <= now;
}
boolean _fetchAlways = timer == null && maxLinger == 0;
if (_expired || _fetchAlways) {
if (_needsFetch) {
e.value = _valueOrException;
e.setLoadedNonValidAndFetch();
return fetchFromSource(e, 0);
} else {
synchronized (lock) {
touchedTime = now;
loadNonFreshCnt++;
}
return Entry.LOADED_NON_VALID;
}
}
return insert(e, _valueOrException, 0, now, INSERT_STAT_UPDATE, _nextRefreshTime);
}
protected long fetchFromSource(E e, long _previousNextRefreshValue) {
T v;
long t0 = System.currentTimeMillis();
try {
if (source == null) {
throw new CacheUsageExcpetion("source not set");
}
if (e.isVirgin() || e.hasException()) {
v = source.get((K) e.key, t0, null, e.getLastModification());
} else {
v = source.get((K) e.key, t0, (T) e.getValue(), e.getLastModification());
}
e.setLastModification(t0);
} catch (Throwable _ouch) {
v = (T) new ExceptionWrapper(_ouch);
}
long t = System.currentTimeMillis();
return insertOrUpdateAndCalculateExpiry(e, v, t0, t, INSERT_STAT_UPDATE, _previousNextRefreshValue);
}
protected final long insertOnPut(E e, T v, long t0, long t, long _previousNextRefreshValue) {
if (writer != null) {
try {
CacheEntry<K, T> ce;
ce = returnCacheEntry((K) e.getKey(), v, null, t0);
writer.write(ce);
} catch (RuntimeException ex) {
cleanupAfterWriterException(e);
throw ex;
} catch (Exception ex) {
cleanupAfterWriterException(e);
throw new CacheException("writer exception", ex);
}
}
e.setLastModification(t0);
return insertOrUpdateAndCalculateExpiry(e, v, t0, t, INSERT_STAT_PUT, _previousNextRefreshValue);
}
/**
* Calculate the next refresh time if a timer / expiry is needed and call insert.
*/
protected final long insertOrUpdateAndCalculateExpiry(E e, T v, long t0, long t, byte _updateStatistics, long _previousNextRefreshTime) {
long _nextRefreshTime = maxLinger == 0 ? 0 : Long.MAX_VALUE;
if (timer != null) {
try {
_nextRefreshTime = calculateNextRefreshTime(e, v, t0, _previousNextRefreshTime);
} catch (Exception ex) {
updateStatistics(e, v, t0, t, _updateStatistics, false);
throw new CacheException("exception in expiry calculation", ex);
}
}
return insert(e, v, t0, t, _updateStatistics, _nextRefreshTime);
}
/**
* @throws Exception any exception from the ExpiryCalculator
*/
private long calculateNextRefreshTime(E _entry, T _newValue, long t0, long _previousNextRefreshTime) {
long _nextRefreshTime;
if (Entry.isDataValidState(_previousNextRefreshTime) || Entry.isExpiredState(_previousNextRefreshTime)) {
_nextRefreshTime = calcNextRefreshTime((K) _entry.getKey(), _newValue, t0, _entry);
} else {
_nextRefreshTime = calcNextRefreshTime((K) _entry.getKey(), _newValue, t0, null);
}
return _nextRefreshTime;
}
final static byte INSERT_STAT_NO_UPDATE = 0;
final static byte INSERT_STAT_UPDATE = 1;
final static byte INSERT_STAT_PUT = 2;
/**
* @param _nextRefreshTime -1/MAXVAL: eternal, 0: expires immediately
*/
protected final long insert(E e, T _value, long t0, long t, byte _updateStatistics, long _nextRefreshTime) {
final boolean _justLoadedFromStorage = (storage != null) && t0 == 0;
if (_nextRefreshTime == -1) {
_nextRefreshTime = Long.MAX_VALUE;
}
final boolean _suppressException =
_value instanceof ExceptionWrapper && hasSuppressExceptions() && e.getValue() != Entry.INITIAL_VALUE && !e.hasException();
if (!_suppressException) {
e.value = _value;
}
if (_value instanceof ExceptionWrapper && !_suppressException && !_justLoadedFromStorage) {
Log log = getLog();
if (log.isDebugEnabled()) {
log.debug(
"source caught exception, expires at: " + formatMillis(_nextRefreshTime),
((ExceptionWrapper) _value).getException());
}
}
CacheStorageException _storageException = null;
if (storage != null && e.isDirty() && (_nextRefreshTime != 0 || hasKeepAfterExpired())) {
try {
storage.put(e, _nextRefreshTime);
} catch (CacheStorageException ex) {
_storageException = ex;
} catch (Throwable ex) {
_storageException = new CacheStorageException(ex);
}
}
synchronized (lock) {
checkClosed();
updateStatisticsNeedsLock(e, _value, t0, t, _updateStatistics, _suppressException);
if (_storageException != null) {
throw _storageException;
}
if (_nextRefreshTime == 0) {
_nextRefreshTime = Entry.FETCH_NEXT_TIME_STATE;
} else {
if (_nextRefreshTime == Long.MAX_VALUE) {
_nextRefreshTime = Entry.FETCHED_STATE;
}
}
if (_updateStatistics == INSERT_STAT_PUT && !e.hasFreshData(t, _nextRefreshTime)) {
putButExpiredCnt++;
}
} // synchronized (lock)
return _nextRefreshTime;
}
private void updateStatistics(E e, T _value, long t0, long t, byte _updateStatistics, boolean _suppressException) {
synchronized (lock) {
updateStatisticsNeedsLock(e, _value, t0, t, _updateStatistics, _suppressException);
}
}
private void updateStatisticsNeedsLock(E e, T _value, long t0, long t, byte _updateStatistics, boolean _suppressException) {
boolean _justLoadedFromStorage = storage != null && t0 == 0;
touchedTime = t;
if (_updateStatistics == INSERT_STAT_UPDATE) {
if (_justLoadedFromStorage) {
loadHitCnt++;
} else {
if (_suppressException) {
suppressedExceptionCnt++;
fetchExceptionCnt++;
} else {
if (_value instanceof ExceptionWrapper) {
fetchExceptionCnt++;
}
}
fetchCnt++;
fetchMillis += t - t0;
if (e.isGettingRefresh()) {
refreshCnt++;
}
if (e.isLoadedNonValidAndFetch()) {
loadNonFreshAndFetchedCnt++;
} else if (!e.isVirgin()) {
fetchButHitCnt++;
}
}
} else if (_updateStatistics == INSERT_STAT_PUT) {
putCnt++;
eventuallyAdjustPutNewEntryCount(e);
if (e.nextRefreshTime == Entry.LOADED_NON_VALID_AND_PUT) {
peekHitNotFreshCnt++;
}
}
}
private void eventuallyAdjustPutNewEntryCount(E e) {
if (e.isVirgin()) {
putNewEntryCnt++;
}
}
private void cleanupAfterWriterException(E e) {
if (e.isVirgin()) {
synchronized (lock) {
putNewEntryCnt++;
}
}
}
protected long stopStartTimer(long _nextRefreshTime, E e, long now) {
if (e.task != null) {
e.task.cancel();
}
if (hasSharpTimeout() && _nextRefreshTime > Entry.EXPIRY_TIME_MIN && _nextRefreshTime != Long.MAX_VALUE) {
_nextRefreshTime = -_nextRefreshTime;
}
if (timer != null &&
(_nextRefreshTime > Entry.EXPIRY_TIME_MIN || _nextRefreshTime < -1)) {
if (_nextRefreshTime < -1) {
long _timerTime =
-_nextRefreshTime - TUNABLE.sharpExpirySafetyGapMillis;
if (_timerTime >= now) {
MyTimerTask tt = new MyTimerTask();
tt.entry = e;
timer.schedule(tt, new Date(_timerTime));
e.task = tt;
_nextRefreshTime = -_nextRefreshTime;
}
} else {
MyTimerTask tt = new MyTimerTask();
tt.entry = e;
timer.schedule(tt, new Date(_nextRefreshTime));
e.task = tt;
}
} else {
}
return _nextRefreshTime;
}
/**
* When the time has come remove the entry from the cache.
*/
protected void timerEvent(final E e, long _executionTime) {
/* checked below, if we do not go through a synchronized clause, we may see old data
if (e.isRemovedFromReplacementList()) {
return;
}
*/
if (refreshPool != null) {
synchronized (lock) {
if (isClosed()) { return; }
if (e.task == null) {
return;
}
if (e.isRemovedFromReplacementList()) {
return;
}
if (mainHashCtrl.remove(mainHash, e)) {
refreshHash = refreshHashCtrl.insert(refreshHash, e);
if (e.hashCode != modifiedHash(e.key.hashCode())) {
synchronized (lock) {
synchronized (e) {
if (!e.isRemovedState() && removeEntryFromHash(e)) {
expiredRemoveCnt++;
}
}
}
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
long _previousNextRefreshTime;
synchronized (e) {
if (e.isRemovedFromReplacementList() || e.isRemovedState() || e.isFetchInProgress()) {
return;
}
_previousNextRefreshTime = e.nextRefreshTime;
e.setGettingRefresh();
}
try {
long t = fetch(e, _previousNextRefreshTime);
finishFetch(e, t);
} catch (CacheClosedException ignore) {
} catch (Throwable ex) {
e.ensureFetchAbort(false);
synchronized (lock) {
internalExceptionCnt++;
}
getLog().warn("Refresh exception", ex);
try {
expireEntry(e);
} catch (CacheClosedException ignore) { }
}
}
};
boolean _submitOkay = refreshPool.submit(r);
if (_submitOkay) {
return;
}
refreshSubmitFailedCnt++;
}
}
}
synchronized (e) {
long nrt = e.nextRefreshTime;
if (nrt < Entry.EXPIRY_TIME_MIN) {
return;
}
long t = System.currentTimeMillis();
if (t >= e.nextRefreshTime) {
try {
expireEntry(e);
} catch (CacheClosedException ignore) { }
} else {
e.nextRefreshTime = -e.nextRefreshTime;
}
}
}
protected void expireEntry(E e) {
synchronized (e) {
if (e.isRemovedState() || e.isExpiredState()) {
return;
}
if (e.isFetchInProgress()) {
e.nextRefreshTime = Entry.FETCH_IN_PROGRESS_NON_VALID;
return;
}
e.setExpiredState();
synchronized (lock) {
checkClosed();
if (hasKeepAfterExpired()) {
expiredKeptCnt++;
} else {
if (removeEntry(e)) {
expiredRemoveCnt++;
}
}
}
}
}
/**
* Returns all cache entries within the heap cache. Entries that
* are expired or contain no valid data are not filtered out.
*/
final protected ClosableConcurrentHashEntryIterator<Entry> iterateAllHeapEntries() {
return
new ClosableConcurrentHashEntryIterator(
mainHashCtrl, mainHash, refreshHashCtrl, refreshHash);
}
@Override
public void removeAllAtOnce(Set<K> _keys) {
}
/** JSR107 convenience getAll from array */
public Map<K, T> getAll(K[] _keys) {
return getAll(new HashSet<K>(Arrays.asList(_keys)));
}
/**
* JSR107 bulk interface. The behaviour is compatible to the JSR107 TCK. We also need
* to be compatible to the exception handling policy, which says that the exception
* is to be thrown when most specific. So exceptions are only thrown, when the value
* which has produced an exception is requested from the map.
*/
public Map<K, T> getAll(final Set<? extends K> _inputKeys) {
final Set<K> _keys = new HashSet<K>();
for (K k : _inputKeys) {
E e = getEntryInternal(k);
if (e != null) {
_keys.add(k);
}
}
final Set<Map.Entry<K, T>> set =
new AbstractSet<Map.Entry<K, T>>() {
@Override
public Iterator<Map.Entry<K, T>> iterator() {
return new Iterator<Map.Entry<K, T>>() {
Iterator<? extends K> keyIterator = _keys.iterator();
@Override
public boolean hasNext() {
return keyIterator.hasNext();
}
@Override
public Map.Entry<K, T> next() {
final K key = keyIterator.next();
return new Map.Entry<K, T>(){
@Override
public K getKey() {
return key;
}
@Override
public T getValue() {
return get(key);
}
@Override
public T setValue(T value) {
throw new UnsupportedOperationException();
}
};
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return _keys.size();
}
};
return new AbstractMap<K, T>() {
@Override
public T get(Object key) {
if (containsKey(key)) {
return BaseCache.this.get((K) key);
}
return null;
}
@Override
public boolean containsKey(Object key) {
return _keys.contains(key);
}
@Override
public Set<Entry<K, T>> entrySet() {
return set;
}
};
}
public Map<K, T> peekAll(final Set<? extends K> _inputKeys) {
Map<K, T> map = new HashMap<K, T>();
for (K k : _inputKeys) {
CacheEntry<K, T> e = peekEntry(k);
if (e != null) {
map.put(k, e.getValue());
}
}
return map;
}
/**
* Retrieve
*/
@SuppressWarnings("unused")
public void getBulk(K[] _keys, T[] _result, BitSet _fetched, int s, int e) {
sequentialGetFallBack(_keys, _result, _fetched, s, e);
}
final void sequentialGetFallBack(K[] _keys, T[] _result, BitSet _fetched, int s, int e) {
for (int i = s; i < e; i++) {
if (!_fetched.get(i)) {
try {
_result[i] = get(_keys[i]);
} catch (Exception ignore) {
}
}
}
}
public void putAll(Map<? extends K, ? extends T> valueMap) {
if (valueMap.containsKey(null)) {
throw new NullPointerException("map contains null key");
}
for (Map.Entry<? extends K, ? extends T> e : valueMap.entrySet()) {
put(e.getKey(), e.getValue());
}
}
/**
* We need the hash code multiple times. Calculate all hash codes.
*/
void calcHashCodes(K[] _keys, int[] _hashCodes) {
for (int i = _keys.length - 1; i >= 0; i
_hashCodes[i] = modifiedHash(_keys[i].hashCode());
}
}
int startOperationForExistingEntriesNoWait(K[] _keys, int[] _hashCodes, E[] _entries, long[] _pNrt) {
int cnt = 0;
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
if (e != null) { continue; }
K key = _keys[i];
e = lookupEntryUnsynchronized(key, _hashCodes[i]);
if (e == null) { continue; }
synchronized (e) {
if (!e.isRemovedState() && !e.isFetchInProgress()) {
_pNrt[i] = e.startFetch();
_entries[i] = e;
cnt++;
}
}
}
return cnt;
}
int startOperationNewEntries(K[] _keys, int[] _hashCodes, E[] _entries, long[] _pNrt) {
int cnt = 0;
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
if (e != null) { continue; }
K key = _keys[i];
e = lookupOrNewEntrySynchronized(key, _hashCodes[i]);
synchronized (e) {
if (!e.isRemovedState() && !e.isFetchInProgress()) {
_pNrt[i] = e.startFetch();
_entries[i] = e;
cnt++;
}
}
}
return cnt;
}
int startOperationNewEntriesAndWait(K[] _keys, int[] _hashCodes, E[] _entries, long[] _pNrt) {
int cnt = 0;
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
if (e != null) { continue; }
K key = _keys[i];
e = lookupOrNewEntrySynchronized(key, _hashCodes[i]);
synchronized (e) {
e.waitForFetch();
if (!e.isRemovedState()) {
_pNrt[i] = e.startFetch();
_entries[i] = e;
cnt++;
}
}
}
return cnt;
}
void startBulkOperation(K[] _keys, int[] _hashCodes, E[] _entries, long[] _pNrt) {
calcHashCodes(_keys, _hashCodes);
int cnt = 0;
cnt = startOperationForExistingEntriesNoWait(_keys, _hashCodes, _entries, _pNrt);
if (cnt == _keys.length) { return; }
cnt += startOperationNewEntries(_keys, _hashCodes, _entries, _pNrt);
if (cnt == _keys.length) { return; }
cnt += startOperationNewEntries(_keys, _hashCodes, _entries, _pNrt);
if (cnt == _keys.length) { return; }
int _spinCount = TUNABLE.maximumEntryLockSpins;
do {
if (_spinCount
throw new CacheLockSpinsExceededError();
}
cnt += startOperationNewEntriesAndWait(_keys, _hashCodes, _entries, _pNrt);
} while (cnt != _keys.length);
if (storage != null) {
throw new UnsupportedOperationException("storage load must happen here");
}
}
void initializeEntries(BulkOperation op, long now, K[] _keys, E[] _entries, long[] _pNrt, EntryForProcessor<K, T>[] _pEntries) {
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
EntryForProcessor<K, T> ep;
_pEntries[i] = ep = new EntryForProcessor<K, T>();
ep.index = i;
ep.lastModification = e.getLastModification();
ep.key = _keys[i];
ep.operation = op;
if (e.hasFreshData(now, _pNrt[i])) {
ep.value = (T) e.getValueOrException();
} else {
ep.removed = ep.notExistingInCacheYet = true;
if (storage != null || source != null) {
ep.needsLoadOrFetch = true;
}
}
}
}
@Override
public <R> R invoke(K key, CacheEntryProcessor<K, T, R> entryProcessor, Object... _args) {
Map<K, EntryProcessingResult<R>> m = invokeAll(Collections.singleton(key), entryProcessor, _args);
return m.size() > 0 ? m.values().iterator().next().getResult() : null;
}
@Override
public <R> Map<K, EntryProcessingResult<R>> invokeAll(Set<? extends K> _inputKeys, CacheEntryProcessor<K ,T, R> p, Object... _args) {
checkClosed();
K[] _keys = _inputKeys.toArray((K[]) Array.newInstance(keyType, 0));
int[] _hashCodes = new int[_keys.length];
E[] _entries = (E[]) Array.newInstance(newEntry().getClass(), _keys.length);
long[] _pNrt = new long[_keys.length];
long t0 = System.currentTimeMillis();
startBulkOperation(_keys, _hashCodes, _entries, _pNrt);
EntryForProcessor<K, T>[] _pEntries = new EntryForProcessor[_keys.length];
BulkOperation op = new BulkOperation(_entries, _pNrt);
initializeEntries(op, t0, _keys, _entries, _pNrt, _pEntries);
Map<K, EntryProcessingResult<R>> _results = new HashMap<K, EntryProcessingResult<R>>();
boolean _gotException = false;
for (int i = _keys.length - 1; i >= 0; i
EntryProcessingResult<R> _result;
try {
R r = p.process(_pEntries[i], _args);
_result = r != null ? new ProcessingResultImpl<R>(r) : null;
} catch (Throwable t) {
_result = new ProcessingResultImpl<R>(t);
_gotException = true;
}
if (_result != null) {
_results.put(_keys[i], _result);
}
}
long[] _newExpiry = new long[_keys.length];
Exception _propagateException = null;
if (!_gotException && timer != null) {
try {
for (int i = _keys.length - 1; i >= 0; i
if (_pEntries[i].updated && !_pEntries[i].removed) {
_newExpiry[i] = calculateNextRefreshTime(_entries[i], (T) _pEntries[i].value, t0, _pNrt[i]);
}
}
} catch (Exception ex) {
_gotException = true;
_propagateException = ex;
}
}
if (!_gotException && writer != null) {
try {
for (int i = _keys.length - 1; i >= 0; i
if (!_pEntries[i].updated) {
continue;
}
if (_pEntries[i].removed) {
writer.delete(_keys[i]);
/* TCK: always calls the writer!!!
if (_entries[i].hasFreshData(System.currentTimeMillis(), _pNrt[i])) {
writer.delete(_keys[i]);
}
*/
} else {
CacheEntry<K, T> ce = returnCacheEntry(_keys[i], _pEntries[i].getValue(), _pEntries[i].getException(), _pEntries[i].getLastModification());
writer.write(ce);
}
}
} catch (Exception ex) {
_gotException = true;
_propagateException = ex;
}
}
if (_gotException) {
for (int i = _keys.length - 1; i >= 0; i
if (_pNrt[i] == Entry.VIRGIN_STATE) {
synchronized (lock) {
invokeNewEntryCnt++;
}
}
finishFetch(_entries[i], _pNrt[i]);
}
} else {
for (int i = _keys.length - 1; i >= 0; i
E e = _entries[i];
if (!_pEntries[i].updated) {
if (_pNrt[i] == Entry.VIRGIN_STATE) {
synchronized (lock) {
invokeNewEntryCnt++;
}
}
finishFetch(e, _pNrt[i]);
continue;
}
if (_pEntries[i].removed) {
if (e.hasFreshData(System.currentTimeMillis(), _pNrt[i])) {
synchronized (e) {
finishFetch(e, Entry.LOADED_NON_VALID);
synchronized (lock) {
removeEntry(e);
removedCnt++;
}
}
} else {
synchronized (lock) {
invokeNewEntryCnt++;
}
finishFetch(e, _pNrt[i]);
}
continue;
}
long t = System.currentTimeMillis();
long _expiry;
if (timer == null) {
_expiry = maxLinger == 0 ? 0 : Long.MAX_VALUE;
} else {
_expiry = _newExpiry[i];
}
e.setLastModification(_pEntries[i].getLastModification());
finishFetch(e, insert(e, (T) _pEntries[i].value, t0, t, INSERT_STAT_PUT, _expiry));
}
}
if (_propagateException != null) {
throw new CacheEntryProcessingException(_propagateException);
}
return _results;
}
class BulkOperation {
E[] entries;
long[] pNrt;
public BulkOperation(E[] entries, long[] pNrt) {
this.entries = entries;
this.pNrt = pNrt;
}
void loadOrFetch(EntryForProcessor<K, T> ep) {
int idx = ep.index;
E e = entries[idx];
if (storage != null) {
pNrt[idx] = fetchWithStorage(e, ep.removed, pNrt[idx]);
} else {
pNrt[idx] = fetch(e, pNrt[idx]);
}
if (e.isVirgin()) {
e.setLoadedNonValidAndFetch();
}
ep.needsLoadOrFetch = false;
if (e.hasFreshData(System.currentTimeMillis(), pNrt[idx])) {
ep.value = (T) e.getValue();
ep.lastModification = e.getLastModification();
} else {
ep.removed = true;
}
}
/*
void loadAndFetch(EntryForProcessor<K, T> ep) {
int idx = ep.index;
E e = entries[idx];
pNrt[idx] = fetch(e, pNrt[idx]);
if (e.isVirgin()) {
e.setLoadedNonValidAndFetch();
}
ep.needsLoad = false;
ep.needsFetch = false;
if (e.hasFreshData(System.currentTimeMillis(), pNrt[idx])) {
ep.value = (T) e.getValue();
ep.lastModification = e.getLastModification();
} else {
ep.removed = true;
}
}
*/
}
public abstract long getHitCnt();
protected final int calculateHashEntryCount() {
return Hash.calcEntryCount(mainHash) + Hash.calcEntryCount(refreshHash);
}
protected final int getLocalSize() {
return mainHashCtrl.size + refreshHashCtrl.size;
}
public final int getTotalEntryCount() {
synchronized (lock) {
if (storage != null) {
return storage.getTotalEntryCount();
}
return getLocalSize();
}
}
public long getExpiredCnt() {
return expiredRemoveCnt + expiredKeptCnt;
}
/**
* For peek no fetch is counted if there is a storage miss, hence the extra counter.
*/
public long getFetchesBecauseOfNewEntries() {
return fetchCnt - fetchButHitCnt;
}
protected int getFetchesInFlight() {
long _fetchesBecauseOfNoEntries = getFetchesBecauseOfNewEntries();
return (int) (newEntryCnt - putNewEntryCnt - virginEvictCnt
- loadNonFreshCnt
- loadHitCnt
- _fetchesBecauseOfNoEntries
- invokeNewEntryCnt
);
}
protected IntegrityState getIntegrityState() {
synchronized (lock) {
return new IntegrityState()
.checkEquals(
"newEntryCnt - virginEvictCnt == " +
"getFetchesBecauseOfNewEntries() + getFetchesInFlight() + putNewEntryCnt + loadNonFreshCnt + loadHitCnt",
newEntryCnt - virginEvictCnt,
getFetchesBecauseOfNewEntries() + getFetchesInFlight() + putNewEntryCnt + loadNonFreshCnt + loadHitCnt)
.checkLessOrEquals("getFetchesInFlight() <= 100", getFetchesInFlight(), 100)
.checkEquals("newEntryCnt == getSize() + evictedCnt + expiredRemoveCnt + removeCnt + clearedCnt", newEntryCnt, getLocalSize() + evictedCnt + expiredRemoveCnt + removedCnt + clearedCnt)
.checkEquals("newEntryCnt == getSize() + evictedCnt + getExpiredCnt() - expiredKeptCnt + removeCnt + clearedCnt", newEntryCnt, getLocalSize() + evictedCnt + getExpiredCnt() - expiredKeptCnt + removedCnt + clearedCnt)
.checkEquals("mainHashCtrl.size == Hash.calcEntryCount(mainHash)", mainHashCtrl.size, Hash.calcEntryCount(mainHash))
.checkEquals("refreshHashCtrl.size == Hash.calcEntryCount(refreshHash)", refreshHashCtrl.size, Hash.calcEntryCount(refreshHash))
.check("!!evictionNeeded | (getSize() <= maxSize)", !!evictionNeeded | (getLocalSize() <= maxSize))
.check("storage => storage.getAlert() < 2", storage == null || storage.getAlert() < 2);
}
}
/** Check internal data structures and throw and exception if something is wrong, used for unit testing */
public final void checkIntegrity() {
synchronized (lock) {
checkClosed();
IntegrityState is = getIntegrityState();
if (is.getStateFlags() > 0) {
throw new CacheIntegrityError(is.getStateDescriptor(), is.getFailingChecks(), toString());
}
}
}
public final Info getInfo() {
synchronized (lock) {
checkClosed();
long t = System.currentTimeMillis();
if (info != null &&
(info.creationTime + info.creationDeltaMs * TUNABLE.minimumStatisticsCreationTimeDeltaFactor + TUNABLE.minimumStatisticsCreationDeltaMillis > t)) {
return info;
}
info = getLatestInfo(t);
}
return info;
}
public final Info getLatestInfo() {
return getLatestInfo(System.currentTimeMillis());
}
private Info getLatestInfo(long t) {
synchronized (lock) {
checkClosed();
info = new Info();
info.creationTime = t;
info.creationDeltaMs = (int) (System.currentTimeMillis() - t);
return info;
}
}
protected String getExtraStatistics() { return ""; }
static String timestampToString(long t) {
if (t == 0) {
return "-";
}
return formatMillis(t);
}
@Override
public CacheManager getCacheManager() {
return manager;
}
@Override
public <X> X requestInterface(Class<X> _type) {
if (_type.equals(ConcurrentMap.class) ||
_type.equals(Map.class)) {
return (X) new ConcurrentMapWrapper<K, T>(this);
}
return null;
}
/**
* Return status information. The status collection is time consuming, so this
* is an expensive operation.
*/
@Override
public String toString() {
synchronized (lock) {
Info fo = getLatestInfo();
return "Cache{" + name + "}"
+ "("
+ "size=" + fo.getSize() + ", "
+ "maxSize=" + fo.getMaxSize() + ", "
+ "usageCnt=" + fo.getUsageCnt() + ", "
+ "missCnt=" + fo.getMissCnt() + ", "
+ "fetchCnt=" + fo.getFetchCnt() + ", "
+ "fetchButHitCnt=" + fetchButHitCnt + ", "
+ "heapHitCnt=" + fo.hitCnt + ", "
+ "virginEvictCnt=" + virginEvictCnt + ", "
+ "fetchesInFlightCnt=" + fo.getFetchesInFlightCnt() + ", "
+ "newEntryCnt=" + fo.getNewEntryCnt() + ", "
+ "bulkGetCnt=" + fo.getBulkGetCnt() + ", "
+ "refreshCnt=" + fo.getRefreshCnt() + ", "
+ "refreshSubmitFailedCnt=" + fo.getRefreshSubmitFailedCnt() + ", "
+ "refreshHitCnt=" + fo.getRefreshHitCnt() + ", "
+ "putCnt=" + fo.getPutCnt() + ", "
+ "putNewEntryCnt=" + fo.getPutNewEntryCnt() + ", "
+ "expiredCnt=" + fo.getExpiredCnt() + ", "
+ "evictedCnt=" + fo.getEvictedCnt() + ", "
+ "removedCnt=" + fo.getRemovedCnt() + ", "
+ "storageLoadCnt=" + fo.getStorageLoadCnt() + ", "
+ "storageMissCnt=" + fo.getStorageMissCnt() + ", "
+ "storageHitCnt=" + fo.getStorageHitCnt() + ", "
+ "hitRate=" + fo.getDataHitString() + ", "
+ "collisionCnt=" + fo.getCollisionCnt() + ", "
+ "collisionSlotCnt=" + fo.getCollisionSlotCnt() + ", "
+ "longestCollisionSize=" + fo.getLongestCollisionSize() + ", "
+ "hashQuality=" + fo.getHashQualityInteger() + ", "
+ "msecs/fetch=" + (fo.getMillisPerFetch() >= 0 ? fo.getMillisPerFetch() : "-") + ", "
+ "created=" + timestampToString(fo.getStarted()) + ", "
+ "cleared=" + timestampToString(fo.getCleared()) + ", "
+ "touched=" + timestampToString(fo.getTouched()) + ", "
+ "fetchExceptionCnt=" + fo.getFetchExceptionCnt() + ", "
+ "suppressedExceptionCnt=" + fo.getSuppressedExceptionCnt() + ", "
+ "internalExceptionCnt=" + fo.getInternalExceptionCnt() + ", "
+ "keyMutationCnt=" + fo.getKeyMutationCnt() + ", "
+ "infoCreated=" + timestampToString(fo.getInfoCreated()) + ", "
+ "infoCreationDeltaMs=" + fo.getInfoCreationDeltaMs() + ", "
+ "impl=\"" + getClass().getSimpleName() + "\""
+ getExtraStatistics() + ", "
+ "integrityState=" + fo.getIntegrityDescriptor() + ")";
}
}
/**
* Stable interface to request information from the cache, the object
* safes values that need a longer calculation time, other values are
* requested directly.
*/
public class Info {
int size = BaseCache.this.getLocalSize();
long creationTime;
int creationDeltaMs;
long missCnt = fetchCnt - refreshCnt + peekHitNotFreshCnt + peekMissCnt;
long storageMissCnt = loadMissCnt + loadNonFreshCnt + loadNonFreshAndFetchedCnt;
long storageLoadCnt = storageMissCnt + loadHitCnt;
long newEntryCnt = BaseCache.this.newEntryCnt - virginEvictCnt;
long hitCnt = getHitCnt();
long correctedPutCnt = putCnt - putButExpiredCnt;
long usageCnt =
hitCnt + newEntryCnt + peekMissCnt;
CollisionInfo collisionInfo;
String extraStatistics;
int fetchesInFlight = BaseCache.this.getFetchesInFlight();
{
collisionInfo = new CollisionInfo();
Hash.calcHashCollisionInfo(collisionInfo, mainHash);
Hash.calcHashCollisionInfo(collisionInfo, refreshHash);
extraStatistics = BaseCache.this.getExtraStatistics();
if (extraStatistics.startsWith(", ")) {
extraStatistics = extraStatistics.substring(2);
}
}
IntegrityState integrityState = getIntegrityState();
String percentString(double d) {
String s = Double.toString(d);
return (s.length() > 5 ? s.substring(0, 5) : s) + "%";
}
public String getName() { return name; }
public String getImplementation() { return BaseCache.this.getClass().getSimpleName(); }
public int getSize() { return size; }
public int getMaxSize() { return maxSize; }
public long getStorageHitCnt() { return loadHitCnt; }
public long getStorageLoadCnt() { return storageLoadCnt; }
public long getStorageMissCnt() { return storageMissCnt; }
public long getReadUsageCnt() { return usageCnt - putCnt - removedCnt - invokeNewEntryCnt; }
public long getUsageCnt() { return usageCnt; }
public long getMissCnt() { return missCnt; }
public long getNewEntryCnt() { return newEntryCnt; }
public long getFetchCnt() { return fetchCnt; }
public int getFetchesInFlightCnt() { return fetchesInFlight; }
public long getBulkGetCnt() { return bulkGetCnt; }
public long getRefreshCnt() { return refreshCnt; }
public long getInternalExceptionCnt() { return internalExceptionCnt; }
public long getRefreshSubmitFailedCnt() { return refreshSubmitFailedCnt; }
public long getSuppressedExceptionCnt() { return suppressedExceptionCnt; }
public long getFetchExceptionCnt() { return fetchExceptionCnt; }
public long getRefreshHitCnt() { return refreshHitCnt; }
public long getExpiredCnt() { return BaseCache.this.getExpiredCnt(); }
public long getEvictedCnt() { return evictedCnt - virginEvictCnt; }
public long getRemovedCnt() { return BaseCache.this.removedCnt; }
public long getPutNewEntryCnt() { return putNewEntryCnt; }
public long getPutCnt() { return correctedPutCnt; }
public long getKeyMutationCnt() { return keyMutationCount; }
public double getDataHitRate() {
long cnt = getReadUsageCnt();
return cnt == 0 ? 0.0 : ((cnt - missCnt) * 100D / cnt);
}
public String getDataHitString() { return percentString(getDataHitRate()); }
public double getEntryHitRate() { return usageCnt == 0 ? 100 : (usageCnt - newEntryCnt + putCnt) * 100D / usageCnt; }
public String getEntryHitString() { return percentString(getEntryHitRate()); }
/** How many items will be accessed with collision */
public int getCollisionPercentage() {
return
(size - collisionInfo.collisionCnt) * 100 / size;
}
/** 100 means each collision has its own slot */
public int getSlotsPercentage() {
return collisionInfo.collisionSlotCnt * 100 / collisionInfo.collisionCnt;
}
public int getHq0() {
return Math.max(0, 105 - collisionInfo.longestCollisionSize * 5) ;
}
public int getHq1() {
final int _metricPercentageBase = 60;
int m =
getCollisionPercentage() * ( 100 - _metricPercentageBase) / 100 + _metricPercentageBase;
m = Math.min(100, m);
m = Math.max(0, m);
return m;
}
public int getHq2() {
final int _metricPercentageBase = 80;
int m =
getSlotsPercentage() * ( 100 - _metricPercentageBase) / 100 + _metricPercentageBase;
m = Math.min(100, m);
m = Math.max(0, m);
return m;
}
public int getHashQualityInteger() {
if (size == 0 || collisionInfo.collisionSlotCnt == 0) {
return 100;
}
int _metric0 = getHq0();
int _metric1 = getHq1();
int _metric2 = getHq2();
if (_metric1 < _metric0) {
int v = _metric0;
_metric0 = _metric1;
_metric1 = v;
}
if (_metric2 < _metric0) {
int v = _metric0;
_metric0 = _metric2;
_metric2 = v;
}
if (_metric2 < _metric1) {
int v = _metric1;
_metric1 = _metric2;
_metric2 = v;
}
if (_metric0 <= 0) {
return 0;
}
_metric0 = _metric0 + ((_metric1 - 50) * 5 / _metric0);
_metric0 = _metric0 + ((_metric2 - 50) * 2 / _metric0);
_metric0 = Math.max(0, _metric0);
_metric0 = Math.min(100, _metric0);
return _metric0;
}
public double getMillisPerFetch() { return fetchCnt == 0 ? 0 : (fetchMillis * 1D / fetchCnt); }
public long getFetchMillis() { return fetchMillis; }
public int getCollisionCnt() { return collisionInfo.collisionCnt; }
public int getCollisionSlotCnt() { return collisionInfo.collisionSlotCnt; }
public int getLongestCollisionSize() { return collisionInfo.longestCollisionSize; }
public String getIntegrityDescriptor() { return integrityState.getStateDescriptor(); }
public long getStarted() { return startedTime; }
public long getCleared() { return clearedTime; }
public long getTouched() { return touchedTime; }
public long getInfoCreated() { return creationTime; }
public int getInfoCreationDeltaMs() { return creationDeltaMs; }
public int getHealth() {
if (storage != null && storage.getAlert() == 2) {
return 2;
}
if (integrityState.getStateFlags() > 0 ||
getHashQualityInteger() < 5) {
return 2;
}
if (storage != null && storage.getAlert() == 1) {
return 1;
}
if (getHashQualityInteger() < 30 ||
getKeyMutationCnt() > 0 ||
getInternalExceptionCnt() > 0) {
return 1;
}
return 0;
}
public String getExtraStatistics() {
return extraStatistics;
}
}
static class CollisionInfo {
int collisionCnt; int collisionSlotCnt; int longestCollisionSize;
}
/**
* This function calculates a modified hash code. The intention is to
* "rehash" the incoming integer hash codes to overcome weak hash code
* implementations. We expect good results for integers also.
* Also add a random seed to the hash to protect against attacks on hashes.
* This is actually a slightly reduced version of the java.util.HashMap
* hash modification.
*/
protected final int modifiedHash(int h) {
h ^= hashSeed;
h ^= h >>> 7;
h ^= h >>> 15;
return h;
}
protected class MyTimerTask extends java.util.TimerTask {
E entry;
public void run() {
timerEvent(entry, scheduledExecutionTime());
}
}
public static class Tunable extends TunableConstants {
/**
* Implementation class to use by default.
*/
public Class<? extends BaseCache> defaultImplementation = ClockProPlusCache.class;
/**
* Log exceptions from the source just as they happen. The log goes to the debug output
* of the cache log, debug level of the cache log must be enabled also.
*/
public boolean logSourceExceptions = false;
public int waitForTimerJobsSeconds = 5;
/**
* Limits the number of spins until an entry lock is expected to
* succeed. The limit is to detect deadlock issues during development
* and testing. It is set to an arbitrary high value to result in
* an exception after about one second of spinning.
*/
public int maximumEntryLockSpins = 333333;
/**
* Maximum number of tries to find an entry for eviction if maximum size
* is reached.
*/
public int maximumEvictSpins = 5;
/**
* Size of the hash table before inserting the first entry. Must be power
* of two. Default: 64.
*/
public int initialHashSize = 64;
/**
* Fill percentage limit. When this is reached the hash table will get
* expanded. Default: 64.
*/
public int hashLoadPercent = 64;
/**
* The hash code will randomized by default. This is a countermeasure
* against from outside that know the hash function.
*/
public boolean disableHashRandomization = false;
/**
* Seed used when randomization is disabled. Default: 0.
*/
public int hashSeed = 0;
/**
* When sharp expiry is enabled, the expiry timer goes
* before the actual expiry to switch back to a time checking
* scheme when the get method is invoked. This prevents
* that an expired value gets served by the cache if the time
* is too late. A recent GC should not produce more then 200
* milliseconds stall. If longer GC stalls are expected, this
* value needs to be changed. A value of LONG.MaxValue
* suppresses the timer usage completely.
*/
public long sharpExpirySafetyGapMillis = 666;
/**
* Some statistic values need processing time to gather and compute it. This is a safety
* time delta, to ensure that the machine is not busy due to statistics generation. Default: 333.
*/
public int minimumStatisticsCreationDeltaMillis = 333;
/**
* Factor of the statistics creation time, that determines the time difference when new
* statistics are generated.
*/
public int minimumStatisticsCreationTimeDeltaFactor = 17;
}
} |
package main.java.gui.application;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.rmi.RemoteException;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import main.java.data.Data;
import main.java.game.ExceptionForbiddenAction;
import main.java.game.ExceptionGameHasNotStarted;
import main.java.game.ExceptionNotYourTurn;
import main.java.game.ExceptionUncompletedPath;
import main.java.gui.board.MapPanel;
import main.java.gui.chat.ChatPanel;
import main.java.gui.components.Panel;
import main.java.gui.components.TitlePanel;
import main.java.player.PlayerIHM;
public class InGamePanel extends Panel {
// Properties
private static final long serialVersionUID = 1L;
Panel bigChatPanel;
Panel chatPanel;
Panel centerMapPanel;
Panel playersSidebarPanel;
Panel deckAndTurnPanel;
TitlePanel titlePanel;
MapPanel mapPanel;
ArrayList<PlayerPanel> playerPanels = new ArrayList<PlayerPanel>();
String[] playersTab;
// Constructors
InGamePanel(GameController gc) {
super();
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(1350, 870));
this.setupGameMapPanel();
this.setupChatPanel();
this.setupPlayersPanel();
}
private void setupGameMapPanel() {
centerMapPanel = new Panel();
centerMapPanel.setLayout(new BorderLayout());
this.add(centerMapPanel, BorderLayout.CENTER);
//deckAndTurnPanel = new Panel();
//centerMapPanel.add(deckAndTurnPanel, BorderLayout.NORTH);
Panel bigMapPanel = new Panel();
bigMapPanel.setLayout(new BorderLayout());
centerMapPanel.add(bigMapPanel, BorderLayout.CENTER);
Panel eastTestPanel = new Panel();
Panel westTestPanel = new Panel();
eastTestPanel.setPreferredSize(new Dimension(18, 0));
westTestPanel.setPreferredSize(new Dimension(18, 0));
eastTestPanel.setBackground(Color.WHITE);
westTestPanel.setBackground(Color.WHITE);
bigMapPanel.add(eastTestPanel, BorderLayout.EAST);
bigMapPanel.add(westTestPanel, BorderLayout.WEST);
this.mapPanel = new MapPanel();
bigMapPanel.add(this.mapPanel, BorderLayout.CENTER);
mapPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
BottomPlayerPanel bottomPlayerPanel = new BottomPlayerPanel();
centerMapPanel.add(bottomPlayerPanel, BorderLayout.SOUTH);
}
private void setupChatPanel() {
this.bigChatPanel = new Panel();
this.bigChatPanel.setLayout(new BorderLayout());
this.bigChatPanel.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.BLACK));
this.bigChatPanel.setPreferredSize(new Dimension(280, 870));
this.bigChatPanel.setBackground(Color.WHITE);
this.add(bigChatPanel, BorderLayout.EAST);
Panel chatInputPanel = new Panel();
chatInputPanel.setBackground(Color.WHITE);
chatInputPanel.setPreferredSize(new Dimension(280, 90));
chatInputPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.BLACK));
this.bigChatPanel.add(chatInputPanel, BorderLayout.SOUTH);
ChatPanel chatTextPanel = new ChatPanel();
bigChatPanel.add(chatTextPanel, BorderLayout.CENTER);
chatTextPanel.setBackground(Color.WHITE);
TitlePanel titlePanel = new TitlePanel("Chat");
this.bigChatPanel.add(titlePanel, BorderLayout.NORTH);
}
private void setupPlayersPanel() {
Data data = StreetCar.player.getGameData();
this.playersTab = data.getPlayerOrder();
int nbPlayers = data.getNbrPlayer();
this.playersSidebarPanel = new Panel();
this.playersSidebarPanel.setLayout(null);
this.playersSidebarPanel.setPreferredSize(new Dimension(330, (nbPlayers-1)*185+30));
this.playersSidebarPanel.setBackground(Color.WHITE);
this.playersSidebarPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.BLACK));
titlePanel = new TitlePanel("Adversaries");
titlePanel.setBounds(0, 0, 329, 30);
playersSidebarPanel.add(titlePanel);
System.out.println(nbPlayers);
// catch the number of bottom player
int bottomPlayerIndex = 0;
for (int i=0; i<nbPlayers; i++) {
try {
if (playersTab[i].equals(StreetCar.player.getPlayerName())) {
bottomPlayerIndex = i;
break;
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
System.out.println("ORDRE DES JOUEURS: ");
for (int i=0; i<nbPlayers; i++) {
System.out.println(playersTab[i]);
}
System.out.println("INDEX DE LOUIS: " + bottomPlayerIndex);
int y = 40;
if (bottomPlayerIndex == nbPlayers-1) { //if bottom player is the last
for (int i=0; i<nbPlayers-1; i++) {
PlayerPanel playerPanel = new PlayerPanel(playersTab[i]);
playerPanels.add(playerPanel);
if (i<nbPlayers-1) { //last bar not displayed
playerPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
}
playerPanel.setBounds(15, y+(185*i), 285, 175);
playersSidebarPanel.add(playerPanel);
}
} else if (bottomPlayerIndex == 0) { // if bottom player is the first
for (int i=0; i<nbPlayers-1; i++) {
PlayerPanel playerPanel = new PlayerPanel(playersTab[i+1]);
playerPanels.add(playerPanel);
if (i<nbPlayers-1) { //last bar not displayed
playerPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
}
playerPanel.setBounds(15, y+(185*i), 285, 175);
playersSidebarPanel.add(playerPanel);
}
} else {
for (int i=0; i<nbPlayers-bottomPlayerIndex-1; i++) {
PlayerPanel playerPanel = new PlayerPanel(playersTab[i+bottomPlayerIndex+1]);
playerPanels.add (playerPanel);
if (i<nbPlayers-1) { //last bar not displayed
playerPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
}
playerPanel.setBounds(15, y+(185*i), 285, 175);
playersSidebarPanel.add(playerPanel);
}
for (int i=nbPlayers-bottomPlayerIndex-1; i<nbPlayers-1; i++) {
PlayerPanel playerPanel = new PlayerPanel(playersTab[i-2]);
playerPanels.add (playerPanel);
if (i<nbPlayers-1) { //last bar not displayed
playerPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
}
playerPanel.setBounds(15, y+(185*i), 285, 175);
playersSidebarPanel.add(playerPanel);
}
}
JScrollPane scrollPane = new JScrollPane(playersSidebarPanel);
scrollPane.setHorizontalScrollBar(null);
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(scrollPane, BorderLayout.WEST);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
// Actions
public void validate() {
// TODO: uncomment and fix
/*
try {
StreetCar.player.validate();
} catch (RemoteException e) {
e.printStackTrace();
} catch (ExceptionGameHasNotStarted e) {
e.printStackTrace();
} catch (ExceptionNotYourTurn e) {
e.printStackTrace();
} catch (ExceptionForbiddenAction e) {
e.printStackTrace();
}*/
}
public void beginTrip() {
System.out.println("THE TERMINUS IS UNDEFINED FOR THE MOMENT");
PlayerIHM player = StreetCar.player;
Point terminus = new Point();
try {
player.startMaidenTravel(player.getPlayerName(), terminus);
} catch (RemoteException e) {
e.printStackTrace();
} catch (ExceptionNotYourTurn e) {
e.printStackTrace();
} catch (ExceptionForbiddenAction e) {
e.printStackTrace();
} catch (ExceptionGameHasNotStarted e) {
e.printStackTrace();
} catch (ExceptionUncompletedPath e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Refresh game
public void refreshGame(PlayerIHM player, Data data) {
// TODO valz comment : was commented
System.out.println("REFRESH GAME");
this.mapPanel.refreshGame(player, data);
for (PlayerPanel playerPanel : this.playerPanels) {
playerPanel.refreshGame(player, data);
}
}
} |
package org.cache2k.impl;
import org.cache2k.*;
import org.cache2k.impl.operation.ExaminationEntry;
import org.cache2k.impl.operation.Semantic;
import org.cache2k.impl.operation.Specification;
import org.cache2k.impl.threading.DefaultThreadFactoryProvider;
import org.cache2k.impl.threading.Futures;
import org.cache2k.impl.threading.ThreadFactoryProvider;
import org.cache2k.impl.util.ThreadDump;
import org.cache2k.impl.util.Log;
import org.cache2k.impl.util.TunableConstants;
import org.cache2k.impl.util.TunableFactory;
import java.lang.reflect.Array;
import java.security.SecureRandom;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.BitSet;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.cache2k.impl.util.Util.*;
/**
* Foundation for all cache variants. All common functionality is in here.
* For a (in-memory) cache we need three things: a fast hash table implementation, an
* LRU list (a simple double linked list), and a fast timer.
* The variants implement different eviction strategies.
*
* <p>Locking: The cache has a single structure lock obtained via {@link #lock} and also
* locks on each entry for operations on it. Though, mutation operations that happen on a
* single entry get serialized.
*
* @author Jens Wilke; created: 2013-07-09
*/
@SuppressWarnings({"unchecked", "SynchronizationOnLocalVariableOrMethodParameter"})
public abstract class BaseCache<K, V>
extends AbstractCache<K, V> {
static final LoadCompletedListener DUMMY_LOAD_COMPLETED_LISTENER = new LoadCompletedListener() {
@Override
public void loadCompleted() {
}
@Override
public void loadException(final Exception _exception) {
}
};
static final Random SEED_RANDOM = new Random(new SecureRandom().nextLong());
static int cacheCnt = 0;
protected static final Tunable TUNABLE = TunableFactory.get(Tunable.class);
/**
* Instance of expiry calculator that extracts the expiry time from the value.
*/
final static EntryExpiryCalculator<?, ValueWithExpiryTime> ENTRY_EXPIRY_CALCULATOR_FROM_VALUE = new
EntryExpiryCalculator<Object, ValueWithExpiryTime>() {
@Override
public long calculateExpiryTime(
Object _key, ValueWithExpiryTime _value, long _fetchTime,
CacheEntry<Object, ValueWithExpiryTime> _oldEntry) {
return _value.getCacheExpiryTime();
}
};
final static ExceptionPropagator DEFAULT_EXCEPTION_PROPAGATOR = new ExceptionPropagator() {
@Override
public void propagateException(String _additionalMessage, Throwable _originalException) {
throw new PropagatedCacheException(_additionalMessage, _originalException);
}
};
protected int hashSeed;
{
if (TUNABLE.disableHashRandomization) {
hashSeed = TUNABLE.hashSeed;
} else {
hashSeed = SEED_RANDOM.nextInt();
}
}
HeapCacheListener<K,V> listener = HeapCacheListener.NO_OPERATION;
/** Maximum amount of elements in cache */
protected int maxSize = 5000;
protected String name;
protected CacheManagerImpl manager;
protected AdvancedCacheLoader<K,V> loader;
protected RefreshHandler<K,V> refreshHandler = new RefreshHandler.Dynamic<K, V>(this);
RefreshHandler.Dynamic<K,V> getDynamicRefreshHandler() {
return (RefreshHandler.Dynamic<K,V>) refreshHandler;
}
/** Statistics */
protected CacheBaseInfo info;
protected long clearedTime = 0;
protected long startedTime;
protected long touchedTime;
protected int timerCancelCount = 0;
protected long keyMutationCount = 0;
protected long putButExpiredCnt = 0;
protected long putNewEntryCnt = 0;
protected long removedCnt = 0;
/** Number of entries removed by clear. */
protected long clearedCnt = 0;
protected long expiredKeptCnt = 0;
protected long expiredRemoveCnt = 0;
protected long evictedCnt = 0;
protected long refreshCnt = 0;
protected long suppressedExceptionCnt = 0;
protected long loadExceptionCnt = 0;
/* that is a miss, but a hit was already counted. */
protected long peekHitNotFreshCnt = 0;
/* no heap hash hit */
protected long peekMissCnt = 0;
protected long loadCnt = 0;
protected long loadFailedCnt = 0;
protected long loadButHitCnt = 0;
protected long bulkGetCnt = 0;
protected long fetchMillis = 0;
protected long refreshHitCnt = 0;
protected long newEntryCnt = 0;
/**
* Read from storage, but the entry was not fresh and cannot be returned.
*/
protected long readNonFreshCnt = 0;
/**
* Entry was read from storage and fresh.
*/
protected long readHitCnt = 0;
/**
* Separate counter for read entries that needed a fetch.
*/
protected long readNonFreshAndFetchedCnt;
/**
* Storage did not contain the requested entry.
*/
protected long readMissCnt = 0;
protected long refreshSubmitFailedCnt = 0;
/**
* An exception that should not have happened and was not thrown to the
* application. Only used for the refresh thread yet.
*/
protected long internalExceptionCnt = 0;
/**
* Needed to correct the counter invariants, because during eviction the entry
* might be removed from the replacement list, but still in the hash.
*/
protected int evictedButInHashCnt = 0;
/**
* A newly inserted entry was removed by the eviction without the fetch to complete.
*/
protected long virginEvictCnt = 0;
CommonMetrics.Updater metrics = new StandardCommonMetrics();
/**
* Structure lock of the cache. Every operation that needs a consistent structure
* of the cache or modifies it needs to synchronize on this. Since this is a global
* lock, locking on it should be avoided and any operation under the lock should be
* quick.
*/
protected final Object lock = new Object();
protected volatile Executor loaderExecutor = new DummyExecutor(this);
static class DummyExecutor implements Executor {
BaseCache cache;
public DummyExecutor(final BaseCache _cache) {
cache = _cache;
}
@Override
public synchronized void execute(final Runnable _command) {
cache.loaderExecutor = cache.provideDefaultLoaderExecutor(0);
cache.loaderExecutor.execute(_command);
}
}
protected Hash<Entry<K, V>> mainHashCtrl;
protected Entry<K, V>[] mainHash;
protected Hash<Entry<K, V>> refreshHashCtrl;
protected Entry<K, V>[] refreshHash;
/** Stuff that we need to wait for before shutdown may complete */
protected Futures.WaitForAllFuture<?> shutdownWaitFuture;
protected boolean shutdownInitiated = false;
/**
* Flag during operation that indicates, that the cache is full and eviction needs
* to be done. Eviction is only allowed to happen after an entry is fetched, so
* at the end of an cache operation that increased the entry count we check whether
* something needs to be evicted.
*/
protected boolean evictionNeeded = false;
protected Class keyType;
protected Class valueType;
protected ExceptionPropagator exceptionPropagator = DEFAULT_EXCEPTION_PROPAGATOR;
private int featureBits = 0;
private static final int SHARP_TIMEOUT_FEATURE = 1;
private static final int KEEP_AFTER_EXPIRED = 2;
private static final int SUPPRESS_EXCEPTIONS = 4;
private static final int NULL_VALUE_SUPPORT = 8;
private static final int BACKGROUND_REFRESH = 16;
protected final boolean hasSharpTimeout() {
return (featureBits & SHARP_TIMEOUT_FEATURE) > 0;
}
protected final boolean hasKeepAfterExpired() {
return (featureBits & KEEP_AFTER_EXPIRED) > 0;
}
protected final boolean hasNullValueSupport() {
return (featureBits & NULL_VALUE_SUPPORT) > 0;
}
protected final boolean hasSuppressExceptions() {
return (featureBits & SUPPRESS_EXCEPTIONS) > 0;
}
protected final boolean hasBackgroundRefresh() { return (featureBits & BACKGROUND_REFRESH) > 0; }
protected final void setFeatureBit(int _bitmask, boolean _flag) {
if (_flag) {
featureBits |= _bitmask;
} else {
featureBits &= ~_bitmask;
}
}
/**
* Returns name of the cache with manager name.
*/
protected String getCompleteName() {
if (manager != null) {
return manager.getName() + ":" + name;
}
return name;
}
/**
* Normally a cache itself logs nothing, so just construct when needed.
*/
@Override
public Log getLog() {
return
Log.getLog(Cache.class.getName() + '/' + getCompleteName());
}
/** called from CacheBuilder */
public void setCacheConfig(CacheConfig c) {
valueType = c.getValueType().getType();
keyType = c.getKeyType().getType();
if (name != null) {
throw new IllegalStateException("already configured");
}
setName(c.getName());
maxSize = c.getEntryCapacity();
if (c.getHeapEntryCapacity() >= 0) {
maxSize = c.getHeapEntryCapacity();
}
if (c.isBackgroundRefresh()) {
setFeatureBit(BACKGROUND_REFRESH, true);
}
if (c.getLoaderThreadCount() > 0) {
loaderExecutor = provideDefaultLoaderExecutor(c.getLoaderThreadCount());
}
setFeatureBit(KEEP_AFTER_EXPIRED, c.isKeepDataAfterExpired());
setFeatureBit(SHARP_TIMEOUT_FEATURE, c.isSharpExpiry());
setFeatureBit(SUPPRESS_EXCEPTIONS, c.isSuppressExceptions());
getDynamicRefreshHandler().configure(c);
}
String getThreadNamePrefix() {
String _prefix = "cache2k-loader-";
if (manager != null &&
!Cache2kManagerProviderImpl.DEFAULT_MANAGER_NAME.equals(manager.getName())) {
_prefix = _prefix + manager.getName() + ":";
}
return _prefix + name;
}
Executor provideDefaultLoaderExecutor(int _threadCount) {
if (_threadCount <= 0) {
_threadCount = Runtime.getRuntime().availableProcessors() * TUNABLE.loaderThreadCountCpuFactor;
}
return
new ThreadPoolExecutor(_threadCount, _threadCount,
21, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(),
TUNABLE.threadFactoryProvider.newThreadFactory(getCacheManager(), getThreadNamePrefix()),
new ThreadPoolExecutor.AbortPolicy());
}
public void setEntryExpiryCalculator(EntryExpiryCalculator<K, V> v) {
getDynamicRefreshHandler().entryExpiryCalculator = v;
}
public void setExceptionExpiryCalculator(ExceptionExpiryCalculator<K> v) {
getDynamicRefreshHandler().exceptionExpiryCalculator = v;
}
/** called via reflection from CacheBuilder */
public void setRefreshController(final RefreshController<V> lc) {
setEntryExpiryCalculator(new EntryExpiryCalculator<K, V>() {
@Override
public long calculateExpiryTime(K _key, V _value, long _fetchTime, CacheEntry<K, V> _oldEntry) {
if (_oldEntry != null) {
return lc.calculateNextRefreshTime(_oldEntry.getValue(), _value, _oldEntry.getLastModification(), _fetchTime);
} else {
return lc.calculateNextRefreshTime(null, _value, 0L, _fetchTime);
}
}
});
}
public void setExceptionPropagator(ExceptionPropagator ep) {
exceptionPropagator = ep;
}
@SuppressWarnings("unused")
public void setSource(final CacheSourceWithMetaInfo<K, V> eg) {
if (eg == null) {
return;
}
loader = new AdvancedCacheLoader<K, V>() {
@Override
public V load(final K key, final long currentTime, final CacheEntry<K, V> previousEntry) throws Exception {
try {
if (previousEntry != null && previousEntry.getException() == null) {
return eg.get(key, currentTime, previousEntry.getValue(), previousEntry.getLastModification());
} else {
return eg.get(key, currentTime, null, 0);
}
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException("rethrow throwable", t);
}
}
};
}
@SuppressWarnings("unused")
public void setSource(final CacheSource<K, V> g) {
if (g == null) {
return;
}
loader = new AdvancedCacheLoader<K, V>() {
@Override
public V load(final K key, final long currentTime, final CacheEntry<K, V> previousEntry) throws Exception {
try {
return g.get(key);
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException("rethrow throwable", t);
}
}
};
}
@SuppressWarnings("unused")
public void setExperimentalBulkCacheSource(final ExperimentalBulkCacheSource<K, V> g) {
if (loader == null) {
loader = new AdvancedCacheLoader<K, V>() {
@Override
public V load(final K key, final long currentTime, final CacheEntry<K, V> previousEntry) throws Exception {
K[] ka = (K[]) Array.newInstance(keyType, 1);
ka[0] = key;
V[] ra = (V[]) Array.newInstance(valueType, 1);
BitSet _fetched = new BitSet(1);
g.getBulk(ka, ra, _fetched, 0, 1);
return ra[0];
}
};
}
}
public void setBulkCacheSource(final BulkCacheSource<K, V> s) {
if (loader == null) {
loader = new AdvancedCacheLoader<K, V>() {
@Override
public V load(final K key, final long currentTime, final CacheEntry<K, V> previousEntry) throws Exception {
CacheEntry<K, V> entry = previousEntry;
if (previousEntry == null)
entry = new CacheEntry<K, V>() {
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return null;
}
@Override
public Throwable getException() {
return null;
}
@Override
public long getLastModification() {
return 0;
}
};
try {
return s.getValues(Collections.singletonList(entry), currentTime).get(0);
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException("rethrow throwable", t);
}
}
};
}
}
public void setLoader(final CacheLoader<K,V> l) {
loader = new AdvancedCacheLoader<K, V>() {
@Override
public V load(final K key, final long currentTime, final CacheEntry<K, V> previousEntry) throws Exception {
return l.load(key);
}
};
}
public void setAdvancedLoader(final AdvancedCacheLoader<K,V> al) {
loader = al;
}
/**
* Set the name and configure a logging, used within cache construction.
*/
public void setName(String n) {
if (n == null) {
n = this.getClass().getSimpleName() + "#" + cacheCnt++;
}
name = n;
}
@Override
public String getName() {
return name;
}
public void setCacheManager(CacheManagerImpl cm) {
manager = cm;
}
@Override
public Class<?> getKeyType() { return keyType; }
@Override
public Class<?> getValueType() { return valueType; }
/**
* Registers the cache in a global set for the clearAllCaches function and
* registers it with the resource monitor.
*/
public void init() {
synchronized (lock) {
if (name == null) {
name = String.valueOf(cacheCnt++);
}
initializeHeapCache();
refreshHandler.init();
if (hasBackgroundRefresh() &&
loader == null) {
throw new CacheMisconfigurationException("backgroundRefresh, but no loader defined");
}
}
}
protected void updateShutdownWaitFuture(Future<?> f) {
synchronized (lock) {
if (shutdownWaitFuture == null || shutdownWaitFuture.isDone()) {
shutdownWaitFuture = new Futures.WaitForAllFuture(f);
} else {
shutdownWaitFuture.add((Future) f);
}
}
}
protected void checkClosed() {
if (isClosed()) {
throw new CacheClosedException();
}
}
public final void clear() {
synchronized (lock) {
checkClosed();
clearLocalCache();
}
}
protected final void clearLocalCache() {
iterateAllEntriesRemoveAndCancelTimer();
clearedCnt += getLocalSize();
initializeHeapCache();
clearedTime = System.currentTimeMillis();
touchedTime = clearedTime;
}
protected void iterateAllEntriesRemoveAndCancelTimer() {
Iterator<org.cache2k.impl.Entry> it = iterateAllHeapEntries();
int _count = 0;
while (it.hasNext()) {
org.cache2k.impl.Entry e = it.next();
e.removedFromList();
refreshHandler.cancelExpiryTimer(e);
_count++;
}
}
protected void initializeHeapCache() {
if (mainHashCtrl != null) {
mainHashCtrl.cleared();
refreshHashCtrl.cleared();
}
mainHashCtrl = new Hash<Entry<K, V>>();
refreshHashCtrl = new Hash<Entry<K, V>>();
mainHash = mainHashCtrl.init((Class<Entry<K, V>>) newEntry().getClass());
refreshHash = refreshHashCtrl.init((Class<Entry<K, V>>) newEntry().getClass());
if (startedTime == 0) {
startedTime = System.currentTimeMillis();
}
refreshHandler.shutdown();
refreshHandler.init();
}
@Override
public void clearTimingStatistics() {
synchronized (lock) {
loadCnt = 0;
fetchMillis = 0;
}
}
/**
* Preparation for shutdown. Cancel all pending timer jobs e.g. for
* expiry/refresh or flushing the storage.
*/
@Override
public Future<Void> cancelTimerJobs() {
synchronized (lock) {
refreshHandler.shutdown();
Future<Void> _waitFuture = new Futures.BusyWaitFuture<Void>() {
@Override
public boolean isDone() {
synchronized (lock) {
return getFetchesInFlight() == 0;
}
}
};
return _waitFuture;
}
}
@Override
public boolean isClosed() {
return shutdownInitiated;
}
@Override
public void destroy() {
close();
}
public void closePart1() {
synchronized (lock) {
if (shutdownInitiated) {
return;
}
shutdownInitiated = true;
}
Future<Void> _await = cancelTimerJobs();
try {
_await.get(TUNABLE.waitForTimerJobsSeconds, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
int _fetchesInFlight;
synchronized (lock) {
_fetchesInFlight = getFetchesInFlight();
}
if (_fetchesInFlight > 0) {
getLog().warn(
"Fetches still in progress after " +
TUNABLE.waitForTimerJobsSeconds + " seconds. " +
"fetchesInFlight=" + _fetchesInFlight);
} else {
getLog().warn(
"timeout waiting for timer jobs termination" +
" (" + TUNABLE.waitForTimerJobsSeconds + " seconds)", ex);
getLog().warn("Thread dump:\n" + ThreadDump.generateThredDump());
}
} catch (Exception ex) {
getLog().warn("exception waiting for timer jobs termination", ex);
}
synchronized (lock) {
mainHashCtrl.close();
refreshHashCtrl.close();
}
try {
Future<?> _future = shutdownWaitFuture;
if (_future != null) {
_future.get();
}
} catch (Exception ex) {
throw new CacheException(ex);
}
}
@Override
public void close() {
closePart1();
closePart2();
}
public void closePart2() {
synchronized (lock) {
refreshHandler.shutdown();
mainHash = refreshHash = null;
if (manager != null) {
manager.cacheDestroyed(this);
manager = null;
}
}
}
@Override
public ClosableIterator<CacheEntry<K, V>> iterator() {
synchronized (lock) {
return new IteratorFilterEntry2Entry(this, (ClosableIterator<Entry>) iterateAllHeapEntries(), true);
}
}
/**
* Filter out non valid entries and wrap each entry with a cache
* entry object.
*/
static class IteratorFilterEntry2Entry<K,V> implements ClosableIterator<CacheEntry<K, V>> {
BaseCache<K,V> cache;
ClosableIterator<Entry> iterator;
Entry entry;
CacheEntry<K, V> lastEntry;
boolean filter = true;
IteratorFilterEntry2Entry(BaseCache<K,V> c, ClosableIterator<Entry> it, boolean _filter) {
cache = c;
iterator = it;
filter = _filter;
}
/**
* Between hasNext() and next() an entry may be evicted or expired.
* In practise we have to deliver a next entry if we return hasNext() with
* true, furthermore, there should be no big gap between the calls to
* hasNext() and next().
*/
@Override
public boolean hasNext() {
if (entry != null) {
return true;
}
if (iterator == null) {
return false;
}
while (iterator.hasNext()) {
Entry e = iterator.next();
if (filter) {
if (e.hasFreshData()) {
entry = e;
return true;
}
} else {
entry = e;
return true;
}
}
entry = null;
close();
return false;
}
@Override
public void close() {
if (iterator != null) {
iterator.close();
iterator = null;
}
}
@Override
public CacheEntry<K, V> next() {
if (entry == null && !hasNext()) {
throw new NoSuchElementException("not available");
}
lastEntry = cache.returnEntry(entry);
entry = null;
return lastEntry;
}
@Override
public void remove() {
if (lastEntry == null) {
throw new IllegalStateException("hasNext() / next() not called or end of iteration reached");
}
cache.remove((K) lastEntry.getKey());
}
}
protected static void removeFromList(final Entry e) {
e.prev.next = e.next;
e.next.prev = e.prev;
e.removedFromList();
}
protected static void insertInList(final Entry _head, final Entry e) {
e.prev = _head;
e.next = _head.next;
e.next.prev = e;
_head.next = e;
}
protected static final int getListEntryCount(final Entry _head) {
org.cache2k.impl.Entry e = _head.next;
int cnt = 0;
while (e != _head) {
cnt++;
if (e == null) {
return -cnt;
}
e = e.next;
}
return cnt;
}
protected static final <E extends org.cache2k.impl.Entry> void moveToFront(final E _head, final E e) {
removeFromList(e);
insertInList(_head, e);
}
protected static final <E extends org.cache2k.impl.Entry> E insertIntoTailCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.next = _head;
e.prev = _head.prev;
_head.prev = e;
e.prev.next = e;
return _head;
}
/**
* Insert X into A B C, yields: A X B C.
*/
protected static final <E extends org.cache2k.impl.Entry> E insertAfterHeadCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.prev = _head;
e.next = _head.next;
_head.next.prev = e;
_head.next = e;
return _head;
}
/** Insert element at the head of the list */
protected static final <E extends org.cache2k.impl.Entry> E insertIntoHeadCyclicList(final E _head, final E e) {
if (_head == null) {
return (E) e.shortCircuit();
}
e.next = _head;
e.prev = _head.prev;
_head.prev.next = e;
_head.prev = e;
return e;
}
protected static <E extends org.cache2k.impl.Entry> E removeFromCyclicList(final E _head, E e) {
if (e.next == e) {
e.removedFromList();
return null;
}
org.cache2k.impl.Entry _eNext = e.next;
e.prev.next = _eNext;
e.next.prev = e.prev;
e.removedFromList();
return e == _head ? (E) _eNext : _head;
}
protected static org.cache2k.impl.Entry removeFromCyclicList(final org.cache2k.impl.Entry e) {
org.cache2k.impl.Entry _eNext = e.next;
e.prev.next = _eNext;
e.next.prev = e.prev;
e.removedFromList();
return _eNext == e ? null : _eNext;
}
protected static int getCyclicListEntryCount(org.cache2k.impl.Entry e) {
if (e == null) { return 0; }
final org.cache2k.impl.Entry _head = e;
int cnt = 0;
do {
cnt++;
e = e.next;
if (e == null) {
return -cnt;
}
} while (e != _head);
return cnt;
}
protected static boolean checkCyclicListIntegrity(org.cache2k.impl.Entry e) {
if (e == null) { return true; }
org.cache2k.impl.Entry _head = e;
do {
if (e.next == null) {
return false;
}
if (e.next.prev == null) {
return false;
}
if (e.next.prev != e) {
return false;
}
e = e.next;
} while (e != _head);
return true;
}
/**
* Record an entry hit.
*/
protected abstract void recordHit(Entry e);
/**
* New cache entry, put it in the replacement algorithm structure
*/
protected abstract void insertIntoReplacementList(Entry e);
/**
* Entry object factory. Return an entry of the proper entry subtype for
* the replacement/eviction algorithm.
*/
protected abstract Entry newEntry();
/**
* Find an entry that should be evicted. Called within structure lock.
* After doing some checks the cache will call {@link #removeEntryFromReplacementList(org.cache2k.impl.Entry)}
* if this entry will be really evicted. Pinned entries may be skipped. A
* good eviction algorithm returns another candidate on sequential calls, even
* if the candidate was not removed.
*
* <p/>Rationale: Within the structure lock we can check for an eviction candidate
* and may remove it from the list. However, we cannot process additional operations or
* events which affect the entry. For this, we need to acquire the lock on the entry
* first.
*/
protected abstract Entry findEvictionCandidate();
protected void removeEntryFromReplacementList(Entry e) {
removeFromList(e);
}
/**
* Check whether we have an entry in the ghost table
* remove it from ghost and insert it into the replacement list.
* null if nothing there. This may also do an optional eviction
* if the size limit of the cache is reached, because some replacement
* algorithms (ARC) do this together.
*/
protected Entry checkForGhost(K key, int hc) { return null; }
/**
* Implement unsynchronized lookup if it is supported by the eviction.
* If a null is returned the lookup is redone synchronized.
*/
protected Entry<K, V> lookupEntryUnsynchronized(K key, int hc) { return null; }
protected Entry lookupEntryUnsynchronizedNoHitRecord(K key, int hc) { return null; }
protected void recordHitLocked(Entry e) {
synchronized (lock) {
recordHit(e);
}
}
@Override
public V get(K key) {
return (V) returnValue(getEntryInternal(key));
}
/**
* Wrap entry in a separate object instance. We can return the entry directly, however we lock on
* the entry object.
*/
protected CacheEntry<K, V> returnEntry(final Entry<K, V> e) {
if (e == null) {
return null;
}
synchronized (e) {
final K _key = e.getKey();
final V _value = e.getValue();
final Throwable _exception = e.getException();
final long _lastModification = e.getLastModification();
return returnCacheEntry(_key, _value, _exception, _lastModification);
}
}
@Override
public String getEntryState(K key) {
Entry e = peekEntryInternal(key);
if (e == null) {
return null;
}
synchronized (e) {
return e.toString(this);
}
}
private CacheEntry<K, V> returnCacheEntry(final K _key, final V _value, final Throwable _exception, final long _lastModification) {
CacheEntry<K, V> ce = new CacheEntry<K, V>() {
@Override
public K getKey() {
return _key;
}
@Override
public V getValue() {
return _value;
}
@Override
public Throwable getException() {
return _exception;
}
@Override
public long getLastModification() {
return _lastModification;
}
@Override
public String toString() {
return "CacheEntry(" +
"key=" + getKey() +
((getException() != null) ? ", exception=" + getException() + ", " : ", value=" + getValue()) +
", updated=" + formatMillis(getLastModification());
}
};
return ce;
}
@Override
public CacheEntry<K, V> getEntry(K key) {
return returnEntry(getEntryInternal(key));
}
protected Entry getEntryInternal(K key) {
Entry e;
for (;;) {
e = lookupOrNewEntrySynchronized(key);
if (e.hasFreshData()) {
return e;
}
synchronized (e) {
e.waitForProcessing();
if (e.hasFreshData()) {
return e;
}
if (e.isGone()) {
continue;
}
e.startProcessing();
break;
}
}
boolean _finished = false;
try {
finishFetch(e, load(e));
_finished = true;
} finally {
e.ensureAbort(_finished);
}
evictEventually();
return e;
}
protected void finishFetch(Entry e, long _nextRefreshTime) {
synchronized (e) {
e.nextRefreshTime = stopStartTimer(_nextRefreshTime, e, System.currentTimeMillis());
e.processingDone();
e.notifyAll();
}
}
protected final void evictEventually() {
int _spinCount = TUNABLE.maximumEvictSpins;
Entry _previousCandidate = null;
while (evictionNeeded) {
if (_spinCount-- <= 0) { return; }
Entry e;
synchronized (lock) {
checkClosed();
if (getLocalSize() <= maxSize) {
evictionNeeded = false;
return;
}
e = findEvictionCandidate();
}
synchronized (e) {
if (e.isGone()) {
continue;
}
if (e.isPinned()) {
if (e != _previousCandidate) {
_previousCandidate = e;
continue;
} else {
return;
}
}
e.startProcessing(Entry.ProcessingState.EVICT);
}
listener.onEvictionFromHeap(e);
synchronized (e) {
finishFetch(e, org.cache2k.impl.Entry.ABORTED);
evictEntryFromHeap(e);
}
}
}
private void evictEntryFromHeap(Entry e) {
synchronized (lock) {
if (e.isRemovedFromReplacementList()) {
if (removeEntryFromHash(e)) {
evictedButInHashCnt
evictedCnt++;
}
} else {
if (removeEntry(e)) {
evictedCnt++;
}
}
evictionNeeded = getLocalSize() > maxSize;
}
e.notifyAll();
}
/**
* Remove the entry from the hash and the replacement list.
* There is a race condition to catch: The eviction may run
* in a parallel thread and may have already selected this
* entry.
*/
protected boolean removeEntry(Entry e) {
if (!e.isRemovedFromReplacementList()) {
removeEntryFromReplacementList(e);
}
return removeEntryFromHash(e);
}
@Override
public V peekAndPut(K key, V _value) {
final int hc = modifiedHash(key.hashCode());
boolean _hasFreshData;
V _previousValue = null;
Entry e;
for (;;) {
e = lookupOrNewEntrySynchronized(key, hc);
synchronized (e) {
e.waitForProcessing();
if (e.isGone()) {
continue;
}
_hasFreshData = e.hasFreshData();
if (_hasFreshData) {
_previousValue = (V) e.getValueOrException();
metrics.heapHitButNoRead();
} else {
peekMissCnt++;
}
putValue(e, _value);
break;
}
}
if (_hasFreshData) {
recordHitLocked(e);
}
return returnValue(_previousValue);
}
@Override
public V peekAndReplace(K key, V _value) {
Entry e;
for (;;) {
e = lookupEntrySynchronized(key);
if (e == null) { break; }
synchronized (e) {
e.waitForProcessing();
if (e.isGone()) {
continue;
}
if (e.hasFreshData()) {
V _previousValue = (V) e.getValueOrException();
putValue(e, _value);
return returnValue(_previousValue);
}
}
break;
}
synchronized (lock) {
peekMissCnt++;
}
return null;
}
private void putValue(final Entry _e, final V _value) {
long t = System.currentTimeMillis();
long _newNrt = insertOnPut(_e, _value, t, t);
_e.nextRefreshTime = stopStartTimer(_newNrt, _e, System.currentTimeMillis());
}
@Override
public boolean replace(K key, V _newValue) {
return replace(key, false, null, _newValue) == null;
}
@Override
public boolean replaceIfEquals(K key, V _oldValue, V _newValue) {
return replace(key, true, _oldValue, _newValue) == null;
}
@Override
public CacheEntry<K, V> replaceOrGet(K key, V _oldValue, V _newValue, CacheEntry<K, V> _dummyEntry) {
Entry e = replace(key, true, _oldValue, _newValue);
if (e == DUMMY_ENTRY_NO_REPLACE) {
return _dummyEntry;
} else if (e != null) {
return returnEntry(e);
}
return null;
}
final Entry DUMMY_ENTRY_NO_REPLACE = new org.cache2k.impl.Entry();
/**
* replace if value matches. if value not matches, return the existing entry or the dummy entry.
*/
protected Entry<K, V> replace(final K key, final boolean _compare, final V _oldValue, final V _newValue) {
Entry e = lookupEntrySynchronized(key);
if (e == null) {
synchronized (lock) {
peekMissCnt++;
}
return DUMMY_ENTRY_NO_REPLACE;
}
synchronized (e) {
e.waitForProcessing();
if (e.isGone() || !e.hasFreshData()) {
return (Entry) DUMMY_ENTRY_NO_REPLACE;
}
if (_compare && !e.equalsValue(_oldValue)) {
return e;
}
putValue(e, _newValue);
}
return null;
}
/**
* Return the entry, if it is in the cache, without invoking the
* cache source.
*
* <p>The cache storage is asked whether the entry is present.
* If the entry is not present, this result is cached in the local
* cache.
*/
final protected Entry<K, V> peekEntryInternal(K key) {
Entry e = lookupEntrySynchronized(key);
if (e == null) {
peekMissCnt++;
return null;
}
if (e.hasFreshData()) {
return e;
}
peekHitNotFreshCnt++;
return null;
}
@Override
public boolean contains(K key) {
Entry e = lookupEntrySynchronized(key);
if (e != null) {
metrics.containsButHit();
if (e.hasFreshData()) {
return true;
}
}
return false;
}
@Override
public V peek(K key) {
Entry<K, V> e = peekEntryInternal(key);
if (e != null) {
return returnValue(e);
}
return null;
}
@Override
public CacheEntry<K, V> peekEntry(K key) {
return returnEntry(peekEntryInternal(key));
}
@Override
public boolean putIfAbsent(K key, V value) {
for (;;) {
Entry e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForProcessing();
if (e.isGone()) {
continue;
}
if (e.hasFreshData()) {
return false;
}
peekMissCnt++;
putValue(e, value);
return true;
}
}
}
@Override
public void put(K key, V value) {
for (;;) {
Entry e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForProcessing();
if (e.isGone()) {
continue;
}
if (!e.isVirgin()) {
metrics.heapHitButNoRead();
}
putValue(e, value);
}
evictEventually();
return;
}
}
@Override
public boolean removeIfEquals(K key, V _value) {
return removeWithFlag(key, true, _value);
}
@Override
public boolean containsAndRemove(K key) {
return removeWithFlag(key, false, null);
}
/**
* Remove the object mapped to a key from the cache.
*
* <p>Operation with storage: If there is no entry within the cache there may
* be one in the storage, so we need to send the remove to the storage. However,
* if a remove() and a get() is going on in parallel it may happen that the entry
* gets removed from the storage and added again by the tail part of get(). To
* keep the cache and the storage consistent it must be ensured that this thread
* is the only one working on the entry.
*/
public boolean removeWithFlag(K key, boolean _checkValue, V _value) {
Entry e = lookupEntrySynchronizedNoHitRecord(key);
if (e == null) {
return false;
}
synchronized (e) {
e.waitForProcessing();
if (e.isGone()) {
return false;
}
synchronized (lock) {
boolean f = e.hasFreshData();
if (_checkValue) {
if (!f || !e.equalsValue(_value)) {
return false;
}
}
if (removeEntry(e)) {
removedCnt++;
metrics.remove();
return f;
}
return false;
}
}
}
@Override
public void remove(K key) {
containsAndRemove(key);
}
public V peekAndRemove(K key) {
Entry e = lookupEntrySynchronized(key);
if (e == null) {
synchronized (lock) {
peekMissCnt++;
}
return null;
}
synchronized (e) {
e.waitForProcessing();
if (e.isGone()) {
synchronized (lock) {
peekMissCnt++;
}
return null;
}
synchronized (lock) {
V _value = null;
boolean f = e.hasFreshData();
if (f) {
_value = (V) e.getValueOrException();
recordHit(e);
} else {
peekMissCnt++;
}
if (removeEntry(e)) {
removedCnt++;
metrics.remove();
}
return returnValue(_value);
}
}
}
/**
* True if we have spare threads in the thread pool that we can use for
* prefetching. If we get an instruction the prefetch, only do so if there
* are enough resources available, since we don't want to block out potentially
* more important refresh tasks from executing.
*/
boolean isLoaderThreadAvailableForPrefetching() {
Executor _loaderExecutor = loaderExecutor;
if (_loaderExecutor instanceof ThreadPoolExecutor) {
ThreadPoolExecutor ex = (ThreadPoolExecutor) _loaderExecutor;
return ex.getQueue().size() == 0;
}
if (_loaderExecutor instanceof DummyExecutor) {
return true;
}
return false;
}
@Override
public void prefetch(final K key) {
if (loader == null) {
return;
}
Entry<K,V> e = lookupEntrySynchronizedNoHitRecord(key);
if (e != null && e.hasFreshData()) {
return;
}
if (isLoaderThreadAvailableForPrefetching()) {
loaderExecutor.execute(new RunWithCatch() {
@Override
public void action() {
get(key);
}
});
}
}
@Override
public void prefetchAll(final Iterable<? extends K> _keys) {
if (loader == null) {
return;
}
Set<K> _keysToLoad = checkAllPresent(_keys);
for (K k : _keysToLoad) {
final K key = k;
if (!isLoaderThreadAvailableForPrefetching()) {
return;
}
Runnable r = new RunWithCatch() {
@Override
public void action() {
getEntryInternal(key);
}
};
loaderExecutor.execute(r);
}
}
@Override
public void loadAll(final Iterable<? extends K> _keys, final LoadCompletedListener l) {
checkLoaderPresent();
final LoadCompletedListener _listener= l != null ? l : DUMMY_LOAD_COMPLETED_LISTENER;
Set<K> _keysToLoad = checkAllPresent(_keys);
if (_keysToLoad.isEmpty()) {
_listener.loadCompleted();
return;
}
final AtomicInteger _countDown = new AtomicInteger(_keysToLoad.size());
for (K k : _keysToLoad) {
final K key = k;
Runnable r = new RunWithCatch() {
@Override
public void action() {
try {
getEntryInternal(key);
} finally {
if (_countDown.decrementAndGet() == 0) {
_listener.loadCompleted();
}
}
}
};
loaderExecutor.execute(r);
}
}
@Override
public void reloadAll(final Iterable<? extends K> _keys, final LoadCompletedListener l) {
checkLoaderPresent();
final LoadCompletedListener _listener= l != null ? l : DUMMY_LOAD_COMPLETED_LISTENER;
Set<K> _keySet = generateKeySet(_keys);
final AtomicInteger _countDown = new AtomicInteger(_keySet.size());
for (K k : _keySet) {
final K key = k;
Runnable r = new RunWithCatch() {
@Override
public void action() {
try {
loadAndReplace(key);
} finally {
if (_countDown.decrementAndGet() == 0) {
_listener.loadCompleted();
}
}
}
};
loaderExecutor.execute(r);
}
}
abstract class RunWithCatch implements Runnable {
protected abstract void action();
@Override
public final void run() {
try {
action();
} catch (CacheClosedException ignore) {
} catch (Throwable t) {
getLog().warn("Loader thread exception", t);
}
}
}
public Set<K> generateKeySet(final Iterable<? extends K> _keys) {
Set<K> _keySet = new HashSet<K>();
for (K k : _keys) {
_keySet.add(k);
}
return _keySet;
}
public Set<K> checkAllPresent(final Iterable<? extends K> keys) {
Set<K> _keysToLoad = new HashSet<K>();
for (K k : keys) {
Entry<K,V> e = lookupEntrySynchronizedNoHitRecord(k);
if (e == null || !e.hasFreshData()) {
_keysToLoad.add(k);
}
}
return _keysToLoad;
}
public Entry<K, V> lookupEntryUnsynchronized(final K k) {
return lookupEntryUnsynchronized(k, modifiedHash(k.hashCode()));
}
/**
* Always fetch the value from the source. That is a copy of getEntryInternal
* without freshness checks.
*/
protected void loadAndReplace(K key) {
Entry e;
for (;;) {
e = lookupOrNewEntrySynchronized(key);
synchronized (e) {
e.waitForProcessing();
if (e.isGone()) {
continue;
}
e.startProcessing();
break;
}
}
boolean _finished = false;
try {
finishFetch(e, load(e));
_finished = true;
} finally {
e.ensureAbort(_finished);
}
evictEventually();
}
/**
* Lookup or create a new entry. The new entry is created, because we need
* it for locking within the data fetch.
*/
protected Entry<K, V> lookupOrNewEntrySynchronized(K key) {
int hc = modifiedHash(key.hashCode());
return lookupOrNewEntrySynchronized(key, hc);
}
protected Entry<K, V> lookupOrNewEntrySynchronized(K key, int hc) {
Entry e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntry(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
return e;
}
protected Entry<K, V> lookupOrNewEntrySynchronizedNoHitRecord(K key) {
int hc = modifiedHash(key.hashCode());
Entry e = lookupEntryUnsynchronizedNoHitRecord(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntryNoHitRecord(key, hc);
if (e == null) {
e = newEntry(key, hc);
}
}
}
return e;
}
protected V returnValue(V v) {
if (v instanceof ExceptionWrapper) {
ExceptionWrapper w = (ExceptionWrapper) v;
if (w.additionalExceptionMessage == null) {
long t = w.until;
if (t > 0) {
w.additionalExceptionMessage = "(expiry=" + (t > 0 ? formatMillis(t) : "none") + ") " + w.getException();
} else {
w.additionalExceptionMessage = w.getException() + "";
}
}
exceptionPropagator.propagateException(w.additionalExceptionMessage, w.getException());
}
return v;
}
protected V returnValue(Entry<K, V> e) {
V v = e.value;
if (v instanceof ExceptionWrapper) {
ExceptionWrapper w = (ExceptionWrapper) v;
if (w.additionalExceptionMessage == null) {
synchronized (e) {
long t = e.getValueExpiryTime();
w.additionalExceptionMessage = "(expiry=" + (t > 0 ? formatMillis(t) : "none") + ") " + w.getException();
}
}
exceptionPropagator.propagateException(w.additionalExceptionMessage, w.getException());
}
return v;
}
protected Entry<K, V> lookupEntrySynchronized(K key) {
int hc = modifiedHash(key.hashCode());
Entry e = lookupEntryUnsynchronized(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntry(key, hc);
}
}
return e;
}
protected Entry lookupEntrySynchronizedNoHitRecord(K key) {
int hc = modifiedHash(key.hashCode());
Entry e = lookupEntryUnsynchronizedNoHitRecord(key, hc);
if (e == null) {
synchronized (lock) {
checkClosed();
e = lookupEntryNoHitRecord(key, hc);
}
}
return e;
}
protected final Entry<K, V> lookupEntry(K key, int hc) {
Entry e = Hash.lookup(mainHash, key, hc);
if (e != null) {
recordHit(e);
return e;
}
e = refreshHashCtrl.remove(refreshHash, key, hc);
if (e != null) {
refreshHitCnt++;
mainHash = mainHashCtrl.insert(mainHash, e);
recordHit(e);
return e;
}
return null;
}
protected final Entry lookupEntryNoHitRecord(K key, int hc) {
Entry e = Hash.lookup(mainHash, key, hc);
if (e != null) {
return e;
}
e = refreshHashCtrl.remove(refreshHash, key, hc);
if (e != null) {
refreshHitCnt++;
mainHash = mainHashCtrl.insert(mainHash, e);
return e;
}
return null;
}
/**
* Insert new entry in all structures (hash and replacement list). May evict an
* entry if the maximum capacity is reached.
*/
protected Entry<K, V> newEntry(K key, int hc) {
if (getLocalSize() >= maxSize) {
evictionNeeded = true;
}
Entry e = checkForGhost(key, hc);
if (e == null) {
e = newEntry();
e.key = key;
e.hashCode = hc;
insertIntoReplacementList(e);
}
mainHash = mainHashCtrl.insert(mainHash, e);
newEntryCnt++;
return e;
}
/**
* Called when expiry of an entry happens. Remove it from the
* main cache, refresh cache and from the (lru) list. Also cancel the timer.
* Called under big lock.
*/
/**
* The entry is already removed from the replacement list. stop/reset timer, if needed.
* Called under big lock.
*/
private boolean removeEntryFromHash(Entry<K, V> e) {
boolean f = mainHashCtrl.remove(mainHash, e) || refreshHashCtrl.remove(refreshHash, e);
checkForHashCodeChange(e);
refreshHandler.cancelExpiryTimer(e);
if (e.isVirgin()) {
virginEvictCnt++;
}
e.setGone();
return f;
}
/**
* Check whether the key was modified during the stay of the entry in the cache.
* We only need to check this when the entry is removed, since we expect that if
* the key has changed, the stored hash code in the cache will not match any more and
* the item is evicted very fast.
*/
private void checkForHashCodeChange(Entry<K, V> e) {
if (modifiedHash(e.key.hashCode()) != e.hashCode && !e.isStale()) {
if (keyMutationCount == 0) {
getLog().warn("Key mismatch! Key hashcode changed! keyClass=" + e.key.getClass().getName());
String s;
try {
s = e.key.toString();
if (s != null) {
getLog().warn("Key mismatch! key.toString(): " + s);
}
} catch (Throwable t) {
getLog().warn("Key mismatch! key.toString() threw exception", t);
}
}
keyMutationCount++;
}
}
protected long load(Entry<K, V> e) {
V v;
long t0 = System.currentTimeMillis();
try {
checkLoaderPresent();
if (e.isVirgin()) {
v = loader.load((K) e.key, t0, null);
} else {
v = loader.load((K) e.key, t0, e);
}
e.setLastModification(t0);
} catch (Throwable _ouch) {
v = (V) new ExceptionWrapper(_ouch);
}
long t = System.currentTimeMillis();
return insertOrUpdateAndCalculateExpiry(e, v, t0, t, INSERT_STAT_UPDATE);
}
private void checkLoaderPresent() {
if (loader == null) {
throw new UnsupportedOperationException("loader not set");
}
}
protected final long insertOnPut(Entry<K, V> e, V v, long t0, long t) {
e.setLastModification(t0);
return insertOrUpdateAndCalculateExpiry(e, v, t0, t, INSERT_STAT_PUT);
}
/**
* Calculate the next refresh time if a timer / expiry is needed and call insert.
*/
protected final long insertOrUpdateAndCalculateExpiry(Entry<K, V> e, V v, long t0, long t, byte _updateStatistics) {
long _nextRefreshTime;
try {
_nextRefreshTime = refreshHandler.calculateNextRefreshTime(e, v, t0);
} catch (Exception ex) {
try {
updateStatistics(e, v, t0, t, _updateStatistics, false);
} catch (Throwable ignore) { }
throw new CacheException("exception in expiry calculation", ex);
}
return insert(e, v, t0, t, _updateStatistics, _nextRefreshTime);
}
final static byte INSERT_STAT_NO_UPDATE = 0;
final static byte INSERT_STAT_UPDATE = 1;
final static byte INSERT_STAT_PUT = 2;
/**
* @param _nextRefreshTime -1/MAXVAL: eternal, 0: expires immediately
*/
protected final long insert(Entry<K, V> e, V _value, long t0, long t, byte _updateStatistics, long _nextRefreshTime) {
if (_nextRefreshTime == -1) {
_nextRefreshTime = Long.MAX_VALUE;
}
final boolean _suppressException =
needsSuppress(e, _value);
if (!_suppressException) {
e.value = _value;
}
if (_value instanceof ExceptionWrapper && !_suppressException) {
Log log = getLog();
if (log.isDebugEnabled()) {
log.debug(
"source caught exception, expires at: " + formatMillis(_nextRefreshTime),
((ExceptionWrapper) _value).getException());
}
}
synchronized (lock) {
checkClosed();
updateStatisticsNeedsLock(e, _value, t0, t, _updateStatistics, _suppressException);
if (_nextRefreshTime == 0) {
_nextRefreshTime = Entry.EXPIRED;
} else {
if (_nextRefreshTime == Long.MAX_VALUE) {
_nextRefreshTime = Entry.DATA_VALID;
}
}
if (_updateStatistics == INSERT_STAT_PUT && !e.hasFreshData(t, _nextRefreshTime)) {
putButExpiredCnt++;
}
} // synchronized (lock)
return _nextRefreshTime;
}
boolean needsSuppress(final Entry<K, V> e, final V _value) {
return _value instanceof ExceptionWrapper && hasSuppressExceptions() && e.getValue() != Entry.INITIAL_VALUE && !e.hasException();
}
private void updateStatistics(Entry e, V _value, long t0, long t, byte _updateStatistics, boolean _suppressException) {
synchronized (lock) {
checkClosed();
updateStatisticsNeedsLock(e, _value, t0, t, _updateStatistics, _suppressException);
}
}
private void updateStatisticsNeedsLock(Entry e, V _value, long t0, long t, byte _updateStatistics, boolean _suppressException) {
touchedTime = t;
if (_updateStatistics == INSERT_STAT_UPDATE) {
if (_suppressException) {
suppressedExceptionCnt++;
loadExceptionCnt++;
} else {
if (_value instanceof ExceptionWrapper) {
loadExceptionCnt++;
}
}
fetchMillis += t - t0;
if (e.isGettingRefresh()) {
refreshCnt++;
} else {
loadCnt++;
if (!e.isVirgin()) {
loadButHitCnt++;
}
}
} else if (_updateStatistics == INSERT_STAT_PUT) {
metrics.putNewEntry();
eventuallyAdjustPutNewEntryCount(e);
}
}
private void eventuallyAdjustPutNewEntryCount(Entry e) {
if (e.isVirgin()) {
putNewEntryCnt++;
}
}
protected long stopStartTimer(long _nextRefreshTime, Entry e, long now) {
return refreshHandler.stopStartTimer(_nextRefreshTime, e, now);
}
void cancelExpiryTimer(Entry e) {
refreshHandler.cancelExpiryTimer(e);
}
/**
* Move entry to a separate hash for the entries that got a refresh.
* @return True, if successful
*/
public boolean moveToRefreshHash(Entry e) {
synchronized (lock) {
if (isClosed()) {
return false;
}
if (mainHashCtrl.remove(mainHash, e)) {
refreshHash = refreshHashCtrl.insert(refreshHash, e);
if (e.hashCode != modifiedHash(e.key.hashCode())) {
if (removeEntryFromHash(e)) {
expiredRemoveCnt++;
}
return false;
}
return true;
}
}
return false;
}
@Override
public void timerEventRefresh(final Entry<K, V> e) {
metrics.timerEvent();
synchronized (e) {
if (e.isGone()) {
return;
}
if (moveToRefreshHash(e)) {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized (e) {
e.waitForProcessing();
if (e.isGone()) {
return;
}
e.setGettingRefresh();
}
try {
finishFetch(e, load(e));
} catch (CacheClosedException ignore) {
} catch (Throwable ex) {
e.ensureAbort(false);
synchronized (lock) {
internalExceptionCnt++;
}
getLog().warn("Refresh exception", ex);
try {
expireEntry(e);
} catch (CacheClosedException ignore) {
}
}
}
};
try {
loaderExecutor.execute(r);
return;
} catch (RejectedExecutionException ignore) {
}
refreshSubmitFailedCnt++;
} else { // if (mainHashCtrl.remove(mainHash, e)) ...
}
timerEventExpireEntryLocked(e);
}
}
@Override
public void timerEventExpireEntry(Entry<K, V> e) {
metrics.timerEvent();
synchronized (e) {
timerEventExpireEntryLocked(e);
}
}
private void timerEventExpireEntryLocked(final Entry<K, V> e) {
long nrt = e.nextRefreshTime;
if (nrt < Entry.EXPIRY_TIME_MIN) {
return;
}
long t = System.currentTimeMillis();
if (t >= e.nextRefreshTime) {
try {
expireEntry(e);
} catch (CacheClosedException ignore) { }
} else {
e.nextRefreshTime = -e.nextRefreshTime;
if (!hasKeepAfterExpired()) {
}
}
}
protected void expireEntry(Entry e) {
synchronized (e) {
if (e.isGone() || e.isExpired()) {
return;
}
e.setExpiredState();
synchronized (lock) {
checkClosed();
if (hasKeepAfterExpired() || e.isProcessing()) {
expiredKeptCnt++;
} else {
if (removeEntry(e)) {
expiredRemoveCnt++;
}
}
}
}
}
/**
* Returns all cache entries within the heap cache. Entries that
* are expired or contain no valid data are not filtered out.
*/
final protected ClosableConcurrentHashEntryIterator<org.cache2k.impl.Entry> iterateAllHeapEntries() {
return
new ClosableConcurrentHashEntryIterator(
mainHashCtrl, mainHash, refreshHashCtrl, refreshHash);
}
@Override
public void removeAllAtOnce(Set<K> _keys) {
throw new UnsupportedOperationException();
}
@Override
public void removeAll(final Set<? extends K> keys) {
for (K k : keys) {
remove(k);
}
}
/**
* JSR107 bulk interface. The behaviour is compatible to the JSR107 TCK. We also need
* to be compatible to the exception handling policy, which says that the exception
* is to be thrown when most specific. So exceptions are only thrown, when the value
* which has produced an exception is requested from the map.
*/
public Map<K, V> getAll(final Iterable<? extends K> _inputKeys) {
final Set<K> _keys = new HashSet<K>();
for (K k : _inputKeys) {
Entry e = getEntryInternal(k);
if (e != null) {
_keys.add(k);
}
}
final Set<Map.Entry<K, V>> set =
new AbstractSet<Map.Entry<K, V>>() {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new Iterator<Map.Entry<K, V>>() {
Iterator<? extends K> keyIterator = _keys.iterator();
@Override
public boolean hasNext() {
return keyIterator.hasNext();
}
@Override
public Map.Entry<K, V> next() {
final K key = keyIterator.next();
return new Map.Entry<K, V>(){
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return get(key);
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
};
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return _keys.size();
}
};
return new AbstractMap<K, V>() {
@Override
public V get(Object key) {
if (containsKey(key)) {
return BaseCache.this.get((K) key);
}
return null;
}
@Override
public boolean containsKey(Object key) {
return _keys.contains(key);
}
@Override
public Set<Entry<K, V>> entrySet() {
return set;
}
};
}
public Map<K, V> convertValueMap(final Map<K, ExaminationEntry<K, V>> _map) {
return new MapValueConverterProxy<K, V, ExaminationEntry<K, V>>(_map) {
@Override
protected V convert(final ExaminationEntry<K, V> v) {
return returnValue(v.getValueOrException());
}
};
}
public Map<K, V> peekAll(final Set<? extends K> _inputKeys) {
Map<K, ExaminationEntry<K, V>> map = new HashMap<K, ExaminationEntry<K, V>>();
for (K k : _inputKeys) {
ExaminationEntry<K, V> e = peekEntryInternal(k);
if (e != null) {
map.put(k, e);
}
}
return convertValueMap(map);
}
public void putAll(Map<? extends K, ? extends V> valueMap) {
if (valueMap.containsKey(null)) {
throw new NullPointerException("map contains null key");
}
for (Map.Entry<? extends K, ? extends V> e : valueMap.entrySet()) {
put(e.getKey(), e.getValue());
}
}
Specification<K,V> spec() { return Specification.SINGLETON; }
@Override
protected <R> EntryAction<K, V, R> createEntryAction(final K key, final Entry<K, V> e, final Semantic<K, V, R> op) {
return new EntryAction<K, V, R>(this, this, op, key, e);
}
/**
* Simply the {@link EntryAction} based code to provide the entry processor. If we code it directly this
* might be a little bit more efficient, but it gives quite a code bloat which has lots of
* corner cases for loader and exception handling.
*/
@Override
public <R> R invoke(K key, CacheEntryProcessor<K, V, R> entryProcessor, Object... args) {
return execute(key, spec().invoke(key, loader != null, entryProcessor, args));
}
public abstract long getHitCnt();
protected final int calculateHashEntryCount() {
return Hash.calcEntryCount(mainHash) + Hash.calcEntryCount(refreshHash);
}
protected final int getLocalSize() {
return mainHashCtrl.size + refreshHashCtrl.size;
}
public final int getTotalEntryCount() {
synchronized (lock) {
checkClosed();
return getLocalSize();
}
}
public long getExpiredCnt() {
return expiredRemoveCnt + expiredKeptCnt;
}
/**
* For peek no fetch is counted if there is a storage miss, hence the extra counter.
*/
public long getFetchesBecauseOfNewEntries() {
return loadCnt - loadButHitCnt + loadFailedCnt;
}
protected int getFetchesInFlight() {
return 0;
}
protected IntegrityState getIntegrityState() {
synchronized (lock) {
checkClosed();
return new IntegrityState()
.checkEquals("newEntryCnt == getSize() + evictedCnt + expiredRemoveCnt + removeCnt + clearedCnt", newEntryCnt, getLocalSize() + evictedCnt + expiredRemoveCnt + removedCnt + clearedCnt)
.checkEquals("newEntryCnt == getSize() + evictedCnt + getExpiredCnt() - expiredKeptCnt + removeCnt + clearedCnt", newEntryCnt, getLocalSize() + evictedCnt + getExpiredCnt() - expiredKeptCnt + removedCnt + clearedCnt)
.checkEquals("mainHashCtrl.size == Hash.calcEntryCount(mainHash)", mainHashCtrl.size, Hash.calcEntryCount(mainHash))
.checkEquals("refreshHashCtrl.size == Hash.calcEntryCount(refreshHash)", refreshHashCtrl.size, Hash.calcEntryCount(refreshHash))
.check("!!evictionNeeded | (getSize() <= maxSize)", !!evictionNeeded | (getLocalSize() <= maxSize));
}
}
/** Check internal data structures and throw and exception if something is wrong, used for unit testing */
public final void checkIntegrity() {
synchronized (lock) {
checkClosed();
IntegrityState is = getIntegrityState();
if (is.getStateFlags() > 0) {
throw new CacheIntegrityError(is.getStateDescriptor(), is.getFailingChecks(), toString());
}
}
}
@Override
public final InternalCacheInfo getInfo() {
synchronized (lock) {
checkClosed();
long t = System.currentTimeMillis();
if (info != null &&
(info.creationTime + info.creationDeltaMs * TUNABLE.minimumStatisticsCreationTimeDeltaFactor + TUNABLE.minimumStatisticsCreationDeltaMillis > t)) {
return info;
}
info = generateInfo(t);
}
return info;
}
@Override
public final InternalCacheInfo getLatestInfo() {
return generateInfo(System.currentTimeMillis());
}
private CacheBaseInfo generateInfo(long t) {
synchronized (lock) {
checkClosed();
info = new CacheBaseInfo(this);
info.creationTime = t;
info.creationDeltaMs = (int) (System.currentTimeMillis() - t);
return info;
}
}
protected String getExtraStatistics() { return ""; }
@Override
public CacheManager getCacheManager() {
return manager;
}
/**
* Return status information. The status collection is time consuming, so this
* is an expensive operation.
*/
@Override
public String toString() {
synchronized (lock) {
if (isClosed()) {
return "Cache{" + name + "}(closed)";
}
InternalCacheInfo fo = getLatestInfo();
return "Cache{" + name + "}"
+ "(" + fo.toString() + ")";
}
}
static class CollisionInfo {
int collisionCnt; int collisionSlotCnt; int longestCollisionSize;
}
/**
* This function calculates a modified hash code. The intention is to
* "rehash" the incoming integer hash codes to overcome weak hash code
* implementations. We expect good results for integers also.
* Also add a random seed to the hash to protect against attacks on hashes.
* This is actually a slightly reduced version of the java.util.HashMap
* hash modification.
*/
protected final int modifiedHash(int h) {
h ^= hashSeed;
h ^= h >>> 7;
h ^= h >>> 15;
return h;
}
public static class Tunable extends TunableConstants {
/**
* Implementation class to use by default.
*/
public Class<? extends InternalCache> defaultImplementation =
"64".equals(System.getProperty("sun.arch.data.model"))
? ClockProPlus64Cache.class : ClockProPlusCache.class;
public int waitForTimerJobsSeconds = 5;
/**
* Limits the number of spins until an entry lock is expected to
* succeed. The limit is to detect deadlock issues during development
* and testing. It is set to an arbitrary high value to result in
* an exception after about one second of spinning.
*/
public int maximumEntryLockSpins = 333333;
/**
* Maximum number of tries to find an entry for eviction if maximum size
* is reached.
*/
public int maximumEvictSpins = 5;
/**
* Size of the hash table before inserting the first entry. Must be power
* of two. Default: 64.
*/
public int initialHashSize = 64;
/**
* Fill percentage limit. When this is reached the hash table will get
* expanded. Default: 64.
*/
public int hashLoadPercent = 64;
/**
* The hash code will randomized by default. This is a countermeasure
* against from outside that know the hash function.
*/
public boolean disableHashRandomization = false;
/**
* Seed used when randomization is disabled. Default: 0.
*/
public int hashSeed = 0;
/**
* When sharp expiry is enabled, the expiry timer goes
* before the actual expiry to switch back to a time checking
* scheme when the get method is invoked. This prevents
* that an expired value gets served by the cache if the time
* is too late. A recent GC should not produce more then 200
* milliseconds stall. If longer GC stalls are expected, this
* value needs to be changed. A value of LONG.MaxValue
* suppresses the timer usage completely.
*/
public long sharpExpirySafetyGapMillis = 666;
/**
* Some statistic values need processing time to gather and compute it. This is a safety
* time delta, to ensure that the machine is not busy due to statistics generation. Default: 333.
*/
public int minimumStatisticsCreationDeltaMillis = 333;
/**
* Factor of the statistics creation time, that determines the time difference when new
* statistics are generated.
*/
public int minimumStatisticsCreationTimeDeltaFactor = 123;
public ThreadFactoryProvider threadFactoryProvider = new DefaultThreadFactoryProvider();
/**
* Number of maximum loader threads, depending on the CPUs.
*/
public int loaderThreadCountCpuFactor = 2;
}
} |
package de.charite.zpgen;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import org.coode.owlapi.obo12.parser.OBOVocabulary;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.io.OWLFunctionalSyntaxOntologyFormat;
import org.semanticweb.owlapi.io.RDFXMLOntologyFormat;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLAnnotationValue;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyID;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.semanticweb.owlapi.model.SetOntologyID;
import com.beust.jcommander.JCommander;
import com.google.common.collect.ImmutableSetMultimap;
public class ZPGen {
static private Logger log = Logger.getLogger(ZPGen.class.getName());
public static void main(String[] args) throws OWLOntologyCreationException, IOException, InterruptedException {
ZPGenCLIConfig zpCLIConfig = new ZPGenCLIConfig();
JCommander jc = new JCommander(zpCLIConfig);
jc.parse(args);
jc.setProgramName(ZPGen.class.getSimpleName());
if (zpCLIConfig.help) {
jc.usage();
System.exit(0);
}
final boolean addSourceInformation = zpCLIConfig.addSourceInformation || zpCLIConfig.sourceInformationFile != null;
final String zfinFilePath = zpCLIConfig.zfinFilePath;
final String previousOntologyFilePath = zpCLIConfig.previousOntologyFilePath;
final String ontologyOutputFilePath = zpCLIConfig.ontologyOutputFilePath;
final String annotFilePath = zpCLIConfig.annotFilePath;
final boolean keepIds = zpCLIConfig.keepIds;
final boolean useInheresInPartOf = zpCLIConfig.useInheresInPartOf;
final boolean useOwlRdfSyntax = zpCLIConfig.useOwlRdfSyntax;
final boolean addZfaUberonEquivalencies = zpCLIConfig.addZfaUberonEquivalencies;
final String uberonOboFilePath = zpCLIConfig.uberonOboFilePath;
/* Create ontology manager and IRIs */
final OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
final IRI zpIRI = IRI.create("http://purl.obolibrary.org/obo/upheno/zp.owl");
final IRI purlOboIRI = IRI.create("http://purl.obolibrary.org/obo/");
/* Load the previous zp, if requested */
final OWLOntology zp;
if (keepIds) {
File ontoFile = new File(previousOntologyFilePath);
if (ontoFile.exists()) {
zp = manager.loadOntologyFromOntologyDocument(ontoFile);
}
else {
// log.info("Ignoring non-existent file \"" +
// ontologyOutputFilePath + "\" for keeping the ids");
// zp = manager.createOntology(zpIRI);
log.severe("Could not find file \"" + previousOntologyFilePath + "\" for keeping the ids");
throw new IllegalArgumentException("Keeping IDs was requested, but no previous file \"" + previousOntologyFilePath
+ "\" was found! Prefer to stop here...");
}
}
else {
zp = manager.createOntology(zpIRI);
}
/*
* Add version IRI by using the date of construction
*/
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
IRI versionIRI = IRI.create("http://purl.obolibrary.org/obo/upheno/releases/" + sdf.format(date) + "/zp.owl");
manager.applyChange(new SetOntologyID(zp, new OWLOntologyID(zpIRI, versionIRI)));
/*
* If user wants to have equivalence axioms between ZFA-classes and UBERON-classes we need the uberon.obo to create a mapping here.
*/
ImmutableSetMultimap<String, String> zfa2uberon = null;
if (addZfaUberonEquivalencies) {
log.info("creating ZFA-UBERON mapping");
if (uberonOboFilePath == null) {
log.severe("No uberon-file was provided for creating the ZFA-UBERON-mapping.");
throw new IllegalArgumentException(
"ZFA-UBERON-mapping requested, but no uberon.obo file was provided! Use option --uberon-obo-file. Prefer to stop here...");
}
File uberonOntoFile = new File(uberonOboFilePath);
if (!uberonOntoFile.exists()) {
log.severe("Could not find file \"" + uberonOboFilePath + "\" for creating the ZFA-UBERON-mapping.");
throw new IllegalArgumentException("ZFA-UBERON-mapping requested, but no uberon.obo file \"" + uberonOboFilePath
+ "\" was found! Prefer to stop here...");
}
Zfa2UberonMapper zfa2uberonMapper = new Zfa2UberonMapper(uberonOboFilePath);
zfa2uberon = zfa2uberonMapper.getZfa2UberonMapping();
}
/* Instanciate the zpid db */
final ZPIDDB zpIdDB = new ZPIDDB(zp);
/* Where to write the annotation file to */
final BufferedWriter annotationOut = new BufferedWriter(new FileWriter(annotFilePath));
/* Obtain the default data factory */
final OWLDataFactory factory = manager.getOWLDataFactory();
/* Open zfin input file */
File f = new File(zfinFilePath);
if (f.isDirectory()) {
System.err.println(String.format(
"Specified zfin parameter value \"%s\" must point to a file (as the name suggests) and not a directory.", zfinFilePath));
System.exit(-1);
}
if (!f.exists()) {
System.err.println(String.format("Specified file \"%s\" doesn't exist!", zfinFilePath));
System.exit(-1);
}
// not sure which one to use RO_0002503 or BFO_0000070 ??
final OWLObjectProperty towards = factory.getOWLObjectProperty(IRI.create(purlOboIRI + "RO_0002503"));
final OWLObjectProperty partOf = factory.getOWLObjectProperty(IRI.create(purlOboIRI + "BFO_0000050"));
// I have for now replaced the BFO-properties with the RO-properties
final OWLObjectProperty inheresProperty;
if (useInheresInPartOf) {
// inheres in part of
inheresProperty = factory.getOWLObjectProperty(IRI.create(purlOboIRI + "RO_0002314"));
}
else {
// inheres in
inheresProperty = factory.getOWLObjectProperty(IRI.create(purlOboIRI + "RO_0000052"));
// inheresProperty = factory.getOWLObjectProperty(IRI.create(zpIRI +
// "BFO_0000052"));
}
final OWLObjectProperty hasPart = factory.getOWLObjectProperty(IRI.create(purlOboIRI + "BFO_0000051"));
/* RO_0002180 = "has qualifier" (previously used) */
/* RO_0002573 = "has modifier" (used in most recent version) */
// final OWLObjectProperty has_qualifier =
// factory.getOWLObjectProperty(IRI.create(zpIRI + "RO_0002180"));
final OWLObjectProperty has_modifier = factory.getOWLObjectProperty(IRI.create(purlOboIRI + "RO_0002573"));
final OWLClass abnormal = factory.getOWLClass(IRI.create(purlOboIRI + "PATO_0000460"));
/* Now walk the file and create instances on the fly */
try {
InputStream is;
/* Open input file. Try gzip compression first */
try {
is = new GZIPInputStream(new FileInputStream(f));
if (is.markSupported())
is.mark(10);
is.read();
if (is.markSupported())
is.reset();
else {
is.close();
is = new GZIPInputStream(new FileInputStream(f));
}
} catch (IOException ex) {
/*
* We did not succeed in open the file and reading in a byte. We assume that the file is not compressed.
*/
is = new FileInputStream(f);
}
/*
* Constructs an OWLClass and Axioms for each zfin entry. We expect the reasoner to collate the classes properly. We also emit
* the annotations here.
*/
class ZFIN implements ZFINVisitor {
/**
* Returns an entity class for the given obo id. This is a simple wrapper for OBOVocabulary.ID2IRI(id) but checks whether
* the term stems from a supported ontology.
*
* @param id
* @return
*/
private OWLClass getEntityClassForOBOID(String id) {
if (id.startsWith("GO:") || id.startsWith("ZFA:") || id.startsWith("BSPO:") || id.startsWith("MPATH:"))
return factory.getOWLClass(OBOVocabulary.ID2IRI(id));
throw new RuntimeException("Unknown ontology prefix for name \"" + id + "\"");
}
/**
* Returns an quality class for the given obo id. This is a simple wrapper for OBOVocabulary.ID2IRI(id) but checks whether
* the term stems from a supported ontology.
*
* @param id
* @return
*/
private OWLClass getQualiClassForOBOID(String id) {
if (id.startsWith("PATO:"))
return factory.getOWLClass(OBOVocabulary.ID2IRI(id));
throw new RuntimeException("Qualifier must be a pato term");
}
public boolean visit(ZFINEntry entry) {
/* we only handle 'abnormal' entries */
if (!entry.isAbnormal)
return true;
/*
* Important: exclude useless annotation that look like this ...ZFA:0001439|anatomical
* system|||||||PATO:0000001|quality|abnormal|
*/
if (entry.entity1SupertermId.equals("ZFA:0001439") && entry.patoID.equals("PATO:0000001") && entry.entity1SubtermId.equals("")
&& entry.entity2SupertermId.equals("") && entry.entity2SubtermId.equals(""))
return true;
OWLClass pato = getQualiClassForOBOID(entry.patoID);
OWLClass cl1 = getEntityClassForOBOID(entry.entity1SupertermId);
OWLClassExpression intersectionExpression;
String label;
Set<OWLClassExpression> intersectionList = new LinkedHashSet<OWLClassExpression>();
intersectionList.add(pato);
// we now use has_modifier (this was has_qualifier before)
intersectionList.add(factory.getOWLObjectSomeValuesFrom(has_modifier, abnormal));
/* Entity 1: Create intersections */
if (entry.entity1SubtermId != null && entry.entity1SubtermId.length() > 0) {
/*
* Pattern is (all-some interpretation): <pato> inheres_in (<cl2> part of <cl1>) AND qualifier abnormal
*/
OWLClass cl2 = getEntityClassForOBOID(entry.entity1SubtermId);
intersectionList.add(factory.getOWLObjectSomeValuesFrom(inheresProperty,
factory.getOWLObjectIntersectionOf(cl2, factory.getOWLObjectSomeValuesFrom(partOf, cl1))));
/*
* Note that is language the last word is the more specific part of the composition, i.e., we say swim bladder
* epithelium, which is the epithelium of the swim bladder
*/
label = "abnormal(ly) " + entry.patoName + " " + entry.entity1SupertermName + " " + entry.entity1SubtermName;
}
else {
/*
* Pattern is (all-some interpretation): <pato> inheres_in <cl1> AND qualifier abnormal
*/
intersectionList.add(factory.getOWLObjectSomeValuesFrom(inheresProperty, cl1));
label = "abnormal(ly) " + entry.patoName + " " + entry.entity1SupertermName;
}
/* Entity 2: Create intersections */
if (entry.entity2SupertermId != null && entry.entity2SupertermId.length() > 0) {
OWLClass cl3 = getEntityClassForOBOID(entry.entity2SupertermId);
if (entry.entity2SubtermId != null && entry.entity2SubtermId.length() > 0) {
/*
* Pattern is (all-some interpretation): <pato> inheres_in (<cl2> part of <cl1>) AND qualifier abnormal
*/
OWLClass cl4 = getEntityClassForOBOID(entry.entity2SubtermId);
intersectionList.add(factory.getOWLObjectSomeValuesFrom(towards,
factory.getOWLObjectIntersectionOf(cl4, factory.getOWLObjectSomeValuesFrom(partOf, cl3))));
/*
* Note that is language the last word is the more specific part of the composition, i.e., we say swim bladder
* epithelium, which is the epithelium of the swim bladder
*/
label += " towards " + entry.entity2SupertermName + " " + entry.entity2SubtermName;
}
else {
intersectionList.add(factory.getOWLObjectSomeValuesFrom(towards, cl3));
label += " towards " + entry.entity2SupertermName;
}
}
/* Create intersection */
intersectionExpression = factory.getOWLObjectIntersectionOf(intersectionList);
OWLClassExpression owlSomeClassExp = factory.getOWLObjectSomeValuesFrom(hasPart, intersectionExpression);
IRI zpIRI = zpIdDB.getZPId(owlSomeClassExp);
String zpID = OBOVocabulary.IRI2ID(zpIRI);
OWLClass zpTerm = factory.getOWLClass(zpIRI);
/* Make term equivalent to the intersection */
OWLEquivalentClassesAxiom axiom = factory.getOWLEquivalentClassesAxiom(zpTerm, owlSomeClassExp);
manager.addAxiom(zp, axiom);
/* Add label */
OWLAnnotation labelAnno = factory.getOWLAnnotation(factory.getRDFSLabel(), factory.getOWLLiteral(label));
OWLAxiom labelAnnoAxiom = factory.getOWLAnnotationAssertionAxiom(zpTerm.getIRI(), labelAnno);
manager.addAxiom(zp, labelAnnoAxiom);
/* Add source information */
if (addSourceInformation) {
addSourceInformation(zpTerm, entry, zp);
}
/*
* Writing the annotation file
*/
try {
annotationOut.write(entry.geneZfinID + "\t" + zpID + "\t" + label + "\n");
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
ZFIN zfinVisitor = new ZFIN();
/* The zp entry that defines the root */
ZFINEntry rootEntry = new ZFINEntry();
rootEntry.geneZfinID = "DUMMY";
rootEntry.isAbnormal = true;
rootEntry.patoID = "PATO:0000001";
rootEntry.patoName = "quality";
rootEntry.entity1SupertermId = "ZFA:0100000";
rootEntry.entity1SupertermName = "zebrafish anatomical entity";
rootEntry.entity2SupertermId = "";
zfinVisitor.visit(rootEntry);
ZFINWalker.walk(is, zfinVisitor);
// if requested, add the equivalence axioms between ZFA-class and
// UBERON-classes
if (zfa2uberon != null && zfa2uberon.keySet().size() > 0) {
for (Entry<String, String> zfa2uberonEntry : zfa2uberon.entries()) {
String zfaIdObo = zfa2uberonEntry.getKey();
String uberonIdObo = zfa2uberonEntry.getValue();
OWLClass zfaClass = factory.getOWLClass(OBOVocabulary.ID2IRI(zfaIdObo));
OWLClass uberonClass = factory.getOWLClass(OBOVocabulary.ID2IRI(uberonIdObo));
OWLEquivalentClassesAxiom equivZfaUberonAxiom = factory.getOWLEquivalentClassesAxiom(zfaClass, uberonClass);
manager.addAxiom(zp, equivZfaUberonAxiom);
}
}
/* Write output files */
File of = new File(ontologyOutputFilePath);
if (useOwlRdfSyntax) {
// save in owl/rdf syntax
manager.saveOntology(zp, new RDFXMLOntologyFormat(), new FileOutputStream(of));
log.info("Wrote \"" + of.toString() + "\" in OWL/RDF syntax");
}
else {
// save in manchester functional syntax
manager.saveOntology(zp, new OWLFunctionalSyntaxOntologyFormat(), new FileOutputStream(of));
log.info("Wrote \"" + of.toString() + "\" in Manchester functional syntax");
}
annotationOut.close();
if (zpCLIConfig.sourceInformationFile != null) {
saveSourceInformation(zp, zpCLIConfig.sourceInformationFile);
}
} catch (FileNotFoundException e) {
System.err.println(String.format("Specified input file \"%s\" doesn't exist!", zfinFilePath));
} catch (IOException e) {
e.printStackTrace();
} catch (OWLOntologyStorageException e) {
e.printStackTrace();
}
}
/**
* Custom IRI for the annotation property for the definition of the class expression.
*/
static final IRI definitionSourcePropertyIRI = IRI.create("http://zfin/definition/source_information");
/**
* Add the source information for the definition of the equivalent class expression for the given ZP class.
*
* @param cls
* @param entry
* @param zp
*/
private static void addSourceInformation(OWLClass cls, ZFINEntry entry, OWLOntology zp) {
OWLOntologyManager m = zp.getOWLOntologyManager();
OWLDataFactory f = m.getOWLDataFactory();
OWLAnnotationProperty definitionSourceProperty = f.getOWLAnnotationProperty(definitionSourcePropertyIRI);
// search for existing source information
Set<OWLAnnotationAssertionAxiom> annotations = zp.getAnnotationAssertionAxioms(cls.getIRI());
boolean hasSourceInformation = false;
for (OWLAnnotationAssertionAxiom ann : annotations) {
if (definitionSourceProperty.equals(ann.getProperty())) {
hasSourceInformation = true;
break;
}
}
// only add new information if no previous one exists
if (hasSourceInformation == false) {
StringBuilder source = new StringBuilder();
source.append(entry.entity1SupertermId); // affected_structure_or_process_1_superterm_id
source.append('\t');
if (entry.entity1SubtermId != null) {
source.append(entry.entity1SubtermId); // affected_structure_or_process_1_subterm_id
}
source.append('\t');
source.append(entry.patoID); // phenotype_keyword_id
source.append('\t');
source.append("PATO:0000460"); // phenotype_modifier, currently
// always abnormal
source.append('\t');
if (entry.entity2SupertermId != null) {
source.append(entry.entity2SupertermId);// affected_structure_or_process_2_superterm_id
}
source.append('\t');
if (entry.entity2SubtermId != null) {
source.append(entry.entity2SubtermId); // affected_structure_or_process_2_subterm_id
}
OWLAnnotation sourceAnno = f.getOWLAnnotation(definitionSourceProperty, f.getOWLLiteral(source.toString()));
OWLAxiom labelAnnoAxiom = f.getOWLAnnotationAssertionAxiom(cls.getIRI(), sourceAnno);
m.addAxiom(zp, labelAnnoAxiom);
}
}
/**
* Save the source information for all ZP classes in a separate file.
*
* @param zp
* @param fileName
*/
private static void saveSourceInformation(OWLOntology zp, String fileName) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(fileName));
OWLOntologyManager m = zp.getOWLOntologyManager();
OWLDataFactory f = m.getOWLDataFactory();
OWLAnnotationProperty definitionSourceProperty = f.getOWLAnnotationProperty(definitionSourcePropertyIRI);
OWLAnnotationProperty rdfsLabel = f.getRDFSLabel();
for (OWLClass cls : zp.getClassesInSignature()) {
String zpID = OBOVocabulary.IRI2ID(cls.getIRI());
if (zpID.startsWith("ZP:") == false) {
// Ignore non ZP classes
continue;
}
String label = null;
String source = null;
// Check annotations for source information and label
Set<OWLAnnotationAssertionAxiom> annotations = zp.getAnnotationAssertionAxioms(cls.getIRI());
for (OWLAnnotationAssertionAxiom ann : annotations) {
OWLAnnotationProperty prop = ann.getProperty();
if (definitionSourceProperty.equals(prop)) {
OWLAnnotationValue value = ann.getValue();
if (value instanceof OWLLiteral) {
source = ((OWLLiteral) value).getLiteral();
}
break;
}
else if (rdfsLabel.equals(prop)) {
OWLAnnotationValue value = ann.getValue();
if (value instanceof OWLLiteral) {
label = ((OWLLiteral) value).getLiteral();
}
}
}
// write the information
if (label != null && source != null) {
writer.append(zpID);
writer.append('\t');
writer.append(label);
writer.append('\t');
writer.append(source);
writer.append('\n');
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
// close quietly
}
}
}
}
} |
package gvs.business.logic;
import java.awt.Point;
import java.util.Collection;
import java.util.Random;
import java.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import gvs.business.logic.physics.helpers.Area;
import gvs.business.logic.physics.helpers.AreaDimension;
import gvs.business.logic.physics.helpers.AreaPoint;
import gvs.business.logic.physics.helpers.Particle;
import gvs.business.logic.physics.rules.Traction;
import gvs.business.logic.physics.ticker.AreaTicker;
import gvs.business.logic.physics.ticker.AreaTickerFactory;
import gvs.business.logic.physics.ticker.Tickable;
import gvs.business.model.graph.Graph;
import gvs.interfaces.Action;
import gvs.interfaces.IEdge;
import gvs.interfaces.IVertex;
/**
* Creates and prepares the elements which need to be layouted.
*
* Executes a separate ticker thread which calls the LayoutController in a given
* interval.
*
* @author mwieland
*
*/
@Singleton
public class Layouter implements Tickable {
private Action completionCallback;
private volatile AreaTicker currentTicker;
private final AreaTickerFactory tickerFactory;
private final Area area;
private final Random random;
private static final int FACTOR = 3;
private static final int DEFAULT_MASS = 40;
private static final int SOFT_MULTIPLIER = 10;
private static final int FIXED_MULTIPLIER = 10;
private static final int DEFAULT_DISTANCE = 300 * FACTOR;
private static final int DEFAULT_IMPACT = 10;
private static final int MAX_LAYOUT_DURATION_MS = 10_000;
private static final int DEFAULT_TICK_RATE = 50;
private static final int DEFAULT_AREA_HEIGHT = 600 * FACTOR;
private static final int DEFAULT_AREA_WIDTH = 800 * FACTOR;
private static final int DEFAULT_SEED = 4000;
private static final Logger logger = LoggerFactory.getLogger(Layouter.class);
@Inject
public Layouter(AreaTickerFactory tickerFactory) {
this.tickerFactory = tickerFactory;
this.area = new Area(
new AreaDimension(DEFAULT_AREA_WIDTH, DEFAULT_AREA_HEIGHT));
this.random = new Random(DEFAULT_SEED);
initializeLayoutGuard();
}
/**
* Initializes the guard, which protects the layouter from running endlessly.
*/
private void initializeLayoutGuard() {
Timer guard = new Timer();
LayoutGuard layoutGuard = new LayoutGuard(area);
guard.schedule(layoutGuard, MAX_LAYOUT_DURATION_MS);
}
/**
* Layout the received vertices
*
* @param graph
* graph with vertices and edges
* @param useSoftPoints
* use soft layout
*/
public void layoutGraph(Graph graph, boolean useSoftPoints,
Action completionCallback) {
logger.info("Received new data to layout");
if (graph.isLayoutable()) {
this.completionCallback = completionCallback;
handleTickerThread();
resetArea();
calculatLayout(graph, useSoftPoints);
}
}
private void resetArea() {
this.area.setIsStable(false);
this.area.resetArea();
}
private void calculatLayout(Graph graph, boolean useSoftPoints) {
createVertexParticles(graph.getVertices(), useSoftPoints);
createEdgeTractions(graph.getEdges());
}
/**
* Only one ticker thread is allowed to be active.
*
* If the autolayout mechanism is executed, the ticker thread executes the
* tick method in a defined interval.
*
* As soon as the area is stable, the ticker thread terminates.
*/
private void handleTickerThread() {
if (currentTicker != null) {
try {
logger.debug("Wait for current AreaTicker thread to terminate.");
currentTicker.join();
logger.debug("AreaTicker thread successfully stopped.");
} catch (InterruptedException e) {
logger.error("Unable to join Area Ticker thread", e);
}
}
currentTicker = tickerFactory.create(this, DEFAULT_TICK_RATE);
logger.debug("Starting thread: {}", currentTicker.getName());
currentTicker.start();
logger.debug("Background process successfully started.");
}
/**
* Check if particles in area are stable. If stable, stop ticking, otherwise
* update positions and continue with the next iteration.
*/
public void tick() {
logger.info("Layout engine iteration completed.");
if (area.isStable()) {
logger.info("Layouting completed. Graph is stable. Stop layout engine.");
currentTicker.terminate();
if (completionCallback != null) {
completionCallback.execute();
}
} else {
logger.info("Continue layouting...");
area.updateAll();
}
}
/**
* Creates a particle for each vertex.
*
*/
private void createVertexParticles(Collection<IVertex> vertices,
boolean generateSoftPoints) {
vertices.forEach(v -> {
Point point = new Point();
if (!v.isFixedPosition()) {
if (generateSoftPoints) {
point = generateSoftPoints(v);
} else {
point = generateRandomPoints(v);
}
} else {
point = generateFixedPoints(v);
}
AreaPoint position = new AreaPoint(point);
long particleId = v.getId();
boolean isFixed = v.isFixedPosition();
Particle newParticle = new Particle(position, particleId, v, isFixed,
DEFAULT_MASS);
area.addParticles(newParticle);
});
}
/**
* Create edge tractions between related vertices.
*
*/
private void createEdgeTractions(Collection<IEdge> edges) {
edges.forEach(e -> {
IVertex vertexFrom = e.getStartVertex();
IVertex vertexTo = e.getEndVertex();
Particle fromParticle = area.getParticleWithID(vertexFrom.getId());
Particle toParticle = area.getParticleWithID(vertexTo.getId());
Traction t = new Traction(fromParticle, toParticle, DEFAULT_IMPACT,
DEFAULT_DISTANCE);
area.addTraction(t);
});
}
/**
* Use random coordinates as input for engine.
*
* @param vertex
* calculation base
* @return random point
*/
private Point generateRandomPoints(IVertex vertex) {
Point randomPoint = new Point();
randomPoint.x = (int) ((double) (area.getUniverseDimension()
.dimensionWidth()) * Math.random());
randomPoint.y = (int) ((double) (area.getUniverseDimension()
.dimensionHeight()) * Math.random());
return randomPoint;
}
/**
* Use soft random coordinates as input for engine.
*
* @param vertex
* calculation base
* @return soft point
*/
private Point generateSoftPoints(IVertex vertex) {
Point softPoint = new Point();
softPoint.x = (int) (random.nextDouble() * SOFT_MULTIPLIER);
softPoint.y = (int) (random.nextDouble() * SOFT_MULTIPLIER);
return softPoint;
}
/**
* Use existing vertex coordinates as input for engine.
*
* @param vertex
* calculation base
* @return fixed point
*/
private Point generateFixedPoints(IVertex vertex) {
Point fixedPoint = new Point();
fixedPoint.x = (int) ((double) vertex.getXPosition() * FIXED_MULTIPLIER);
fixedPoint.y = (int) ((double) vertex.getYPosition() * FIXED_MULTIPLIER);
return fixedPoint;
}
} |
package org.jpromise;
import java.util.concurrent.*;
class FuturePromise<V> extends AbstractPromise<V> implements Runnable {
private final Future<V> future;
private final Long timeout;
private final TimeUnit timeUnit;
FuturePromise(Executor executor, Future<V> future) {
this.future = future;
this.timeout = null;
this.timeUnit = null;
start(executor);
}
FuturePromise(Executor executor, Future<V> future, long timeout, TimeUnit timeUnit) {
this.future = future;
this.timeout = timeout;
this.timeUnit = timeUnit;
start(executor);
}
private void start(Executor executor) {
if (future.isDone()) {
this.run();
}
else {
executor.execute(this);
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
@Override
public void run() {
try {
if (timeout == null) {
complete(future.get());
}
else {
complete(future.get(timeout, timeUnit));
}
}
catch (ExecutionException exception) {
Throwable cause = exception.getCause();
if (cause == null) {
cause = exception;
}
completeWithException(cause);
}
catch (TimeoutException | InterruptedException exception) {
completeWithException(exception);
}
}
} |
package hu.bme.mit.spaceship;
/**
* A simple spaceship with two proton torpedos and four lasers
*/
public class GT4500 implements SpaceShip {
private TorpedoStore primaryTorpedoStore;
private TorpedoStore secondaryTorpedoStore;
private boolean wasPrimaryFiredLast = false;
public GT4500() {
this.primaryTorpedoStore = new TorpedoStore(10);
this.secondaryTorpedoStore = new TorpedoStore(10);
}
public boolean fireLasers(FiringMode firingMode) {
// TODO not implemented yet
return false;
}
/**
* Tries to fire the torpedo stores of the ship.
*
* @param firingMode how many torpedo bays to fire
* SINGLE: fires only one of the bays.
* - For the first time the primary store is fired.
* - To give some cooling time to the torpedo stores, torpedo stores are fired alternating.
* - But if the store next in line is empty the ship tries to fire the other store.
* - If the fired store reports a failure, the ship does not try to fire the other one.
* ALL: tries to fire both of the torpedo stores.
*
* @return whether at least one torpedo was fired successfully
*/
@Override
public boolean fireTorpedos(FiringMode firingMode) {
boolean firingSuccess = false;
switch (firingMode) {
case SINGLE:
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
else {
// try to fire the primary first
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
break;
case ALL:
boolean innerSuccess;
if (! secondaryTorpedoStore.isEmpty()) {
innerSuccess=firingSuccess = secondaryTorpedoStore.fire(1);
}
if (! primaryTorpedoStore.isEmpty()) {
innerSuccess=innerSuccess || primaryTorpedoStore.fire(1);
}
firingSuccess=innerSuccess;
break;
default:
firingSuccess = false;
break;
}
return firingSuccess;
}
} |
package codequiz;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class QuizUI extends JPanel {
private QuizController controller;
private JPanel gamePanel;
private JPanel questionPanel;
private JPanel eastPanel;
private JPanel westPanel;
private JPanel southPanel;
private JPanel northPanel;
private JLabel lblQuestion = new JLabel();
// private JTextField tfAnswers = new JTextField();
private JButton btnSubmit = new JButton("OK");
private JButton btnNewQuestion = new JButton("Ny fråga");
private ButtonGroup buttonGroup = new ButtonGroup();
private JRadioButton rb1 = new JRadioButton(" Alternativ 1");
private JRadioButton rb2 = new JRadioButton(" Alternativ 2");
private JRadioButton rb3 = new JRadioButton(" Alternativ 3");
private JRadioButton rb4 = new JRadioButton(" Alternativ 4");
private JButton btnback = new JButton("Huvudmeny");
private JLabel lblPoints;
private JLabel lblLives;
private JLabel lblResult = new JLabel("");
private JLabel lblBackground = new JLabel(new ImageIcon(
"src/media/Story1.jpg"));
private int lives = 1;
private int points = 0;
private int id;
public QuizUI() {
setBackground(Color.BLACK);
setPreferredSize(new Dimension(800, 600));
lblBackground.setLayout(new BorderLayout());
add(lblBackground);
lblBackground.add(questionPanel(), BorderLayout.CENTER);
lblBackground.add(eastPanel(), BorderLayout.EAST);
lblBackground.add(westPanel(), BorderLayout.WEST);
lblBackground.add(southPanel(), BorderLayout.SOUTH);
lblBackground.add(northPanel(), BorderLayout.NORTH);
}
/**
* opaque panel
*
* @return
*/
public JPanel northPanel() {
northPanel = new JPanel(new FlowLayout());
northPanel.setPreferredSize(new Dimension(30, 20));
northPanel.setOpaque(false);
return northPanel;
}
/**
* opaque panel
*
* @return
*/
public JPanel westPanel() {
westPanel = new JPanel(new FlowLayout());
westPanel.setPreferredSize(new Dimension(30, 20));
westPanel.setOpaque(false);
return westPanel;
}
/**
* opaque panel
*
* @return
*/
public JPanel eastPanel() {
eastPanel = new JPanel(new FlowLayout());
eastPanel.setPreferredSize(new Dimension(430, 150));
eastPanel.setOpaque(false);
btnback.setVisible(false);
eastPanel.add(btnback);
return eastPanel;
}
/**
* Contains game questions
*
* @return
*/
public JPanel questionPanel() {
questionPanel = new JPanel(new GridLayout(8, 1));
questionPanel.setPreferredSize(new Dimension(420, 20));
questionPanel.setOpaque(false);
questionPanel.add(lblQuestion);
lblQuestion.setPreferredSize(new Dimension(300, 50));
lblQuestion.setOpaque(false);
buttonGroup.add(rb1);
buttonGroup.add(rb2);
buttonGroup.add(rb3);
buttonGroup.add(rb4);
rb1.setOpaque(false);
rb2.setOpaque(false);
rb3.setOpaque(false);
rb4.setOpaque(false);
btnSubmit.setEnabled(false);
btnSubmit.setOpaque(false);
questionPanel.add(new JLabel("Välj ett svar:"));
questionPanel.add(rb1);
questionPanel.add(rb2);
questionPanel.add(rb3);
questionPanel.add(rb4);
questionPanel.add(lblResult);
questionPanel.add(btnSubmit);
btnSubmit.addActionListener(new SubmitListener());
return questionPanel;
}
public JPanel southPanel() {
southPanel = new JPanel(new GridLayout(2, 2));
southPanel.setPreferredSize(new Dimension(100, 50));
southPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
southPanel.add(lblPoints = new JLabel("POÄNG: " + points));
southPanel.add(lblLives = new JLabel("Liv: " + lives));
southPanel.add(btnNewQuestion);
btnNewQuestion.setOpaque(false);
southPanel.setOpaque(false);
btnNewQuestion.addActionListener(new QuestionListener());
return southPanel;
}
public void setController(QuizController controller) {
this.controller = controller;
}
private class QuestionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//controller.nextQuestion();
controller.increaseIndex();
// ImageIcon icon = controller.setQuestionScenario();
// setBackground(icon);
controller.getQuestion();
buttonGroup.clearSelection();
btnSubmit.setEnabled(true);
lblResult.setText("");
}
}
private class SubmitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
btnSubmit.setEnabled(false);
String answer = null;
String correctAnswer = controller.getCorrectAnswer();
System.out.println(correctAnswer);
if (rb1.isSelected()) {
answer = rb1.getText();
}
if (rb2.isSelected()) {
answer = rb2.getText();
}
if (rb3.isSelected()) {
answer = rb3.getText();
}
if (rb4.isSelected()) {
answer = rb4.getText();
}
if (answer.equals(correctAnswer)) {
// ImageIcon icon = controller.setCorrectScenario();
// setBackground(icon);
points += 10;// skall skapas en metod i Controllern
lblResult.setText("RÄTT!");
lblResult.setForeground(Color.GREEN);
lblPoints.setText("POÄNG: " + points);
} else {
// ImageIcon icon = controller.setIncorrectScenario();
// setBackground(icon);
lblResult.setText("FEL!");
lblResult.setForeground(Color.RED);
points -= 10;
lives -= 1;
lblPoints.setText("POÄNG: " + points);
lblLives.setText("LIV: " + lives);
}
if(lives==0){
setBackground(new ImageIcon("src/media/dead.jpeg"));
questionPanel.setVisible(false);
btnNewQuestion.setVisible(false);
btnback.setVisible(true);
}
}
}
public void setQuestion(String question) {
lblQuestion.setText(question);
}
public void setBackground(ImageIcon inIcon) {
lblBackground.setIcon(inIcon);
}
public void setAlternatives(String al1, String al2, String al3, String al4) {
rb1.setText(al1);
rb2.setText(al2);
rb3.setText(al3);
rb4.setText(al4);
}
} |
package com.redhat.ceylon.eclipse.code.preferences;
import static com.redhat.ceylon.eclipse.code.wizard.NewProjectWizard.DEFAULT_RESOURCE_FOLDER;
import static com.redhat.ceylon.eclipse.code.wizard.NewProjectWizard.DEFAULT_SOURCE_FOLDER;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getCeylonModulesOutputFolder;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaModelStatus;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.CoreUtility;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathSupport;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListElement;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListLabelProvider;
//import org.eclipse.jdt.internal.ui.wizards.buildpaths.ClasspathOrderingWorkbookPage;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.FolderSelectionDialog;
//import org.eclipse.jdt.internal.ui.wizards.buildpaths.LibrariesWorkbookPage;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.ProjectsWorkbookPage;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
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.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
import org.eclipse.ui.views.navigator.ResourceComparator;
import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider;
import com.redhat.ceylon.eclipse.core.builder.CeylonProjectConfig;
public class CeylonBuildPathsBlock {
public static interface IRemoveOldBinariesQuery {
/**
* Do the callback. Returns <code>true</code> if .class files should be removed from the
* old output location.
* @param removeLocation true if the folder at oldOutputLocation should be removed, false if only its content
* @param oldOutputLocation The old output location
* @return Returns true if .class files should be removed.
* @throws OperationCanceledException if the operation was canceled
*/
boolean doQuery(boolean removeLocation, IPath oldOutputLocation)
throws OperationCanceledException;
}
private IWorkspaceRoot fWorkspaceRoot;
private CheckedListDialogField<CPListElement> fClassPathList;
private CheckedListDialogField<CPListElement> fResourcePathList;
private StringButtonDialogField fJavaBuildPathDialogField;
private StatusInfo fClassPathStatus;
private StatusInfo fOutputFolderStatus;
private StatusInfo fBuildPathStatus;
private IJavaProject fCurrJProject;
private IPath fJavaOutputLocationPath;
private IStatusChangeListener fContext;
private Control fSWTWidget;
private TabFolder fTabFolder;
private int fPageIndex;
private SourceContainerWorkbookPage fSourceContainerPage;
private ResourceContainerWorkbookPage fResourceContainerPage;
private ProjectsWorkbookPage fProjectsPage;
// private LibrariesWorkbookPage fLibrariesPage;
private BuildPathBasePage fCurrPage;
private String fUserSettingsTimeStamp;
private long fFileTimeStamp;
//private IRunnableContext fRunnableContext;
//private boolean fUseNewPage;
private final IWorkbenchPreferenceContainer fPageContainer; // null when invoked from a non-property page context
private final static int IDX_UP= 0;
private final static int IDX_DOWN= 1;
private final static int IDX_TOP= 3;
private final static int IDX_BOTTOM= 4;
private final static int IDX_SELECT_ALL= 6;
private final static int IDX_UNSELECT_ALL= 7;
public CeylonBuildPathsBlock(/*IRunnableContext runnableContext,*/
IStatusChangeListener context, int pageToShow, /*boolean useNewPage,*/
IWorkbenchPreferenceContainer pageContainer) {
fPageContainer= pageContainer;
fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot();
fContext= context;
//fUseNewPage= useNewPage;
fPageIndex= pageToShow;
fSourceContainerPage= null;
fResourceContainerPage=null;
// fLibrariesPage= null;
fProjectsPage= null;
fCurrPage= null;
//fRunnableContext= runnableContext;
JavaBuildPathAdapter jadapter= new JavaBuildPathAdapter();
String[] buttonLabels= new String[] {
/* IDX_UP */ NewWizardMessages.BuildPathsBlock_classpath_up_button,
/* IDX_DOWN */ NewWizardMessages.BuildPathsBlock_classpath_down_button,
null,
/* IDX_TOP */ NewWizardMessages.BuildPathsBlock_classpath_top_button,
/* IDX_BOTTOM */ NewWizardMessages.BuildPathsBlock_classpath_bottom_button,
null,
/* IDX_SELECT_ALL */ NewWizardMessages.BuildPathsBlock_classpath_checkall_button,
/* IDX_UNSELECT_ALL */ NewWizardMessages.BuildPathsBlock_classpath_uncheckall_button
};
fClassPathList= new CheckedListDialogField<CPListElement>(jadapter, buttonLabels,
new CPListLabelProvider());
fClassPathList.setDialogFieldListener(jadapter);
fClassPathList.setLabelText(NewWizardMessages.BuildPathsBlock_classpath_label);
fClassPathList.setUpButtonIndex(IDX_UP);
fClassPathList.setDownButtonIndex(IDX_DOWN);
fClassPathList.setCheckAllButtonIndex(IDX_SELECT_ALL);
fClassPathList.setUncheckAllButtonIndex(IDX_UNSELECT_ALL);
fResourcePathList= new CheckedListDialogField<CPListElement>(jadapter, buttonLabels,
new ResourceListLabelProvider());
fResourcePathList.setDialogFieldListener(jadapter);
fResourcePathList.setLabelText("Build &resource path order");
fResourcePathList.setUpButtonIndex(IDX_UP);
fResourcePathList.setDownButtonIndex(IDX_DOWN);
fResourcePathList.setCheckAllButtonIndex(IDX_SELECT_ALL);
fResourcePathList.setUncheckAllButtonIndex(IDX_UNSELECT_ALL);
fJavaBuildPathDialogField= new StringButtonDialogField(jadapter);
fJavaBuildPathDialogField.setButtonLabel(NewWizardMessages.BuildPathsBlock_buildpath_button);
fJavaBuildPathDialogField.setDialogFieldListener(jadapter);
//fJavaPathDialogField.setLabelText(NewWizardMessages.BuildPathsBlock_buildpath_label);
fJavaBuildPathDialogField.setLabelText("Default Java binary class output folder:");
fBuildPathStatus= new StatusInfo();
fClassPathStatus= new StatusInfo();
fOutputFolderStatus= new StatusInfo();
fCurrJProject= null;
}
public Control createControl(Composite parent) {
fSWTWidget= parent;
Composite composite= new Composite(parent, SWT.NONE);
composite.setFont(parent.getFont());
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
layout.numColumns= 1;
composite.setLayout(layout);
TabFolder folder= new TabFolder(composite, SWT.NONE);
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
folder.setFont(composite.getFont());
TabItem item;
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.BuildPathsBlock_tab_source);
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT));
/*if (fUseNewPage) {
fSourceContainerPage= new NewSourceContainerWorkbookPage(fClassPathList, fBuildPathDialogField, fRunnableContext, this);
} else {*/
fSourceContainerPage= new SourceContainerWorkbookPage(fClassPathList, fJavaBuildPathDialogField);
item.setData(fSourceContainerPage);
item.setControl(fSourceContainerPage.getControl(folder));
item= new TabItem(folder, SWT.NONE);
item.setText("Resources");
item.setImage(CeylonLabelProvider.FOLDER);
fResourceContainerPage = new ResourceContainerWorkbookPage(fResourcePathList, fJavaBuildPathDialogField);
item.setData(fResourceContainerPage);
item.setControl(fResourceContainerPage.getControl(folder));
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
Image projectImage= workbench.getSharedImages().getImage(IDE.SharedImages.IMG_OBJ_PROJECT);
fProjectsPage= new ProjectsWorkbookPage(fClassPathList, fPageContainer);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.BuildPathsBlock_tab_projects);
item.setImage(projectImage);
item.setData(fProjectsPage);
item.setControl(fProjectsPage.getControl(folder));
// fLibrariesPage= new LibrariesWorkbookPage(fClassPathList, fPageContainer);
// item= new TabItem(folder, SWT.NONE);
// item.setText(NewWizardMessages.BuildPathsBlock_tab_libraries);
// item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_LIBRARY));
// item.setData(fLibrariesPage);
// item.setControl(fLibrariesPage.getControl(folder));
// a non shared image
Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage();
composite.addDisposeListener(new ImageDisposer(cpoImage));
// ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList);
// item= new TabItem(folder, SWT.NONE);
// item.setText(NewWizardMessages.BuildPathsBlock_tab_order);
// item.setImage(cpoImage);
// item.setData(ordpage);
// item.setControl(ordpage.getControl(folder));
if (fCurrJProject != null) {
fSourceContainerPage.init(fCurrJProject);
fResourceContainerPage.init(fCurrJProject);
// fLibrariesPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
}
folder.setSelection(fPageIndex);
fCurrPage= (BuildPathBasePage) folder.getItem(fPageIndex).getData();
folder.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
tabChanged(e.item);
}
});
fTabFolder= folder;
Dialog.applyDialogFont(composite);
return composite;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Initializes the classpath for the given project. Multiple calls to init are allowed,
* but all existing settings will be cleared and replace by the given or default paths.
* @param jproject The java project to configure. Does not have to exist.
* @param javaOutputLocation The output location to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project- the
* output location of the existing project
* @param classpathEntries The classpath entries to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project - the
* classpath entries of the existing project
*/
public void init(IJavaProject jproject, IPath javaOutputLocation,
IClasspathEntry[] classpathEntries, boolean javaCompilationEnabled) {
fCurrJProject= jproject;
boolean projectExists= false;
final List<CPListElement> newClassPath;
IProject project= fCurrJProject.getProject();
projectExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$
IClasspathEntry[] existingEntries= null;
if (projectExists) {
if (javaOutputLocation == null) {
javaOutputLocation= fCurrJProject.readOutputLocation();
}
existingEntries= fCurrJProject.readRawClasspath();
if (classpathEntries == null) {
classpathEntries= existingEntries;
//TODO: read existing ceylon output location from classpathEntries
}
}
if (javaOutputLocation == null) {
javaOutputLocation= getDefaultJavaOutputLocation(jproject);
}
if (classpathEntries != null) {
newClassPath= getCPListElements(classpathEntries, existingEntries);
}
else {
newClassPath= getDefaultClassPath(jproject);
}
final List<CPListElement> newResourcePath = new ArrayList<CPListElement>();
if (projectExists) {
CeylonProjectConfig config = CeylonProjectConfig.get(project);
for (final String path: config.getProjectResourceDirectories()) {
if (path.startsWith(".")) {
IFolder folder = fCurrJProject.getProject()
.getFolder(Path.fromOSString(path));
newResourcePath.add(new CPListElement(fCurrJProject,
IClasspathEntry.CPE_SOURCE,
folder.getFullPath(),
folder));
}
else {
try {
project.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource)
throws CoreException {
if (resource.isLinked() &&
resource.getLocation().toOSString().equals(path)) {
newResourcePath.add(new CPListElement(null,
fCurrJProject, IClasspathEntry.CPE_SOURCE,
resource.getFullPath(),
resource, resource.getLocation()));
}
return resource instanceof IFolder ||
resource instanceof IProject;
}
});
}
catch (CoreException e) {
e.printStackTrace();
}
}
}
}
else {
IFolder defaultResourceFolder = fCurrJProject.getProject().getFolder(DEFAULT_RESOURCE_FOLDER);
newResourcePath.add(new CPListElement(fCurrJProject,
IClasspathEntry.CPE_SOURCE,
defaultResourceFolder.getFullPath(),
defaultResourceFolder));
}
List<CPListElement> exportedEntries = new ArrayList<CPListElement>();
for (int i= 0; i < newClassPath.size(); i++) {
CPListElement curr= newClassPath.get(i);
if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
exportedEntries.add(curr);
}
}
fJavaOutputLocationPath = javaOutputLocation.makeRelative();
// inits the dialog field
fJavaBuildPathDialogField.setText(fJavaOutputLocationPath.toString());
fJavaBuildPathDialogField.enableButton(project.exists());
fClassPathList.setElements(newClassPath);
fClassPathList.setCheckedElements(exportedEntries);
fClassPathList.selectFirstElement();
fResourcePathList.setElements(newResourcePath);
// fResourcePathList.setCheckedElements(exportedEntries);
fResourcePathList.selectFirstElement();
if (fSourceContainerPage != null) {
fSourceContainerPage.init(fCurrJProject);
fResourceContainerPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
// fLibrariesPage.init(fCurrJProject);
}
initializeTimeStamps();
updateUI();
}
protected void updateUI() {
if (fSWTWidget == null || fSWTWidget.isDisposed()) {
return;
}
if (Display.getCurrent() != null) {
doUpdateUI();
} else {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (fSWTWidget == null || fSWTWidget.isDisposed()) {
return;
}
doUpdateUI();
}
});
}
}
protected void doUpdateUI() {
fJavaBuildPathDialogField.refresh();
fClassPathList.refresh();
fResourcePathList.refresh();
doStatusLineUpdate();
}
private String getEncodedSettings() {
StringBuffer buf= new StringBuffer();
CPListElement.appendEncodePath(fJavaOutputLocationPath, buf).append(';');
int nElements= fClassPathList.getSize();
buf.append('[').append(nElements).append(']');
for (int i= 0; i < nElements; i++) {
CPListElement elem= fClassPathList.getElement(i);
elem.appendEncodedSettings(buf);
}
nElements= fResourcePathList.getSize();
buf.append('[').append(nElements).append(']');
for (int i= 0; i < nElements; i++) {
CPListElement elem= fResourcePathList.getElement(i);
elem.appendEncodedSettings(buf);
}
return buf.toString();
}
public boolean hasChangesInDialog() {
String currSettings= getEncodedSettings();
return !currSettings.equals(fUserSettingsTimeStamp);
}
public boolean hasChangesInClasspathFile() {
IFile file= fCurrJProject.getProject().getFile(".classpath"); //$NON-NLS-1$
return fFileTimeStamp != file.getModificationStamp();
}
public boolean isClassfileMissing() {
return !fCurrJProject.getProject().getFile(".classpath").exists(); //$NON-NLS-1$
}
public void initializeTimeStamps() {
IFile file= fCurrJProject.getProject().getFile(".classpath"); //$NON-NLS-1$
fFileTimeStamp= file.getModificationStamp();
fUserSettingsTimeStamp= getEncodedSettings();
}
private ArrayList<CPListElement> getCPListElements(IClasspathEntry[] classpathEntries,
IClasspathEntry[] existingEntries) {
List<IClasspathEntry> existing= existingEntries == null ?
Collections.<IClasspathEntry>emptyList() : Arrays.asList(existingEntries);
ArrayList<CPListElement> newClassPath= new ArrayList<CPListElement>();
for (int i= 0; i < classpathEntries.length; i++) {
IClasspathEntry curr= classpathEntries[i];
newClassPath.add(CPListElement.create(curr, ! existing.contains(curr), fCurrJProject));
}
return newClassPath;
}
/**
* @return Returns the Java project. Can return <code>null<code> if the page has not
* been initialized.
*/
public IJavaProject getJavaProject() {
return fCurrJProject;
}
/**
* @return Returns the current output location. Note that the path returned must not be valid.
*/
public IPath getJavaOutputLocation() {
return new Path(fJavaBuildPathDialogField.getText()).makeAbsolute();
}
/**
* @return Returns the current class path (raw). Note that the entries returned must not be valid.
*/
public IClasspathEntry[] getRawClassPath() {
List<CPListElement> elements= fClassPathList.getElements();
int nElements= elements.size();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= 0; i < nElements; i++) {
CPListElement currElement= elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
return entries;
}
public int getPageIndex() {
return fPageIndex;
}
private List<CPListElement> getDefaultClassPath(IJavaProject jproj) {
List<CPListElement> list= new ArrayList<CPListElement>();
IResource srcFolder;
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String sourceFolderName= DEFAULT_SOURCE_FOLDER;//store.getString(PreferenceConstants.SRCBIN_SRCNAME);
if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) {
srcFolder= jproj.getProject().getFolder(sourceFolderName);
} else {
srcFolder= jproj.getProject();
}
list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
list.addAll(getCPListElements(jreEntries, null));
return list;
}
public static IPath getDefaultJavaOutputLocation(IJavaProject jproj) {
return jproj.getProject().getFullPath().append("classes");
}
private class JavaBuildPathAdapter implements IStringButtonAdapter,
IDialogFieldListener, IListAdapter<CPListElement> {
public void changeControlPressed(DialogField field) {
buildPathChangeControlPressed(field);
}
public void dialogFieldChanged(DialogField field) {
buildPathDialogFieldChanged(field);
}
public void customButtonPressed(ListDialogField<CPListElement> field, int index) {
buildPathCustomButtonPressed(field, index);
}
public void doubleClicked(ListDialogField<CPListElement> field) {
}
public void selectionChanged(ListDialogField<CPListElement> field) {
updateTopButtonEnablement();
}
}
private void buildPathChangeControlPressed(DialogField field) {
if (field == fJavaBuildPathDialogField) {
IContainer container= chooseContainer(fJavaOutputLocationPath);
if (container != null) {
fJavaBuildPathDialogField.setText(container.getFullPath().makeRelative().toString());
}
}
}
public void updateTopButtonEnablement() {
fClassPathList.enableButton(IDX_BOTTOM, fClassPathList.canMoveDown());
fClassPathList.enableButton(IDX_TOP, fClassPathList.canMoveUp());
}
public void buildPathCustomButtonPressed(ListDialogField<CPListElement> field, int index) {
List<CPListElement> elems= field.getSelectedElements();
field.removeElements(elems);
if (index == IDX_BOTTOM) {
field.addElements(elems);
} else if (index == IDX_TOP) {
field.addElements(elems, 0);
}
}
private void buildPathDialogFieldChanged(DialogField field) {
if (field == fClassPathList) {
updateClassPathStatus();
updateTopButtonEnablement();
}
else if (field == fJavaBuildPathDialogField) {
updateJavaOutputLocationStatus();
}
doStatusLineUpdate();
}
private void doStatusLineUpdate() {
if (Display.getCurrent() != null) {
IStatus res= findMostSevereStatus();
fContext.statusChanged(res);
}
}
private IStatus findMostSevereStatus() {
return StatusUtil.getMostSevere(new IStatus[] { fClassPathStatus, fOutputFolderStatus, fBuildPathStatus });
}
/**
* Validates the build path.
*/
public void updateClassPathStatus() {
fClassPathStatus.setOK();
List<CPListElement> elements= fClassPathList.getElements();
CPListElement entryMissing= null;
CPListElement entryDeprecated= null;
int nEntriesMissing= 0;
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i
CPListElement currElement= elements.get(i);
boolean isChecked= fClassPathList.isChecked(currElement);
if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
if (!isChecked) {
fClassPathList.setCheckedWithoutUpdate(currElement, true);
}
if (!fClassPathList.isGrayed(currElement)) {
fClassPathList.setGrayedWithoutUpdate(currElement, true);
}
} else {
currElement.setExported(isChecked);
}
entries[i]= currElement.getClasspathEntry();
if (currElement.isMissing()) {
nEntriesMissing++;
if (entryMissing == null) {
entryMissing= currElement;
}
}
if (entryDeprecated == null & currElement.isDeprecated()) {
entryDeprecated= currElement;
}
}
if (nEntriesMissing > 0) {
if (nEntriesMissing == 1) {
fClassPathStatus.setWarning(Messages.format(NewWizardMessages.BuildPathsBlock_warning_EntryMissing,
BasicElementLabels.getPathLabel(entryMissing.getPath(), false)));
} else {
fClassPathStatus.setWarning(Messages.format(NewWizardMessages.BuildPathsBlock_warning_EntriesMissing,
String.valueOf(nEntriesMissing)));
}
} else if (entryDeprecated != null) {
fClassPathStatus.setInfo(entryDeprecated.getDeprecationMessage());
}
/* if (fCurrJProject.hasClasspathCycle(entries)) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
}
*/
updateBuildPathStatus();
}
/**
* Validates output location & build path.
*/
private void updateJavaOutputLocationStatus() {
fJavaOutputLocationPath= null;
String text= fJavaBuildPathDialogField.getText();
if ("".equals(text)) { //$NON-NLS-1$
fOutputFolderStatus.setError(NewWizardMessages.BuildPathsBlock_error_EnterBuildPath);
return;
}
IPath path= getJavaOutputLocation();
fJavaOutputLocationPath= path;
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fOutputFolderStatus.setError(NewWizardMessages.BuildPathsBlock_error_InvalidBuildPath);
return;
}
}
fOutputFolderStatus.setOK();
String pathStr= fJavaBuildPathDialogField.getText();
Path outputPath= (new Path(pathStr));
pathStr= outputPath.lastSegment();
if (pathStr.equals(".settings") && outputPath.segmentCount() == 2) { //$NON-NLS-1$
fOutputFolderStatus.setWarning(NewWizardMessages.OutputLocation_SettingsAsLocation);
}
if (pathStr.charAt(0) == '.' && pathStr.length() > 1) {
fOutputFolderStatus.setWarning(Messages.format(NewWizardMessages.OutputLocation_DotAsLocation,
BasicElementLabels.getResourceName(pathStr)));
}
updateBuildPathStatus();
}
private void updateBuildPathStatus() {
List<CPListElement> elements= fClassPathList.getElements();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i
CPListElement currElement= elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
IJavaModelStatus status= JavaConventions.validateClasspath(fCurrJProject, entries,
fJavaOutputLocationPath);
if (!status.isOK()) {
fBuildPathStatus.setError(status.getMessage());
return;
}
fBuildPathStatus.setOK();
}
public static void createProject(IProject project, URI locationURI, IProgressMonitor monitor)
throws CoreException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.BuildPathsBlock_operationdesc_project, 10);
// create the project
try {
if (!project.exists()) {
IProjectDescription desc= project.getWorkspace()
.newProjectDescription(project.getName());
if (locationURI != null && ResourcesPlugin.getWorkspace()
.getRoot().getLocationURI().equals(locationURI)) {
locationURI= null;
}
desc.setLocationURI(locationURI);
project.create(desc, monitor);
monitor= null;
}
if (!project.isOpen()) {
project.open(monitor);
monitor= null;
}
} finally {
if (monitor != null) {
monitor.done();
}
}
}
public static void addJavaNature(IProject project, IProgressMonitor monitor)
throws CoreException {
if (monitor != null && monitor.isCanceled()) {
throw new OperationCanceledException();
}
if (!project.hasNature(JavaCore.NATURE_ID)) {
IProjectDescription description = project.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= JavaCore.NATURE_ID;
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
} else {
if (monitor != null) {
monitor.worked(1);
}
}
}
public void configureJavaProject(IProgressMonitor monitor)
throws CoreException, OperationCanceledException {
configureJavaProject(null, monitor);
}
public void configureJavaProject(String newProjectCompliance, IProgressMonitor monitor)
throws CoreException, OperationCanceledException {
flush(fClassPathList.getElements(), fResourcePathList.getElements(),
getJavaOutputLocation(), getJavaProject(), newProjectCompliance,
monitor);
initializeTimeStamps();
updateUI();
}
/**
* Sets the configured build path and output location to the given Java project.
* If the project already exists, only build paths are updated.
* <p>
* If the classpath contains an Execution Environment entry, the EE's compiler compliance options
* are used as project-specific options (unless the classpath already contained the same Execution Environment)
*
* @param classPathEntries the new classpath entries (list of {@link CPListElement})
* @param javaOutputLocation the output location
* @param javaProject the Java project
* @param newProjectCompliance compliance to set for a new project, can be <code>null</code>
* @param monitor a progress monitor, or <code>null</code>
* @throws CoreException if flushing failed
* @throws OperationCanceledException if flushing has been cancelled
*/
public static void flush(List<CPListElement> classPathEntries, List<CPListElement> resourcePathEntries,
IPath javaOutputLocation, IJavaProject javaProject, String newProjectCompliance,
IProgressMonitor monitor)
throws CoreException, OperationCanceledException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.setTaskName(NewWizardMessages.BuildPathsBlock_operationdesc_java);
monitor.beginTask("", classPathEntries.size() * 4 + 4); //$NON-NLS-1$
try {
IProject project= javaProject.getProject();
IPath projPath= project.getFullPath();
IPath oldOutputLocation;
try {
oldOutputLocation= javaProject.getOutputLocation();
} catch (CoreException e) {
oldOutputLocation= projPath.append(PreferenceConstants.getPreferenceStore()
.getString(PreferenceConstants.SRCBIN_BINNAME));
}
if (oldOutputLocation.equals(projPath) && !javaOutputLocation.equals(projPath)) {
if (CeylonBuildPathsBlock.hasClassfiles(project)) {
if (CeylonBuildPathsBlock.getRemoveOldBinariesQuery(JavaPlugin.getActiveWorkbenchShell())
.doQuery(false, projPath)) {
CeylonBuildPathsBlock.removeOldClassfiles(project);
}
}
} else if (!javaOutputLocation.equals(oldOutputLocation)) {
IFolder folder= ResourcesPlugin.getWorkspace().getRoot().getFolder(oldOutputLocation);
if (folder.exists()) {
if (folder.members().length==0) {
CeylonBuildPathsBlock.removeOldClassfiles(folder);
}
else {
if (CeylonBuildPathsBlock.getRemoveOldBinariesQuery(JavaPlugin.getActiveWorkbenchShell())
.doQuery(folder.isDerived(), oldOutputLocation)) {
CeylonBuildPathsBlock.removeOldClassfiles(folder);
}
}
}
}
getCeylonModulesOutputFolder(project).delete(true, monitor);
monitor.worked(1);
IWorkspaceRoot fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot();
//create and set the output path first
if (!fWorkspaceRoot.exists(javaOutputLocation)) {
CoreUtility.createDerivedFolder(fWorkspaceRoot.getFolder(javaOutputLocation),
true, true, new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
for (Iterator<CPListElement> iter= resourcePathEntries.iterator(); iter.hasNext();) {
CPListElement entry= iter.next();
IResource res= entry.getResource();
//1 tick
if (res instanceof IFolder && entry.getLinkTarget() == null && !res.exists()) {
CoreUtility.createFolder((IFolder)res, true, true,
new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
//3 ticks
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath folderOutput= (IPath) entry.getAttribute(CPListElement.OUTPUT);
if (folderOutput != null && folderOutput.segmentCount() > 1) {
IFolder folder= fWorkspaceRoot.getFolder(folderOutput);
CoreUtility.createDerivedFolder(folder, true, true,
new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
IPath path= entry.getPath();
if (projPath.equals(path)) {
monitor.worked(2);
continue;
}
if (projPath.isPrefixOf(path)) {
path= path.removeFirstSegments(projPath.segmentCount());
}
IFolder folder= project.getFolder(path);
IPath orginalPath= entry.getOrginalPath();
if (orginalPath == null) {
if (!folder.exists()) {
//New source folder needs to be created
if (entry.getLinkTarget() == null) {
CoreUtility.createFolder(folder, true, true,
new SubProgressMonitor(monitor, 2));
} else {
folder.createLink(entry.getLinkTarget(),
IResource.ALLOW_MISSING_LOCAL,
new SubProgressMonitor(monitor, 2));
}
}
} else {
if (projPath.isPrefixOf(orginalPath)) {
orginalPath= orginalPath.removeFirstSegments(projPath.segmentCount());
}
IFolder orginalFolder= project.getFolder(orginalPath);
if (entry.getLinkTarget() == null) {
if (!folder.exists()) {
//Source folder was edited, move to new location
IPath parentPath= entry.getPath().removeLastSegments(1);
if (projPath.isPrefixOf(parentPath)) {
parentPath= parentPath.removeFirstSegments(projPath.segmentCount());
}
if (parentPath.segmentCount() > 0) {
IFolder parentFolder= project.getFolder(parentPath);
if (!parentFolder.exists()) {
CoreUtility.createFolder(parentFolder, true, true,
new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
} else {
monitor.worked(1);
}
orginalFolder.move(entry.getPath(), true, true,
new SubProgressMonitor(monitor, 1));
}
} else {
if (!folder.exists() || !entry.getLinkTarget().equals(entry.getOrginalLinkTarget())) {
orginalFolder.delete(true, new SubProgressMonitor(monitor, 1));
folder.createLink(entry.getLinkTarget(), IResource.ALLOW_MISSING_LOCAL,
new SubProgressMonitor(monitor, 1));
}
}
}
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
}
int nEntries= classPathEntries.size();
IClasspathEntry[] classpath= new IClasspathEntry[nEntries];
int i= 0;
for (Iterator<CPListElement> iter= classPathEntries.iterator(); iter.hasNext();) {
CPListElement entry= iter.next();
classpath[i]= entry.getClasspathEntry();
i++;
IResource res= entry.getResource();
//1 tick
if (res instanceof IFolder && entry.getLinkTarget() == null && !res.exists()) {
CoreUtility.createFolder((IFolder)res, true, true,
new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
//3 ticks
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath folderOutput= (IPath) entry.getAttribute(CPListElement.OUTPUT);
if (folderOutput != null && folderOutput.segmentCount() > 1) {
IFolder folder= fWorkspaceRoot.getFolder(folderOutput);
CoreUtility.createDerivedFolder(folder, true, true,
new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
IPath path= entry.getPath();
if (projPath.equals(path)) {
monitor.worked(2);
continue;
}
if (projPath.isPrefixOf(path)) {
path= path.removeFirstSegments(projPath.segmentCount());
}
IFolder folder= project.getFolder(path);
IPath orginalPath= entry.getOrginalPath();
if (orginalPath == null) {
if (!folder.exists()) {
//New source folder needs to be created
if (entry.getLinkTarget() == null) {
CoreUtility.createFolder(folder, true, true,
new SubProgressMonitor(monitor, 2));
} else {
folder.createLink(entry.getLinkTarget(),
IResource.ALLOW_MISSING_LOCAL,
new SubProgressMonitor(monitor, 2));
}
}
} else {
if (projPath.isPrefixOf(orginalPath)) {
orginalPath= orginalPath.removeFirstSegments(projPath.segmentCount());
}
IFolder orginalFolder= project.getFolder(orginalPath);
if (entry.getLinkTarget() == null) {
if (!folder.exists()) {
//Source folder was edited, move to new location
IPath parentPath= entry.getPath().removeLastSegments(1);
if (projPath.isPrefixOf(parentPath)) {
parentPath= parentPath.removeFirstSegments(projPath.segmentCount());
}
if (parentPath.segmentCount() > 0) {
IFolder parentFolder= project.getFolder(parentPath);
if (!parentFolder.exists()) {
CoreUtility.createFolder(parentFolder, true, true,
new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
} else {
monitor.worked(1);
}
orginalFolder.move(entry.getPath(), true, true,
new SubProgressMonitor(monitor, 1));
}
} else {
if (!folder.exists() || !entry.getLinkTarget().equals(entry.getOrginalLinkTarget())) {
orginalFolder.delete(true, new SubProgressMonitor(monitor, 1));
folder.createLink(entry.getLinkTarget(), IResource.ALLOW_MISSING_LOCAL,
new SubProgressMonitor(monitor, 1));
}
}
}
} else {
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
IPath path= entry.getPath();
if (! path.equals(entry.getOrginalPath())) {
String eeID= JavaRuntime.getExecutionEnvironmentId(path);
if (eeID != null) {
BuildPathSupport.setEEComplianceOptions(javaProject, eeID, newProjectCompliance);
newProjectCompliance= null; // don't set it again below
}
}
if (newProjectCompliance != null) {
setOptionsFromJavaProject(javaProject,
newProjectCompliance);
}
}
monitor.worked(3);
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
}
javaProject.setRawClasspath(classpath, javaOutputLocation,
new SubProgressMonitor(monitor, 2));
CeylonProjectConfig config = CeylonProjectConfig.get(project);
List<String> srcDirs = new ArrayList<String>();
for (CPListElement cpe: classPathEntries) {
if (cpe.getEntryKind()==IClasspathEntry.CPE_SOURCE) {
srcDirs.add(configFilePath(project, cpe));
}
}
config.setProjectSourceDirectories(srcDirs);
List<String> rsrcDirs = new ArrayList<String>();
for (CPListElement cpe: resourcePathEntries) {
rsrcDirs.add(configFilePath(project, cpe));
}
config.setProjectResourceDirectories(rsrcDirs);
config.save();
} finally {
monitor.done();
}
}
private static String configFilePath(IProject project, CPListElement cpe) {
IPath linkTarget = cpe.getLinkTarget();
if (linkTarget==null) {
return "." + File.separator + cpe.getPath().makeRelativeTo(project.getFullPath()).toOSString();
}
else {
return cpe.getLinkTarget().toOSString();
}
}
private static void setOptionsFromJavaProject(IJavaProject javaProject,
String newProjectCompliance) {
@SuppressWarnings("unchecked")
Map<String, String> options= javaProject.getOptions(false);
JavaModelUtil.setComplianceOptions(options, newProjectCompliance);
JavaModelUtil.setDefaultClassfileOptions(options, newProjectCompliance); // complete compliance options
javaProject.setOptions(options);
}
public static boolean hasClassfiles(IResource resource) throws CoreException {
if (resource.isDerived()) {
return true;
}
if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
if (hasClassfiles(members[i])) {
return true;
}
}
}
return false;
}
public static void removeOldClassfiles(IResource resource) throws CoreException {
if (resource.isDerived()) {
resource.delete(false, null);
} else if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
removeOldClassfiles(members[i]);
}
}
}
public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) {
return new IRemoveOldBinariesQuery() {
public boolean doQuery(final boolean removeFolder, final IPath oldOutputLocation)
throws OperationCanceledException {
final int[] res= new int[] { 1 };
Display.getDefault().syncExec(new Runnable() {
public void run() {
Shell sh= shell != null ? shell : JavaPlugin.getActiveWorkbenchShell();
String title= NewWizardMessages.BuildPathsBlock_RemoveBinariesDialog_title;
String message;
String pathLabel= BasicElementLabels.getPathLabel(oldOutputLocation, false);
if (removeFolder) {
message= Messages.format(NewWizardMessages.BuildPathsBlock_RemoveOldOutputFolder_description, pathLabel);
} else {
message= Messages.format(NewWizardMessages.BuildPathsBlock_RemoveBinariesDialog_description, pathLabel);
}
MessageDialog dialog= new MessageDialog(sh, title, null, message, MessageDialog.QUESTION,
new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 0);
res[0]= dialog.open();
}
});
if (res[0] == 0) {
return true;
} else if (res[0] == 1) {
return false;
}
throw new OperationCanceledException();
}
};
}
private IContainer chooseContainer(IPath outputPath) {
Class<?>[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList<IProject> rejectedElements= new ArrayList<IProject>(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSelection= null;
if (outputPath != null) {
initSelection= fWorkspaceRoot.findMember(outputPath);
}
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setTitle(NewWizardMessages.BuildPathsBlock_ChooseOutputFolderDialog_title);
dialog.setValidator(validator);
dialog.setMessage(NewWizardMessages.BuildPathsBlock_ChooseOutputFolderDialog_description);
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setInitialSelection(initSelection);
dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
if (dialog.open() == Window.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
private void tabChanged(Widget widget) {
if (widget instanceof TabItem) {
TabItem tabItem= (TabItem) widget;
BuildPathBasePage newPage= (BuildPathBasePage) tabItem.getData();
if (fCurrPage != null) {
List<?> selection= fCurrPage.getSelection();
if (!selection.isEmpty()) {
newPage.setSelection(selection, false);
}
}
fCurrPage= newPage;
fPageIndex= tabItem.getParent().getSelectionIndex();
}
}
private int getPageIndex(int entryKind) {
switch (entryKind) {
case IClasspathEntry.CPE_CONTAINER:
case IClasspathEntry.CPE_LIBRARY:
case IClasspathEntry.CPE_VARIABLE:
return 2;
case IClasspathEntry.CPE_PROJECT:
return 1;
case IClasspathEntry.CPE_SOURCE:
return 0;
}
return 0;
}
private CPListElement findElement(IClasspathEntry entry) {
CPListElement prefixMatch= null;
int entryKind= entry.getEntryKind();
for (int i= 0, len= fClassPathList.getSize(); i < len; i++) {
CPListElement curr= fClassPathList.getElement(i);
if (curr.getEntryKind() == entryKind) {
IPath entryPath= entry.getPath();
IPath currPath= curr.getPath();
if (currPath.equals(entryPath)) {
return curr;
}
// in case there's no full match, look for a similar container (same ID segment):
if (prefixMatch == null && entryKind == IClasspathEntry.CPE_CONTAINER) {
int n= entryPath.segmentCount();
if (n > 0) {
IPath genericContainerPath= n == 1 ?
entryPath : entryPath.removeLastSegments(n - 1);
if (n > 1 && genericContainerPath.isPrefixOf(currPath)) {
prefixMatch= curr;
}
}
}
}
}
return prefixMatch;
}
public void setElementToReveal(IClasspathEntry entry, String attributeKey) {
int pageIndex= getPageIndex(entry.getEntryKind());
if (fTabFolder == null) {
fPageIndex= pageIndex;
} else {
fTabFolder.setSelection(pageIndex);
CPListElement element= findElement(entry);
if (element != null) {
Object elementToSelect= element;
if (attributeKey != null) {
Object attrib= element.findAttributeElement(attributeKey);
if (attrib != null) {
elementToSelect= attrib;
}
}
BuildPathBasePage page= (BuildPathBasePage) fTabFolder.getItem(pageIndex).getData();
List<Object> selection= new ArrayList<Object>(1);
selection.add(elementToSelect);
page.setSelection(selection, true);
}
}
}
public void addElement(IClasspathEntry entry) {
int pageIndex= getPageIndex(entry.getEntryKind());
if (fTabFolder == null) {
fPageIndex= pageIndex;
} else {
fTabFolder.setSelection(pageIndex);
// Object page= fTabFolder.getItem(pageIndex).getData();
// if (page instanceof LibrariesWorkbookPage) {
// CPListElement element= CPListElement.create(entry, true, fCurrJProject);
// ((LibrariesWorkbookPage) page).addElement(element);
}
}
public boolean isOKStatus() {
return findMostSevereStatus().isOK();
}
public void setFocus() {
fSourceContainerPage.setFocus();
}
} |
package innovimax.mixthem;
/**
* <p>This is a enumeration of rule parameters types.</p>
* @author Innovimax
* @version 1.0
*/
public enum ParamType {
_STRING,
_INTEGER;
} |
package com.redhat.ceylon.eclipse.code.search;
import static com.redhat.ceylon.eclipse.util.Highlights.ID_STYLER;
import static com.redhat.ceylon.eclipse.util.Highlights.KW_STYLER;
import static com.redhat.ceylon.eclipse.util.Highlights.PACKAGE_STYLER;
import static com.redhat.ceylon.eclipse.util.Highlights.TYPE_ID_STYLER;
import static com.redhat.ceylon.eclipse.util.Highlights.styleJavaType;
import static org.eclipse.jdt.core.Signature.getSignatureSimpleName;
import static org.eclipse.jface.viewers.StyledString.COUNTER_STYLER;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.swt.graphics.Image;
import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider;
import com.redhat.ceylon.eclipse.util.Highlights;
public class SearchResultsLabelProvider extends CeylonLabelProvider {
@Override
public Image getImage(Object element) {
if (element instanceof WithSourceFolder) {
element = ((WithSourceFolder) element).element;
}
String key;
int decorations;
if (element instanceof ArchiveMatches) {
key = RUNTIME_OBJ;
decorations = 0;
}
else if (element instanceof CeylonElement) {
key = ((CeylonElement) element).getImageKey();
decorations = ((CeylonElement) element).getDecorations();
}
else if (element instanceof IType ||
element instanceof IField ||
element instanceof IMethod) {
key = getImageKeyForDeclaration((IJavaElement) element);
decorations = 0;
}
else {
key = super.getImageKey(element);
decorations = super.getDecorationAttributes(element);
}
return getDecoratedImage(key, decorations, false);
}
@Override
public StyledString getStyledText(Object element) {
if (element instanceof WithSourceFolder) {
element = ((WithSourceFolder) element).element;
}
if (element instanceof ArchiveMatches) {
return new StyledString("Source Archive Matches");
}
else if (element instanceof CeylonElement) {
return getStyledLabelForSearchResult((CeylonElement) element);
}
else if (element instanceof IType ||
element instanceof IField||
element instanceof IMethod) {
return getStyledLabelForSearchResult((IJavaElement) element);
}
else {
return super.getStyledText(element);
}
}
private StyledString getStyledLabelForSearchResult(CeylonElement ce) {
StyledString styledString = new StyledString();
IFile file = ce.getFile();
String path = file==null ?
ce.getVirtualFile().getPath() :
file.getFullPath().toString();
styledString.append(ce.getLabel())
.append(" - " + ce.getPackageLabel(), PACKAGE_STYLER)
.append(" - " + path, COUNTER_STYLER);
return styledString;
}
private StyledString getStyledLabelForSearchResult(IJavaElement je) {
StyledString styledString = new StyledString();
String name = je.getElementName();
if (je instanceof IMethod) {
try {
String returnType = ((IMethod) je).getReturnType();
if (returnType.equals("V")) {
styledString.append("void", Highlights.KW_STYLER);
}
else {
styledString.append("method", KW_STYLER);
/*styleJavaType(styledString,
getSignatureSimpleName(returnType));*/
}
}
catch (Exception e) {
e.printStackTrace();
}
styledString.append(' ').append(name, ID_STYLER);
try {
styledString.append('(');
String[] parameterTypes = ((IMethod) je).getParameterTypes();
String[] parameterNames = ((IMethod) je).getParameterNames();
boolean first = true;
for (int i=0; i<parameterTypes.length && i<parameterNames.length; i++) {
if (first) {
first = false;
}
else {
styledString.append(", ");
}
styleJavaType(styledString,
getSignatureSimpleName(parameterTypes[i]));
styledString.append(' ')
.append(parameterNames[i], ID_STYLER);
}
styledString.append(')');
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (je instanceof IField) {
styledString.append("field", KW_STYLER);
/*try {
String type = ((IField) je).getTypeSignature();
styleJavaType(styledString,
getSignatureSimpleName(type));
}
catch (Exception e) {
e.printStackTrace();
}*/
styledString.append(' ').append(name, ID_STYLER);
}
else if (je instanceof IType) {
IType type = (IType) je;
try {
if (type.isAnnotation()) {
styledString.append('@').append("interface ", KW_STYLER);
}
else if (type.isInterface()) {
styledString.append("interface ", KW_STYLER);
}
else if (type.isClass()) {
styledString.append("class ", KW_STYLER);
}
else if (type.isEnum()) {
styledString.append("enum ", KW_STYLER);
}
}
catch (Exception e) {
e.printStackTrace();
}
styledString.append(name, TYPE_ID_STYLER);
}
IJavaElement pkg = ((IJavaElement) je.getOpenable()).getParent();
styledString.append(" - ", PACKAGE_STYLER)
.append(pkg.getElementName(), PACKAGE_STYLER);
IFile file = (IFile) je.getResource();
if (file!=null) {
styledString.append(" - " + file.getFullPath().toString(), COUNTER_STYLER);
}
return styledString;
}
private static String getImageKeyForDeclaration(IJavaElement e) {
if (e==null) return null;
boolean shared = false;
if (e instanceof IMember) {
try {
shared = Flags.isPublic(((IMember) e).getFlags());
}
catch (JavaModelException jme) {
jme.printStackTrace();
}
}
switch(e.getElementType()) {
case IJavaElement.METHOD:
if (shared) {
return CEYLON_METHOD;
}
else {
return CEYLON_LOCAL_METHOD;
}
case IJavaElement.FIELD:
if (shared) {
return CEYLON_ATTRIBUTE;
}
else {
return CEYLON_LOCAL_ATTRIBUTE;
}
case IJavaElement.TYPE:
if (shared) {
return CEYLON_CLASS;
}
else {
return CEYLON_LOCAL_CLASS;
}
default:
return null;
}
}
} |
package innovimax.mixthem;
/**
* <p>Rule additional parameters management.</p>
* @author Innovimax
* @version 1.0
*/
public class RuleParam {
private final String name;
private final boolean required;
/**
* Creates a rule parameter.
* @param name The name of the parameter
* @param required Equals true if this parameter is required
*/
RuleParam(String name, boolean required) {
this.name = name;
this.required = required;
}
/**
* Returns the name of the rule parameter.
* @return The name of the rule parameter
*/
String getName() {
return this.name;
}
/**
* Returns true if this parameter is required.
* @return Returns true if this parameter is required
*/
boolean isRequired() {
return this.required;
}
// This is the unique optional parameter of rule _RANDOM_ALT_LINE
static RuleParam RANDOM_ALT_LINE_SEED = new RuleParam("seed", false);
// This is the first optional parameter of rule _JOIN
static RuleParam JOIN_COL1 = new RuleParam("col1", false);
// This is the second optional parameter of rule _JOIN
static RuleParam JOIN_COL2 = new RuleParam("col2", false);
} |
package interpres.ast;
import java.util.List;
import java.util.ArrayList;
import interpres.DefinitionTable;
public class StringLiteral extends AST {
private String literal;
public StringLiteral(String literal) {
this.literal = literal;
}
public List<Object> evaluate(DefinitionTable definitionTable) {
List<Object> instructions = new ArrayList<Object>();
for (int i = literal.length() - 1; i >= 0; i
instructions.add("LOADL " + (int) literal.charAt(i));
}
return instructions;
}
public String toString() {
return this.literal.toString();
}
} |
package io.coinswap.client;
import com.google.common.collect.ImmutableList;
import org.bitcoinj.kits.WalletAppKit;
import org.bitcoinj.core.*;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.List;
/**
* Contains the settings and state for one currency. Includes an AltcoinJ wallet,
* and a JS-side Currency model for interfacing with UI.
*/
public class Currency {
private static final Logger log = LoggerFactory.getLogger(Currency.class);
private static final File checkpointDir = new File("./checkpoints");
protected NetworkParameters params;
protected File directory;
protected WalletAppKit wallet;
protected String name, id, symbol;
protected String[] pairs;
protected int index;
protected boolean hashlock; // whether or not this coin can be used on the Alice-side of a swap
protected int confirmationDepth;
private boolean setup;
private SettableFuture<Object> setupFuture;
public Currency(NetworkParameters params, File directory,
String name, String id, String symbol, String[] pairs,
int index, boolean hashlock, int confirmationDepth) {
this.params = params;
this.directory = directory;
this.name = name;
this.id = id;
this.symbol = symbol;
this.pairs = pairs;
this.index = index;
this.hashlock = hashlock;
this.confirmationDepth = confirmationDepth;
setupFuture = SettableFuture.create();
// create the AltcoinJ wallet to interface with the currency
wallet = new WalletAppKit(params, directory, name.toLowerCase()) {
@Override
protected void onSetupCompleted() {
makeBackup();
peerGroup().setMaxConnections(8);
peerGroup().setFastCatchupTimeSecs(wallet.wallet().getEarliestKeyCreationTime());
setup = true;
setupFuture.set(null);
}
};
wallet.setUserAgent(Main.APP_NAME, Main.APP_VERSION);
wallet.setBlockingStartup(false);
// load a checkpoint file (if it exists) to speed up initial blockchain sync
InputStream checkpointStream = Main.class.getResourceAsStream("/checkpoints/"+name.toLowerCase()+".txt");
if(checkpointStream != null) {
wallet.setCheckpoints(checkpointStream);
} else {
log.info("No checkpoints found for " + name);
}
}
public void start() {
wallet.startAsync();
wallet.awaitRunning();
}
public void stop() {
wallet.stopAsync();
wallet.awaitTerminated();
}
private void makeBackup() {
File backupDir = new File(directory, "backup");
if(!backupDir.exists()) {
boolean success = backupDir.mkdir();
if(!success) throw new RuntimeException();
}
File backup = new File(backupDir, name.toLowerCase()+".wallet");
if(!backup.exists()) {
try {
wallet.wallet().saveToFile(backup);
} catch(IOException e) {
throw new RuntimeException();
}
}
}
public String getId() { return id; }
public int getIndex() { return index; }
public boolean supportsHashlock() { return hashlock; }
public int getConfirmationDepth() { return confirmationDepth; }
public String[] getPairs() { return pairs; }
public boolean isSetup() { return setup; }
public WalletAppKit getWallet() { return wallet; }
public NetworkParameters getParams() { return params; }
public ListenableFuture<Object> getSetupFuture() { return setupFuture; }
} |
package io.teiler.server.util;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.LinkedList;
import java.util.List;
/**
* Error wrapper to smoothly get error codes across the REST API.
*
* @author lroellin
*/
public class Error {
@Expose
@SerializedName("error")
private List<String> errorCodes = new LinkedList<>();
public Error(String errorCode) {
this.errorCodes.add(errorCode);
}
} |
package io.vertx.codegen;
/**
* Describes a module.
*
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public class ModuleInfo {
private final String fqn;
private final String name;
public ModuleInfo(String fqn, String name) {
this.fqn = fqn;
this.name = name;
}
/**
* @return the module fqn, i.e the name of the package annotated with the {@link io.vertx.codegen.annotations.GenModule} annotation
*/
public String getFqn() {
return fqn;
}
/**
* @return the module name
*/
public String getName() {
return name;
}
/**
* @param _case the formatting case
* @return the module name in the specified case
*/
public String getName(Case _case) {
return _case.format(Case.CAMEL.parse(name));
}
} |
package com.matthewtamlin.spyglass.processors.annotation_utils;
import com.matthewtamlin.java_utilities.testing.Tested;
import java.lang.annotation.Annotation;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
import static com.matthewtamlin.spyglass.processors.core.AnnotationRegistry.CALL_HANDLER_ANNOTATIONS;
@Tested(testMethod = "automated")
public class CallHandlerAnnotationUtil {
public static AnnotationMirror getCallHandlerAnnotationMirror(final ExecutableElement element) {
checkNotNull(element, "Argument \'element\' cannot be null.");
for (final Class<? extends Annotation> annotationClass : CALL_HANDLER_ANNOTATIONS) {
final AnnotationMirror mirror = AnnotationMirrorUtil.getAnnotationMirror(element, annotationClass);
if (mirror != null) {
return mirror;
}
}
return null;
}
public static boolean hasCallHandlerAnnotation(final ExecutableElement element) {
checkNotNull(element, "Argument \'element\' cannot be null.");
for (final Class<? extends Annotation> a : CALL_HANDLER_ANNOTATIONS) {
if (element.getAnnotation(a) != null) {
return true;
}
}
return false;
}
private CallHandlerAnnotationUtil() {
throw new RuntimeException("Utility class. Do not instantiate.");
}
} |
package xal.tools.apputils;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Frame;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import xal.tools.annotation.AProperty.NoEdit;
import xal.tools.annotation.AProperty.Units;
import xal.model.probe.Probe;
import xal.model.IAlgorithm;
import xal.tools.swing.*;
import xal.tools.data.*;
import java.beans.*;
import java.lang.reflect.*;
/** SimpleProbeEditor */
public class SimpleProbeEditor extends JDialog {
/** Private serializable version ID */
private static final long serialVersionUID = 1L;
/** Table model of ProbeProperty records */
final private KeyValueFilteredTableModel<PropertyRecord> PROPERTY_TABLE_MODEL;
/** List of properties that appear in the properties table */
final private List<PropertyRecord> PROBE_PROPERTY_RECORDS;
/** Probe that is being edited */
final private Probe PROBE;
/** model column for the value in the property table */
final private int PROPERTY_TABLE_VALUE_COLUMN;
/* Constructor that takes a window parent
* and a probe to fetch properties from
*/
public SimpleProbeEditor( final Frame owner, final Probe probe ) {
super( owner, "Probe Editor", true ); //Set JDialog's owner, title, and modality
PROBE = probe; // Set the probe to edit
// generate the probe property tree
final EditablePropertyContainer probePropertyTree = EditableProperty.getInstanceWithRoot( "Probe", probe );
//System.out.println( probePropertyTree );
PROBE_PROPERTY_RECORDS = PropertyRecord.toRecords( probePropertyTree );
PROPERTY_TABLE_MODEL = new KeyValueFilteredTableModel<>( PROBE_PROPERTY_RECORDS, "displayLabel", "value", "units" );
PROPERTY_TABLE_MODEL.setMatchingKeyPaths( "path" ); // match on the path
PROPERTY_TABLE_MODEL.setColumnName( "displayLabel", "Property" );
PROPERTY_TABLE_MODEL.setColumnEditKeyPath( "value", "editable" ); // the value is editable if the record is editable
PROPERTY_TABLE_VALUE_COLUMN = PROPERTY_TABLE_MODEL.getColumnForKeyPath( "value" ); // store the column for the "value" key path
setSize( 600, 600 ); // Set the window size
initializeComponents(); // Set up each component in the editor
setLocationRelativeTo( owner ); // Center the editor in relation to the frame that constructed the editor
setVisible(true); // Make the window visible
}
/**
* Get the probe to edit
* @return probe associated with this editor
*/
public Probe getProbe() {
return PROBE;
}
/** publish record values to the probe */
private void publishToProbe() {
for ( final PropertyRecord record : PROBE_PROPERTY_RECORDS ) {
record.publishIfNeeded();
}
PROPERTY_TABLE_MODEL.fireTableDataChanged();
}
/** revert the record values from the probe */
private void revertFromProbe() {
for ( final PropertyRecord record : PROBE_PROPERTY_RECORDS ) {
record.revertIfNeeded();
}
PROPERTY_TABLE_MODEL.fireTableDataChanged();
}
/** Initialize the components of the probe editor */
public void initializeComponents() {
//main view containing all components
final Box mainContainer = new Box( BoxLayout.Y_AXIS );
// button to revert changes back to last saved state
final JButton revertButton = new JButton( "Revert" );
revertButton.setToolTipText( "Revert values back to those in probe." );
revertButton.setEnabled( false );
// button to publish changes
final JButton publishButton = new JButton( "Publish" );
publishButton.setToolTipText( "Publish values to the probe." );
publishButton.setEnabled( false );
// button to publish changes and dismiss the panel
final JButton okayButton = new JButton( "Okay" );
okayButton.setToolTipText( "Publish values to the probe and dismiss the dialog." );
okayButton.setEnabled( true );
//Add the action listener as the ApplyButtonListener
revertButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
revertFromProbe();
revertButton.setEnabled( false );
publishButton.setEnabled( false );
}
});
//Add the action listener as the ApplyButtonListener
publishButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
publishToProbe();
revertButton.setEnabled( false );
publishButton.setEnabled( false );
}
});
//Add the action listener as the ApplyButtonListener
okayButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
try {
publishToProbe();
dispose();
}
catch( Exception exception ) {
JOptionPane.showMessageDialog( SimpleProbeEditor.this, exception.getMessage(), "Error Publishing", JOptionPane.ERROR_MESSAGE );
System.err.println( "Exception publishing values to probe: " + exception );
}
}
});
PROPERTY_TABLE_MODEL.addKeyValueRecordListener( new KeyValueRecordListener<KeyValueTableModel<PropertyRecord>,PropertyRecord>() {
public void recordModified( final KeyValueTableModel<PropertyRecord> source, final PropertyRecord record, final String keyPath, final Object value ) {
revertButton.setEnabled( true );
publishButton.setEnabled( true );
}
});
//Table containing the properties that can be modified
final JTable propertyTable = new JTable() {
/** Serializable version ID */
private static final long serialVersionUID = 1L;
/** renderer for a table section */
private final TableCellRenderer SECTION_RENDERER = makeSectionRenderer();
//Get the cell editor for the table
@Override
public TableCellEditor getCellEditor( final int row, final int col ) {
//Value at [row, col] of the table
final Object value = getValueAt( row, col );
if ( value == null ) {
return super.getCellEditor( row, col );
}
else {
return getDefaultEditor( value.getClass() );
}
}
//Get the cell renderer for the table to change how values are displayed
@Override
public TableCellRenderer getCellRenderer( final int row, final int column ) {
// index of the record in the model
final int recordIndex = this.convertRowIndexToModel( row );
final PropertyRecord record = PROPERTY_TABLE_MODEL.getRecordAtRow( recordIndex );
final Object value = getValueAt( row, column );
//Set the renderer according to the property type (e.g. Boolean => checkbox display, numeric => right justified)
if ( !record.isEditable() ) {
return SECTION_RENDERER;
}
else if ( value == null ) {
return super.getCellRenderer( row, column );
}
else {
final TableCellRenderer renderer = getDefaultRenderer( value.getClass() );
if ( renderer instanceof DefaultTableCellRenderer ) {
final DefaultTableCellRenderer defaultRenderer = (DefaultTableCellRenderer)renderer;
final int modelColumn = convertColumnIndexToModel( column );
// highlight the cell if the column corresponds to the value and it has unpublished changes
defaultRenderer.setForeground( modelColumn == PROPERTY_TABLE_VALUE_COLUMN && record.hasChanges() ? Color.BLUE : Color.BLACK );
}
return renderer;
}
}
private TableCellRenderer makeSectionRenderer() {
final DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setBackground( Color.GRAY );
renderer.setForeground( Color.WHITE );
return renderer;
}
};
//Set the table to allow one-click edit
((DefaultCellEditor) propertyTable.getDefaultEditor(Object.class)).setClickCountToStart(1);
//Resize the last column
propertyTable.setAutoResizeMode( JTable.AUTO_RESIZE_LAST_COLUMN);
//Allow single selection only
propertyTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
//Set the model to the table
propertyTable.setModel( PROPERTY_TABLE_MODEL );
//Configure the text field to filter the table
final JTextField filterTextField = new JTextField();
filterTextField.setMaximumSize( new Dimension( 32000, filterTextField.getPreferredSize().height ) );
filterTextField.putClientProperty( "JTextField.variant", "search" );
filterTextField.putClientProperty( "JTextField.Search.Prompt", "Property Filter" );
PROPERTY_TABLE_MODEL.setInputFilterComponent( filterTextField );
mainContainer.add( filterTextField, BorderLayout.NORTH );
//Add the scrollpane to the table with a vertical scrollbar
final JScrollPane scrollPane = new JScrollPane( propertyTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
mainContainer.add( scrollPane );
//Add the buttons to the bottom of the dialog
final Box controlPanel = new Box( BoxLayout.X_AXIS );
controlPanel.add( revertButton );
controlPanel.add( Box.createHorizontalGlue() );
controlPanel.add( publishButton );
controlPanel.add( okayButton );
mainContainer.add( controlPanel );
//Add everything to the dialog
add( mainContainer );
}
}
/** Wraps a property for display as a record in a table */
class PropertyRecord {
/** wrapped property */
final private EditableProperty PROPERTY;
/** current value which may be pending */
private Object _value;
/** indicates that this record has unsaved changes */
private boolean _hasChanges;
/** Constructor */
public PropertyRecord( final EditableProperty property ) {
PROPERTY = property;
// initialize the value and status from the underlying property
revert();
}
/** name of the property */
public String getName() {
return PROPERTY.getName();
}
/** Get the path to this property */
public String getPath() {
return PROPERTY.getPath();
}
/** Get the label for display. */
public String getDisplayLabel() {
return isEditable() ? getName() : getPath();
}
/** Get the property type */
public Class<?> getPropertyType() {
return PROPERTY.getPropertyType();
}
/** Get the value for this property */
public Object getValue() {
return _value;
}
/** set the pending value */
public void setValueAsObject( final Object value ) {
if ( isEditable() ) {
_value = value;
// get the property's current value
final Object propertyValue = PROPERTY.getValue();
// if the value is really different from the property's current value then mark it as having changes
// if the value is null then look for strict equality otherwise compare using equals
if ( ( value == null && value != propertyValue ) || ( value != null && !value.equals( propertyValue ) ) ) {
_hasChanges = true;
}
else {
_hasChanges = false;
}
}
}
/** set the pending value */
public void setValue( final boolean value ) {
setValueAsObject( Boolean.valueOf( value ) );
}
/** Set the pending string value. Most values (except for boolean) are set as string since the table cell editor does so. */
public void setValue( final String value ) {
final Class<?> rawType = getPropertyType();
if ( rawType == String.class ) {
setValueAsObject( value );
}
else {
try {
final Class<?> type = rawType.isPrimitive() ? _value.getClass() : rawType; // convert to wrapper type (e.g. double.class to Double.class) if necessary
final Object objectValue = toObjectOfType( value, type );
setValueAsObject( objectValue );
}
catch( Exception exception ) {
System.err.println( "Exception: " + exception );
System.err.println( "Error parsing the value: " + value + " as " + rawType );
}
}
}
/** Convert the string to an Object of the specified type */
static private Object toObjectOfType( final String stringValue, final Class<?> type ) {
try {
// every wrapper class has a static method named "valueOf" that takes a String and returns a corresponding instance of the wrapper
final Method converter = type.getMethod( "valueOf", String.class );
return converter.invoke( null, stringValue );
}
catch ( Exception exception ) {
throw new RuntimeException( "No match to parse string: " + stringValue + " as " + type );
}
}
/** synonym for isEditable so the table model will work */
public boolean getEditable() {
return isEditable();
}
/** only primitive properties are editable */
public boolean isEditable() {
return PROPERTY.isPrimitive();
}
/** indicates whether this record has unpublished changes */
public boolean hasChanges() {
return _hasChanges;
}
/** revert to the property value if this record is editable and has unpublished changes */
public void revertIfNeeded() {
if ( isEditable() && hasChanges() ) {
revert();
}
}
/** revert back to the current value of the underlying property */
public void revert() {
// the value is only meaningful for primitive properties (only thing we want to display)
_value = PROPERTY.isPrimitive() ? PROPERTY.getValue() : null;
_hasChanges = false;
}
/** publish the pending value to the underlying property if editable and marked with unpublished changes */
public void publishIfNeeded() {
if ( isEditable() && hasChanges() ) {
publish();
}
}
/** publish the pending value to the underlying property */
public void publish() {
PROPERTY.setValue( _value );
_hasChanges = false;
}
/** Get the units */
public String getUnits() {
return PROPERTY.getUnits();
}
/** Generate a flat list of records from the given property tree */
static public List<PropertyRecord> toRecords( final EditablePropertyContainer propertyTree ) {
final List<PropertyRecord> records = new ArrayList<>();
appendPropertiesToRecords( propertyTree, records );
return records;
}
/** append the properties in the given tree to the records nesting deeply */
static private void appendPropertiesToRecords( final EditablePropertyContainer propertyTree, final List<PropertyRecord> records ) {
records.add( new PropertyRecord( propertyTree ) ); // add the container itself
// add all the primitive properties
final List<EditablePrimitiveProperty> properties = propertyTree.getChildPrimitiveProperties();
for ( final EditablePrimitiveProperty property : properties ) {
records.add( new PropertyRecord( property ) );
}
// navigate down through each container and append their sub trees
final List<EditablePropertyContainer> containers = propertyTree.getChildPropertyContainers();
for ( final EditablePropertyContainer container : containers ) {
appendPropertiesToRecords( container, records ); // add the containers descendents
}
}
}
/** base class for a editable property */
abstract class EditableProperty {
/** array of classes for which the property can be edited directly */
final static protected Set<Class<?>> EDITABLE_PROPERTY_TYPES = new HashSet<>();
/** property name */
final protected String NAME;
/** path to this property */
final protected String PATH;
/** target object which is assigned the property */
final protected Object TARGET;
/** property descriptor */
final protected PropertyDescriptor PROPERTY_DESCRIPTOR;
// static initializer
static {
// cache the editable properties in a set for quick comparison later
final Class<?>[] editablePropertyTypes = { Double.class, Double.TYPE, Float.class, Float.TYPE, Integer.class, Integer.TYPE, Short.class, Short.TYPE, Long.class, Long.TYPE, Boolean.class, Boolean.TYPE, String.class };
for ( final Class<?> type : editablePropertyTypes ) {
EDITABLE_PROPERTY_TYPES.add( type );
}
}
/** Constructor */
protected EditableProperty( final String pathPrefix, final String name, final Object target, final PropertyDescriptor descriptor ) {
NAME = name;
PATH = pathPrefix != null && pathPrefix.length() > 0 ? pathPrefix + "." + name : name;
TARGET = target;
PROPERTY_DESCRIPTOR = descriptor;
}
/** Constructor */
protected EditableProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor ) {
this( pathPrefix, descriptor.getName(), target, descriptor );
}
/** Get an instance starting at the root object */
static public EditablePropertyContainer getInstanceWithRoot( final String name, final Object root ) {
return EditablePropertyContainer.getInstanceWithRoot( name, root );
}
/** name of the property */
public String getName() {
return NAME;
}
/** Get the path to this property */
public String getPath() {
return PATH;
}
/** Get the property type */
public Class<?> getPropertyType() {
return PROPERTY_DESCRIPTOR != null ? PROPERTY_DESCRIPTOR.getPropertyType() : null;
}
/** Get the value for this property */
public Object getValue() {
if ( TARGET != null && PROPERTY_DESCRIPTOR != null ) {
final Method getter = PROPERTY_DESCRIPTOR.getReadMethod();
try {
return getter.invoke( TARGET );
}
catch( Exception exception ) {
System.err.println( exception );
return null;
}
}
else {
return null;
}
}
/** set the value */
abstract public void setValue( final Object value );
/** Get the units */
public String getUnits() {
return null;
}
/** determine whether the property is a container */
abstract public boolean isContainer();
/** determine whether the property is a primitive */
abstract public boolean isPrimitive();
/*
* Get the property descriptors for the given bean info
* @param target object for which to get the descriptors
* @return the property descriptors for non-null beanInfo otherwise null
*/
static protected PropertyDescriptor[] getPropertyDescriptors( final Object target ) {
if ( target != null ) {
final BeanInfo beanInfo = getBeanInfo( target );
return getPropertyDescriptorsForBeanInfo( beanInfo );
}
else {
return null;
}
}
/*
* Get the property descriptors for the given bean info
* @param beanInfo bean info
* @return the property descriptors for non-null beanInfo otherwise null
*/
static private PropertyDescriptor[] getPropertyDescriptorsForBeanInfo( final BeanInfo beanInfo ) {
return beanInfo != null ? beanInfo.getPropertyDescriptors() : null;
}
/** Convenience method to get the BeanInfo for an object's class */
static private BeanInfo getBeanInfo( final Object object ) {
if ( object != null ) {
return getBeanInfoForType( object.getClass() );
}
else {
return null;
}
}
/** Convenience method to get the BeanInfo for the given type */
static private BeanInfo getBeanInfoForType( final Class<?> propertyType ) {
if ( propertyType != null ) {
try {
return Introspector.getBeanInfo( propertyType );
}
catch( IntrospectionException exception ) {
return null;
}
}
else {
return null;
}
}
/** Get a string represenation of this property */
public String toString() {
return getPath();
}
}
/** editable property representing a primitive that is directly editable */
class EditablePrimitiveProperty extends EditableProperty {
/** property's units */
final private String UNITS;
/** Constructor */
protected EditablePrimitiveProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor ) {
super( pathPrefix, target, descriptor );
UNITS = fetchUnits();
}
/** fetch the units */
private String fetchUnits() {
// first check to see if there is a Units annotation (ideal when known at compile time) on the accessor method and use it otherwise fallback to fetching by unit property methods
final Method readMethod = PROPERTY_DESCRIPTOR.getReadMethod();
final Units units = readMethod != null ? readMethod.getAnnotation( Units.class ) : null;
if ( units != null ) {
return units.value();
}
else { // unit property methods allow for dynamic units (i.e. units not known at runtime)
// form the accessor as get<PropertyName>Units() replacing <PropertyName> with the property's name whose first character is upper case
final char[] nameChars = getName().toCharArray();
nameChars[0] = Character.toUpperCase( nameChars[0] ); // capitalize the first character of the name
final String propertyName = String.valueOf( nameChars ); // property name whose first character is upper case
// first look for a method of the form get<PropertyName>Units() taking no arguments and returning a String
final String unitsAccessorName = "get" + propertyName + "Units";
try {
final Method unitsAccessor = TARGET.getClass().getMethod( unitsAccessorName );
if ( unitsAccessor.getReturnType() == String.class ) {
return (String)unitsAccessor.invoke( TARGET );
}
}
catch ( NoSuchMethodException exception ) {
// fallback look for a method of the form getUnitsForProperty( String name ) returning a String
try {
final Method unitsAccessor = TARGET.getClass().getMethod( "getUnitsForProperty", String.class );
if ( unitsAccessor.getReturnType() == String.class ) {
return (String)unitsAccessor.invoke( TARGET, getName() );
}
return "";
}
catch( Exception fallbackException ) {
return "";
}
}
catch( Exception exception ) {
System.out.println( exception );
return "";
}
return "";
}
}
/** determine whether the property is a container */
public boolean isContainer() {
return false;
}
/** determine whether the property is a primitive */
public boolean isPrimitive() {
return true;
}
/** Set the value for this property */
public void setValue( final Object value ) {
if ( TARGET != null && PROPERTY_DESCRIPTOR != null ) {
final Method setter = PROPERTY_DESCRIPTOR.getWriteMethod();
try {
setter.invoke( TARGET, value );
}
catch( Exception exception ) {
throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " with descriptor: " + PROPERTY_DESCRIPTOR.getName(), exception );
}
}
else {
if ( TARGET == null && PROPERTY_DESCRIPTOR == null ) {
throw new RuntimeException( "Cannot set value " + value + " on target because both the target and descriptor are null." );
}
else if ( TARGET == null ) {
throw new RuntimeException( "Cannot set value " + value + " on target with descriptor: " + PROPERTY_DESCRIPTOR.getName() + " because the target is null." );
}
else if ( PROPERTY_DESCRIPTOR == null ) {
throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " because the property descriptor is null." );
}
}
}
/** Get the units */
public String getUnits() {
return UNITS;
}
/** Get a string represenation of this property */
public String toString() {
return getPath() + ": " + getValue() + " " + getUnits();
}
}
/** base class for a container of editable properties */
class EditablePropertyContainer extends EditableProperty {
/** target for child properties */
final protected Object CHILD_TARGET;
/** set of ancestors to reference to prevent cycles */
final private Set<Object> ANCESTORS;
/** list of child primitive properties */
protected List<EditablePrimitiveProperty> _childPrimitiveProperties;
/** list of child property containers */
protected List<EditablePropertyContainer> _childPropertyContainers;
/** Primary Constructor */
protected EditablePropertyContainer( final String pathPrefix, final String name, final Object target, final PropertyDescriptor descriptor, final Object childTarget, final Set<Object> ancestors ) {
super( pathPrefix, name, target, descriptor );
CHILD_TARGET = childTarget;
ANCESTORS = ancestors;
}
/** Constructor */
protected EditablePropertyContainer( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Object childTarget, final Set<Object> ancestors ) {
this( pathPrefix, descriptor.getName(), target, descriptor, childTarget, ancestors );
}
/** Constructor */
protected EditablePropertyContainer( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Set<Object> ancestors ) {
this( pathPrefix, target, descriptor, generateChildTarget( target, descriptor ), ancestors );
}
/** Create an instance with the specified root Object */
static public EditablePropertyContainer getInstanceWithRoot( final String name, final Object rootObject ) {
final Set<Object> ancestors = new HashSet<Object>();
return new EditablePropertyContainer( "", name, null, null, rootObject, ancestors );
}
/** Generat the child target from the target and descriptor */
static private Object generateChildTarget( final Object target, final PropertyDescriptor descriptor ) {
try {
final Method readMethod = descriptor.getReadMethod();
return readMethod.invoke( target );
}
catch( Exception exception ) {
return null;
}
}
/** determine whether the property is a container */
public boolean isContainer() {
return true;
}
/** determine whether the property is a primitive */
public boolean isPrimitive() {
return false;
}
/** set the value */
public void setValue( final Object value ) {
throw new RuntimeException( "Usupported operation attempting to set the value of the editable property container: " + getPath() + " with value " + value );
}
/** determine whether this container has any child properties */
public boolean isEmpty() {
return getChildCount() == 0;
}
/** get the number of child properties */
public int getChildCount() {
generateChildPropertiesIfNeeded();
return _childPrimitiveProperties.size() + _childPropertyContainers.size();
}
/** Get the child properties */
public List<EditableProperty> getChildProperties() {
generateChildPropertiesIfNeeded();
final List<EditableProperty> properties = new ArrayList<>();
properties.addAll( _childPrimitiveProperties );
properties.addAll( _childPropertyContainers );
return properties;
}
/** Get the list of child primitive properties */
public List<EditablePrimitiveProperty> getChildPrimitiveProperties() {
generateChildPropertiesIfNeeded();
return _childPrimitiveProperties;
}
/** Get the list of child property containers */
public List<EditablePropertyContainer> getChildPropertyContainers() {
generateChildPropertiesIfNeeded();
return _childPropertyContainers;
}
/** generate the child properties if needed */
protected void generateChildPropertiesIfNeeded() {
if ( _childPrimitiveProperties == null ) {
generateChildProperties();
}
}
/** Generate the child properties this container's child target */
protected void generateChildProperties() {
_childPrimitiveProperties = new ArrayList<>();
_childPropertyContainers = new ArrayList<>();
final PropertyDescriptor[] descriptors = getPropertyDescriptors( CHILD_TARGET );
if ( descriptors != null ) {
for ( final PropertyDescriptor descriptor : descriptors ) {
if ( descriptor.getPropertyType() != Class.class ) {
generateChildPropertyForDescriptor( descriptor );
}
}
}
}
/** Generate the child properties starting at the specified descriptor for this container's child target */
protected void generateChildPropertyForDescriptor( final PropertyDescriptor descriptor ) {
final Method getter = descriptor.getReadMethod();
// include only properties if the getter exists and is not deprecated and not marked hidden
if ( getter != null && getter.getAnnotation( Deprecated.class ) == null && getter.getAnnotation( NoEdit.class ) == null ) {
final Class<?> propertyType = descriptor.getPropertyType();
if ( EDITABLE_PROPERTY_TYPES.contains( propertyType ) ) {
// if the property is an editable primitive with both a getter and setter then return the primitive property instance otherwise null
final Method setter = descriptor.getWriteMethod();
// include only properties if the setter exists and is not deprecated (getter was already filtered in an enclosing block) and not marked hidden
if ( setter != null && setter.getAnnotation( Deprecated.class ) == null && setter.getAnnotation( NoEdit.class ) == null ) {
_childPrimitiveProperties.add( new EditablePrimitiveProperty( PATH, CHILD_TARGET, descriptor ) );
}
return; // reached end of branch so we are done
}
else if ( propertyType == null ) {
return;
}
else if ( propertyType.isArray() ) {
// property is an array
// System.out.println( "Property type is array for target: " + CHILD_TARGET + " with descriptor: " + descriptor.getName() );
return;
}
else {
// property is a plain container
if ( !ANCESTORS.contains( CHILD_TARGET ) ) { // only propagate down the branch if the targets are unique (avoid cycles)
final Set<Object> ancestors = new HashSet<Object>( ANCESTORS );
ancestors.add( CHILD_TARGET );
final EditablePropertyContainer container = new EditablePropertyContainer( PATH, CHILD_TARGET, descriptor, ancestors );
if ( container.getChildCount() > 0 ) { // only care about containers that lead to editable properties
_childPropertyContainers.add( container );
}
}
return;
}
}
}
/** Get a string represenation of this property */
public String toString() {
final StringBuilder buffer = new StringBuilder();
buffer.append( getPath() + ":\n" );
for ( final EditableProperty property : getChildProperties() ) {
buffer.append( "\t" + property.toString() + "\n" );
}
return buffer.toString();
}
}
/** container for an editable property that is an array */
class EditableArrayProperty extends EditablePropertyContainer {
/** Constructor */
protected EditableArrayProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Set<Object> ancestors ) {
super( pathPrefix, target, descriptor, ancestors );
}
// TODO: complete implementation of array property
} |
package com.speedment.runtime.application.internal.util;
import com.speedment.common.logger.Logger;
import com.speedment.common.logger.LoggerManager;
import com.speedment.runtime.core.ApplicationBuilder;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.*;
public final class JpmsUtil {
private static final Logger LOGGER = LoggerManager.getLogger(ApplicationBuilder.LogType.MODULE_SYSTEM.getLoggerName());
private JpmsUtil() {}
public static void logModulesIfEnabled() {
final Map<String, List<String>> moduleNames = modules().stream()
.map(Object::toString)
.map(JpmsUtil::removeModuleTag)
.collect(groupingBy(JpmsUtil::initialPath, TreeMap::new, mapping(JpmsUtil::restPath, toList())));
LOGGER.debug("JPMS Modules: ");
moduleNames.forEach((key, value) -> LOGGER.debug("%s.%s", key, format(value)));
}
private static String format(List<String> value) {
if (value.size() == 1) {
return value.iterator().next();
} else {
return value.stream().collect(Collectors.joining(", ", "[", "]"));
}
}
private static Set<Object> modules() {
try {
final MethodHandles.Lookup lookup = MethodHandles.lookup();
final Class<?> moduleLayerClass = Class.forName("java.lang.ModuleLayer");
final MethodType bootType = MethodType.methodType(moduleLayerClass);
final MethodHandle methodHandleBoot = lookup.findStatic(moduleLayerClass,"boot", bootType);
final Object boot = methodHandleBoot.invoke();
final MethodType modulesType = MethodType.methodType(Set.class);
final MethodHandle methodHandleModules = lookup.findVirtual(moduleLayerClass,"modules", modulesType);
final Object modules = methodHandleModules.invoke(boot);
@SuppressWarnings("unchecked")
final Set<Object> result = (Set<Object>)modules;
return result;
} catch (Throwable ignore) {
}
return Collections.emptySet();
}
private static String removeModuleTag(String s) {
final String module = "module ";
if (s.startsWith(module)) {
return s.substring(module.length());
}
return s;
}
private static String initialPath(String s) {
int index = s.lastIndexOf('.');
if (index == -1) {
return s;
} else if (index == 0) {
return "?";
} else {
return s.substring(0, index);
}
}
private static String restPath(String s) {
int index = s.lastIndexOf('.');
if (index == -1) {
return "";
} else {
return s.substring(index + 1);
}
}
} |
package logbook.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import logbook.bean.AppCondition;
import logbook.bean.BattleLog;
import logbook.bean.BattleTypes.AirBaseAttack;
import logbook.bean.BattleTypes.AtType;
import logbook.bean.BattleTypes.CombinedType;
import logbook.bean.BattleTypes.FriendlyBattle;
import logbook.bean.BattleTypes.FriendlyInfo;
import logbook.bean.BattleTypes.IAirBaseAttack;
import logbook.bean.BattleTypes.IAirbattle;
import logbook.bean.BattleTypes.IBattle;
import logbook.bean.BattleTypes.ICombinedEcBattle;
import logbook.bean.BattleTypes.ICombinedEcMidnightBattle;
import logbook.bean.BattleTypes.IHougeki;
import logbook.bean.BattleTypes.IKouku;
import logbook.bean.BattleTypes.IMidnightBattle;
import logbook.bean.BattleTypes.INSupport;
import logbook.bean.BattleTypes.INightToDayBattle;
import logbook.bean.BattleTypes.ISortieHougeki;
import logbook.bean.BattleTypes.ISupport;
import logbook.bean.BattleTypes.Kouku;
import logbook.bean.BattleTypes.MidnightHougeki;
import logbook.bean.BattleTypes.MidnightSpList;
import logbook.bean.BattleTypes.Raigeki;
import logbook.bean.BattleTypes.SortieAtType;
import logbook.bean.BattleTypes.SortieAtTypeRaigeki;
import logbook.bean.BattleTypes.Stage3;
import logbook.bean.BattleTypes.SupportAiratack;
import logbook.bean.BattleTypes.SupportHourai;
import logbook.bean.BattleTypes.SupportInfo;
import logbook.bean.Chara;
import logbook.bean.Enemy;
import logbook.bean.Friend;
import logbook.bean.Ship;
import logbook.bean.SlotItem;
import logbook.bean.SlotItemCollection;
import logbook.bean.SlotitemMst;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
@Getter
public class PhaseState {
private CombinedType combinedType = CombinedType.;
private boolean combined;
private List<Friend> afterFriendly = new ArrayList<>();
private List<Ship> afterFriend = new ArrayList<>();
private List<Ship> afterFriendCombined = new ArrayList<>();
private List<Enemy> afterEnemy = new ArrayList<>();
private List<Enemy> afterEnemyCombined = new ArrayList<>();
private List<AttackDetail> attackDetails = new ArrayList<>();
private Map<Integer, SlotItem> itemMap;
private Set<Integer> escape;
/**
*
*
* @param log
*/
public PhaseState(BattleLog log) {
this(log.getCombinedType(), log.getBattle(), log.getDeckMap(), log.getItemMap(), log.getEscape());
}
/**
*
*
* @param combinedType
* @param b
* @param deckMap
* @param itemMap
* @param escape ID
*/
public PhaseState(CombinedType combinedType, IBattle b,
Map<Integer, List<Ship>> deckMap, Map<Integer, SlotItem> itemMap, Set<Integer> escape) {
this.itemMap = itemMap != null ? itemMap : SlotItemCollection.get().getSlotitemMap();
this.escape = escape != null ? escape : AppCondition.get().getEscape();
this.combinedType = combinedType;
this.combined = combinedType != CombinedType. && (b.isICombinedBattle() || b.isICombinedEcMidnightBattle());
if ((b.isICombinedBattle() || b.isICombinedEcMidnightBattle())
&& this.combinedType != CombinedType. && b.getDockId() == 1) {
for (Ship ship : deckMap.get(1)) {
this.afterFriend.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
for (Ship ship : deckMap.get(2)) {
this.afterFriendCombined.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
} else {
List<Ship> ships;
if (b.isICombinedEcMidnightBattle()) {
ICombinedEcMidnightBattle ecmb = b.asICombinedEcMidnightBattle();
ships = deckMap.get(ecmb.getActiveDeck().get(0));
} else {
ships = deckMap.get(b.getDockId());
}
for (Ship ship : ships) {
this.afterFriend.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
}
for (int i = 0, s = b.getShipKe().size(); i < s; i++) {
if (b.getShipKe().get(i) != -1) {
Enemy e = new Enemy();
e.setShipId(b.getShipKe().get(i));
e.setLv(b.getShipLv().get(i));
e.setSlot(b.getESlot().get(i));
e.setOrder(i);
this.afterEnemy.add(e);
}
}
if (b.isICombinedEcBattle()) {
ICombinedEcBattle ecb = b.asICombinedEcBattle();
for (int i = 0, s = ecb.getShipKeCombined().size(); i < s; i++) {
if (ecb.getShipKeCombined().get(i) != -1) {
Enemy e = new Enemy();
e.setShipId(ecb.getShipKeCombined().get(i));
e.setLv(ecb.getShipLvCombined().get(i));
e.setSlot(ecb.getESlotCombined().get(i));
e.setOrder(i + 6);
this.afterEnemyCombined.add(e);
}
}
}
this.setInitialHp(b);
}
/**
* <br>
* ps
*
* @param ps
*/
public PhaseState(PhaseState ps) {
this.itemMap = ps.itemMap;
this.escape = ps.escape;
this.combinedType = ps.combinedType;
this.combined = ps.combined;
for (Friend friend : ps.afterFriendly) {
this.afterFriendly.add(Optional.ofNullable(friend).map(Friend::clone).orElse(null));
}
for (Ship ship : ps.afterFriend) {
this.afterFriend.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
for (Ship ship : ps.afterFriendCombined) {
this.afterFriendCombined.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
for (Enemy enemy : ps.afterEnemy) {
this.afterEnemy.add(Optional.ofNullable(enemy).map(Enemy::clone).orElse(null));
}
for (Enemy enemy : ps.afterEnemyCombined) {
this.afterEnemyCombined.add(Optional.ofNullable(enemy).map(Enemy::clone).orElse(null));
}
}
/**
* ()
*
* @param airBaseAttack
*/
public void applyAirBaseInject(IAirBaseAttack airBaseAttack) {
if (airBaseAttack.getAirBaseInjection() != null) {
this.applyAirBaseAttack(Arrays.asList(airBaseAttack.getAirBaseInjection()));
}
}
/**
*
*
* @param airBaseAttack
*/
public void applyAirBaseAttack(IAirBaseAttack airBaseAttack) {
this.applyAirBaseAttack(airBaseAttack.getAirBaseAttack());
}
/**
* ()
*
* @param battle
*/
public void applyInjectionKouku(IKouku battle) {
this.applyKouku(battle.getInjectionKouku());
}
/**
*
*
* @param battle
*/
public void applyKouku(IKouku battle) {
this.applyKouku(battle.getKouku());
}
/**
*
*
* @param battle
*/
public void applySupport(ISupport battle) {
this.applySupport(battle.getSupportInfo());
}
/**
*
*
* @param battle
*/
public void applySortieHougeki(ISortieHougeki battle) {
this.applyHougeki(battle.getOpeningTaisen());
this.applyRaigeki(battle.getOpeningAtack());
if (!this.combined && battle.isICombinedEcBattle()) {
this.applyHougeki(battle.getHougeki1());
this.applyRaigeki(battle.getRaigeki());
this.applyHougeki(battle.getHougeki2());
this.applyHougeki(battle.getHougeki3());
} else if (!this.combined) {
this.applyHougeki(battle.getHougeki1());
this.applyHougeki(battle.getHougeki2());
this.applyRaigeki(battle.getRaigeki());
} else if (this.combinedType == CombinedType. || this.combinedType == CombinedType.) {
this.applyHougeki(battle.getHougeki1());
this.applyRaigeki(battle.getRaigeki());
this.applyHougeki(battle.getHougeki2());
this.applyHougeki(battle.getHougeki3());
} else if (this.combinedType == CombinedType.) {
this.applyHougeki(battle.getHougeki1());
this.applyHougeki(battle.getHougeki2());
this.applyHougeki(battle.getHougeki3());
this.applyRaigeki(battle.getRaigeki());
}
}
/**
*
*
* @param battle
*/
public void applyAirbattle(IAirbattle battle) {
this.applyKouku(battle.getKouku2());
}
/**
*
*
* @param battle
*/
public void applySupport(INSupport battle) {
this.applySupport(battle.getNSupportInfo());
}
/**
*
*
* @param battle
*/
public void applyFriendlyHougeki(IMidnightBattle battle) {
if (battle.getFriendlyBattle() != null) {
this.afterFriendly.clear();
if (battle.getFriendlyInfo() != null) {
FriendlyInfo friendlyInfo = battle.getFriendlyInfo();
for (int i = 0, s = friendlyInfo.getShipId().size(); i < s; i++) {
Friend f = new Friend();
f.setShipId(friendlyInfo.getShipId().get(i));
f.setLv(friendlyInfo.getShipLv().get(i));
f.setSlot(friendlyInfo.getSlot().get(i));
f.setMaxhp(friendlyInfo.getMaxhps().get(i));
f.setNowhp(friendlyInfo.getNowhps().get(i));
this.afterFriendly.add(f);
}
}
this.applyFriendlyHougeki(battle.getFriendlyBattle());
}
}
/**
*
*
* @param battle
*/
public void applyMidnightBattle(IMidnightBattle battle) {
this.applyHougeki(battle.getHougeki());
}
/**
*
*
* @param battle
*/
public void applyMidnightBattle(INightToDayBattle battle) {
this.applyHougeki(battle.getNHougeki1());
this.applyHougeki(battle.getNHougeki2());
}
/**
*
*
* @param battle
*/
public void apply(IBattle battle) {
if (battle == null) {
return;
}
if (!(battle.isINightToDayBattle())) {
if (battle.isIAirBaseAttack()) {
this.applyAirBaseInject(battle.asIAirBaseAttack());
}
if (battle.isIKouku()) {
this.applyInjectionKouku(battle.asIKouku());
}
if (battle.isIAirBaseAttack()) {
this.applyAirBaseAttack(battle.asIAirBaseAttack());
}
if (battle.isIKouku()) {
this.applyKouku(battle.asIKouku());
}
if (battle.isISupport()) {
this.applySupport(battle.asISupport());
}
if (battle.isISortieHougeki()) {
this.applySortieHougeki(battle.asISortieHougeki());
}
if (battle.isIAirbattle()) {
this.applyAirbattle(battle.asIAirbattle());
}
if (battle.isINSupport()) {
this.applySupport(battle.asINSupport());
}
if (battle.isIMidnightBattle()) {
this.applyFriendlyHougeki(battle.asIMidnightBattle());
this.applyMidnightBattle(battle.asIMidnightBattle());
}
} else {
if (battle.isINSupport()) {
this.applySupport(battle.asINSupport());
}
if (battle.isINightToDayBattle()) {
this.applyMidnightBattle(battle.asINightToDayBattle());
}
if (battle.isIAirBaseAttack()) {
this.applyAirBaseInject(battle.asIAirBaseAttack());
}
if (battle.isIKouku()) {
this.applyInjectionKouku(battle.asIKouku());
}
if (battle.isIAirBaseAttack()) {
this.applyAirBaseAttack(battle.asIAirBaseAttack());
}
if (battle.isIKouku()) {
this.applyKouku(battle.asIKouku());
}
if (battle.isISupport()) {
this.applySupport(battle.asISupport());
}
if (battle.isISortieHougeki()) {
this.applySortieHougeki(battle.asISortieHougeki());
}
}
}
/**
*
*
* @param attacks
*/
private void applyAirBaseAttack(List<AirBaseAttack> attacks) {
if (attacks != null) {
for (AirBaseAttack attack : attacks) {
Stage3 stage3 = attack.getStage3();
if (stage3 != null) {
List<Double> edam = stage3.getEdam();
if (edam != null) {
this.applyEnemyDamage(edam);
}
}
Stage3 stage3Combined = attack.getStage3Combined();
if (stage3Combined != null) {
List<Double> edam = stage3Combined.getEdam();
if (edam != null) {
this.applyEnemyDamageCombined(edam);
}
}
}
}
}
/**
*
*
* @param kouku
*/
private void applyKouku(Kouku kouku) {
if (kouku == null) {
return;
}
Stage3 stage3 = kouku.getStage3();
if (stage3 != null) {
this.applyFriendDamage(stage3.getFdam());
this.applyEnemyDamage(stage3.getEdam());
}
Stage3 stage3Combined = kouku.getStage3Combined();
if (stage3Combined != null) {
if (stage3Combined.getFdam() != null) {
this.applyFriendDamageCombined(stage3Combined.getFdam());
}
if (stage3Combined.getEdam() != null) {
this.applyEnemyDamageCombined(stage3Combined.getEdam());
}
}
}
/**
*
*
* @param support
*/
private void applySupport(SupportInfo support) {
if (support != null) {
SupportAiratack air = support.getSupportAiratack();
if (air != null) {
Stage3 stage3 = air.getStage3();
if (stage3 != null) {
this.applyEnemyDamage(stage3.getEdam());
}
}
SupportHourai hou = support.getSupportHourai();
if (hou != null) {
this.applyEnemyDamage(hou.getDamage());
}
}
}
/**
*
*
* @param raigeki
*/
private void applyRaigeki(Raigeki raigeki) {
if (raigeki == null) {
return;
}
this.addDetailRaigeki(raigeki);
// API
this.applyFriendDamage(raigeki.getFdam());
this.applyEnemyDamage(raigeki.getEdam());
}
/**
*
*
* @param hougeki
*/
private void applyHougeki(IHougeki hougeki) {
this.applyHougeki(hougeki, false);
}
/**
*
*
* @param friendlyBattle
*/
private void applyFriendlyHougeki(FriendlyBattle friendlyBattle) {
if (friendlyBattle != null) {
this.applyHougeki(friendlyBattle.getHougeki(), true);
}
}
/**
*
*
* @param hougeki
* @param isFriendlyBattle
*/
private void applyHougeki(IHougeki hougeki, boolean isFriendlyBattle) {
if (hougeki == null || hougeki.getAtEflag() == null) {
return;
}
for (int i = 0, s = hougeki.getDamage().size(); i < s; i++) {
int index = i;
int at = hougeki.getAtList().get(i);
AtType atType;
if (hougeki instanceof MidnightHougeki) {
atType = Optional.ofNullable(((MidnightHougeki) hougeki).getSpList())
.map(l -> l.get(index))
.map(MidnightSpList::toMidnightSpList)
.orElse(MidnightSpList.toMidnightSpList(0));
} else {
atType = Optional.ofNullable(hougeki.getAtType())
.map(l -> l.get(index))
.map(SortieAtType::toSortieAtType)
.orElse(SortieAtType.toSortieAtType(0));
}
// true
boolean atkfriend = hougeki.getAtEflag().get(i) == 0;
Map<Integer, List<Integer>> dfMap = new LinkedHashMap<>();
Map<Integer, List<Integer>> clMap = new LinkedHashMap<>();
List<Integer> dfList = hougeki.getDfList().get(i);
List<Double> damageList = hougeki.getDamage().get(i);
List<Integer> clList = hougeki.getClList().get(i);
for (int j = 0; j < dfList.size(); j++) {
if (dfList.get(j) >= 0) {
int damage = Math.max(damageList.get(j).intValue(), 0);
int critical = clList.get(j).intValue();
List<Integer> df = dfMap.computeIfAbsent(dfList.get(j), (k) -> new ArrayList<>());
df.add(damage);
List<Integer> cl = clMap.computeIfAbsent(dfList.get(j), (k) -> new ArrayList<>());
cl.add(critical);
}
}
for (Entry<Integer, List<Integer>> dfDamage : dfMap.entrySet()) {
int df = dfDamage.getKey();
int damage = dfDamage.getValue().stream()
.mapToInt(Integer::intValue)
.filter(d -> d > 0)
.sum();
List<Integer> damages = dfDamage.getValue();
List<Integer> critical = clMap.get(dfDamage.getKey());
Chara attacker = null;
Chara defender = null;
if (atkfriend) {
if (isFriendlyBattle) {
attacker = this.afterFriendly.get(at);
} else {
if (Math.max(this.afterFriend.size(), 6) > at) {
attacker = this.afterFriend.get(at);
} else {
attacker = this.afterFriendCombined.get(at - 6);
}
}
if (Math.max(this.afterEnemy.size(), 6) > df) {
defender = this.afterEnemy.get(df);
} else {
defender = this.afterEnemyCombined.get(df - 6);
}
} else {
if (Math.max(this.afterEnemy.size(), 6) > at) {
attacker = this.afterEnemy.get(at);
} else {
attacker = this.afterEnemyCombined.get(at - 6);
}
if (isFriendlyBattle) {
defender = this.afterFriendly.get(df);
} else {
if (Math.max(this.afterFriend.size(), 6) > df) {
defender = this.afterFriend.get(df);
} else {
defender = this.afterFriendCombined.get(df - 6);
}
}
}
this.damage(defender, damage);
this.addDetail(attacker, defender, damage, damages, critical, atType);
}
}
}
/**
* (1,2)
*
* @param damages (zero-based)
*/
private void applyFriendDamage(List<Double> damages) {
for (int i = 0, s = damages.size(); i < s; i++) {
int damage = damages.get(i).intValue();
if (damage != 0) {
Ship ship = Math.max(this.afterFriend.size(), 6) > i
? this.afterFriend.get(i)
: this.afterFriendCombined.get(i - 6);
if (ship != null) {
this.damage(ship, damage);
}
}
}
}
/**
* (2)
*
* @param damages (zero-based)
*/
private void applyFriendDamageCombined(List<Double> damages) {
for (int i = 0, s = damages.size(); i < s; i++) {
int damage = damages.get(i).intValue();
if (damage != 0) {
Ship ship = this.afterFriendCombined.get(i);
if (ship != null) {
this.damage(ship, damage);
}
}
}
}
/**
* (1,2)
*
* @param damages
*/
private void applyEnemyDamage(List<Double> damages) {
for (int i = 0, s = damages.size(); i < s; i++) {
int damage = damages.get(i).intValue();
if (damage != 0) {
Enemy enemy = Math.max(this.afterEnemy.size(), 6) > i
? this.afterEnemy.get(i)
: this.afterEnemyCombined.get(i - 6);
if (enemy != null) {
this.damage(enemy, damage);
}
}
}
}
/**
* (2)
*
* @param damages
*/
private void applyEnemyDamageCombined(List<Double> damages) {
for (int i = 0, s = damages.size(); i < s; i++) {
int damage = damages.get(i).intValue();
if (damage != 0) {
Enemy enemy = this.afterEnemyCombined.get(i);
if (enemy != null) {
this.damage(enemy, damage);
}
}
}
}
/**
* HP
*
* @param b
*/
private void setInitialHp(IBattle b) {
for (int i = 0, s = b.getFMaxhps().size(); i < s; i++) {
if (b.getFMaxhps().get(i) == -1) {
continue;
}
if (this.afterFriend.get(i) != null) {
this.afterFriend.get(i).setMaxhp(b.getFMaxhps().get(i));
this.afterFriend.get(i).setNowhp(b.getFNowhps().get(i));
}
}
for (int i = 0, s = b.getEMaxhps().size(); i < s; i++) {
if (b.getEMaxhps().get(i) == -1) {
continue;
}
if (this.afterEnemy.get(i) != null) {
this.afterEnemy.get(i).setMaxhp(b.getEMaxhps().get(i));
this.afterEnemy.get(i).setNowhp(b.getENowhps().get(i));
}
}
if (b.isICombinedBattle()) {
List<Integer> fNowHps = b.asICombinedBattle().getFNowhpsCombined();
if (fNowHps != null) {
for (int i = 0, s = fNowHps.size(); i < s; i++) {
if (fNowHps.get(i) == -1) {
continue;
}
Chara chara = this.afterFriendCombined.get(i);
if (chara != null) {
chara.setNowhp(fNowHps.get(i));
}
}
}
}
if (b.isICombinedEcBattle()) {
List<Integer> eMaxHps = b.asICombinedEcBattle().getEMaxhpsCombined();
List<Integer> eNowHps = b.asICombinedEcBattle().getENowhpsCombined();
if (eNowHps != null) {
for (int i = 0, s = eNowHps.size(); i < s; i++) {
if (eNowHps.get(i) == -1) {
continue;
}
Chara chara = this.afterEnemyCombined.get(i);
if (chara != null) {
chara.setMaxhp(eMaxHps.get(i));
chara.setNowhp(eNowHps.get(i));
}
}
}
}
}
/**
*
*
* @param defender
* @param damage
*/
private void damage(Chara defender, int damage) {
int nowHp;
if (defender.getNowhp() - damage <= 0 && defender.isShip()) {
Ship ship = defender.asShip();
Optional<SlotitemMst> mst = Stream.concat(Stream.of(ship.getSlotEx()), ship.getSlot().stream())
.map(this.itemMap::get)
.map(Items::slotitemMst)
.filter(Optional::isPresent)
.map(Optional::get)
.filter(i -> i.is(SlotItemType.))
.findFirst();
if (mst.isPresent()) {
if (mst.get().getName().equals("")) {
nowHp = defender.getMaxhp();
} else {
// HP20%()
nowHp = (int) ((double) defender.getMaxhp() * 0.2D);
}
} else {
nowHp = defender.getNowhp() - damage;
}
} else {
nowHp = defender.getNowhp() - damage;
}
defender.setNowhp(nowHp);
}
/**
* ()
*
* @param raigeki
*/
private void addDetailRaigeki(Raigeki raigeki) {
this.addDetailRaigeki0(this.afterEnemy, this.afterEnemyCombined, this.afterFriend,
this.afterFriendCombined,
raigeki.getErai(), raigeki.getEydam(), raigeki.getEcl());
this.addDetailRaigeki0(this.afterFriend, this.afterFriendCombined, this.afterEnemy, this.afterEnemyCombined,
raigeki.getFrai(), raigeki.getFydam(), raigeki.getFcl());
}
/**
* ()
*
* @param attackerFleet
* @param attackerFleetCombined (2)
* @param defenderFleet
* @param defenderFleetCombined (2)
* @param index
* @param ydam
* @param critical
*/
private void addDetailRaigeki0(List<? extends Chara> attackerFleet, List<? extends Chara> attackerFleetCombined,
List<? extends Chara> defenderFleet, List<? extends Chara> defenderFleetCombined,
List<Integer> index, List<Double> ydam, List<Integer> critical) {
if (defenderFleet != null)
defenderFleet = defenderFleet.stream()
.map(c -> c != null ? c.clone() : null)
.collect(Collectors.toList());
if (defenderFleetCombined != null)
defenderFleetCombined = defenderFleetCombined.stream()
.map(c -> c != null ? c.clone() : null)
.collect(Collectors.toList());
for (int i = 0; i < index.size(); i++) {
if (index.get(i) >= 0) {
Chara attacker = Math.max(attackerFleet.size(), 6) > i
? attackerFleet.get(i)
: attackerFleetCombined.get(i - 6);
Chara defender = Math.max(defenderFleet.size(), 6) > index.get(i)
? defenderFleet.get(index.get(i))
: defenderFleetCombined.get(index.get(i) - 6);
int damage = (int) ydam.get(i).doubleValue();
defender.setNowhp(defender.getNowhp() - damage);
this.addDetail(attacker, defender, damage, Collections.singletonList(damage), critical,
SortieAtTypeRaigeki.);
}
}
}
/**
*
*
* @param attacker
* @param defender
* @param damage
* @param damages ()
* @param critical ()
* @param atType
*/
private void addDetail(Chara attacker, Chara defender, int damage, List<Integer> damages, List<Integer> critical,
AtType atType) {
this.attackDetails.add(new AttackDetail(
Optional.ofNullable(attacker).map(Chara::clone).orElse(null),
Optional.ofNullable(defender).map(Chara::clone).orElse(null), damage, damages, critical, atType));
}
/**
* HP
*
* @return HP
*/
public double friendTotalHp() {
return Stream.concat(this.afterFriend.stream(), this.afterFriendCombined.stream())
.filter(Objects::nonNull)
.mapToInt(Chara::getNowhp)
.map(hp -> Math.max(hp, 0))
.sum();
}
/**
* HP
*
* @return HP
*/
public double enemyTotalHp() {
return Stream.concat(this.afterEnemy.stream(), this.afterEnemyCombined.stream())
.filter(Objects::nonNull)
.mapToInt(Chara::getNowhp)
.map(hp -> Math.max(hp, 0))
.sum();
}
/**
* HP1
*
* @return HP1
*/
public int friendAliveCount() {
return (int) Stream.concat(this.afterFriend.stream(), this.afterFriendCombined.stream())
.filter(Objects::nonNull)
.mapToInt(Chara::getNowhp)
.filter(hp -> hp > 0)
.count();
}
/**
* HP1
*
* @return HP1
*/
public int enemydAliveCount() {
return (int) Stream.concat(this.afterEnemy.stream(), this.afterEnemyCombined.stream())
.filter(Objects::nonNull)
.mapToInt(Chara::getNowhp)
.filter(hp -> hp > 0)
.count();
}
@Data
@AllArgsConstructor
public static class AttackDetail {
private Chara attacker;
private Chara defender;
private int damage;
private List<Integer> damages;
private List<Integer> critical;
private AtType atType;
}
} |
package org.eclipse.mylar.zest.core.viewers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylar.zest.core.ZestException;
import org.eclipse.mylar.zest.core.ZestPlugin;
import org.eclipse.mylar.zest.core.ZestStyles;
import org.eclipse.mylar.zest.core.internal.graphmodel.GraphItem;
import org.eclipse.mylar.zest.core.internal.graphmodel.GraphModel;
import org.eclipse.mylar.zest.core.internal.graphmodel.GraphModelConnection;
import org.eclipse.mylar.zest.core.internal.graphmodel.GraphModelNode;
import org.eclipse.mylar.zest.core.internal.graphmodel.IGraphItem;
import org.eclipse.mylar.zest.core.internal.graphmodel.IGraphModelConnection;
import org.eclipse.mylar.zest.core.internal.graphmodel.IGraphModelNode;
import org.eclipse.mylar.zest.core.internal.graphmodel.IStylingGraphModelFactory;
import org.eclipse.mylar.zest.core.internal.graphmodel.IZestGraphDefaults;
import org.eclipse.mylar.zest.layouts.LayoutAlgorithm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.widgets.Widget;
/**
* Abstraction of graph viewers to implement functionality used by all of them.
* Not intended to be implemented by clients. Use one of the provided children
* instead.
*
* @author Del Myers
*
*/
public abstract class AbstractStructuredGraphViewer extends AbstractZoomableViewer {
/**
* Contains top-level styles for the entire graph. Set in the constructor. *
*/
private int graphStyle;
/**
* Contains node-level styles for the graph. Set in setNodeStyle(). Defaults
* are used in the constructor.
*/
private int nodeStyle;
/**
* Contains arc-level styles for the graph. Set in setConnectionStyle().
* Defaults are used in the constructor.
*/
private int connectionStyle;
/**
* The main graph model
*/
private GraphModel model;
/**
* The constraint adatpers
*/
private List constraintAdapters = new ArrayList();
/**
* A simple graph comparator that orders graph elements based on thier type
* (connection or node), and their unique object identification.
*/
private class SimpleGraphComparator implements Comparator {
TreeSet storedStrings;
public SimpleGraphComparator() {
this.storedStrings = new TreeSet();
}
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object arg0, Object arg1) {
if (arg0 instanceof IGraphModelNode
&& arg1 instanceof IGraphModelConnection) {
return 1;
} else if (arg0 instanceof IGraphModelConnection
&& arg1 instanceof IGraphModelNode) {
return -1;
}
if (arg0.equals(arg1))
return 0;
return getObjectString(arg0).compareTo(getObjectString(arg1));
}
private String getObjectString(Object o) {
String s = o.getClass().getName() + "@"
+ Integer.toHexString(o.hashCode());
while (storedStrings.contains(s)) {
s = s + 'X';
}
return s;
}
}
protected AbstractStructuredGraphViewer(int graphStyle) {
this.graphStyle = graphStyle;
this.connectionStyle = IZestGraphDefaults.CONNECTION_STYLE;
this.nodeStyle = IZestGraphDefaults.NODE_STYLE;
}
/**
* Sets the default style for nodes in this graph. Note: if an input is set
* on the viewer, a ZestException will be thrown.
*
* @param nodeStyle
* the style for the nodes.
* @see #ZestStyles
*/
public void setNodeStyle(int nodeStyle) {
if (getInput() != null)
ZestPlugin.error(ZestException.ERROR_CANNOT_SET_STYLE);
this.nodeStyle = nodeStyle;
}
/**
* Sets the default style for connections in this graph. Note: if an input
* is set on the viewer, a ZestException will be thrown.
*
* @param connectionStyle
* the style for the connections.
* @see #ZestStyles
*/
public void setConnectionStyle(int connectionStyle) {
if (getInput() != null)
ZestPlugin.error(ZestException.ERROR_CANNOT_SET_STYLE);
if (!ZestStyles.validateConnectionStyle(connectionStyle))
ZestPlugin.error(ZestException.ERROR_INVALID_STYLE);
this.connectionStyle = connectionStyle;
}
/**
* Returns the style set for the graph
*
* @return The style set of the graph
*/
public int getGraphStyle() {
return graphStyle;
}
/**
* Returns the style set for the nodes.
*
* @return the style set for the nodes.
*/
public int getNodeStyle() {
return nodeStyle;
}
/**
* @return the connection style.
*/
public int getConnectionStyle() {
return connectionStyle;
}
/**
* Adds a new constraint adapter to the list of constraints
* @param constraintAdapter
*/
public void addConstraintAdapter(ConstraintAdapter constraintAdapter ) {
this.constraintAdapters.add(constraintAdapter);
}
/**
* Gets all the constraint adapters currently on the viewer
* @return
*/
public List getConstraintAdapters() {
return this.constraintAdapters;
}
/**
* Sets the layout algorithm for this viewer. Subclasses may place
* restrictions on the algorithms that it accepts.
*
* @param algorithm
* the layout algorithm
* @param run
* true if the layout algorithm should be run immediately. This
* is a hint.
*/
public abstract void setLayoutAlgorithm(LayoutAlgorithm algorithm,
boolean run);
/**
* Gets the current layout algorithm.
*
* @return the current layout algorithm.
*/
protected abstract LayoutAlgorithm getLayoutAlgorithm();
/**
* Equivalent to setLayoutAlgorithm(algorithm, false).
*
* @param algorithm
*/
public void setLayoutAlgorithm(LayoutAlgorithm algorithm) {
setLayoutAlgorithm(algorithm, false);
}
protected void handleDispose(DisposeEvent event) {
if (model != null && !model.isDisposed()) {
model.dispose();
}
super.handleDispose(event);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.StructuredViewer#internalRefresh(java.lang.Object)
*/
protected void internalRefresh(Object element) {
if ( getInput() == null ) return;
if (element == getInput() )
getFactory().refreshGraph(getModel());
else
getFactory().refresh(getModel(), element);
}
protected void doUpdateItem(Widget item, Object element, boolean fullMap) {
if (item == getModel()) {
getFactory().update(getModel().getNodesArray());
getFactory().update(getModel().getConnectionsArray());
} else if (item instanceof IGraphItem) {
getFactory().update((IGraphItem) item);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.StructuredViewer#doFindInputItem(java.lang.Object)
*/
protected Widget doFindInputItem(Object element) {
if (element == getInput())
return getModel();
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.StructuredViewer#doFindItem(java.lang.Object)
*/
protected Widget doFindItem(Object element) {
Widget node = (GraphItem) getModel().getNodesMap().get(element);
Widget connection = (GraphItem) getModel().getConnectionMap().get(
element);
return (node != null) ? node : connection;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.StructuredViewer#getSelectionFromWidget()
*/
protected List getSelectionFromWidget() {
List internalSelection = getWidgetSelection();
LinkedList externalSelection = new LinkedList();
for (Iterator i = internalSelection.iterator(); i.hasNext();) {
// @tag zest.todo : should there be a method on IGraphItem to get
// the external data?
IGraphItem item = (IGraphItem) i.next();
if (item instanceof IGraphModelNode) {
externalSelection.add(((IGraphModelNode) item)
.getExternalNode());
} else if (item instanceof IGraphModelConnection) {
externalSelection.add(((IGraphModelConnection) item)
.getExternalConnection());
} else if (item instanceof Widget) {
externalSelection.add(((Widget) item).getData());
}
}
return externalSelection;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.StructuredViewer#setSelectionToWidget(java.util.List,
* boolean)
*/
protected void setSelectionToWidget(List l, boolean reveal) {
EditPartViewer viewer = getEditPartViewer();
List selection = new LinkedList();
for (Iterator i = l.iterator(); i.hasNext();) {
Object obj = i.next();
IGraphModelNode node = getModel().getInternalNode(obj);
IGraphModelConnection conn = getModel().getInternalConnection(obj);
if (node != null) {
selection.add(node);
}
if (conn != null) {
selection.add(conn);
}
}
viewer.setSelection(new StructuredSelection(selection));
}
/**
* Gets the internal model elements that are selected.
*
* @return
*/
protected List getWidgetSelection() {
List editParts = getEditPartViewer().getSelectedEditParts();
List modelElements = new ArrayList();
for (Iterator i = editParts.iterator(); i.hasNext();) {
EditPart part = (EditPart) i.next();
if (part.getModel() instanceof Widget)
modelElements.add(part.getModel());
}
return modelElements;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.Viewer#inputChanged(java.lang.Object,
* java.lang.Object)
*/
protected void inputChanged(Object input, Object oldInput) {
IStylingGraphModelFactory factory = getFactory();
factory.setConnectionStyle(getConnectionStyle());
factory.setNodeStyle(getNodeStyle());
GraphModel newModel = factory.createGraphModel();
// get current list of nodes before they are re-created from the
// factory & content provider
Map oldNodesMap = (model != null ? model.getNodesMap()
: Collections.EMPTY_MAP);
if (model != null && !model.isDisposed()) {
// Dispose the model
model.dispose();
}
model = newModel;
model.setNodeStyle(getNodeStyle());
model.setConnectionStyle(getConnectionStyle());
// check if any of the pre-existing nodes are still present
// in this case we want them to keep the same location & size
for (Iterator iter = oldNodesMap.keySet().iterator(); iter.hasNext();) {
Object data = iter.next();
IGraphModelNode newNode = model.getInternalNode(data);
if (newNode != null) {
IGraphModelNode oldNode = (IGraphModelNode) oldNodesMap
.get(data);
newNode.setPreferredLocation(oldNode.getXInLayout(), oldNode
.getYInLayout());
newNode.setSizeInLayout(oldNode.getWidthInLayout(), oldNode
.getHeightInLayout());
}
}
getEditPartViewer().setContents(model);
applyLayout();
}
/**
* Returns the factory used to create the model. This must not be called
* before the content provider is set.
*
* @return
*/
protected abstract IStylingGraphModelFactory getFactory();
protected void filterVisuals() {
if (getModel() == null)
return;
Object[] filtered = getFilteredChildren(getInput());
SimpleGraphComparator comparator = new SimpleGraphComparator();
TreeSet filteredElements = new TreeSet(comparator);
TreeSet unfilteredElements = new TreeSet(comparator);
List connections = getModel().getConnections();
List nodes = getModel().getNodes();
if (filtered.length == 0) {
// set everything to invisible.
// @tag zest.bug.156528-Filters.check : should we only filter out
// the nodes?
for (Iterator i = connections.iterator(); i.hasNext();) {
IGraphModelConnection c = (IGraphModelConnection) i.next();
c.setVisible(false);
}
for (Iterator i = nodes.iterator(); i.hasNext();) {
IGraphModelNode n = (IGraphModelNode) i.next();
n.setVisible(false);
}
return;
}
for (Iterator i = connections.iterator(); i.hasNext();) {
IGraphModelConnection c = (IGraphModelConnection) i.next();
if (c.getExternalConnection() != null)
unfilteredElements.add(c);
}
for (Iterator i = nodes.iterator(); i.hasNext();) {
IGraphModelNode n = (IGraphModelNode) i.next();
if (n.getExternalNode() != null)
unfilteredElements.add(n);
}
for (int i = 0; i < filtered.length; i++) {
Object modelElement = getModel().getInternalConnection(filtered[i]);
if (modelElement == null) {
modelElement = getModel().getInternalNode(filtered[i]);
}
if (modelElement != null) {
filteredElements.add(modelElement);
}
}
unfilteredElements.removeAll(filteredElements);
// set all the elements that did not pass the filters to invisible, and
// all the elements that passed to visible.
while (unfilteredElements.size() > 0) {
IGraphItem i = (IGraphItem) unfilteredElements.first();
i.setVisible(false);
unfilteredElements.remove(i);
}
while (filteredElements.size() > 0) {
IGraphItem i = (IGraphItem) filteredElements.first();
i.setVisible(true);
filteredElements.remove(i);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.StructuredViewer#getRawChildren(java.lang.Object)
*/
protected Object[] getRawChildren(Object parent) {
if (parent == getInput()) {
// get the children from the model.
LinkedList children = new LinkedList();
if (getModel() != null) {
List connections = getModel().getConnections();
List nodes = getModel().getNodes();
for (Iterator i = connections.iterator(); i.hasNext();) {
IGraphModelConnection c = (IGraphModelConnection) i.next();
if (c.getExternalConnection() != null) {
children.add(c.getExternalConnection());
}
}
for (Iterator i = nodes.iterator(); i.hasNext();) {
IGraphModelNode n = (IGraphModelNode) i.next();
if (n.getExternalNode() != null) {
children.add(n.getExternalNode());
}
}
return children.toArray();
}
}
return super.getRawChildren(parent);
}
public void reveal(Object element) {
Widget[] items = this.findItems(element);
for (int i = 0; i < items.length; i++) {
Widget item = items[i];
if ( item instanceof GraphModelNode ) {
GraphModelNode graphModelNode = (GraphModelNode) item;
graphModelNode.highlight();
}
else if ( item instanceof GraphModelConnection ) {
GraphModelConnection graphModelConnection = (GraphModelConnection) item;
graphModelConnection.highlight();
}
}
}
public void unReveal(Object element) {
Widget[] items = this.findItems(element);
for (int i = 0; i < items.length; i++) {
Widget item = items[i];
if ( item instanceof GraphModelNode ) {
GraphModelNode graphModelNode = (GraphModelNode) item;
graphModelNode.unhighlight();
}
else if ( item instanceof GraphModelConnection ) {
GraphModelConnection graphModelConnection = (GraphModelConnection) item;
graphModelConnection.unhighlight();
}
}
}
/**
* Applies the viewers layouts.
*
*/
public abstract void applyLayout();
/**
* Returns the internal graph model.
*
* @return the internal graph model.
*/
protected final GraphModel getModel() {
if (model == null)
createModel();
return model;
}
protected final GraphModel createModel() {
this.model = getFactory().createGraphModel();
return model;
}
/**
* Returns the underlying editpart viewer for this viewer.
*
* @return the underlying editpart viewer for this viewer.
*/
protected abstract EditPartViewer getEditPartViewer();
/**
* Removes the given connection object from the layout algorithm and the
* model.
*
* @param connection
*/
public void removeRelationship(Object connection) {
IGraphModelConnection relation = model
.getInternalConnection(connection);
if (relation != null) {
// remove the relationship from the layout algorithm
if (getLayoutAlgorithm() != null)
getLayoutAlgorithm().removeRelationship(relation);
// remove the relationship from the model
getModel().removeConnection(relation);
applyLayout();
}
}
/**
* Creates a new node and adds it to the graph. If it already exists nothing
* happens.
*
* @param newNode
*/
public void addNode(Object element) {
if (model.getInternalNode(element) == null) {
// create the new node
IGraphModelNode newNode = getFactory().createNode(model, element);
// add it to the layout algorithm
if (getLayoutAlgorithm() != null)
getLayoutAlgorithm().addEntity(newNode);
applyLayout();
}
}
/**
* Removes the given element from the layout algorithm and the model.
*
* @param element
* The node element to remove.
*/
public void removeNode(Object element) {
IGraphModelNode node = model.getInternalNode(element);
if (node != null) {
// remove the node from the layout algorithm and all the connections
if (getLayoutAlgorithm() != null) {
getLayoutAlgorithm().removeEntity(node);
getLayoutAlgorithm().removeRelationships(
node.getSourceConnections());
getLayoutAlgorithm().removeRelationships(
node.getTargetConnections());
}
// remove the node and it's connections from the model
getModel().removeNode(node);
applyLayout();
}
}
/**
* Creates a new relationship between the source node and the destination
* node. If either node doesn't exist then it will be created.
*
* @param connection
* The connection data object.
* @param srcNode
* The source node data object.
* @param destNode
* The destination node data object.
*/
public void addRelationship(Object connection, Object srcNode,
Object destNode) {
// create the new relationship
IStylingGraphModelFactory modelFactory = getFactory();
IGraphModelConnection newConnection = modelFactory.createConnection(
model, connection, srcNode, destNode);
// add it to the layout algorithm
if (getLayoutAlgorithm() != null)
getLayoutAlgorithm().addRelationship(newConnection);
applyLayout();
}
/**
* Adds a new relationship given the connection. It will use the content
* provider to determine the source and destination nodes.
*
* @param connection
* The connection data object.
*/
public void addRelationship(Object connection) {
IStylingGraphModelFactory modelFactory = getFactory();
if (model.getInternalConnection(connection) == null) {
if (modelFactory.getContentProvider() instanceof IGraphContentProvider) {
IGraphContentProvider content = ((IGraphContentProvider) modelFactory
.getContentProvider());
Object source = content.getSource(connection);
Object dest = content.getDestination(connection);
// create the new relationship
IGraphModelConnection newConnection = modelFactory
.createConnection(model, connection, source, dest);
// add it to the layout algorithm
if (getLayoutAlgorithm() != null)
getLayoutAlgorithm().addRelationship(newConnection);
} else {
throw new UnsupportedOperationException();
}
}
}
} |
package common;
import java.util.*;
public class Universe<E> {
private final List<E> ie;
private final Map<E,Integer> ei;
public Universe(Collection<? extends E> c){
this.ie = new ArrayList<E>(c);
this.ei = new HashMap<>();
for(int i=0; i<ei.size(); ++i){
ei.put(ie.get(i), i);
}
}
public boolean contains(Object o){
return ei.containsKey(o);
}
public int size(){
return ie.size();
}
public E get(int i){
return ie.get(i);
}
public int index(E e){
return ei.get(e);
}
public BackedSet<E> set(Collection<? extends E> c){
return new BackedSet<E>(this,c);
}
public boolean equals(Object o){
if(o instanceof Universe<?>){
Universe<?> u = (Universe<?>) o;
return ie.equals(u.ie) && ei.equals(u.ei);
}
return false;
}
/**
* <p>A convenience method returning an empty BackedSet backed
* by this Universe.</p>
* @return an empty BackedSet backed by this Universe
*/
public BackedSet<E> back(){
return new BackedSet<>(this);
}
/**
* <p>A convenience method returning a BackedSet backed by this
* Universe. containing the contents of {@code c}.</p>
* @returna BackedSet backed by this Universe. containing the
* contents of {@code c}
*/
public BackedSet<E> back(Collection<? extends E> c){
return new BackedSet<>(this, c);
}
} |
package com.vip.saturn.job.console.controller.rest;
import com.vip.saturn.job.console.aop.annotation.Audit;
import com.vip.saturn.job.console.aop.annotation.AuditType;
import com.vip.saturn.job.console.domain.JobConfig;
import com.vip.saturn.job.console.domain.JobType;
import com.vip.saturn.job.console.domain.RestApiJobInfo;
import com.vip.saturn.job.console.exception.SaturnJobConsoleException;
import com.vip.saturn.job.console.exception.SaturnJobConsoleHttpException;
import com.vip.saturn.job.console.service.RestApiService;
import com.vip.saturn.job.console.utils.SaturnBeanUtils;
import com.vip.saturn.job.console.vo.UpdateJobConfigVo;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* RESTful APIs of Job Operations.
*
* @author hebelala
*/
@RequestMapping("/rest/v1")
public class JobOperationRestApiController extends AbstractRestController {
@Resource
private RestApiService restApiService;
@Audit(type = AuditType.REST)
@RequestMapping(value = "/{namespace}/jobs", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> create(@PathVariable("namespace") String namespace, @RequestBody Map<String, Object> reqParams)
throws SaturnJobConsoleException {
try {
JobConfig jobConfig = constructJobConfig(namespace, reqParams);
restApiService.createJob(namespace, jobConfig);
return new ResponseEntity<>(HttpStatus.CREATED);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@RequestMapping(value = "/{namespace}/jobs/{jobName}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> query(@PathVariable("namespace") String namespace, @PathVariable("jobName") String jobName)
throws SaturnJobConsoleException {
HttpHeaders httpHeaders = new HttpHeaders();
try {
RestApiJobInfo restAPIJobInfo = restApiService.getRestAPIJobInfo(namespace, jobName);
return new ResponseEntity<Object>(restAPIJobInfo, httpHeaders, HttpStatus.OK);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@RequestMapping(value = "/{namespace}/jobs", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> queryAll(@PathVariable("namespace") String namespace) throws SaturnJobConsoleException {
HttpHeaders httpHeaders = new HttpHeaders();
try {
List<RestApiJobInfo> restApiJobInfos = restApiService.getRestApiJobInfos(namespace);
return new ResponseEntity<Object>(restApiJobInfos, httpHeaders, HttpStatus.OK);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@Audit(type = AuditType.REST)
@RequestMapping(value = {"/{namespace}/{jobName}/enable",
"/{namespace}/jobs/{jobName}/enable"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> enable(@PathVariable("namespace") String namespace, @PathVariable("jobName") String jobName)
throws SaturnJobConsoleException {
HttpHeaders httpHeaders = new HttpHeaders();
try {
restApiService.enableJob(namespace, jobName);
return new ResponseEntity<>(httpHeaders, HttpStatus.OK);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@Audit(type = AuditType.REST)
@RequestMapping(value = {"/{namespace}/{jobName}/disable",
"/{namespace}/jobs/{jobName}/disable"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> disable(@PathVariable("namespace") String namespace, @PathVariable("jobName") String jobName)
throws SaturnJobConsoleException {
HttpHeaders httpHeaders = new HttpHeaders();
try {
restApiService.disableJob(namespace, jobName);
return new ResponseEntity<>(httpHeaders, HttpStatus.OK);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@Audit(type = AuditType.REST)
@RequestMapping(value = {"/{namespace}/{jobName}/cron",
"/{namespace}/jobs/{jobName}/cron"}, method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> updateJobCron(@PathVariable("namespace") String namespace, @PathVariable("jobName") String jobName,
@RequestBody Map<String, String> params, HttpServletRequest request) throws SaturnJobConsoleException {
HttpHeaders httpHeaders = new HttpHeaders();
try {
String cron = params.remove("cron");
checkMissingParameter("cron", cron);
restApiService.updateJobCron(namespace, jobName, cron, params);
return new ResponseEntity<>(httpHeaders, HttpStatus.OK);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@Audit(type = AuditType.REST)
@RequestMapping(value = "/{namespace}/jobs/{jobName}/run", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> run(@PathVariable("namespace") String namespace, @PathVariable("jobName") String jobName)
throws SaturnJobConsoleException {
try {
restApiService.runJobAtOnce(namespace, jobName);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@Audit(type = AuditType.REST)
@RequestMapping(value = "/{namespace}/jobs/{jobName}/stop", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> stop(@PathVariable("namespace") String namespace, @PathVariable("jobName") String jobName)
throws SaturnJobConsoleException {
try {
restApiService.stopJobAtOnce(namespace, jobName);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@Audit(type = AuditType.REST)
@RequestMapping(value = "/{namespace}/jobs/{jobName}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> delete(@PathVariable("namespace") String namespace, @PathVariable("jobName") String jobName)
throws SaturnJobConsoleException {
try {
restApiService.deleteJob(namespace, jobName);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
@Audit(type = AuditType.REST)
@RequestMapping(value = "/{namespace}/jobs/{jobName}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> update(@PathVariable("namespace") String namespace, @PathVariable String jobName,
@RequestBody Map<String, Object> reqParams) throws SaturnJobConsoleException {
try {
UpdateJobConfigVo updateJobConfigVo = constructUpdateJobConfig(namespace, reqParams);
restApiService.updateJob(namespace, jobName, updateJobConfigVo);
return new ResponseEntity<>(HttpStatus.OK);
} catch (SaturnJobConsoleException e) {
throw e;
} catch (Exception e) {
throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
}
}
private JobConfig constructJobConfig(String namespace, Map<String, Object> reqParams) throws SaturnJobConsoleException {
checkMissingParameter("namespace", namespace);
if (!reqParams.containsKey("jobConfig")) {
throw new SaturnJobConsoleHttpException(HttpStatus.BAD_REQUEST.value(),
String.format(INVALID_REQUEST_MSG, "jobConfig", "cannot be blank"));
}
JobConfig jobConfig = new JobConfig();
Map<String, Object> configParams = (Map<String, Object>) reqParams.get("jobConfig");
jobConfig.setJobName(checkAndGetParametersValueAsString(reqParams, "jobName", true));
jobConfig.setDescription(checkAndGetParametersValueAsString(reqParams, "description", false));
jobConfig.setChannelName(checkAndGetParametersValueAsString(configParams, "channelName", false));
jobConfig.setCron(checkAndGetParametersValueAsString(configParams, "cron", false));
jobConfig.setJobClass(checkAndGetParametersValueAsString(configParams, "jobClass", false));
jobConfig.setJobParameter(checkAndGetParametersValueAsString(configParams, "jobParameter", false));
String jobType = checkAndGetParametersValueAsString(configParams, "jobType", true);
if (JobType.UNKOWN_JOB.equals(JobType.getJobType(jobType))) {
throw new SaturnJobConsoleHttpException(HttpStatus.BAD_REQUEST.value(), String.format(INVALID_REQUEST_MSG, "jobType", "is malformed"));
}
jobConfig.setJobType(jobType);
jobConfig.setLoadLevel(checkAndGetParametersValueAsInteger(configParams, "loadLevel", false));
jobConfig.setLocalMode(checkAndGetParametersValueAsBoolean(configParams, "localMode", false));
jobConfig.setPausePeriodDate(checkAndGetParametersValueAsString(configParams, "pausePeriodDate", false));
jobConfig.setPausePeriodTime(checkAndGetParametersValueAsString(configParams, "pausePeriodTime", false));
jobConfig.setPreferList(checkAndGetParametersValueAsString(configParams, "preferList", false));
jobConfig.setQueueName(checkAndGetParametersValueAsString(configParams, "queueName", false));
jobConfig.setShardingItemParameters(checkAndGetParametersValueAsString(configParams, "shardingItemParameters", true));
jobConfig.setShardingTotalCount(checkAndGetParametersValueAsInteger(configParams, "shardingTotalCount", true));
jobConfig.setTimeout4AlarmSeconds(checkAndGetParametersValueAsInteger(configParams, "timeout4AlarmSeconds", false));
jobConfig.setTimeoutSeconds(checkAndGetParametersValueAsInteger(configParams, "timeout4Seconds", false));
jobConfig.setUseDispreferList(checkAndGetParametersValueAsBoolean(configParams, "useDispreferList", false));
jobConfig.setUseSerial(checkAndGetParametersValueAsBoolean(configParams, "useSerial", false));
jobConfig.setJobDegree(checkAndGetParametersValueAsInteger(configParams, "jobDegree", false));
jobConfig.setDependencies(checkAndGetParametersValueAsString(configParams, "dependencies", false));
jobConfig.setTimeZone(checkAndGetParametersValueAsString(configParams, "timeZone", false));
jobConfig.setTimeoutSeconds(checkAndGetParametersValueAsInteger(configParams, "timeoutSeconds", false));
jobConfig.setProcessCountIntervalSeconds(checkAndGetParametersValueAsInteger(configParams, "processCountIntervalSeconds", false));
jobConfig.setGroups(checkAndGetParametersValueAsString(configParams, "groups", false));
jobConfig.setShowNormalLog(checkAndGetParametersValueAsBoolean(configParams, "showNormalLog", false));
return jobConfig;
}
private UpdateJobConfigVo constructUpdateJobConfig(String namespace, Map<String, Object> reqParams)
throws SaturnJobConsoleException {
JobConfig jobConfig = constructJobConfig(namespace, reqParams);
UpdateJobConfigVo updateJobConfigVo = new UpdateJobConfigVo();
SaturnBeanUtils.copyProperties(jobConfig, updateJobConfigVo);
Map<String, Object> configParams = (Map<String, Object>) reqParams.get("jobConfig");
updateJobConfigVo
.setOnlyUsePreferList(checkAndGetParametersValueAsBoolean(configParams, "onlyUseDispreferList", false));
return updateJobConfigVo;
}
} |
package org.collectionspace.services.client.test;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.collectionspace.services.client.AcquisitionClient;
import org.collectionspace.services.acquisition.AcquisitionsCommon;
import org.collectionspace.services.acquisition.AcquisitionsCommonList;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
import org.testng.Assert;
import org.testng.annotations.Test;
public class AcquisitionServiceTest extends AbstractServiceTest {
// Instance variables specific to this test.
private AcquisitionClient client = new AcquisitionClient();
final String SERVICE_PATH_COMPONENT = "acquisitions";
private String knownResourceId = null;
// CRUD tests : CREATE tests
// Success outcomes
@Override
@Test
public void create() {
// Perform setup, such as initializing the type of service request
// (e.g. CREATE, DELETE), its valid and expected status codes, and
// its associated HTTP method name (e.g. POST, DELETE).
setupCreate();
// Submit the request to the service and store the response.
String identifier = createIdentifier();
MultipartOutput multipart = createAcquisitionInstance(identifier);
ClientResponse<Response> res = client.create(multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
// Specifically:
// Does it fall within the set of valid status codes?
// Does it exactly match the expected status code?
verbose("create: status = " + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Store the ID returned from this create operation for
// additional tests below.
knownResourceId = extractId(res);
verbose("create: knownResourceId=" + knownResourceId);
}
@Override
@Test(dependsOnMethods = {"create"})
public void createList() {
for(int i = 0; i < 3; i++){
create();
}
}
// Failure outcomes
// Placeholders until the three tests below can be uncommented.
// See Issue CSPACE-401.
public void createWithEmptyEntityBody() {
}
public void createWithMalformedXml() {
}
public void createWithWrongXmlSchema() {
}
/*
@Override
@Test(dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithMalformedXml() {
// Perform setup.
setupCreateWithMalformedXml();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
final String entity = MALFORMED_XML_DATA; // Constant from base class.
int statusCode = submitRequest(method, url, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("createWithMalformedXml url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithWrongXmlSchema() {
// Perform setup.
setupCreateWithWrongXmlSchema();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
final String entity = WRONG_XML_SCHEMA_DATA;
int statusCode = submitRequest(method, url, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("createWithWrongSchema url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
*/
// CRUD tests : READ tests
// Success outcomes
@Override
@Test(dependsOnMethods = {"create"})
public void read() {
// Perform setup.
setupRead();
// Submit the request to the service and store the response.
ClientResponse<MultipartInput> res = client.read(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("read: status = " + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
//FIXME: remove the following try catch once Aron fixes signatures
try{
MultipartInput input = (MultipartInput) res.getEntity();
AcquisitionsCommon acquistionObject = (AcquisitionsCommon) extractPart(input,
getCommonPartName(), AcquisitionsCommon.class);
Assert.assertNotNull(acquistionObject);
}catch(Exception e){
throw new RuntimeException(e);
}
}
// Failure outcomes
@Override
@Test(dependsOnMethods = {"read"})
public void readNonExistent() {
// Perform setup.
setupReadNonExistent();
// Submit the request to the service and store the response.
ClientResponse<MultipartInput> res = client.read(NON_EXISTENT_ID);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("readNonExistent: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// CRUD tests : READ_LIST tests
// Success outcomes
@Override
@Test(dependsOnMethods = {"createList", "read"})
public void readList() {
// Perform setup.
setupReadList();
// Submit the request to the service and store the response.
ClientResponse<AcquisitionsCommonList> res = client.readList();
AcquisitionsCommonList list = res.getEntity();
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("readList: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Optionally output additional data about list members for debugging.
boolean iterateThroughList = false;
if(iterateThroughList && logger.isDebugEnabled()){
List<AcquisitionsCommonList.AcquisitionListItem> items =
list.getAcquisitionListItem();
int i = 0;
for(AcquisitionsCommonList.AcquisitionListItem item : items){
verbose("readList: list-item[" + i + "] csid=" +
item.getCsid());
verbose("readList: list-item[" + i + "] objectNumber=" +
item.getAccessiondate());
verbose("readList: list-item[" + i + "] URI=" +
item.getUri());
i++;
}
}
}
// Failure outcomes
// None at present.
// CRUD tests : UPDATE tests
// Success outcomes
@Override
@Test(dependsOnMethods = {"read"})
public void update() {
// Perform setup.
setupUpdate();
try{ //ideally, just remove try-catch and let the exception bubble up
// Retrieve an existing resource that we can update.
ClientResponse<MultipartInput> res =
client.read(knownResourceId);
verbose("update: read status = " + res.getStatus());
Assert.assertEquals(res.getStatus(), EXPECTED_STATUS_CODE);
verbose("got object to update with ID: " + knownResourceId);
MultipartInput input = (MultipartInput) res.getEntity();
AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input,
getCommonPartName(), AcquisitionsCommon.class);
Assert.assertNotNull(acquisition);
// Update the content of this resource.
acquisition.setAccessiondate("updated-" + acquisition.getAccessiondate());
verbose("updated object", acquisition, AcquisitionsCommon.class);
// Submit the request to the service and store the response.
MultipartOutput output = new MultipartOutput();
OutputPart commonPart = output.addPart(acquisition, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", getCommonPartName());
res = client.update(knownResourceId, output);
int statusCode = res.getStatus();
// Check the status code of the response: does it match the expected response(s)?
verbose("update: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
input = (MultipartInput) res.getEntity();
AcquisitionsCommon updatedAcquisition =
(AcquisitionsCommon) extractPart(input,
getCommonPartName(), AcquisitionsCommon.class);
Assert.assertNotNull(updatedAcquisition);
Assert.assertEquals(updatedAcquisition.getAccessiondate(),
acquisition.getAccessiondate(),
"Data in updated object did not match submitted data.");
}catch(Exception e){
e.printStackTrace();
}
}
// Failure outcomes
// Placeholders until the three tests below can be uncommented.
// See Issue CSPACE-401.
public void updateWithEmptyEntityBody() {
}
public void updateWithMalformedXml() {
}
public void updateWithWrongXmlSchema() {
}
/*
@Override
@Test(dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithEmptyEntityBody() {
// Perform setup.
setupUpdateWithEmptyEntityBody();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
String mediaType = MediaType.APPLICATION_XML;
final String entity = "";
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateWithEmptyEntityBody url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithEmptyEntityBody() {
// Perform setup.
setupCreateWithEmptyEntityBody();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
String mediaType = MediaType.APPLICATION_XML;
final String entity = "";
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("createWithEmptyEntityBody url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithMalformedXml() {
// Perform setup.
setupUpdateWithMalformedXml();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
final String entity = MALFORMED_XML_DATA;
int statusCode = submitRequest(method, url, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateWithMalformedXml: url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithWrongXmlSchema() {
// Perform setup.
setupUpdateWithWrongXmlSchema();
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
final String entity = WRONG_XML_SCHEMA_DATA;
int statusCode = submitRequest(method, url, entity);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateWithWrongSchema: url=" + url + " status=" + statusCode);
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
*/
@Override
@Test(dependsOnMethods = {"update", "testSubmitRequest"})
public void updateNonExistent() {
// Perform setup.
setupUpdateNonExistent();
// Submit the request to the service and store the response.
// Note: The ID used in this 'create' call may be arbitrary.
// The only relevant ID may be the one used in update(), below.
MultipartOutput multipart = createAcquisitionInstance(NON_EXISTENT_ID);
ClientResponse<MultipartInput> res =
client.update(NON_EXISTENT_ID, multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("updateNonExistent: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// CRUD tests : DELETE tests
// Success outcomes
@Override
@Test(dependsOnMethods = {"create", "read", "update"})
public void delete() {
// Perform setup.
setupDelete();
// Submit the request to the service and store the response.
ClientResponse<Response> res = client.delete(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("delete: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Failure outcomes
@Override
@Test(dependsOnMethods = {"delete"})
public void deleteNonExistent() {
// Perform setup.
setupDeleteNonExistent();
// Submit the request to the service and store the response.
ClientResponse<Response> res = client.delete(NON_EXISTENT_ID);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
verbose("deleteNonExistent: status = " + res.getStatus());
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Utility tests : tests of code used in tests above
/**
* Tests the code for manually submitting data that is used by several
* of the methods above.
*/
@Test(dependsOnMethods = {"create", "read"})
public void testSubmitRequest() {
// Expected status code: 200 OK
final int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
// Submit the request to the service and store the response.
String method = ServiceRequestType.READ.httpMethodName();
String url = getResourceURL(knownResourceId);
int statusCode = submitRequest(method, url);
// Check the status code of the response: does it match
// the expected response(s)?
verbose("testSubmitRequest: url=" + url + " status=" + statusCode);
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Utility methods used by tests above
@Override
public String getServicePathComponent() {
return SERVICE_PATH_COMPONENT;
}
private MultipartOutput createAcquisitionInstance(String identifier) {
AcquisitionsCommon acquisition = new AcquisitionsCommon();
acquisition.setAccessiondate("accessionDate-" + identifier);
MultipartOutput multipart = new MultipartOutput();
OutputPart commonPart = multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", getCommonPartName());
verbose("to be created, acquisition common ", acquisition, AcquisitionsCommon.class);
return multipart;
}
} |
package net.imagej.legacy;
import ij.Executer;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.Macro;
import ij.Menus;
import ij.OtherInstance;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.gui.Toolbar;
import ij.io.DirectoryChooser;
import ij.io.OpenDialog;
import ij.io.Opener;
import ij.io.SaveDialog;
import ij.macro.Interpreter;
import ij.plugin.Commands;
import ij.plugin.PlugIn;
import ij.plugin.filter.PlugInFilter;
import ij.plugin.filter.PlugInFilterRunner;
import ij.plugin.frame.Recorder;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.Window;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.swing.SwingUtilities;
import net.imagej.display.ImageDisplay;
import net.imagej.patcher.LegacyHooks;
import org.scijava.AbstractContextual;
import org.scijava.Context;
import org.scijava.MenuEntry;
import org.scijava.MenuPath;
import org.scijava.event.EventHandler;
import org.scijava.log.LogService;
import org.scijava.module.ModuleInfo;
import org.scijava.platform.event.AppAboutEvent;
import org.scijava.platform.event.AppOpenFilesEvent;
import org.scijava.platform.event.AppPreferencesEvent;
import org.scijava.platform.event.AppQuitEvent;
import org.scijava.plugin.Parameter;
import org.scijava.script.ScriptService;
import org.scijava.util.ClassUtils;
/**
* A helper class to interact with ImageJ 1.x.
* <p>
* The LegacyService needs to patch ImageJ 1.x's classes before they are loaded.
* Unfortunately, this is tricky: if the LegacyService already uses those
* classes, it is a matter of luck whether we can get the patches in before
* those classes are loaded.
* </p>
* <p>
* Therefore, we put as much interaction with ImageJ 1.x as possible into this
* class and keep a reference to it in the LegacyService.
* </p>
*
* @author Johannes Schindelin
*/
public class IJ1Helper extends AbstractContextual {
/** A reference to the legacy service, just in case we need it. */
private final LegacyService legacyService;
@Parameter
private LogService log;
/** Whether we are in the process of forcibly shutting down ImageJ1. */
private boolean disposing;
public IJ1Helper(final LegacyService legacyService) {
setContext(legacyService.getContext());
this.legacyService = legacyService;
}
public void initialize() {
// initialize legacy ImageJ application
final ImageJ ij1 = IJ.getInstance();
if (Menus.getCommands() == null) {
IJ.runPlugIn("ij.IJ.init", "");
}
if (ij1 != null) {
// NB: *Always* call System.exit(0) when quitting:
// - In the case of batch mode, the JVM needs to terminate at the
// conclusion of the macro/script, regardless of the actions performed
// by that macro/script.
// - In the case of GUI mode, the JVM needs to terminate when the user
// quits the program because ImageJ1 has many plugins which do not
// properly clean up their resources. This is a vicious cycle:
// ImageJ1's main method sets exitWhenQuitting to true, which has
// historically masked the problems with these plugins. So we have
// little choice but to continue this tradition, at least with the
// legacy ImageJ1 user interface.
ij1.exitWhenQuitting(true);
// make sure that the Event Dispatch Thread's class loader is set
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Thread.currentThread().setContextClassLoader(IJ.getClassLoader());
}
});
final LegacyImageMap imageMap = legacyService.getImageMap();
for (int i = 1; i <= WindowManager.getImageCount(); i++) {
imageMap.registerLegacyImage(WindowManager.getImage(i));
}
// set icon and title of main window (which are instantiated before the
// initializer is called)
try {
final LegacyHooks hooks =
(LegacyHooks) IJ.class.getField("_hooks").get(null);
ij1.setTitle(hooks.getAppName());
final URL iconURL = hooks.getIconURL();
if (iconURL != null) try {
final Object producer = iconURL.getContent();
final Image image = ij1.createImage((ImageProducer) producer);
ij1.setIconImage(image);
if (IJ.isMacOSX()) try {
// NB: We also need to set the dock icon
final Class<?> clazz = Class.forName("com.apple.eawt.Application");
final Object app = clazz.getMethod("getApplication").invoke(null);
clazz.getMethod("setDockIconImage", Image.class).invoke(app, image);
}
catch (final Throwable t) {
t.printStackTrace();
}
}
catch (final IOException e) {
IJ.handleException(e);
}
}
catch (final Throwable t) {
t.printStackTrace();
}
// FIXME: handle window location via LegacyUI
// This is necessary because the ImageJ 1.x window will not set its
// location if created with mode NO_SHOW, which is exactly how it is
// created right now by the legacy layer. This is a work-around by
// ensuring the preferred (e.g. saved and loaded) location is current at
// the time the IJ1Helper is initialized. Ideally we would like to handle
// positioning via the LegacyUI though, so that we can restore positions
// on secondary monitors and such.
ij1.setLocation(ij1.getPreferredLocation());
}
}
/**
* Forcibly shuts down ImageJ1, with no user interaction or opportunity to
* cancel. If ImageJ1 is not currently initialized, or if ImageJ1 is already
* in the process of quitting (i.e., {@link ij.ImageJ#quitting()} returns
* {@code true}), then this method does nothing.
*/
public synchronized void dispose() {
final ImageJ ij = IJ.getInstance();
if (ij != null && ij.quitting()) return; // IJ1 is already on its way out
disposing = true;
closeImageWindows();
disposeNonImageWindows();
if (ij != null) {
// quit legacy ImageJ on the same thread
ij.exitWhenQuitting(false); // do *not* quit the JVM!
ij.run();
}
disposing = false;
}
/** Whether we are in the process of forcibly shutting down ImageJ1. */
public boolean isDisposing() {
return disposing;
}
/** Add name aliases for ImageJ1 classes to the ScriptService. */
public void addAliases(final ScriptService scriptService) {
scriptService.addAlias(ImagePlus.class);
}
public boolean isVisible() {
final ImageJ ij = IJ.getInstance();
if (ij == null) return false;
return ij.isVisible();
}
/**
* Determines whether <it>Edit>Options>Misc...>Run single instance
* listener</it> is set.
*
* @return true if <it>Run single instance listener</it> is set
*/
public boolean isRMIEnabled() {
return OtherInstance.isRMIEnabled();
}
private boolean batchMode;
void setBatchMode(final boolean batch) {
Interpreter.batchMode = batch;
batchMode = batch;
}
void invalidateInstance() {
try {
final Method cleanup = IJ.class.getDeclaredMethod("cleanup");
cleanup.setAccessible(true);
cleanup.invoke(null);
}
catch (final Throwable t) {
t.printStackTrace();
log.error(t);
}
}
/**
* Sets {@link WindowManager} {@code checkForDuplicateName} field.
*/
public void setCheckNameDuplicates(final boolean checkDuplicates) {
WindowManager.checkForDuplicateName = checkDuplicates;
}
public void setVisible(final boolean toggle) {
if (batchMode) return;
final ImageJ ij = IJ.getInstance();
if (ij != null) {
if (toggle) ij.pack();
ij.setVisible(toggle);
}
// hide/show the legacy ImagePlus instances
final LegacyImageMap imageMap = legacyService.getImageMap();
for (final ImagePlus imp : imageMap.getImagePlusInstances()) {
final ImageWindow window = imp.getWindow();
if (window != null) window.setVisible(toggle);
}
}
public void syncActiveImage(final ImageDisplay activeDisplay) {
final LegacyImageMap imageMap = legacyService.getImageMap();
final ImagePlus activeImagePlus = imageMap.lookupImagePlus(activeDisplay);
// NB - old way - caused probs with 3d Project
// WindowManager.setTempCurrentImage(activeImagePlus);
// NB - new way - test thoroughly
if (activeImagePlus == null) WindowManager.setCurrentWindow(null);
else WindowManager.setCurrentWindow(activeImagePlus.getWindow());
}
public void setKeyDown(final int keyCode) {
IJ.setKeyDown(keyCode);
}
public void setKeyUp(final int keyCode) {
IJ.setKeyUp(keyCode);
}
public boolean hasInstance() {
return IJ.getInstance() != null;
}
/** Gets the version of ImageJ 1.x. */
public String getVersion() {
// NB: We cannot hardcode a reference to ImageJ.VERSION. Java often inlines
// string constants at compile time. This means that if a different version
// of ImageJ 1.x is used at runtime, this method could return an incorrect
// value. Calling IJ.getVersion() would be more reliable, except that we
// override its behavior to return LegacyHooks#getAppVersion(). So instead,
// we resort to referencing the ImageJ#VERSION constant via reflection.
try {
final Field field = ImageJ.class.getField("VERSION");
if (field != null) {
final Object version = field.get(null);
if (version != null) return version.toString();
}
}
catch (final NoSuchFieldException exc) {
log.error(exc);
}
catch (final IllegalAccessException exc) {
log.error(exc);
}
return "Unknown";
}
public boolean isMacintosh() {
return IJ.isMacintosh();
}
public void setStatus(final String message) {
IJ.showStatus(message);
}
public void setProgress(final int val, final int max) {
IJ.showProgress(val, max);
}
public Component getToolBar() {
return Toolbar.getInstance();
}
public Panel getStatusBar() {
if (!hasInstance()) return null;
return IJ.getInstance().getStatusBar();
}
public Frame getIJ() {
if (hasInstance()) {
return IJ.getInstance();
}
return null;
}
public void setLocation(final int x, final int y) {
if (!hasInstance()) return;
IJ.getInstance().setLocation(x, y);
}
public int getX() {
if (!hasInstance()) return 0;
return IJ.getInstance().getX();
}
public int getY() {
if (!hasInstance()) return 0;
return IJ.getInstance().getY();
}
public boolean isWindowClosed(final Frame window) {
if (window instanceof ImageWindow) {
return ((ImageWindow) window).isClosed();
}
return false;
}
public boolean quitting() {
if (hasInstance()) return IJ.getInstance().quitting();
return false;
}
public int[] getIDList() {
return WindowManager.getIDList();
}
public ImagePlus getImage(final int imageID) {
return WindowManager.getImage(imageID);
}
/**
* Returns {@link ImagePlus#getTitle()} if the object is an {@link ImagePlus},
* otherwise null.
*/
public static String getTitle(final Object o) {
return o instanceof ImagePlus ? ((ImagePlus) o).getTitle() : null;
}
public ClassLoader getClassLoader() {
return IJ.getClassLoader();
}
public void showMessage(final String title, final String message) {
IJ.showMessage(title, message);
}
public boolean showMessageWithCancel(final String title,
final String message)
{
return IJ.showMessageWithCancel(title, message);
}
public String commandsName() {
return Commands.class.getName();
}
public void updateRecentMenu(final String path) {
final Menu menu = Menus.getOpenRecentMenu();
if (menu == null) return;
final int n = menu.getItemCount();
int index = -1;
for (int i = 0; i < n; i++) {
if (menu.getItem(i).getLabel().equals(path)) {
index = i;
break;
}
}
// Move to most recent
if (index > 0) {
final MenuItem item = menu.getItem(index);
menu.remove(index);
menu.insert(item, 0);
}
// not found, so replace oldest
else if (index < 0) {
final int count = menu.getItemCount();
if (count >= Menus.MAX_OPEN_RECENT_ITEMS) {
menu.remove(count - 1);
}
final MenuItem item = new MenuItem(path);
final ImageJ instance = IJ.getInstance();
if (instance != null) item.addActionListener(instance);
menu.insert(item, 0);
}
// if index was 0, already at the head so do nothing
}
/**
* Opens an image and adds the path to the <it>File>Open Recent</it> menu.
*
* @param file the image to open
*/
public static void openAndAddToRecent(final File file) {
new Opener().openAndAddToRecent(file.getAbsolutePath());
}
/**
* Records an option in ImageJ 1.x's macro recorder, <em>safely</em>.
* <p>
* Both the key and the value will be escaped to avoid problems. This behavior
* differs from direct calls to {@link Recorder#recordOption(String, String)},
* which do not escape either string.
* </p>
*
* @param key the name of the option
* @param value the value of the option
*/
public void recordOption(final String key, final String value) {
Recorder.recordOption(escape(key), escape(value));
}
/**
* Determines whether we're running inside a macro right now.
*
* @return whether we're running a macro right now.
*/
public boolean isMacro() {
return IJ.isMacro();
}
/**
* Gets a macro parameter of type <i>boolean</i>.
*
* @param label the name of the macro parameter
* @param defaultValue the default value
* @return the boolean value
*/
public boolean getMacroParameter(final String label,
final boolean defaultValue)
{
return getMacroParameter(label) != null || defaultValue;
}
/**
* Gets a macro parameter of type <i>double</i>.
*
* @param label the name of the macro parameter
* @param defaultValue the default value
* @return the double value
*/
public double getMacroParameter(final String label,
final double defaultValue)
{
final String value = Macro.getValue(getOptions(), label, null);
return value != null ? Double.parseDouble(value) : defaultValue;
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label the name of the macro parameter
* @param defaultValue the default value
* @return the value
*/
public String getMacroParameter(final String label,
final String defaultValue)
{
return Macro.getValue(getOptions(), label, defaultValue);
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label the name of the macro parameter
* @return the value, <code>null</code> if the parameter was not specified
*/
public String getMacroParameter(final String label) {
return Macro.getValue(getOptions(), label, null);
}
/** Returns the active macro {@link Interpreter}. */
public static Object getInterpreter() {
return Interpreter.getInstance();
}
/**
* Gets the value of the specified variable, from the given macro
* {@link Interpreter}.
*
* @param interpreter The macro {@link Interpreter} to query.
* @return The list of variables in {@code key\tvalue} form, as given by
* {@link Interpreter#getVariables()}.
* @throws ClassCastException if the given interpreter is not an
* {@link Interpreter}.
*/
public String[] getVariables(final Object interpreter) {
return ((Interpreter) interpreter).getVariables();
}
/**
* Gets the value of the specified variable, from the given macro
* {@link Interpreter}.
*
* @param interpreter The macro {@link Interpreter} to query.
* @param name The name of the variable to retrieve.
* @return The value of the requested variable, as either a {@link String}, a
* {@link Double} or {@code null}.
* @throws ClassCastException if the given interpreter is not an
* {@link Interpreter}.
*/
public Object getVariable(final Object interpreter, final String name) {
final Interpreter interp = (Interpreter) interpreter;
// might be a string
final String sValue = interp.getStringVariable(name);
if (sValue != null) return sValue;
// probably a number
final double nValue = interp.getVariable2(name);
if (!Double.isNaN(nValue)) return nValue;
return null;
}
/** Returns true if the object is an instance of {@link ImagePlus}. */
public boolean isImagePlus(final Object o) {
return o instanceof ImagePlus;
}
/** Returns true if the class is assignable to {@link ImagePlus}. */
public boolean isImagePlus(final Class<?> c) {
return ImagePlus.class.isAssignableFrom(c);
}
public int getImageID(final Object o) {
return ((ImagePlus) o).getID();
}
/** Gets the SciJava application context linked to the ImageJ 1.x instance. */
public static Context getLegacyContext() {
// NB: This call instantiates a Context if there is none.
// IJ.runPlugIn() will be intercepted by the legacy hooks if they are
// installed and return the current Context.
// If no legacy hooks are installed, ImageJ 1.x will instantiate the Context
// using the PluginClassLoader and the LegacyService will install the legacy
// hooks.
final Object o = IJ.runPlugIn("org.scijava.Context", "");
if (o == null) return null;
if (!(o instanceof Context)) {
throw new IllegalStateException("Unexpected type of context: " +
o.getClass().getName());
}
return (Context) o;
}
/**
* Partial replacement for ImageJ 1.x's MacAdapter.
* <p>
* ImageJ 1.x has a MacAdapter plugin that intercepts MacOSX-specific events
* and handles them. The way it does it is deprecated now, however, and
* unfortunately incompatible with the way ImageJ 2's platform service does
* it.
* </p>
* <p>
* This class implements the same functionality as the MacAdapter, but in a
* way that is compatible with the SciJava platform service.
* </p>
* <p>
* Note that the {@link AppAboutEvent}, {@link AppPreferencesEvent} and
* {@link AppQuitEvent} are handled separately, indirectly, by the
* {@link LegacyImageJApp}. See also {@link IJ1Helper#appAbout},
* {@link IJ1Helper#appPrefs} and {@link IJ1Helper#appQuit}.
* </p>
*
* @author Johannes Schindelin
*/
private static class LegacyEventDelegator extends AbstractContextual {
@Parameter(required = false)
private LegacyService legacyService;
// -- MacAdapter re-implementations --
/** @param event */
@EventHandler
private void onEvent(final AppOpenFilesEvent event) {
if (isLegacyMode()) {
final List<File> files = new ArrayList<>(event.getFiles());
for (final File file : files) {
openAndAddToRecent(file);
}
}
}
private boolean isLegacyMode() {
// We call setContext() indirectly from LegacyService#initialize,
// therefore legacyService might still be null at this point even if the
// context knows a legacy service now.
if (legacyService == null) {
final Context context = getContext();
if (context != null) {
legacyService = context.getService(LegacyService.class);
}
}
return legacyService != null && legacyService.isLegacyMode();
}
}
private static LegacyEventDelegator eventDelegator;
public static void subscribeEvents(final Context context) {
if (context == null) {
eventDelegator = null;
}
else {
eventDelegator = new LegacyEventDelegator();
eventDelegator.setContext(context);
}
}
static void run(final Class<?> c) {
IJ.resetEscape();
if (PlugIn.class.isAssignableFrom(c)) {
try {
final PlugIn plugin = (PlugIn) c.newInstance();
plugin.run("");
}
catch (final Exception e) {
throw e instanceof RuntimeException ?
(RuntimeException) e : new RuntimeException(e);
}
return;
}
if (PlugInFilter.class.isAssignableFrom(c)) {
try {
final PlugInFilter plugin = (PlugInFilter) c.newInstance();
final ImagePlus image = WindowManager.getCurrentImage();
if (image != null && image.isLocked()) {
final String msg = "The image '" +
image.getTitle() + "' appears to be locked... Unlock?";
if (!IJ.showMessageWithCancel("Unlock image?", msg)) return;
image.unlock();
}
new PlugInFilterRunner(plugin, c.getName(), "");
}
catch (final Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
return;
}
throw new RuntimeException("TODO: construct class loader");
}
private boolean menuInitialized;
/**
* Adds legacy-compatible scripts and commands to the ImageJ1 menu structure.
*/
public synchronized void addMenuItems() {
if (menuInitialized) return;
final Map<String, ModuleInfo> modules =
legacyService.getScriptsAndNonLegacyCommands();
@SuppressWarnings("unchecked")
final Hashtable<String, String> ij1Commands = Menus.getCommands();
final ImageJ ij1 = hasInstance() ? IJ.getInstance() : null;
final IJ1MenuWrapper wrapper = ij1 == null ? null : new IJ1MenuWrapper(ij1);
class Item implements Comparable<Item> {
private double weight;
private MenuPath path;
private String name, identifier;
private ModuleInfo info;
@Override
public int compareTo(final Item o) {
if (weight != o.weight) return Double.compare(weight, o.weight);
return compare(path, o.path);
}
public int compare(final MenuPath a, final MenuPath b) {
int i = 0;
while (i < a.size() && i < b.size()) {
final MenuEntry a2 = a.get(i), b2 = b.get(i);
int diff = Double.compare(a.get(i).getWeight(), b.get(i).getWeight());
if (diff != 0) return diff;
diff = a2.getName().compareTo(b2.getName());
if (diff != 0) return diff;
i++;
}
return 0;
}
}
final List<Item> items = new ArrayList<>();
for (final Entry<String, ModuleInfo> entry : modules.entrySet()) {
final String key = entry.getKey();
final ModuleInfo info = entry.getValue();
final MenuEntry leaf = info.getMenuPath().getLeaf();
if (leaf == null) continue;
final MenuPath path = info.getMenuPath();
final String name = leaf.getName();
final Item item = new Item();
item.weight = leaf.getWeight();
item.path = path;
item.name = name;
item.identifier = key;
item.info = info;
items.add(item);
}
// sort by menu weight, then alphabetically
Collections.sort(items);
for (final Item item : items) {
if (ij1Commands.containsKey(item.name)) {
log.info("Overriding " + item.name +
"; identifier: " + item.identifier +
"; jar: " + ClassUtils.getLocation(item.info.getDelegateClassName()));
if (wrapper != null) try {
wrapper.create(item.path, true);
}
catch (final Throwable t) {
log.error(t);
}
}
else if (wrapper != null) try {
wrapper.create(item.path, false);
}
catch (final Throwable t) {
log.error(t);
}
ij1Commands.put(item.name, item.identifier);
}
menuInitialized = true;
}
/**
* Helper class for wrapping ImageJ2 menu paths to ImageJ1 {@link Menu}
* structures, and inserting them into the proper positions of the
* {@link MenuBar}.
*/
private static class IJ1MenuWrapper {
final ImageJ ij1;
final MenuBar menuBar = Menus.getMenuBar();
final MenuCache menuCache = new MenuCache();
final Set<Menu> separators = new HashSet<>();
private IJ1MenuWrapper(final ImageJ ij1) {
this.ij1 = ij1;
}
/**
* Creates a {@link MenuItem} matching the structure of the provided path.
* Expected path structure is:
* <ul>
* <li>Level1 > Level2 > ... > Leaf entry</li>
* </ul>
* <p>
* For example, a valid path would be:
* </p>
* <ul>
* <li>Edit > Options > ImageJ2 plugins > Discombobulator</li>
* </ul>
*/
private MenuItem create(final MenuPath path, final boolean reuseExisting) {
// Find the menu structure where we can insert our command.
// NB: size - 1 is the leaf position, so we want to go to size - 2 to
// find the parent menu location
final Menu menu = getParentMenu(path, path.size() - 2);
final String label = path.getLeaf().getName();
// If we are overriding an item, find the item being overridden
if (reuseExisting) {
for (int i = 0; i < menu.getItemCount(); i++) {
final MenuItem item = menu.getItem(i);
if (label.equals(item.getLabel())) {
return item;
}
}
}
if (!separators.contains(menu)) {
if (menu.getItemCount() > 0) menu.addSeparator();
separators.add(menu);
}
// Otherwise, we are creating a new item
final MenuItem item = new MenuItem(label);
menu.insert(item, getIndex(menu, label));
item.addActionListener(ij1);
return item;
}
/**
* Helper method to look up special cases for menu weighting
*/
private int getIndex(final Menu menu, final String label) {
// Place export sub-menu after import sub-menu
if (menu.getLabel().equals("File") && label.equals("Export")) {
for (int i = 0; i < menu.getItemCount(); i++) {
final MenuItem menuItem = menu.getItem(i);
if (menuItem.getLabel().equals("Import")) return i + 1;
}
}
// TODO pass and use actual command weight from IJ2.. maybe?
// No special case: append to end of menu
return menu.getItemCount();
}
/** Recursive helper method to build the final {@link Menu} structure. */
private Menu getParentMenu(final MenuPath menuPath, final int depth) {
final MenuEntry currentItem = menuPath.get(depth);
final String currentLabel = currentItem.getName();
// Check to see if we already know the menu associated with the desired
// label/path
final Menu cached = menuCache.get(menuPath, depth);
if (cached != null) return cached;
// We are at the root of the menu, so see if we have a matching menu
if (depth == 0) {
// Special case check the help menu
if ("Help".equals(currentLabel)) {
final Menu menu = menuBar.getHelpMenu();
menuCache.put(menuPath, depth, menu);
return menu;
}
// Check the other menus of the menu bar to see if our desired label
// already exists
for (int i = 0; i < menuBar.getMenuCount(); i++) {
final Menu menu = menuBar.getMenu(i);
if (currentLabel.equals(menu.getLabel())) {
menuCache.put(menuPath, depth, menu);
return menu;
}
}
// Didn't find a match so we have to create a new menu entry
final Menu menu = new Menu(currentLabel);
menuBar.add(menu);
menuCache.put(menuPath, depth, menu);
return menu;
}
final Menu parent = getParentMenu(menuPath, depth - 1);
// Once the parent of this entry is obtained, we need to check if it
// already contains the current entry.
for (int i = 0; i < parent.getItemCount(); i++) {
final MenuItem item = parent.getItem(i);
if (currentLabel.equals(item.getLabel())) {
if (item instanceof Menu) {
// Found a menu entry that matches our desired label, so return
final Menu menu = (Menu) item;
menuCache.put(menuPath, depth, menu);
return menu;
}
// Found a match but it was an existing non-menu item, so our menu
// structure is invalid.
// TODO consider mangling the IJ2 menu name instead...
throw new IllegalArgumentException("Not a menu: " + currentLabel);
}
}
if (!separators.contains(parent)) {
if (parent.getItemCount() > 0) parent.addSeparator();
separators.add(parent);
}
// An existing entry in the parent menu was not found, so we need to
// create a new entry.
final Menu menu = new Menu(currentLabel);
parent.insert(menu, getIndex(parent, menu.getLabel()));
menuCache.put(menuPath, depth, menu);
return menu;
}
}
private static class MenuCache {
private final Map<String, Menu> map = new HashMap<>();
public void put(final MenuPath menuPath, final int depth, final Menu menu) {
map.put(key(menuPath, depth), menu);
}
public Menu get(final MenuPath menuPath, final int depth) {
return map.get(key(menuPath, depth));
}
private String key(final MenuPath menuPath, final int depth) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i <= depth; i++) {
sb.append(menuPath.get(i).getName());
sb.append("\n"); // NB: an unambiguous separator
}
return sb.toString();
}
}
private <T> T runMacroFriendly(final Callable<T> call) {
if (EventQueue.isDispatchThread()) {
throw new IllegalStateException("Cannot run macro from the EDT!");
}
final Thread thread = Thread.currentThread();
final String name = thread.getName();
try {
// to make getOptions() work
if (!name.startsWith("Run$_")) thread.setName("Run$_" + name);
// to make Macro.abort() work
if (!name.endsWith("Macro$")) thread.setName(thread.getName() + "Macro$");
return call.call();
}
catch (final RuntimeException e) {
throw e;
}
catch (final Exception e) {
throw new RuntimeException(e);
}
finally {
thread.setName(name);
// HACK: Try to null out the ij.macro.Interpreter, just in case.
try {
final Method m = Interpreter.class.getDeclaredMethod("setInstance",
Interpreter.class);
m.setAccessible(true);
m.invoke(null, new Object[] { null });
}
catch (final NoSuchMethodException | IllegalAccessException
| InvocationTargetException exc)
{
log.error(exc);
}
}
}
/**
* Evaluates the specified command.
*
* @param command the command to execute
*/
public void run(final String command) {
runMacroFriendly(new Callable<Void>() {
@Override
public Void call() throws Exception {
IJ.run(command);
return null;
}
});
}
/**
* Evaluates the specified macro.
*
* @param macro the macro to evaluate
* @return the return value
*/
public String runMacro(final String macro) {
return runMacroFriendly(new Callable<String>() {
@Override
public String call() throws Exception {
return IJ.runMacro(macro);
}
});
}
/**
* Evaluates the specified macro.
*
* @param path the macro file to evaluate
* @param arg the macro argument
* @return the return value
*/
public String runMacroFile(final String path, final String arg) {
return runMacroFriendly(new Callable<String>() {
@Override
public String call() throws Exception {
return IJ.runMacroFile(path, arg);
}
});
}
/**
* Opens an image using ImageJ 1.x.
*
* @param path the image file to open
* @return the image
*/
public Object openImage(final String path) {
return openImage(path, false);
}
/**
* Opens an image using ImageJ 1.x.
*
* @param path the image file to open
* @return the image
*/
public Object openImage(final String path, final boolean show) {
final ImagePlus imp = IJ.openImage(path);
if (show && imp != null) imp.show();
return imp;
}
/**
* Opens a path using ImageJ 1.x, bypassing the (javassisted) IJ utility
* class.
*
* @param path the image file to open
*/
public void openPathDirectly(final String path) {
new Opener().open(path);
}
/**
* Enables or disables ImageJ 1.x' debug mode.
*
* @param debug whether to show debug messages or not
*/
public void setDebugMode(final boolean debug) {
IJ.debugMode = debug;
}
/**
* Delegate exception handling to ImageJ 1.x.
*
* @param e the exception to handle
*/
public void handleException(final Throwable e) {
IJ.handleException(e);
}
/**
* Ask ImageJ 1.x whether it thinks whether the Shift key is held down.
*
* @return whether the Shift key is considered <i>down</i>
*/
public boolean shiftKeyDown() {
return IJ.shiftKeyDown();
}
/**
* Delegates to ImageJ 1.x' {@link Macro#getOptions()} function.
*
* @return the macro options, or null
*/
public String getOptions() {
final String options = Macro.getOptions();
return options == null ? "" : options;
}
/**
* Delegates to ImageJ 1.x' {@link Macro#setOptions(String)} function.
*
* @param options the macro options, or null to reset
*/
public void setOptions(final String options) {
Macro.setOptions(options);
}
/** Handles shutdown of ImageJ 1.x. */
public void appQuit() {
if (legacyService.isLegacyMode()) {
new Executer("Quit", null); // works with the CommandListener
}
}
/** Displays the About ImageJ 1.x dialog. */
public void appAbout() {
if (legacyService.isLegacyMode()) {
IJ.run("About ImageJ...");
}
}
/** Sets OpenDialog's default directory */
public void setDefaultDirectory(final File directory) {
OpenDialog.setDefaultDirectory(directory.getPath());
}
/** Uses ImageJ 1.x' OpenDialog */
public File openDialog(final String title) {
final OpenDialog openDialog = new OpenDialog(title);
final String directory = openDialog.getDirectory();
// NB: As a side effect, ImageJ1 normally appends the selected
// file as a macro parameter when the getFileName() is called!
// We need to suppress that problematic behavior here; see:
final boolean recording = Recorder.record;
Recorder.record = false;
final String fileName = openDialog.getFileName();
Recorder.record = recording;
if (directory != null && fileName != null) {
return new File(directory, fileName);
}
return null;
}
/** Uses ImageJ 1.x' SaveDialog */
public File saveDialog(final String title, final File file,
final String extension)
{
// Use ImageJ1's SaveDialog.
final String defaultName;
if (file == null) defaultName = null;
else {
final int dotIndex = file.getName().indexOf('.');
defaultName = dotIndex > 0 ?
file.getName().substring(0, dotIndex) : file.getName();
}
final SaveDialog saveDialog = new SaveDialog(title, defaultName, extension);
final String directory = saveDialog.getDirectory();
// NB: As a side effect, ImageJ1 normally appends the selected
// file as a macro parameter when the getFileName() is called!
// We need to suppress that problematic behavior here; see:
final boolean recording = Recorder.record;
Recorder.record = false;
final String fileName = saveDialog.getFileName();
Recorder.record = recording;
if (directory != null && fileName != null) {
return new File(directory, fileName);
}
return null;
}
/** Chooses a directory using ImageJ 1.x' directory chooser. */
public String getDirectory(final String title, final File file) {
if (file != null) {
final String defaultDir =
file.isDirectory() ? file.getPath() : file.getParent();
if (defaultDir != null) DirectoryChooser.setDefaultDirectory(defaultDir);
}
// NB: As a side effect, ImageJ1 normally appends the selected
// directory as a macro parameter when getDirectory() is called!
// We need to suppress that problematic behavior here; see:
final boolean recording = Recorder.record;
Recorder.record = false;
final String directory = new DirectoryChooser(title).getDirectory();
Recorder.record = recording;
return directory;
}
/** Handles display of the ImageJ 1.x preferences. */
public void appPrefs() {
if (legacyService.isLegacyMode()) {
IJ.error("The ImageJ preferences are in the Edit>Options menu.");
}
}
// -- Helper methods --
/** Closes all image windows on the event dispatch thread. */
private void closeImageWindows() {
// TODO: Consider using ThreadService#invoke to simplify this logic.
final Runnable run = new Runnable() {
@Override
public void run() {
// close out all image windows, without dialog prompts
while (true) {
final ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) break;
imp.changes = false;
imp.close();
}
}
};
if (EventQueue.isDispatchThread()) {
run.run();
}
else {
try {
EventQueue.invokeAndWait(run);
}
catch (final Exception e) {
// report & ignore
log.error(e);
}
}
}
private void disposeNonImageWindows() {
disposeNonImageFrames();
disposeOtherNonImageWindows();
}
/**
* Disposes all the non-image window frames, as given by
* {@link WindowManager#getNonImageWindows()}.
*/
private void disposeNonImageFrames() {
for (final Frame frame : WindowManager.getNonImageWindows()) {
frame.dispose();
}
}
/**
* Ensures <em>all</em> the non-image windows are closed.
* <p>
* This is a non-trivial problem, as
* {@link WindowManager#getNonImageWindows()} <em>only</em> returns
* {@link Frame}s. However there are non-image, non-{@link Frame} windows that
* are critical to close: for example, the
* {@link ij.plugin.frame.ContrastAdjuster} spawns a polling thread to do its
* work, which will continue to run until the {@code ContrastAdjuster} is
* explicitly closed.
* </p>
*/
private void disposeOtherNonImageWindows() {
// NB: As of v1.49b, getNonImageTitles is not restricted to Frames,
// so we can use it to iterate through the available windows.
for (final String title : WindowManager.getNonImageTitles()) {
final Window window = WindowManager.getWindow(title);
// NB: We can NOT set these windows as active and run the Commands
// plugin with argument "close", because the default behavior is to
// try closing the window as an Image. As we know these are not Images,
// that is never the right thing to do.
WindowManager.removeWindow(window);
window.dispose();
}
}
/** Escapes the given string according to the Java language specification. */
private String escape(final String s) {
// NB: It would be nice to use the StringEscapeUtils.escapeJava method of
// Apache Commons Lang, but we eschew it for now to avoid the dependency.
// escape quotes and backslashes
String escaped = s.replaceAll("([\"\\\\])", "\\\\$1");
// escape special characters
escaped = escaped.replaceAll("\b", "\\\\b");
escaped = escaped.replaceAll("\n", "\\\\n");
escaped = escaped.replaceAll("\t", "\\\\t");
escaped = escaped.replaceAll("\f", "\\\\f");
escaped = escaped.replaceAll("\r", "\\\\r");
return escaped;
}
} |
package net.techcable.srglib;
import static com.google.common.base.Preconditions.*;
/**
* Static utility methods for handling srg.
*/
public final class SrgLib {
private SrgLib() {}
/**
* Checks if the given name is a valid java identifier
*
* Java identifiers are used for field or method names
*
* @param name the name to check
*/
public static boolean isValidIdentifier(String name) {
checkArgument(!name.isEmpty(), "Empty name: %s", name);
return Character.isJavaIdentifierStart(name.codePointAt(0)) && name.codePoints()
.skip(1) // Skip the first char, since we already checked it
.allMatch(Character::isJavaIdentifierPart);
}
} |
//This code is developed as part of the Java CoG Kit project
//This message may not be removed or altered.
package org.globus.cog.abstraction.coaster.service.job.manager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.coaster.service.LocalTCPService;
import org.globus.cog.abstraction.coaster.service.job.manager.Worker.ShutdownCallback;
import org.globus.cog.abstraction.impl.common.AbstractionFactory;
import org.globus.cog.abstraction.impl.common.ProviderMethodException;
import org.globus.cog.abstraction.impl.common.StatusImpl;
import org.globus.cog.abstraction.impl.common.execution.WallTime;
import org.globus.cog.abstraction.impl.common.task.ExecutionServiceImpl;
import org.globus.cog.abstraction.impl.common.task.ExecutionTaskHandler;
import org.globus.cog.abstraction.impl.common.task.InvalidProviderException;
import org.globus.cog.abstraction.impl.common.task.InvalidServiceContactException;
import org.globus.cog.abstraction.impl.common.task.JobSpecificationImpl;
import org.globus.cog.abstraction.impl.common.task.TaskImpl;
import org.globus.cog.abstraction.impl.common.task.TaskSubmissionException;
import org.globus.cog.abstraction.interfaces.ExecutionService;
import org.globus.cog.abstraction.interfaces.JobSpecification;
import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.abstraction.interfaces.TaskHandler;
import org.globus.cog.karajan.workflow.service.channels.ChannelContext;
public class WorkerManager extends Thread {
public static final Logger logger = Logger.getLogger(WorkerManager.class);
/**
* We allow for at least one minute of extra time compared to the requested
* walltime
*/
public static final Seconds TIME_RESERVE = new Seconds(60);
public static final File scriptDir =
new File(System.getProperty("user.home") + File.separator + ".globus" + File.separator
+ "coasters");
public static final String SCRIPT = "worker.pl";
public static final int OVERALLOCATION_FACTOR = 10;
public static final int MAX_WORKERS = 256;
public static final int MAX_STARTING_WORKERS = 32;
public static final List coasterAttributes =
Arrays.asList(new String[] { "coasterspernode", "coasterinternalip",
"coasterworkermaxwalltime" });
private SortedMap ready;
private Map ids;
private Set busy;
private Set startingTasks;
private Map requested;
private boolean shutdownFlag;
private LinkedList allocationRequests;
private File script;
private IDGenerator sr;
private URI callbackURI;
private LocalTCPService localService;
private TaskHandler handler;
private int currentWorkers;
public WorkerManager(LocalTCPService localService) throws IOException {
super("Worker Manager");
ready = new TreeMap();
busy = new HashSet();
ids = new HashMap();
startingTasks = new HashSet();
requested = new HashMap();
allocationRequests = new LinkedList();
this.localService = localService;
this.callbackURI = localService.getContact();
writeScript();
sr = new IDGenerator();
handler = new ExecutionTaskHandler();
}
private void writeScript() throws IOException {
scriptDir.mkdirs();
if (!scriptDir.exists()) {
throw new IOException("Failed to create script dir (" + scriptDir + ")");
}
script = File.createTempFile("cscript", ".pl", scriptDir);
script.deleteOnExit();
InputStream is = WorkerManager.class.getClassLoader().getResourceAsStream(SCRIPT);
if (is == null) {
throw new IOException("Could not find resource in class path: " + SCRIPT);
}
FileOutputStream fos = new FileOutputStream(script);
byte[] buf = new byte[1024];
int len = is.read(buf);
while (len != -1) {
fos.write(buf, 0, len);
len = is.read(buf);
}
fos.close();
is.close();
}
public void run() {
try {
if (logger.isInfoEnabled()) {
startInfoThread();
}
AllocationRequest req;
while (!shutdownFlag) {
synchronized (allocationRequests) {
while (allocationRequests.isEmpty()) {
allocationRequests.wait();
}
req = (AllocationRequest) allocationRequests.removeFirst();
if (logger.isInfoEnabled()) {
logger.info("Got allocation request: " + req);
}
}
try {
startWorker(new Seconds(req.maxWallTime.getSeconds()).multiply(
OVERALLOCATION_FACTOR).add(TIME_RESERVE), req.prototype);
}
catch (NoClassDefFoundError e) {
req.prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(),
new TaskSubmissionException(e)));
}
catch (Exception e) {
req.prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (Error e) {
e.printStackTrace();
System.exit(126);
}
}
private void startWorker(Seconds maxWallTime, Task prototype)
throws InvalidServiceContactException, InvalidProviderException,
ProviderMethodException {
int numWorkers = this.getCoastersPerNode(prototype);
String workerMaxwalltimeString =
(String) ((JobSpecification) prototype.getSpecification()).getAttribute("coasterWorkerMaxwalltime");
if (workerMaxwalltimeString != null) {
// override the computed maxwalltime
maxWallTime = new Seconds(WallTime.timeToSeconds(workerMaxwalltimeString));
int taskSeconds = AssociatedTask.getMaxWallTime(prototype).getSeconds();
if (TIME_RESERVE.add(taskSeconds).isGreaterThan(maxWallTime)) {
prototype.setStatus(new StatusImpl(Status.FAILED,
"Job cannot be run with the given max walltime worker constraint (task: "
+ taskSeconds + ", maxwalltime: " + maxWallTime + ")", null));
return;
}
logger.debug("Overridden worker maxwalltime is " + maxWallTime);
}
logger.info("Starting new worker set with " + numWorkers + " workers");
Task t = new TaskImpl();
t.setType(Task.JOB_SUBMISSION);
t.setSpecification(buildSpecification(prototype));
copyAttributes(t, prototype, maxWallTime);
t.setRequiredService(1);
t.setService(0, buildService(prototype));
synchronized (this) {
if (!startingTasks.contains(prototype)) {
return;
}
}
Map newlyRequested = new HashMap();
for (int n = 0; n < numWorkers; n++) {
int id = sr.nextInt();
if (logger.isInfoEnabled()) {
logger.info("Starting worker with id=" + id + " and maxwalltime=" + maxWallTime
+ "s");
}
String sid = String.valueOf(id);
((JobSpecification) t.getSpecification()).addArgument(sid);
try {
Worker wr = new Worker(this, sid, maxWallTime, t, prototype);
newlyRequested.put(sid, wr);
}
catch (Exception e) {
prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
}
try {
handler.submit(t);
}
catch (Exception e) {
prototype.setStatus(new StatusImpl(Status.FAILED, e.getMessage(), e));
}
synchronized (this) {
requested.putAll(newlyRequested);
}
}
private JobSpecification buildSpecification(Task prototype) {
JobSpecification ps = (JobSpecification) prototype.getSpecification();
JobSpecification js = new JobSpecificationImpl();
js.setExecutable("/usr/bin/perl");
js.addArgument(script.getAbsolutePath());
String internalHostname = (String) ps.getAttribute("coasterInternalIP");
if (internalHostname != null) { // override automatically determined
// hostname
// TODO detect if we've done this already for a different
// value? (same non-determinism as for coastersPerWorker and
// walltime handling that jobs may come in with different
// values and we can only use one)
try {
logger.warn("original callback URI is " + callbackURI.toString());
callbackURI =
new URI(callbackURI.getScheme(), callbackURI.getUserInfo(),
internalHostname, callbackURI.getPort(), callbackURI.getPath(),
callbackURI.getQuery(), callbackURI.getFragment());
logger.warn("callback URI has been overridden to " + callbackURI.toString());
}
catch (URISyntaxException use) {
throw new RuntimeException(use);
}
// TODO nasty exception in the line above
}
js.addArgument(callbackURI.toString());
// js.addArgument(id);
return js;
}
private ExecutionService buildService(Task prototype) throws InvalidServiceContactException,
InvalidProviderException, ProviderMethodException {
ExecutionService s = new ExecutionServiceImpl();
s.setServiceContact(prototype.getService(0).getServiceContact());
ExecutionService p = (ExecutionService) prototype.getService(0);
String jm = p.getJobManager();
int colon = jm.indexOf(':');
// remove provider used to bootstrap coasters
jm = jm.substring(colon + 1);
colon = jm.indexOf(':');
if (colon == -1) {
s.setProvider(jm);
}
else {
s.setJobManager(jm.substring(colon + 1));
s.setProvider(jm.substring(0, colon));
}
if (p.getSecurityContext() != null) {
s.setSecurityContext(p.getSecurityContext());
}
else {
s.setSecurityContext(AbstractionFactory.newSecurityContext(s.getProvider()));
}
return s;
}
private void copyAttributes(Task t, Task prototype, Seconds maxWallTime) {
JobSpecification pspec = (JobSpecification) prototype.getSpecification();
JobSpecification tspec = (JobSpecification) t.getSpecification();
Iterator i = pspec.getAttributeNames().iterator();
while (i.hasNext()) {
String name = (String) i.next();
if (!coasterAttributes.contains(name)) {
tspec.setAttribute(name, pspec.getAttribute(name));
}
}
tspec.setAttribute("maxwalltime", new WallTime((int) maxWallTime.getSeconds()).format());
}
private int k;
private long last;
public Worker request(WallTime maxWallTime, Task prototype) throws InterruptedException {
WorkerKey key =
new WorkerKey(new Seconds(maxWallTime.getSeconds()).add(TIME_RESERVE).add(
Seconds.now()));
Worker w = null;
if (logger.isDebugEnabled()) {
logger.debug("Looking for worker for key " + key);
logger.debug("Ready: " + ready);
}
synchronized (this) {
Collection tm = ready.tailMap(key).values();
Iterator i = tm.iterator();
if (i.hasNext()) {
w = (Worker) i.next();
i.remove();
if (!w.isFailed()) {
busy.add(w);
}
else {
currentWorkers
ids.remove(w.getId());
}
startingTasks.remove(prototype);
}
}
if (w != null) {
if (k == 0) {
last = System.currentTimeMillis();
}
if (++k % 100 == 0) {
long crt = System.currentTimeMillis();
int js = 0;
if (last != 0) {
js = (int) (80000 / (crt - last));
}
last = crt;
System.err.println(" " + k / 80 + "; " + js + " J/s");
}
logger.info("Using worker " + w + " for task " + prototype);
w.setRunning(prototype);
return w;
}
else {
synchronized (this) {
if (currentWorkers >= MAX_WORKERS) {
this.wait(250);
return null;
}
boolean alreadyThere;
alreadyThere = !startingTasks.add(prototype);
if (!alreadyThere) {
currentWorkers += getCoastersPerNode(prototype);
if (logger.isInfoEnabled()) {
logger.info("No suitable worker found. Attempting to start a new one.");
}
synchronized (allocationRequests) {
if (allocationRequests.size() < MAX_STARTING_WORKERS) {
allocationRequests.add(new AllocationRequest(maxWallTime, prototype));
allocationRequests.notify();
}
else {
this.wait(250);
return null;
}
}
}
}
return null;
}
}
public void workerTerminated(Worker worker) {
if (logger.isInfoEnabled()) {
logger.info("Worker terminated: " + worker);
}
Status s = worker.getStatus();
Task running = worker.getRunning();
synchronized (this) {
if (s.getStatusCode() == Status.FAILED || requested.containsKey(worker.getId())) {
if (logger.isInfoEnabled()) {
logger.info("Failed or starting: " + worker);
}
worker.setFailed(true);
if (s.getStatusCode() != Status.FAILED) {
worker.setStatus(new StatusImpl(Status.FAILED, "Worker ended prematurely", null));
}
if (requested.remove(worker.getId()) != null) {
startingTasks.remove(running);
// only do this for workers that haven't quite started
// yet
// this will cause all the jobs associated with the worker
// fail. We want at least one job to fail for each starting
// failed worker in order to avoid a deadlock and notify
// the user of potential problems
ready.put(new WorkerKey(worker), worker);
// but now that we're doing this, make sure the worker has
// a chance of being selected
worker.setScheduledTerminationTime(Seconds.NEVER);
return;
}
}
currentWorkers
if (busy.remove(worker)) {
if (logger.isInfoEnabled()) {
logger.info(worker + " was busy");
}
}
if (ready.remove(new WorkerKey(worker)) != null) {
if (logger.isInfoEnabled()) {
logger.info(worker + " was ready");
}
}
ids.remove(worker.getId());
}
if (running != null) {
running.setStatus(new StatusImpl(Status.FAILED,
"Worker terminated while job was running", null));
}
}
public void registrationReceived(String id, String url, ChannelContext cc) {
Worker wr;
synchronized (this) {
wr = (Worker) requested.remove(id);
}
if (wr == null) {
logger.warn("Received unrequested registration (id = " + id + ", url = " + url);
throw new IllegalArgumentException("Invalid worker id (" + id
+ "). This worker manager instance does not "
+ "recall requesting a worker with such an id.");
}
wr.setScheduledTerminationTime(Seconds.now().add(wr.getMaxWallTime()));
wr.setChannelContext(cc);
if (logger.isInfoEnabled()) {
logger.info("Worker registration received: " + wr);
}
synchronized (this) {
startingTasks.remove(wr.getRunning());
ready.put(new WorkerKey(wr), wr);
ids.put(id, wr);
wr.workerRegistered();
}
}
public void removeWorker(Worker worker) {
synchronized (this) {
ready.remove(new WorkerKey(worker));
currentWorkers
busy.remove(worker);
startingTasks.remove(worker.getRunning());
ids.remove(worker.getId());
}
}
public void workerTaskDone(Worker wr) {
synchronized (this) {
busy.remove(wr);
ready.put(new WorkerKey(wr), wr);
notifyAll();
wr.setRunning(null);
}
}
public int availableWorkers() {
synchronized (this) {
return ready.size();
}
}
public ChannelContext getChannelContext(String id) {
Worker wr = (Worker) ids.get(id);
if (wr == null) {
throw new IllegalArgumentException("No worker with id=" + id);
}
else {
return wr.getChannelContext();
}
}
protected TaskHandler getTaskHandler() {
return handler;
}
protected int getCoastersPerNode(Task t) {
String numWorkersString =
(String) ((JobSpecification) t.getSpecification()).getAttribute("coastersPerNode");
if (numWorkersString == null) {
return 1;
}
else {
return Integer.parseInt(numWorkersString);
}
}
private static class AllocationRequest {
public WallTime maxWallTime;
public Task prototype;
public AllocationRequest(WallTime maxWallTime, Task prototype) {
this.maxWallTime = maxWallTime;
this.prototype = prototype;
}
}
public void shutdown() {
try {
synchronized (this) {
Iterator i;
List callbacks = new ArrayList();
i = ready.values().iterator();
while (i.hasNext()) {
Worker wr = (Worker) i.next();
callbacks.add(wr.shutdown());
}
i = callbacks.iterator();
while (i.hasNext()) {
ShutdownCallback cb = (ShutdownCallback) i.next();
if (cb != null) {
cb.waitFor();
}
}
i = new ArrayList(requested.values()).iterator();
while (i.hasNext()) {
Worker wr = (Worker) i.next();
try {
handler.cancel(wr.getWorkerTask());
}
catch (Exception e) {
logger.warn("Failed to cancel queued worker task " + wr.getWorkerTask(), e);
}
}
}
}
catch (InterruptedException e) {
logger.warn("Interrupted", e);
}
}
private void startInfoThread() {
new Thread() {
{
setDaemon(true);
}
public void run() {
while (true) {
try {
Thread.sleep(20000);
synchronized (WorkerManager.this) {
logger.info("Current workers: " + currentWorkers);
logger.info("Ready: " + ready);
logger.info("Busy: " + busy);
logger.info("Requested: " + requested);
logger.info("Starting: " + startingTasks);
logger.info("Ids: " + ids);
}
synchronized (allocationRequests) {
logger.info("AllocationR: " + allocationRequests);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
} |
package com.diozero;
import com.diozero.api.AnalogInputDevice;
import com.diozero.internal.DeviceFactoryHelper;
import com.diozero.internal.spi.AnalogInputDeviceFactoryInterface;
import com.diozero.util.RuntimeIOException;
public class LDR extends AnalogInputDevice {
private float vRef;
private float r1;
/**
* @param pinNumber Pin to which the LDR is connected.
* @param vRef Reference voltage.
* @param r1 Resistor between the LDR and ground.
* @throws RuntimeIOException If an I/O error occurred.
*/
public LDR(int pinNumber, float vRef, float r1) throws RuntimeIOException {
this(DeviceFactoryHelper.getNativeDeviceFactory(), pinNumber, vRef, r1);
}
/**
* @param deviceFactory Device factory to use to construct the device.
* @param pinNumber Pin to which the LDR is connected.
* @param vRef Reference voltage.
* @param r1 Resistor between the LDR and ground.
* @throws RuntimeIOException If an I/O error occurred.
*/
public LDR(AnalogInputDeviceFactoryInterface deviceFactory, int pinNumber,
float vRef, float r1) throws RuntimeIOException {
super(deviceFactory, pinNumber, vRef);
this.vRef = vRef;
this.r1 = r1;
}
/**
* Read the resistance across the LDR.
* @return Resistance (Ohms)
* @throws RuntimeIOException If an I/O error occurred.
*/
public float getLdrResistance() throws RuntimeIOException {
// Get the scaled value (voltage)
float v_ldr = getScaledValue();
return r1 / (vRef / v_ldr - 1);
}
/**
* Read the LDR luminosity. <strong>Not yet implemented</strong> (not sure if this can be reliably implemented).
* @return Luminosity (lux).
* @throws RuntimeIOException If an I/O error occurred.
*/
private float getLuminosity() throws RuntimeIOException {
// Get the scaled value (voltage)
float v_ldr = getScaledValue();
float r_ldr = getLdrResistance();
// FIXME Can this be reliably calculated?
// rLDR = 500 / Lux
// Lux = (vRef*500/V(LDR) - 500) / R
//double lux = (vRef * 500 / v_ldr - 500) / r;
//Logger.debug("Lux={}", lux);
//double lux = 500 * (vRef - v_ldr) / (r + v_ldr);
// I[lux] = 10000 / (R[kohms]*10)^(4/3)
return r_ldr;
}
} |
package org.levigo.jadice.server.converterclient.gui.inspector;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import org.controlsfx.control.MasterDetailPane;
import org.controlsfx.control.PropertySheet;
import org.controlsfx.control.PropertySheet.Item;
import org.controlsfx.property.BeanPropertyUtils;
import org.levigo.jadice.server.converterclient.JobCard;
import org.levigo.jadice.server.converterclient.JobCardFactory;
import org.levigo.jadice.server.converterclient.configurations.WorkflowConfiguration;
import org.levigo.jadice.server.converterclient.gui.ComponentWrapper;
import org.levigo.jadice.server.converterclient.gui.inspector.WorkflowLayout.Type;
import org.levigo.jadice.server.converterclient.util.UiUtil;
import com.levigo.jadice.server.Job;
import com.levigo.jadice.server.Node;
import com.levigo.jadice.server.client.JobFactory;
import com.levigo.jadice.server.client.jms.JMSJobFactory;
import javafx.application.Platform;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.cell.ComboBoxListCell;
import javafx.scene.layout.BorderPane;
import javafx.util.StringConverter;
public class ConfigurationInspectorPaneController implements NodeSelectionListener {
private static final Logger LOGGER = Logger.getLogger(ConfigurationInspectorPaneController.class);
private static final String[] HIDDEN_NODE_PROPERTY_NAMES = new String[] {
"UUID", "job", "limits", "nodeLimits",
"inputCardinality", "outputCardinality", "streamBundle",
"predecessors", "successors", "subsidiaryNodes"
};
private static final Set<String> HIDDEN_NODE_PROPERTY_NAMES_SET = new HashSet<>(Arrays.asList(HIDDEN_NODE_PROPERTY_NAMES));
@FXML
private ComboBox<WorkflowConfiguration> configurations;
@FXML
private ComboBox<WorkflowLayout.Type> layouts;
@FXML
private Button home;
@FXML
private Button exportJava;
@FXML
MasterDetailPane masterDetailPane;
@FXML
private BorderPane displayPane;
@FXML
private PropertySheet propertySheet;
private final WorkflowDisplay display = new WorkflowDisplay();
private final JobFactory dummyJobFactory = initDummyJobFactory();
@FXML
protected void initialize() {
UiUtil.configureHomeButton(home);
initConfigurationCB();
final ObservableList<Type> layoutValues = FXCollections.observableArrayList(WorkflowLayout.Type.values());
layouts.setItems(layoutValues);
layouts.setCellFactory(ComboBoxListCell.forListView(layoutValues));
layouts.valueProperty().addListener((observable, oldValue, newValue) -> {
SwingUtilities.invokeLater(() -> {
display.setGraphLayout(newValue);
});
});
layouts.setValue(layouts.getItems().get(0));
display.addSelectionListener(this);
displayPane.setCenter(new ComponentWrapper<>(display));
masterDetailPane.showDetailNodeProperty().bind(new SimpleListProperty<>(propertySheet.getItems()).emptyProperty().not());
}
@FXML
protected void exportJava() {
final String java = CodeGenerator.exportJavaImplementation(display.getJob());
LOGGER.info("Created java code:\n" + java);
}
private JobFactory initDummyJobFactory() {
return new JMSJobFactory(new DummyQueueConnectionFactory(), "DUMMY");
}
private void initConfigurationCB() {
configurations.itemsProperty().bind(new SimpleListProperty<>(JobCardFactory.getInstance().getConfigurations()));
final StringConverter<WorkflowConfiguration> sc = new StringConverter<WorkflowConfiguration>() {
@Override
public String toString(WorkflowConfiguration object) {
return String.format("%s [%s]", object.getDescription(), object.getID());
}
@Override
public WorkflowConfiguration fromString(String string) {
return null;
}
};
configurations.setCellFactory(ComboBoxListCell.forListView(sc, configurations.getItems()));
configurations.setButtonCell(new ComboBoxListCell<>(sc, configurations.getItems()));
configurations.setValue(configurations.getItems().get(0));
configurations.valueProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == null) {
clearGraph();
return;
}
try {
showGraph(newValue);
} catch (Exception e) {
LOGGER.error("Error when showing workflow configuration", e);
}
});
}
private void clearGraph() {
display.clear();
}
public void showGraph(JobCard jobCard) {
SwingUtilities.invokeLater(() -> {
display.showJob(jobCard.job);
});
}
private void showGraph(WorkflowConfiguration item) throws Exception {
final Job dummyJob = item.configureWorkflow(dummyJobFactory);
SwingUtilities.invokeLater(() -> {
display.showJob(dummyJob);
});
}
public void deselected(Node deselected) {
LOGGER.debug("DESELECTED: " + deselected);
Platform.runLater(() -> {
propertySheet.getItems().clear();
});
}
public void selected(final Node selected) {
LOGGER.debug("SELECTED: " + selected);
final ObservableList<Item> properties = BeanPropertyUtils.getProperties(selected, item -> !HIDDEN_NODE_PROPERTY_NAMES_SET.contains(item.getName()));
properties.stream().forEach(item -> {
try {
item.getValue();
} catch (Exception e) {
LOGGER.error("Could not read property " + item.getName(), e);
}
});
Platform.runLater(() -> {
propertySheet.getItems().clear();
propertySheet.getItems().addAll(properties);
}) ;
}
} |
package org.imirsel.nema.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GenerationType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Proxy;
/**
* Represents a Meandre flow.
*
* @author shirk
*/
@Entity
@Table(name="flow")
@Proxy(lazy=false)
public class Flow implements Serializable {
/**
* Version of this class.
*/
private static final long serialVersionUID = 8013326562531128503L;
private Long id;
private String name;
private String description;
private Date dateCreated;
private String keyWords;
private Boolean template = false;
private String url;
private Long creatorId;
private Flow instanceOf = null;
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="name",nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="description",nullable=false)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name="dateCreated",nullable=false)
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
@Column(name="keyWords",nullable=false)
public String getKeyWords() {
return keyWords;
}
public void setKeyWords(String keyWords) {
this.keyWords = keyWords;
}
@Column(name="isTemplate",nullable=false)
public Boolean isTemplate() {
return template;
}
public void setTemplate(Boolean template) {
this.template = template;
}
@Column(name="url",nullable=false)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Column(name="creatorId",nullable=false)
public Long getCreatorId() {
return creatorId;
}
public void setCreatorId(Long creatorId) {
this.creatorId = creatorId;
}
@JoinColumn(name = "instanceOf", nullable=true)
@ManyToOne(fetch=FetchType.EAGER)
public Flow getInstanceOf() {
return instanceOf;
}
public void setInstanceOf(Flow instanceOf) {
this.instanceOf = instanceOf;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((creatorId == null) ? 0 : creatorId.hashCode());
result = prime * result
+ ((dateCreated == null) ? 0 : dateCreated.hashCode());
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((instanceOf == null) ? 0 : instanceOf.hashCode());
result = prime * result
+ ((template == null) ? 0 : template.hashCode());
result = prime * result
+ ((keyWords == null) ? 0 : keyWords.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Flow other = (Flow) obj;
if (creatorId == null) {
if (other.creatorId != null)
return false;
} else if (!creatorId.equals(other.creatorId))
return false;
if (dateCreated == null) {
if (other.dateCreated != null)
return false;
} else if (!dateCreated.equals(other.dateCreated))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (instanceOf == null) {
if (other.instanceOf != null)
return false;
} else if (!instanceOf.equals(other.instanceOf))
return false;
if (template == null) {
if (other.template != null)
return false;
} else if (!template.equals(other.template))
return false;
if (keyWords == null) {
if (other.keyWords != null)
return false;
} else if (!keyWords.equals(other.keyWords))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
}
} |
package org.jbehave.scenario.reporters;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.jbehave.Ensure.ensureThat;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.jbehave.scenario.Scenario;
import org.jbehave.scenario.definition.Blurb;
import org.jbehave.scenario.definition.ExamplesTable;
import org.jbehave.scenario.definition.ScenarioDefinition;
import org.jbehave.scenario.definition.StoryDefinition;
import org.jbehave.scenario.i18n.I18nKeyWords;
import org.jbehave.scenario.parser.UnderscoredCamelCaseResolver;
import org.junit.Test;
public class PrintStreamScenarioReporterBehaviour {
@Test
public void shouldReportEventsToPrintStream() {
// Given
OutputStream out = new ByteArrayOutputStream();
ScenarioReporter reporter = new PrintStreamScenarioReporter(new PrintStream(out));
// When
narrateAnInterestingStory(reporter);
// Then
String expected =
"An interesting story\n" +
"Scenario: I ask for a loan\n" +
"GivenScenarios: [/given/scenario1,/given/scenario2]\n" +
"Given I have a balance of $50\n" +
"When I request $20\n" +
"When I ask Liz for a loan of $100\n" +
"Then I should have a balance of $30 (PENDING)\n" +
"Then I should have $20 (NOT PERFORMED)\n" +
"Then I don't return loan (FAILED)\n" +
"Examples:\n\n" +
"|money|to|\n" +
"|$30|Mauro|\n" +
"|$50|Paul|\n" +
"\n\n" + // Examples table
"\nExample: {to=Mauro, money=$30}\n" +
"\nExample: {to=Paul, money=$50}\n" +
"\n\n"; // end of scenario and story
ensureThatOutputIs(out, expected);
}
@Test
public void shouldReportEventsToHtmlPrintStream() {
// Given
final OutputStream out = new ByteArrayOutputStream();
PrintStreamFactory factory = new PrintStreamFactory() {
public PrintStream getPrintStream() {
return new PrintStream(out);
}
};
ScenarioReporter reporter = new HtmlPrintStreamScenarioReporter(factory.getPrintStream());
// When
narrateAnInterestingStory(reporter);
// Then
String expected =
"<div class=\"story\">\n<h1>An interesting story</h1>\n(/path/to/story)\n" +
"<div class=\"scenario\">\n<h2>Scenario: I ask for a loan</h2>\n" +
"<div class=\"givenScenarios\">GivenScenarios: [/given/scenario1,/given/scenario2]</div>\n" +
"<div class=\"step.successful\">Given I have a balance of $50</div>\n" +
"<div class=\"step.successful\">When I request $20</div>\n" +
"<div class=\"step.successful\">When I ask Liz for a loan of $100</div>\n" +
"<div class=\"step.pending\">Then I should have a balance of $30<span class=\"keyword.pending\">(PENDING)</span></div>\n" +
"<div class=\"step.notPerformed\">Then I should have $20<span class=\"keyword.notPerformed\">(NOT PERFORMED)</span></div>\n" +
"<div class=\"step.failed\">Then I don't return loan<span class=\"keyword.failed\">(FAILED)</span></div>\n" +
"<h3 class=\"examplesTable\">Examples:</h3>\n<table class=\"examplesTable\">\n<thead>\n<tr>\n<th>to</th><th>money</th></tr>\n</thead>\n<tbody>\n<tr>\n<td>Mauro</td><td>$30</td></tr>\n<tr>\n<td>Paul</td><td>$50</td></tr>\n</tbody>\n</table>\n"+
"\n<h3 class=\"examplesTableRow\">Example: {to=Mauro, money=$30}</h3>\n" +
"\n<h3 class=\"examplesTableRow\">Example: {to=Paul, money=$50}</h3>\n"+
"</div>\n</div>\n"; // end of scenario and story
ensureThatOutputIs(out, expected);
}
private void narrateAnInterestingStory(ScenarioReporter reporter) {
StoryDefinition story = new StoryDefinition(new Blurb("An interesting story"), new ArrayList<ScenarioDefinition>(), "/path/to/story");
boolean embeddedStory = true;
reporter.beforeStory(story, embeddedStory);
String title = "I ask for a loan";
reporter.beforeScenario(title);
reporter.givenScenarios(asList("/given/scenario1,/given/scenario2"));
reporter.successful("Given I have a balance of $50");
reporter.successful("When I request $20");
reporter.successful("When I ask Liz for a loan of $100");
reporter.pending("Then I should have a balance of $30");
reporter.notPerformed("Then I should have $20");
reporter.failed("Then I don't return loan", new Exception("Naughty me!"));
ExamplesTable table = new ExamplesTable("|money|to|\n|$30|Mauro|\n|$50|Paul|\n");
reporter.examplesTable(table);
reporter.examplesTableRow(table.getRow(0));
reporter.examplesTableRow(table.getRow(1));
reporter.afterScenario();
reporter.afterStory(embeddedStory);
}
private void ensureThatOutputIs(OutputStream out, String expected) {
// JUnit assertion allows easier comparison of strings in IDE
assertEquals(expected, dos2unix(out.toString()));
//ensureThat(out.toString(), equalTo(expected));
}
private String dos2unix(String string) {
return string.replace("\r\n", "\n");
}
@Test
public void shouldReportThrowablesWhenToldToDoSo() {
// Given
IllegalAccessException exception = new IllegalAccessException("Leave my money alone!");
OutputStream stackTrace = new ByteArrayOutputStream();
exception.printStackTrace(new PrintStream(stackTrace));
OutputStream out = new ByteArrayOutputStream();
ScenarioReporter reporter = new PrintStreamScenarioReporter(new PrintStream(out), new Properties(), new I18nKeyWords(), true);
// When
reporter.beforeScenario("A title");
reporter.successful("Given I have a balance of $50");
reporter.successful("When I request $20");
reporter.failed("When I ask Liz for a loan of $100", exception);
reporter.pending("Then I should have a balance of $30");
reporter.notPerformed("Then I should have $20");
reporter.afterScenario();
// Then
String expected =
"Scenario: A title\n" +
"Given I have a balance of $50\n" +
"When I request $20\n" +
"When I ask Liz for a loan of $100 (FAILED)\n" +
"Then I should have a balance of $30 (PENDING)\n" +
"Then I should have $20 (NOT PERFORMED)\n" +
"\n" + dos2unix(stackTrace.toString()) + "\n";
ensureThatOutputIs(out, expected);
// Given
out = new ByteArrayOutputStream();
reporter = new PrintStreamScenarioReporter(new PrintStream(out));
// When
reporter.beforeScenario("A title");
reporter.successful("Given I have a balance of $50");
reporter.successful("When I request $20");
reporter.failed("When I ask Liz for a loan of $100", exception);
reporter.pending("Then I should have a balance of $30");
reporter.notPerformed("Then I should have $20");
reporter.afterScenario();
// Then
ensureThat(!out.toString().contains(stackTrace.toString()));
}
@Test
public void shouldReportEventsToPrintStreamWithCustomPatterns() {
// Given
IllegalAccessException exception = new IllegalAccessException("Leave my money alone!");
OutputStream out = new ByteArrayOutputStream();
Properties patterns = new Properties();
patterns.setProperty("pending", "{0} - {1} - need to implement me\n");
patterns.setProperty("failed", "{0} <<< {1}\n");
patterns.setProperty("notPerformed", "{0} : {1} (because of previous pending)\n");
ScenarioReporter reporter = new PrintStreamScenarioReporter(new PrintStream(out), patterns, new I18nKeyWords(), true);
// When
reporter.successful("Given I have a balance of $50");
reporter.successful("When I request $20");
reporter.failed("When I ask Liz for a loan of $100", exception);
reporter.pending("Then I should have a balance of $30");
reporter.notPerformed("Then I should have $20");
// Then
String expected = "Given I have a balance of $50\n" +
"When I request $20\n" +
"When I ask Liz for a loan of $100 <<< FAILED\n" +
"Then I should have a balance of $30 - PENDING - need to implement me\n" +
"Then I should have $20 : NOT PERFORMED (because of previous pending)\n";
ensureThatOutputIs(out, expected);
}
@Test
public void shouldReportEventsToPrintStreamInItalian() {
// Given
IllegalAccessException exception = new IllegalAccessException("Lasciate in pace i miei soldi!");
OutputStream out = new ByteArrayOutputStream();
I18nKeyWords keywords = new I18nKeyWords(Locale.ITALIAN);
ScenarioReporter reporter = new PrintStreamScenarioReporter(new PrintStream(out), new Properties(), keywords, true);
// When
reporter.successful("Dato che ho un saldo di $50");
reporter.successful("Quando richiedo $20");
reporter.failed("Quando chiedo a Liz un prestito di $100", exception);
reporter.pending("Allora dovrei avere un saldo di $30");
reporter.notPerformed("Allora dovrei avere $20");
// Then
String expected =
"Dato che ho un saldo di $50\n" +
"Quando richiedo $20\n" +
"Quando chiedo a Liz un prestito di $100 (FALLITO)\n" +
"Allora dovrei avere un saldo di $30 (PENDENTE)\n" +
"Allora dovrei avere $20 (NON ESEGUITO)\n";
ensureThatOutputIs(out, expected);
}
@Test
public void shouldCreateAndWriteToFilePrintStreamForScenarioClass() throws IOException{
UnderscoredCamelCaseResolver converter = new UnderscoredCamelCaseResolver(".scenario");
// Given
Class<MyScenario> scenarioClass = MyScenario.class;
File file = fileFor(scenarioClass, converter);
file.delete();
ensureThat(!file.exists());
// When
FilePrintStreamFactory factory = new FilePrintStreamFactory(scenarioClass, converter);
PrintStream printStream = factory.getPrintStream();
printStream.print("Hello World");
// Then
ensureThat(file.exists());
ensureThat(IOUtils.toString(new FileReader(file)), equalTo("Hello World"));
}
private File fileFor(Class<MyScenario> scenarioClass, UnderscoredCamelCaseResolver converter) {
File outputDirectory = FilePrintStreamFactory.outputDirectory(scenarioClass);
String fileName = FilePrintStreamFactory.fileName(scenarioClass, converter, FilePrintStreamFactory.HTML);
return new File(outputDirectory, fileName);
}
private static class MyScenario extends Scenario {
}
} |
package org.joda.modulenames;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.INFO;
import static java.lang.System.Logger.Level.WARNING;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
class Bucket implements AutoCloseable {
private static final System.Logger LOG = System.getLogger(Bucket.class.getName());
private static final int MAX_KEYS_PER_PAGE = 1000;
private final String bucketName;
private final Path cache;
private final AmazonS3 s3;
private final FileSystem zipfs;
Bucket(String bucketName, String bucketRegion) throws IOException {
this.bucketName = bucketName;
this.s3 = AmazonS3ClientBuilder.standard().withRegion(bucketRegion).build();
try {
if (!s3.doesBucketExistV2(bucketName)) {
var message = String.format("Bucket %s not found in %s", bucketName, bucketRegion);
throw new IllegalArgumentException(message);
}
} catch (AmazonS3Exception e) {
throw new IllegalArgumentException("Illegal bucket name or region?", e);
}
var loader = getClass().getClassLoader();
this.cache = Path.of("etc", "cache", bucketName);
var zipfile = cache.resolve(bucketName + ".zip");
if (Files.exists(zipfile)) {
this.zipfs = FileSystems.newFileSystem(zipfile, loader);
if (LOG.isLoggable(INFO)) {
var count = Files.list(zipfs.getPath("/")).count();
LOG.log(INFO, "{0} entries in {1}", count, zipfs);
}
} else {
this.zipfs = null;
}
}
@Override
public void close() {
s3.shutdown();
if (zipfs != null) {
try {
zipfs.close();
} catch (IOException e) {
LOG.log(WARNING, "Closing file system failed!", e);
}
}
}
List<String> getKeys(int limit, String after) {
if (limit < 0) {
throw new IllegalArgumentException("limit must not be negative: " + limit);
}
if (limit == 0) {
return List.of();
}
if (after == null) {
throw new IllegalArgumentException("after must not be null");
}
LOG.log(INFO, "Get keys from {0} bucket (limit={1}, after={2})...", bucketName, limit, after);
var keys = new ArrayList<String>();
var bytes = 0L;
var request = new ListObjectsV2Request().withBucketName(bucketName);
if (!after.isBlank()) {
LOG.log(INFO, "Set start after to: {0}", after);
request.setStartAfter(after);
}
while (true) {
var pendingKeys = limit - keys.size();
if (pendingKeys <= 0) {
LOG.log(DEBUG, "No more keys are pending: done.");
break;
}
request.setMaxKeys(Math.min(pendingKeys, MAX_KEYS_PER_PAGE));
LOG.log(INFO, "Get objects list... (max={0})", request.getMaxKeys());
var objects = s3.listObjectsV2(request);
var summaries = objects.getObjectSummaries();
for (var summary : summaries) {
LOG.log(DEBUG, " o {0} (bytes: {1})", summary.getKey(), summary.getSize());
keys.add(summary.getKey());
bytes += summary.getSize();
}
LOG.log(INFO, " - {0} objects retrieved", keys.size());
if (!objects.isTruncated()) {
LOG.log(DEBUG, "Objects result is not truncated: done.");
break;
}
request.setContinuationToken(objects.getNextContinuationToken());
}
LOG.log(INFO, "Got {0} keys (bytes: {1})", keys.size(), bytes);
return keys;
}
void processObject(String key, Consumer<String> consumeLine) throws IOException {
Path path = toPath(key);
LOG.log(INFO, "Processing {0} by reading lines from {1}...", key, path);
Files.readAllLines(path).forEach(consumeLine);
}
private Path toPath(String key) throws IOException {
if (zipfs != null) {
var zip = zipfs.getPath(key);
if (Files.exists(zip)) {
LOG.log(DEBUG, "Extracting {0} from {1}...", key, zipfs);
return zip;
}
}
var csv = cache.resolve(key);
if (Files.notExists(csv)) {
LOG.log(DEBUG, "Downloading {0} from remote {1}...", key, bucketName);
Files.createDirectories(cache);
try (var object = s3.getObject(new GetObjectRequest(bucketName, key))) {
Files.copy(object.getObjectContent().getDelegateStream(), csv);
}
LOG.log(DEBUG, "Loaded {0} bytes to {1}", Files.size(csv), csv);
}
return csv;
}
} |
package prefuse.action.assignment;
import java.util.logging.Logger;
import prefuse.Constants;
import prefuse.data.tuple.TupleSet;
import prefuse.util.DataLib;
import prefuse.util.MathLib;
import prefuse.util.PrefuseLib;
import prefuse.visual.VisualItem;
public class DataSizeAction extends SizeAction {
protected static final double NO_SIZE = Double.NaN;
protected String m_dataField;
protected double m_minSize = 1;
protected double m_sizeRange;
protected int m_scale = Constants.LINEAR_SCALE;
protected int m_bins = Constants.CONTINUOUS;
protected boolean m_inferBounds = true;
protected boolean m_inferRange = true;
protected boolean m_is2DArea = true;
protected double[] m_dist;
protected int m_tempScale;
/**
* Create a new DataSizeAction.
* @param group the data group to process
* @param field the data field to base size assignments on
*/
public DataSizeAction(String group, String field) {
super(group, NO_SIZE);
m_dataField = field;
}
/**
* Create a new DataSizeAction.
* @param group the data group to process
* @param field the data field to base size assignments on
* @param bins the number of discrete size values to use
*/
public DataSizeAction(String group, String field, int bins) {
this(group, field, bins, Constants.LINEAR_SCALE);
}
/**
* Create a new DataSizeAction.
* @param group the data group to process
* @param field the data field to base size assignments on
* @param bins the number of discrete size values to use
* @param scale the scale type to use. One of
* {@link prefuse.Constants#LINEAR_SCALE},
* {@link prefuse.Constants#LOG_SCALE},
* {@link prefuse.Constants#SQRT_SCALE}, or
* {@link prefuse.Constants#QUANTILE_SCALE}. If a quantile scale is
* used, the number of bins must be greater than zero.
*/
public DataSizeAction(String group, String field, int bins, int scale) {
super(group, NO_SIZE);
m_dataField = field;
setScale(scale);
setBinCount(bins);
}
/**
* Returns the data field used to encode size values.
* @return the data field that is mapped to size values
*/
public String getDataField() {
return m_dataField;
}
/**
* Set the data field used to encode size values.
* @param field the data field to map to size values
*/
public void setDataField(String field) {
m_dataField = field;
}
/**
* Returns the scale type used for encoding size values from the data.
* @return the scale type. One of
* {@link prefuse.Constants#LINEAR_SCALE},
* {@link prefuse.Constants#LOG_SCALE},
* {@link prefuse.Constants#SQRT_SCALE},
* {@link prefuse.Constants#QUANTILE_SCALE}.
*/
public int getScale() {
return m_scale;
}
/**
* Set the scale (linear, square root, or log) to use for encoding size
* values from the data.
* @param scale the scale type to use. This value should be one of
* {@link prefuse.Constants#LINEAR_SCALE},
* {@link prefuse.Constants#SQRT_SCALE},
* {@link prefuse.Constants#LOG_SCALE},
* {@link prefuse.Constants#QUANTILE_SCALE}.
* If {@link prefuse.Constants#QUANTILE_SCALE} is used, the number of
* bins to use must also be specified to a value greater than zero using
* the {@link #setBinCount(int)} method.
*/
public void setScale(int scale) {
if ( scale < 0 || scale >= Constants.SCALE_COUNT )
throw new IllegalArgumentException(
"Unrecognized scale value: "+scale);
m_scale = scale;
}
/**
* Returns the number of "bins" or distinct categories of sizes
* @return the number of bins.
*/
public int getBinCount() {
return m_bins;
}
/**
* Sets the number of "bins" or distinct categories of sizes
* @param count the number of bins to set. The value
* {@link Constants#CONTINUOUS} indicates not to use any binning. If the
* scale type set using the {@link #setScale(int)} method is
* {@link Constants#QUANTILE_SCALE}, the bin count <strong>must</strong>
* be greater than zero.
*/
public void setBinCount(int count) {
if ( m_scale == Constants.QUANTILE_SCALE && count <= 0 ) {
throw new IllegalArgumentException(
"The quantile scale can not be used without binning. " +
"Use a bin value greater than zero.");
}
m_bins = count;
}
/**
* Indicates if the size values set by this function represent 2D areas.
* That is, if the size is a 2D area or a 1D length. The size value will
* be scaled appropriately to facilitate better perception of size
* differences.
* @return true if this instance is configured for area sizes, false for
* length sizes.
* @see prefuse.util.PrefuseLib#getSize2D(double)
*/
public boolean is2DArea() {
return m_is2DArea;
}
/**
* Sets if the size values set by this function represent 2D areas.
* That is, if the size is a 2D area or a 1D length. The size value will
* be scaled appropriately to facilitate better perception of size
* differences.
* @param isArea true to configure this instance for area sizes, false for
* length sizes
* @see prefuse.util.PrefuseLib#getSize2D(double)
*/
public void setIs2DArea(boolean isArea) {
m_is2DArea = isArea;
}
/**
* Gets the size assigned to the lowest-valued data items, typically 1.0.
* @return the size for the lowest-valued data items
*/
public double getMinimumSize() {
return m_minSize;
}
/**
* Sets the size assigned to the lowest-valued data items. By default,
* this value is 1.0.
* @param size the new size for the lowest-valued data items
*/
public void setMinimumSize(double size) {
if ( Double.isInfinite(size) ||
Double.isNaN(size) ||
size <= 0 )
{
throw new IllegalArgumentException("Minimum size value must be a "
+ "finite number greater than zero.");
}
if ( m_inferRange ) {
m_sizeRange += m_minSize - size;
}
m_minSize = size;
}
/**
* Gets the maximum size value that will be assigned by this action. By
* default, the maximum size value is determined automatically from the
* data, faithfully representing the scale differences between data values.
* However, this can sometimes result in very large differences. For
* example, if the minimum data value is 1.0 and the largest is 200.0, the
* largest items will be 200 times larger than the smallest. While
* accurate, this may not result in the most readable display. To correct
* these cases, use the {@link #setMaximumSize(double)} method to manually
* set the range of allowed sizes.
* @return the current maximum size. For the returned value to accurately
* reflect the size range used by this action, either the action must
* have already been run (allowing the value to be automatically computed)
* or the maximum size must have been explicitly set.
*/
public double getMaximumSize() {
return m_minSize + m_sizeRange;
}
/**
* Set the maximum size value that will be assigned by this action. By
* default, the maximum size value is determined automatically from the
* data, faithfully representing the scale differences between data values.
* However, this can sometimes result in very large differences. For
* example, if the minimum data value is 1.0 and the largest is 200.0, the
* largest items will be 200 times larger than the smallest. While
* accurate, this may not result in the most readable display. To correct
* these cases, use the {@link #setMaximumSize(double)} method to manually
* set the range of allowed sizes.
* @param maxSize the maximum size to use. If this value is less than or
* equal to zero, infinite, or not a number (NaN) then the input value
* will be ignored and instead automatic inference of the size range
* will be performed.
*/
public void setMaximumSize(double maxSize) {
if ( Double.isInfinite(maxSize) ||
Double.isNaN(maxSize) ||
maxSize <= 0 )
{
m_inferRange = true;
} else {
m_inferRange = false;
m_sizeRange = maxSize-m_minSize;
}
}
/**
* This operation is not supported by the DataSizeAction type.
* Calling this method will result in a thrown exception.
* @see prefuse.action.assignment.SizeAction#setDefaultSize(double)
* @throws UnsupportedOperationException
*/
public void setDefaultSize(double defaultSize) {
throw new UnsupportedOperationException();
}
/**
* @see prefuse.action.EncoderAction#setup()
*/
protected void setup() {
TupleSet ts = m_vis.getGroup(m_group);
// cache the scale value in case it gets changed due to error
m_tempScale = m_scale;
if ( m_inferBounds ) {
if ( m_scale == Constants.QUANTILE_SCALE && m_bins > 0 ) {
double[] values =
DataLib.toDoubleArray(ts.tuples(), m_dataField);
m_dist = MathLib.quantiles(m_bins, values);
} else {
// check for non-binned quantile scale error
if ( m_scale == Constants.QUANTILE_SCALE ) {
Logger.getLogger(getClass().getName()).warning(
"Can't use quantile scale with no binning. " +
"Defaulting to linear scale. Set the bin value " +
"greater than zero to use a quantile scale.");
m_scale = Constants.LINEAR_SCALE;
}
m_dist = new double[2];
m_dist[0]= DataLib.min(ts, m_dataField).getDouble(m_dataField);
m_dist[1]= DataLib.max(ts, m_dataField).getDouble(m_dataField);
}
if ( m_inferRange ) {
m_sizeRange = m_dist[m_dist.length-1]/m_dist[0] - m_minSize;
}
}
}
/**
* @see prefuse.action.EncoderAction#finish()
*/
protected void finish() {
// reset scale in case it needed to be changed due to errors
m_scale = m_tempScale;
}
/**
* @see prefuse.action.assignment.SizeAction#getSize(prefuse.visual.VisualItem)
*/
public double getSize(VisualItem item) {
// check for any cascaded rules first
double size = super.getSize(item);
if ( !Double.isNaN(size) ) {
return size;
}
// otherwise perform data-driven assignment
double v = item.getDouble(m_dataField);
double f = MathLib.interp(m_scale, v, m_dist);
if ( m_bins < 1 ) {
// continuous scale
v = m_minSize + f * m_sizeRange;
} else {
// binned sizes
int bin = f < 1.0 ? (int)(f*m_bins) : m_bins-1;
v = m_minSize + bin*(m_sizeRange/(m_bins-1));
}
// return the size value. if this action is configured to return
// 2-dimensional sizes (ie area rather than length) then the
// size value is appropriately scaled first
return m_is2DArea ? PrefuseLib.getSize2D(v) : v;
}
} // end of class DataSizeAction |
package org.jtrfp.trcl.core;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.concurrent.Callable;
import javax.imageio.ImageIO;
import javax.media.opengl.GL3;
import org.jtrfp.trcl.core.VQCodebookManager.RasterRowWriter;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.img.vq.ByteBufferVectorList;
import org.jtrfp.trcl.img.vq.PalettedVectorList;
import org.jtrfp.trcl.img.vq.RGBA8888VectorList;
import org.jtrfp.trcl.img.vq.RasterizedBlockVectorList;
import org.jtrfp.trcl.img.vq.VectorList;
import org.jtrfp.trcl.mem.PagedByteBuffer;
public class Texture implements TextureDescription {
private final TR tr;
private final GPU gpu;
private final TextureManager tm ;
private final VQCodebookManager cbm;
private final TextureTOCWindow toc;
private final SubTextureWindow stw;
private Color averageColor;
private final String debugName;
private Integer tocIndex;
private int[] subTextureIDs;
private int[][] codebookStartOffsetsAbsolute;
private ByteBuffer rgba;
private final boolean uvWrapping;
private volatile int texturePage;
private int width;
@Override
public void finalize() throws Throwable{
System.out.println("Texture.finalize() "+debugName);
//TOC ID
if(tocIndex!=null)
toc.free(tocIndex);
//Subtexture IDs
if(subTextureIDs!=null)
for(int stID:subTextureIDs)
stw.free(stID);
//Codebook entries
if(codebookStartOffsetsAbsolute!=null)
for(int [] array:codebookStartOffsetsAbsolute){
for(int entry:array){
tm.vqCodebookManager.get().freeCodebook256(entry/256);
}//end for(entries)
}//end for(arrays)
super.finalize();
}//end finalize()
Texture(Color c, TR tr){
this(new PalettedVectorList(colorZeroRasterVL(), colorVL(c)),"SolidColor r="+c.getRed()+" g="+c.getGreen()+" b="+c.getBlue(),tr,false);
}//end constructor
private static VectorList colorZeroRasterVL(){
return new VectorList(){
@Override
public int getNumVectors() {
return 16;
}
@Override
public int getNumComponentsPerVector() {
return 1;
}
@Override
public double componentAt(int vectorIndex, int componentIndex) {
return 0;
}
@Override
public void setComponentAt(int vectorIndex, int componentIndex,
double value) {
throw new RuntimeException("Cannot write to Texture.colorZeroRasterVL VectorList");
}};
}//end colorZeroRasterVL
private static VectorList colorVL(Color c){
final double [] color = new double[]{
c.getRed()/255.,c.getGreen()/255.,c.getBlue()/255.,1.};
return new VectorList(){
@Override
public int getNumVectors() {
return 1;
}
@Override
public int getNumComponentsPerVector() {
return 4;
}
@Override
public double componentAt(int vectorIndex, int componentIndex) {
return color[componentIndex];
}
@Override
public void setComponentAt(int vectorIndex, int componentIndex,
double value) {
throw new RuntimeException("Static palette created by Texture(Color c, TR tr) cannot be written to.");
}};
}//end colorVL(...)
private Texture(TR tr, String debugName, boolean uvWrapping){
this.tr=tr;
this.gpu =tr.gpu.get();
this.tm =gpu.textureManager.get();
this.cbm =tm.vqCodebookManager.get();
this.toc =tm.getTOCWindow();
this.stw =tm.getSubTextureWindow();
this.debugName =debugName.replace('.', '_');
this.uvWrapping =uvWrapping;
}//end constructor
private Texture(Texture parent, double uOff, double vOff, double uSize,
double vSize, TR tr, boolean uvWrapping) {
this(tr,"subtexture: "+parent.debugName,uvWrapping);
}//end constructor
public Texture subTexture(double uOff, double vOff, double uSize,
double vSize){
return new Texture(this,uOff,vOff,uSize,vSize,tr,false);
}
Texture(PalettedVectorList vl, String debugName, TR tr, boolean uvWrapping){
this(tr,debugName,uvWrapping);
vqCompress(vl);
}//end constructor
Texture(ByteBuffer imageRGBA8888, String debugName, TR tr, boolean uvWrapping) {
this(tr,debugName,uvWrapping);
if (imageRGBA8888.capacity() == 0) {
throw new IllegalArgumentException(
"Cannot create texture of zero size.");
}//end if capacity==0
imageRGBA8888.clear();//Doesn't erase, just resets the tracking vars
vqCompress(imageRGBA8888);
}// end constructor
private void vqCompress(PalettedVectorList squareImageIndexed){
final int sideLength = (int)Math.sqrt(squareImageIndexed.getNumVectors());
vqCompress(squareImageIndexed,sideLength);
}
private void vqCompress(ByteBuffer imageRGBA8888){
final int sideLength = (int)Math.sqrt((imageRGBA8888.capacity() / 4));
// Break down into 4x4 blocks
final ByteBufferVectorList bbvl = new ByteBufferVectorList(imageRGBA8888);
final RGBA8888VectorList rgba8888vl = new RGBA8888VectorList(bbvl);
vqCompress(rgba8888vl,sideLength);
}
private void vqCompress(VectorList rgba8888vl, final int sideLength){
width=sideLength;
final RasterizedBlockVectorList rbvl = new RasterizedBlockVectorList(
rgba8888vl, sideLength, 4);
// Calculate a rough average color by averaging random samples.
float redA=0,greenA=0,blueA=0;
final double size = rbvl.getNumVectors();
for(int i=0; i<10; i++){
redA+=rbvl.componentAt((int)(Math.random()*size), 0);
greenA+=rbvl.componentAt((int)(Math.random()*size), 1);
blueA+=rbvl.componentAt((int)(Math.random()*size), 2);
}averageColor = new Color(redA/10f,greenA/10f,blueA/10f);
// Get a TOC
tocIndex = toc.create();
setTexturePage((toc.getPhysicalAddressInBytes(tocIndex)/PagedByteBuffer.PAGE_SIZE_BYTES));
if(toc.getPhysicalAddressInBytes(tocIndex)%PagedByteBuffer.PAGE_SIZE_BYTES!=0)
throw new RuntimeException("Nonzero modulus.");
tr.getThreadManager().submitToThreadPool(new Callable<Void>(){
@Override
public Void call() throws Exception {
// Create subtextures
final int diameterInCodes = (int)Math.ceil((double)sideLength/(double)VQCodebookManager.CODE_SIDE_LENGTH);
final int diameterInSubtextures = (int)Math.ceil((double)diameterInCodes/(double)SubTextureWindow.SIDE_LENGTH_CODES);
subTextureIDs = new int[diameterInSubtextures*diameterInSubtextures];
codebookStartOffsetsAbsolute = new int[diameterInSubtextures*diameterInSubtextures][6];
for(int i=0; i<subTextureIDs.length; i++){
//Create subtexture ID
subTextureIDs[i]=stw.create();
for(int off=0; off<6; off++){
codebookStartOffsetsAbsolute[i][off] = tm.vqCodebookManager.get()
.newCodebook256() * 256;}
}//end for(subTextureIDs)
tr.getThreadManager().submitToGPUMemAccess(new Callable<Void>() {
@Override
public Void call() {
//Set magic
toc.magic.set(tocIndex, 1337);
for(int i=0; i<subTextureIDs.length; i++){
final int id = subTextureIDs[i];
//Convert subtexture index to index of TOC
final int tocSubTexIndex = (i%diameterInSubtextures)+(i/diameterInSubtextures)*TextureTOCWindow.WIDTH_IN_SUBTEXTURES;
//Load subtexture ID into TOC
toc.subtextureAddrsVec4.setAt(tocIndex, tocSubTexIndex,stw.getPhysicalAddressInBytes(id)/GPU.BYTES_PER_VEC4);
//Render Flags
toc.renderFlags.set(tocIndex,
(uvWrapping?0x1:0x0)
);
//Fill the subtexture code start offsets
for(int off=0; off<6; off++)
stw.codeStartOffsetTable.setAt(id, off, codebookStartOffsetsAbsolute[i][off]);
}//end for(subTextureIDs)
// Set the TOC vars
toc.height .set(tocIndex, sideLength);
toc.width .set(tocIndex, sideLength);
final int numCodes = diameterInCodes*diameterInCodes;
for(int i = 0; i < numCodes; i++){
final int codeX = i % diameterInCodes;
final int codeY = i / diameterInCodes;
final int subtextureX = codeX / SubTextureWindow.SIDE_LENGTH_CODES;
final int subtextureY = codeY / SubTextureWindow.SIDE_LENGTH_CODES;
final int subtextureCodeX = codeX % SubTextureWindow.SIDE_LENGTH_CODES;
final int subtextureCodeY = codeY % SubTextureWindow.SIDE_LENGTH_CODES;
final int codeIdx = subtextureCodeX + subtextureCodeY * SubTextureWindow.SIDE_LENGTH_CODES;
final int subTextureIdx = subtextureX + subtextureY * diameterInSubtextures;
final int subtextureID = subTextureIDs[subTextureIdx];
stw.codeIDs.setAt(subtextureID, codeIdx, (byte)(codeIdx%256));
}//end for(numCodes)
return null;
}// end run()
}).get();//end gpuMemThread
// Push codes to subtextures
for(int codeY=0; codeY<diameterInCodes; codeY++){
for(int codeX=0; codeX<diameterInCodes; codeX++){
final int subtextureX = codeX / SubTextureWindow.SIDE_LENGTH_CODES;
final int subtextureY = codeY / SubTextureWindow.SIDE_LENGTH_CODES;
final int subTextureIdx = subtextureX + subtextureY * diameterInSubtextures;
final int subtextureCodeX = codeX % SubTextureWindow.SIDE_LENGTH_CODES;
final int subtextureCodeY = codeY % SubTextureWindow.SIDE_LENGTH_CODES;
final int codeIdx = subtextureCodeX + subtextureCodeY * SubTextureWindow.SIDE_LENGTH_CODES;
final int globalCodeIndex = codeIdx%256
+ codebookStartOffsetsAbsolute[subTextureIdx][codeIdx/256];
final int blockPosition = codeX+codeY*diameterInCodes;
final RasterRowWriter rw = new RasterRowWriter(){
@Override
public void applyRow(int row, ByteBuffer dest) {
int position = row*16;
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
dest.put((byte) (rbvl
.componentAt(blockPosition, position++) * 255.));
}//end applyRow
};
try{cbm.setRGBA(globalCodeIndex, rw);}
catch(ArrayIndexOutOfBoundsException e){
throw new RuntimeException("this="+Texture.this.toString(),e);
}
}//end for(codeX)
}//end for(codeY)
return null;
}}).get();//end pool thread
}//end vqCompress(...)
Texture(BufferedImage img, String debugName, TR tr, boolean uvWrapping) {
this(tr,debugName,uvWrapping);
long redA = 0, greenA = 0, blueA = 0;
rgba = ByteBuffer.allocateDirect(img.getWidth() * img.getHeight()
* 4);
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
Color c = new Color(img.getRGB(x, y), true);
rgba.put((byte) c.getRed());
rgba.put((byte) c.getGreen());
rgba.put((byte) c.getBlue());
rgba.put((byte) c.getAlpha());
redA += c.getRed();
greenA += c.getGreen();
blueA += c.getBlue();
}// end for(x)
}// end for(y)
final int div = rgba.capacity() / 4;
averageColor = new Color((redA / div) / 255f,
(greenA / div) / 255f, (blueA / div) / 255f);
if(tr.getTrConfig().isUsingNewTexturing()){
vqCompress(rgba);
}//else{registerNode(newNode);}
}//end constructor
public static ByteBuffer RGBA8FromPNG(File f) {
try {
return RGBA8FromPNG(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
public static ByteBuffer RGBA8FromPNG(InputStream is) {
try {
BufferedImage bi = ImageIO.read(is);
return RGBA8FromPNG(bi, 0, 0, bi.getWidth(), bi.getHeight());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}//end RGBA8FromPNG(...)
public static ByteBuffer RGBA8FromPNG(BufferedImage image, int startX,
int startY, int sizeX, int sizeY) {
int color;
ByteBuffer buf = ByteBuffer.allocateDirect(image.getWidth()
* image.getHeight() * 4);
for (int y = startY; y < startY + sizeY; y++) {
for (int x = startX; x < startX + sizeX; x++) {
color = image.getRGB(x, y);
buf.put((byte) ((color & 0x00FF0000) >> 16));
buf.put((byte) ((color & 0x0000FF00) >> 8));
buf.put((byte) (color & 0x000000FF));
buf.put((byte) ((color & 0xFF000000) >> 24));
}// end for(x)
}// end for(y)
buf.clear();// Rewind
return buf;
}// end RGB8FromPNG(...)
public static final Color[] GREYSCALE;
static {
GREYSCALE = new Color[256];
for (int i = 0; i < 256; i++) {
GREYSCALE[i] = new Color(i, i, i);
}
}// end static{}
public static ByteBuffer fragmentRGBA(ByteBuffer input, int quadDepth,
int x, int y) {
final int originalSideLen = (int) Math.sqrt(input.capacity() / 4);
final int splitAmount = (int) Math.pow(2, quadDepth);
final int newSideLen = originalSideLen / splitAmount;
ByteBuffer result = ByteBuffer.allocateDirect((int) (Math.pow(
newSideLen, 2) * 4));
for (int row = y * newSideLen; row < (y + 1) * newSideLen; row++) {
input.clear();
input.limit((x + 1) * newSideLen * 4 + row * originalSideLen * 4);
input.position(x * newSideLen * 4 + row * originalSideLen * 4);
result.put(input);
}
return result;
}// end fragmentRGBA(...)
public static ByteBuffer indexed2RGBA8888(ByteBuffer indexedPixels,
Color[] palette) {
Color color;
ByteBuffer buf = ByteBuffer.allocate(indexedPixels.capacity() * 4);
final int cap = indexedPixels.capacity();
for (int i = 0; i < cap; i++) {
color = palette[(indexedPixels.get() & 0xFF)];
buf.put((byte) color.getRed());
buf.put((byte) color.getGreen());
buf.put((byte) color.getBlue());
buf.put((byte) color.getAlpha());
}// end for(i)
buf.clear();// Rewind
return buf;
}// end indexed2RGBA8888(...)
public static ByteBuffer[] indexed2RGBA8888(ByteBuffer[] indexedPixels,
Color[] palette) {
final int len = indexedPixels.length;
ByteBuffer[] result = new ByteBuffer[len];
for (int i = 0; i < len; i++) {
result[i] = indexed2RGBA8888(indexedPixels[i], palette);
}
return result;
}// end indexed2RGBA8888(...)
/**
* @return the uvWrapping
*/
public boolean isUvWrapping() {
return uvWrapping;
}
/**
* @return the texturePage
*/
public int getTexturePage() {
return texturePage;
}
/**
* @param texturePage the texturePage to set
*/
public void setTexturePage(int texturePage) {
this.texturePage = texturePage;
}
@Override
public Color getAverageColor() {
return averageColor;
}
public static final int createTextureID(GL3 gl) {
IntBuffer ib = IntBuffer.allocate(1);
gl.glGenTextures(1, ib);
ib.clear();
return ib.get();
}//end createTextureID
@Override
public String toString(){
return "Texture debugName="+debugName+" width="+width;
}
}// end Texture |
package dk.statsbiblioteket.doms.updatetracker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fcrepo.server.Context;
import org.fcrepo.server.Server;
import org.fcrepo.server.errors.ConnectionPoolNotFoundException;
import org.fcrepo.server.errors.InitializationException;
import org.fcrepo.server.management.ManagementModule;
import org.fcrepo.server.proxy.AbstractInvocationHandler;
import org.fcrepo.server.proxy.ModuleConfiguredInvocationHandler;
import org.fcrepo.server.storage.ConnectionPool;
import org.fcrepo.server.storage.ConnectionPoolManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
/**
* The update tracker fedora hook. This hook stores information about all changing methods in a database, for later
* replay in the update tracker.
* The database is chosen via the fedora ConnectionPoolManager. Set the variable updateTrackerPoolName alongside the
* decorator to specify which pool should be used.
* Only changing operations are hooked.
*/
public class DomsUpdateTrackerHook extends AbstractInvocationHandler implements ModuleConfiguredInvocationHandler {
/** Logger for this class. */
private static Log logger = LogFactory.getLog(DomsUpdateTrackerHook.class);
private static Log replayableLog = LogFactory.getLog("dk.statsbiblioteket.doms.updatetracker.ReplayLog");
private Database database;
@Override
public void init(Server server) throws InitializationException {
ConnectionPoolManager cpm
= (ConnectionPoolManager) server.getModule("org.fcrepo.server.storage.ConnectionPoolManager");
if (cpm == null) {
throw new InitializationException("ConnectionPoolManager module was required, but apparently has not been" +
" loaded.");
}
ManagementModule managementModule
= (ManagementModule) server.getModule("org.fcrepo.server.management.Management");
if (managementModule == null) {
throw new InitializationException("ManagementModule module was required, but apparently has not been " +
"loaded.");
}
String cPoolName = managementModule.getParameter("updateTrackerPoolName");
ConnectionPool cPool = null;
try {
if (cPoolName == null) {
logger.debug("connectionPool unspecified; using default from ConnectionPoolManager.");
cPool = cpm.getPool();
} else {
logger.debug("connectionPool specified: " + cPoolName);
cPool = cpm.getPool(cPoolName);
}
} catch (ConnectionPoolNotFoundException e) {
throw new InitializationException("Failed to find specified connection '" + cPoolName + "'", e);
}
try {
database = new Database(cPool);
} catch (Exception e) {
cPool.close();
final StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
throw new InitializationException("Failed to open connection: " + out.toString(), e);
}
}
public static String toUri(String pid) {
if (!pid.startsWith("info:fedora/")) {
return "info:fedora/" + pid;
} else {
return pid;
}
}
public static String toPid(String uri) {
uri = clean(uri);
if (uri.startsWith("info:fedora/")) {
return uri.substring("info:fedora/".length());
}
return uri;
}
public static String clean(String uri) {
if (uri.startsWith("<")) {
uri = uri.substring(1);
}
if (uri.endsWith(">")) {
uri = uri.substring(0, uri.length() - 1);
}
return uri;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws
Throwable {
try {
final String methodName = method.getName();
switch (methodName) {
case "getObjectXML":
case "export":
case "getDatastream":
case "getDatastreams":
case "getDatastreamHistory":
case "compareDatastreamChecksum":
case "getNextPID":
case "getRelationships":
case "validate":
case "getTempStream":
case "putTempStream":
//These methods should not be hooked, so go on immediately
return method.invoke(target, args);
}
String pid;
Date now;
String param;
try {
Context context = (Context) args[0];
now = Server.getCurrentDate(context);
pid = toPid(args[1].toString());
param = null;
if (args.length > 2 && args[2] != null) {
param = args[2].toString();
}
} catch (Exception e) {
final String message = "Failed to parse params for method '" + methodName + "': " + Arrays.toString(args) +
"'";
logger.error(message, e);
throw new InvocationTargetException(e, message);
}
switch (methodName) {
case "ingest":
param = null;
pid = invokeIngestHook(method, args, now);
replayableLog.info("Method: " + methodName + "(" + pid + ", " + now.getTime() + ", " + param + ")");
return pid;
case "modifyObject":
case "purgeObject":
case "addDatastream":
case "modifyDatastreamByReference":
case "modifyDatastreamByValue":
case "purgeDatastream":
case "setDatastreamState":
case "setDatastreamVersionable":
case "addRelationship":
case "purgeRelationship":
replayableLog.info("Method: " + methodName + "(" + pid + ", " + now.getTime() + ", " + param + ")");
return invokeHook(method, args, methodName, pid, now, param);
default:
logger.warn("Unknown method invoked: " + methodName + "(" + pid + ", " + now.getTime() + ", " +
param +
")");
return method.invoke(target, args);
}
} catch (InvocationTargetException e){
throw e.getCause();
}
}
private String invokeIngestHook(Method method, Object[] args, Date now) throws
InvocationTargetException,
IllegalAccessException {
String methodName = "ingest";
String pid = (String) method.invoke(target, args);
addLogEntry(methodName, pid, now, null);
return pid;
}
private Object invokeHook(Method method, Object[] args, String methodName, String pid, Date now,
String param) throws IllegalAccessException, InvocationTargetException {
Long logkey;
logkey = addLogEntry(methodName, pid, now, param);
try {
return method.invoke(target, args);
} catch (RuntimeException | InvocationTargetException rte) {
logger.info("Caught exception while invoking method " + methodName + "(" + pid + ", " + now.getTime() +
", " +
param +
")" + " . Now attempting to remove log entry from database", rte);
removeLogEntry(methodName, pid, now, param, logkey);
throw rte;
}
}
private void removeLogEntry(String methodName, String pid, Date now, String param, Long logkey) {
try {
database.removeLogEntry(logkey);
logger.info("For method" + "" + methodName + "(" + pid + ", " + now.getTime() + ", " +
param +
")" + ", we removed logKey '" + logkey + "' from the database");
} catch (IOException e) {
logger.error("For method" + "" + methodName + "(" + pid + ", " + now.getTime() + ", " +
param +
")" + ", we failed to remove logKey '" + logkey + "' from the database", e);
}
}
private Long addLogEntry(String methodName, String pid, Date now, String param) throws InvocationTargetException {
Long logkey;
try {
logger.debug("For method" + "" + methodName + "(" + pid + ", " + now.getTime() + ", " + param +
")" + ", add a log entry to the database");
logkey = database.addLogEntry(pid, now, methodName, param);
} catch (IOException e) {
final String message = "For method" + "" + methodName + "(" + pid + ", " + now.getTime() + ", " + param +
")" + ", we failed to add log to database";
logger.error(message, e);
throw new InvocationTargetException(e, message);
}
return logkey;
}
} |
package org.lantern;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.lastbamboo.common.stun.client.PublicIpAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
/**
* Class that keeps track of which countries are considered censored.
*/
public class DefaultCensored implements Censored {
private final Logger LOG =
LoggerFactory.getLogger(DefaultCensored.class);
private static final Collection<String> CENSORED =
new TreeSet<String>(Sets.newHashSet(
// These are taken from ONI data -- 11/16/11 - any country containing
// any type of censorship considered "substantial" or "pervasive".
"AE", // United Arab Emirates
"AM", // Armenia
"BH", // Bahrain
"CN", // China
"CU", // Cuba
"ET", // Ethiopia
//"ID", // Indonesia
"IR", // Iran
"KP", // North Korea
"KR", // South Korea
"KW", // Kuwait
"MM", // Myanmar
"OM", // Oman
//"PK", // Pakistan
"PS", // Palestine
"QA", // Qatar
"SA", // Saudi Arabia
"SD", // Sudan
"SY", // Syria
"TM", // Turkmenistan
"UZ", // Uzbekistan
"VN", // Vietnam
"YE" // Yemen
));
public DefaultCensored() {
CENSORED.add("CU");
CENSORED.add("KP");
}
// These country codes have US export restrictions, and therefore cannot
// access App Engine sites.
private final Collection<String> EXPORT_RESTRICTED =
Sets.newHashSet(
"SY");
private String countryCode;
@Override
public String countryCode() {
if (StringUtils.isNotBlank(countryCode)) {
LOG.info("Returning cached country code: {}", countryCode);
return countryCode;
}
LOG.info("Returning country code: {}", countryCode);
countryCode = country().getCode().trim();
return countryCode;
}
@Override
public Country country() {
final InetAddress address = new PublicIpAddress().getPublicIpAddress();
if (address == null) {
// Just return an empty country instead of throwing null pointer.
return new Country("", "");
}
final com.maxmind.geoip.Country country =
LanternHub.getGeoIpLookup().getCountry(address);
return new Country(country.getCode(), country.getName());
}
@Override
public boolean isCensored() {
return isCensored(new PublicIpAddress().getPublicIpAddress());
}
@Override
public boolean isCensored(final Country country) {
final String cc = country.getCode().trim();
return CENSORED.contains(cc);
}
@Override
public Collection<String> getCensored() {
return CENSORED;
}
@Override
public boolean isCensored(final String address) throws IOException {
return isCensored(InetAddress.getByName(address));
}
@Override
public boolean isCountryCodeCensored(final String cc) {
if (StringUtils.isBlank(cc)) {
return false;
}
return CENSORED.contains(cc);
}
public boolean isExportRestricted() {
return isExportRestricted(new PublicIpAddress().getPublicIpAddress());
}
public boolean isExportRestricted(final InetAddress address) {
return isMatch(address, EXPORT_RESTRICTED);
}
@Override
public boolean isExportRestricted(final String address)
throws IOException {
return isExportRestricted(InetAddress.getByName(address));
}
private boolean isCensored(final InetAddress address) {
return isMatch(address, CENSORED);
}
private boolean isMatch(final InetAddress address,
final Collection<String> countries) {
if (address == null) {
return false;
}
return countries.contains(countryCode(address));
}
private String countryCode(final InetAddress address) {
final com.maxmind.geoip.Country country =
LanternHub.getGeoIpLookup().getCountry(address);
LOG.info("Country is: {}", country.getName());
return country.getCode().trim();
}
} |
package info.bitrich.xchangestream.coinmate;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectReader;
import info.bitrich.xchangestream.coinmate.dto.CoinmateWebsocketBalance;
import info.bitrich.xchangestream.core.StreamingAccountService;
import info.bitrich.xchangestream.service.netty.StreamingObjectMapperHelper;
import io.reactivex.Observable;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.Wallet;
import java.util.*;
public class CoinmateStreamingAccountService implements StreamingAccountService {
private final CoinmateStreamingServiceFactory serviceFactory;
private final Set<Wallet.WalletFeature> walletFeatures =
new HashSet<>(Arrays.asList(Wallet.WalletFeature.TRADING, Wallet.WalletFeature.FUNDING));
public CoinmateStreamingAccountService(CoinmateStreamingServiceFactory serviceFactory) {
this.serviceFactory = serviceFactory;
}
@Override
public Observable<Balance> getBalanceChanges(Currency currency, Object... args) {
return getCoinmateBalances()
.map(balanceMap -> balanceMap.get(currency.toString()))
.map(
(balance) -> {
return new Balance.Builder()
.currency(currency)
.total(balance.getBalance())
.available(balance.getBalance().subtract(balance.getReserved()))
.frozen(balance.getReserved())
.build();
});
}
public Observable<Wallet> getWalletChanges(Object... args) {
return getCoinmateBalances()
.map(
(balanceMap) -> {
List<Balance> balances = new ArrayList<>();
balanceMap.forEach(
(s, coinmateWebsocketBalance) -> {
balances.add(
new Balance.Builder()
.currency(new Currency(s))
.total(coinmateWebsocketBalance.getBalance())
.available(
coinmateWebsocketBalance
.getBalance()
.subtract(coinmateWebsocketBalance.getReserved()))
.frozen(coinmateWebsocketBalance.getReserved())
.build());
});
return balances;
})
.map(
(balances) -> {
return Wallet.Builder.from(balances).features(walletFeatures).id("spot").build();
});
}
private Observable<Map<String, CoinmateWebsocketBalance>> getCoinmateBalances() {
String channelName = "channel/my-balances";
ObjectReader reader = StreamingObjectMapperHelper.getObjectMapper().readerFor(new TypeReference<Map<String, CoinmateWebsocketBalance>>() {});
CoinmateStreamingService service = serviceFactory.createAndConnect(channelName, true);
return service.subscribeMessages()
.map((message) -> reader.readValue(message.get("balances")));
}
} |
package org.monarch.golr;
import static com.google.common.collect.Collections2.transform;
import static java.util.Collections.singleton;
import io.scigraph.frames.CommonProperties;
import io.scigraph.frames.NodeProperties;
import io.scigraph.internal.CypherUtil;
import io.scigraph.internal.GraphApi;
import io.scigraph.internal.TinkerGraphUtil;
import io.scigraph.neo4j.DirectedRelationshipType;
import io.scigraph.neo4j.Graph;
import io.scigraph.neo4j.GraphUtil;
import io.scigraph.owlapi.OwlRelationships;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.inject.Inject;
import org.apache.commons.lang3.ClassUtils;
import org.monarch.golr.beans.Closure;
import org.monarch.golr.beans.GolrCypherQuery;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.DynamicLabel;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.traversal.Evaluators;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Uniqueness;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Resources;
import com.tinkerpop.blueprints.impls.tg.TinkerGraph;
public class GolrLoader {
private static final String EVIDENCE_GRAPH = "evidence_graph";
private static final String EVIDENCE_FIELD = "evidence";
private static final String SOURCE_FIELD = "source";
private static final String EVIDENCE_OBJECT_FIELD = "evidence_object";
private static final String DEFINED_BY = "is_defined_by";
private final GraphDatabaseService graphDb;
private final ResultSerializerFactory factory;
private final EvidenceProcessor processor;
private final Graph graph;
private final CypherUtil cypherUtil;
private final GraphApi api;
private static final RelationshipType inTaxon = DynamicRelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002162");
private static final String CHROMOSOME_TYPE = "http://purl.obolibrary.org/obo/SO_0000340";
private static final RelationshipType location = DynamicRelationshipType.withName("location");
private static final RelationshipType begin = DynamicRelationshipType.withName("begin");
private static final RelationshipType reference = DynamicRelationshipType.withName("reference");
private static final Label GENE_LABEL = DynamicLabel.label("gene");
private static final Label VARIANT_LABEL = DynamicLabel.label("sequence feature");
private static final Label GENOTYPE_LABEL = DynamicLabel.label("genotype");
private Collection<RelationshipType> parts_of;
private Collection<RelationshipType> hasParts;
private Collection<RelationshipType> variants;
private TraversalDescription taxonDescription;
private TraversalDescription chromosomeDescription;
private TraversalDescription diseaseDescription;
private TraversalDescription phenotypeDescription;
private Collection<Node> chromsomeEntailment;
private TraversalDescription geneDescription;
private Collection<String> variantStrings;
@Inject
GolrLoader(GraphDatabaseService graphDb, Graph graph, CypherUtil cypherUtil, ResultSerializerFactory factory, EvidenceProcessor processor,
GraphApi api) {
this.graphDb = graphDb;
this.cypherUtil = cypherUtil;
this.graph = graph;
this.factory = factory;
this.processor = processor;
this.api = api;
try (Transaction tx = graphDb.beginTx()) {
buildTraversals();
tx.success();
}
}
private void buildTraversals() {
parts_of = cypherUtil.getEntailedRelationshipTypes(Collections.singleton("http://purl.obolibrary.org/obo/BFO_0000051"));
hasParts = cypherUtil.getEntailedRelationshipTypes(Collections.singleton("http://purl.obolibrary.org/obo/RO_0002525"));
variants = cypherUtil.getEntailedRelationshipTypes(Collections.singleton("http://purl.obolibrary.org/obo/GENO_0000410"));
taxonDescription =
graphDb.traversalDescription().breadthFirst().relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH)
.relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH).relationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.OUTGOING)
.relationships(OwlRelationships.RDF_TYPE, Direction.OUTGOING).relationships(inTaxon, Direction.OUTGOING).uniqueness(Uniqueness.NONE);
for (RelationshipType part_of : parts_of) {
taxonDescription = taxonDescription.relationships(part_of, Direction.OUTGOING);
}
for (RelationshipType hasPart : hasParts) {
taxonDescription = taxonDescription.relationships(hasPart, Direction.INCOMING);
}
for (RelationshipType variant : variants) {
taxonDescription = taxonDescription.relationships(variant, Direction.OUTGOING);
}
chromosomeDescription =
graphDb.traversalDescription().breadthFirst().relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH)
.relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH).relationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.OUTGOING)
.relationships(OwlRelationships.RDF_TYPE, Direction.OUTGOING).relationships(location, Direction.OUTGOING)
.relationships(begin, Direction.OUTGOING).relationships(reference, Direction.OUTGOING);
Optional<Long> nodeId = graph.getNode(CHROMOSOME_TYPE);
if (!nodeId.isPresent()) {
// TODO: Move all of this to some external configuration
return;
}
Node chromsomeParent = graphDb.getNodeById(nodeId.get());
chromsomeEntailment =
api.getEntailment(chromsomeParent, new DirectedRelationshipType(OwlRelationships.RDFS_SUBCLASS_OF, Direction.INCOMING), true);
geneDescription = graphDb.traversalDescription().depthFirst().relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH);
for (RelationshipType part_of : parts_of) {
geneDescription = geneDescription.relationships(part_of, Direction.OUTGOING);
}
for (RelationshipType variant : variants) {
geneDescription = geneDescription.relationships(variant, Direction.INCOMING);
}
variantStrings = transform(variants, new Function<RelationshipType, String>() {
@Override
public String apply(RelationshipType type) {
return type.name();
}
});
diseaseDescription =
graphDb.traversalDescription().depthFirst()
.relationships(DynamicRelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002200"), Direction.OUTGOING)
.relationships(DynamicRelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002610"), Direction.OUTGOING)
.relationships(DynamicRelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002326"), Direction.OUTGOING)
.evaluator(Evaluators.atDepth(1));
phenotypeDescription =
graphDb.traversalDescription().depthFirst()
.relationships(DynamicRelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002200"), Direction.OUTGOING)
.relationships(DynamicRelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002610"), Direction.OUTGOING)
.relationships(DynamicRelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002326"), Direction.OUTGOING)
.evaluator(Evaluators.fromDepth(1)).evaluator(Evaluators.toDepth(2));
}
Optional<Node> getTaxon(Node source) {
for (Path path : taxonDescription.traverse(source)) {
if (path.length() > 0 && path.lastRelationship().isType(inTaxon)) {
return Optional.of(path.endNode());
}
}
return Optional.absent();
}
Optional<Node> getChromosome(Node source) {
for (Path path : chromosomeDescription.traverse(source)) {
if (path.length() > 0 && path.lastRelationship().isType(OwlRelationships.RDF_TYPE)) {
if (chromsomeEntailment.contains(path.endNode())) {
return Optional.of(path.lastRelationship().getOtherNode(path.endNode()));
}
}
}
return Optional.absent();
}
Optional<Node> getGene(Node source) {
for (Path path : geneDescription.traverse(source)) {
if (path.length() > 0 && variantStrings.contains(path.lastRelationship().getType().name())) {
return Optional.of(path.endNode());
}
}
return Optional.absent();
}
Collection<Node> getDiseases(Node source) throws IOException {
String cypher = Resources.toString(Resources.getResource("disease.cypher"), Charsets.UTF_8);
Multimap<String, Object> params = HashMultimap.create();
params.put("id", source.getId());
Result result = cypherUtil.execute(cypher, params);
Collection<Node> diseases = new HashSet<>();
while (result.hasNext()) {
Map<String, Object> row = result.next();
diseases.add((Node) row.get("disease"));
}
return diseases;
}
Collection<Node> getPhenotypes(Node source) throws IOException {
String cypher = Resources.toString(Resources.getResource("phenotype.cypher"), Charsets.UTF_8);
Multimap<String, Object> params = HashMultimap.create();
params.put("id", source.getId());
Result result = cypherUtil.execute(cypher, params);
Collection<Node> phenotypes = new HashSet<>();
while (result.hasNext()) {
Map<String, Object> row = result.next();
phenotypes.add((Node) row.get("phenotype"));
}
return phenotypes;
}
long process(GolrCypherQuery query, Writer writer) throws IOException, ExecutionException {
long recordCount = 0;
LoadingCache<Node, Optional<Node>> taxonCache = CacheBuilder.newBuilder().maximumSize(100_000).build(new CacheLoader<Node, Optional<Node>>() {
@Override
public Optional<Node> load(Node source) throws Exception {
return getTaxon(source);
}
});
LoadingCache<Node, Optional<Node>> chromosomeCache =
CacheBuilder.newBuilder().maximumSize(100_000).build(new CacheLoader<Node, Optional<Node>>() {
@Override
public Optional<Node> load(Node source) throws Exception {
return getChromosome(source);
}
});
LoadingCache<Node, Optional<Node>> geneCache = CacheBuilder.newBuilder().maximumSize(100_000).build(new CacheLoader<Node, Optional<Node>>() {
@Override
public Optional<Node> load(Node source) throws Exception {
return getGene(source);
}
});
try (Transaction tx = graphDb.beginTx()) {
Result result = cypherUtil.execute(query.getQuery());
JsonGenerator generator = new JsonFactory().createGenerator(writer);
ResultSerializer serializer = factory.create(generator);
generator.writeStartArray();
// TODO temporary fix
// String subjectIri = "";
// String objectIri = "";
while (result.hasNext()) {
recordCount++;
generator.writeStartObject();
Map<String, Object> row = result.next();
com.tinkerpop.blueprints.Graph evidenceGraph = new TinkerGraph();
Set<Long> ignoredNodes = new HashSet<>();
boolean emitEvidence = true;
for (Entry<String, Object> entry : row.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (null == value) {
continue;
}
// Add evidence
if (value instanceof PropertyContainer) {
TinkerGraphUtil.addElement(evidenceGraph, (PropertyContainer) value);
} else if (value instanceof Path) {
TinkerGraphUtil.addPath(evidenceGraph, (Path) value);
}
if (value instanceof Node) {
ignoredNodes.add(((Node) value).getId());
// TODO: Clean this up
if ("subject".equals(key) || "object".equals(key)) {
Node node = (Node) value;
Optional<Node> taxon = taxonCache.get(node);
if (taxon.isPresent()) {
serializer.serialize(key + "_taxon", taxon.get());
}
if (node.hasLabel(GENE_LABEL) || node.hasLabel(VARIANT_LABEL) || node.hasLabel(GENOTYPE_LABEL)) {
// Attempt to add gene and chromosome for monarch-initiative/monarch-app/#746
if (node.hasLabel(GENE_LABEL)) {
serializer.serialize(key + "_gene", node);
} else {
Optional<Node> gene = geneCache.get(node);
if (gene.isPresent()) {
serializer.serialize(key + "_gene", gene.get());
}
}
Optional<Node> chromosome = chromosomeCache.get(node);
if (chromosome.isPresent()) {
serializer.serialize(key + "_chromosome", chromosome.get());
}
}
// TODO temporary fix
// if ("subject".equals(key)) {
// subjectIri = (String) ((Node) value).getProperty(NodeProperties.IRI);
// if ("object".equals(key)) {
// objectIri = (String) ((Node) value).getProperty(NodeProperties.IRI);
}
if ("feature".equals(key)) {
// Add disease and phenotype for feature
serializer.serialize("disease", getDiseases((Node) value));
serializer.serialize("phenotype", getPhenotypes((Node) value));
}
if (query.getCollectedTypes().containsKey(key)) {
serializer.serialize(key, singleton((Node) value), query.getCollectedTypes().get(key));
} else {
serializer.serialize(key, value);
}
} else if (value instanceof Relationship) {
String objectPropertyIri = GraphUtil.getProperty((Relationship) value, CommonProperties.IRI, String.class).get();
Node objectProperty = graphDb.getNodeById(graph.getNode(objectPropertyIri).get());
serializer.serialize(key, objectProperty);
} else if (ClassUtils.isPrimitiveOrWrapper(value.getClass()) || value instanceof String) {
// Serialize primitive types and Strings
if ((key.equals("subject_category") || key.equals("object_category")) && value.equals("ontology")) {
emitEvidence = false;
}
serializer.serialize(key, value);
}
}
// TODO temporary fix
// if (subjectIri != "" && objectIri != "") {
// String pathCypherQueryReplaced = query.getPathQuery().replace("SUBJECTIRI",
// subjectIri).replace("OBJECTIRI", objectIri);
// Result pathResult = cypherUtil.execute(pathCypherQueryReplaced);
// Map<String, Object> pathRow = pathResult.next();
// for (Entry<String, Object> entry : pathRow.entrySet()) {
// String key = entry.getKey();
// Object value = entry.getValue();
// if (value instanceof Path) {
// TinkerGraphUtil.addPath(evidenceGraph, (Path) value);
processor.addAssociations(evidenceGraph);
serializer.serialize(EVIDENCE_GRAPH, processor.getEvidenceGraph(evidenceGraph));
// TODO: Hackish to remove evidence but the resulting JSON is blooming out of control
// Don't emit evidence for ontology sources
if (emitEvidence) {
List<Closure> evidenceObjectClosure = processor.getEvidenceObject(evidenceGraph, ignoredNodes);
serializer.writeQuint(EVIDENCE_OBJECT_FIELD, evidenceObjectClosure);
List<Closure> evidenceClosure = processor.getEvidence(evidenceGraph);
serializer.writeQuint(EVIDENCE_FIELD, evidenceClosure);
List<Closure> sourceClosure = processor.getSource(evidenceGraph);
serializer.writeQuint(SOURCE_FIELD, sourceClosure);
serializer.writeArray(DEFINED_BY, processor.getDefinedBys(evidenceGraph));
}
generator.writeEndObject();
}
generator.writeEndArray();
generator.close();
tx.success();
}
return recordCount;
}
} |
package org.xwiki.velocity.internal;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.Deque;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeInstance;
import org.apache.velocity.runtime.directive.StopCommand;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.InstantiationStrategy;
import org.xwiki.component.descriptor.ComponentInstantiationStrategy;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.velocity.VelocityConfiguration;
import org.xwiki.velocity.VelocityContextFactory;
import org.xwiki.velocity.VelocityEngine;
import org.xwiki.velocity.XWikiVelocityException;
import org.xwiki.velocity.internal.directive.TryCatchDirective;
/**
* Default implementation of the Velocity service which initializes the Velocity system using configuration values
* defined in the component's configuration. Note that the {@link #initialize} method has to be executed before any
* other method can be called.
*
* @version $Id$
*/
@Component
@InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP)
public class DefaultVelocityEngine implements VelocityEngine
{
private static final String ECONTEXT_TEMPLATES = "velocity.templates";
private static class SingletonResourceReader extends StringResourceLoader
{
private final Reader reader;
SingletonResourceReader(Reader r)
{
this.reader = r;
}
@Override
public Reader getResourceReader(String source, String encoding)
{
return this.reader;
}
}
private class TemplateEntry
{
private Template template;
private String namespace;
private int counter;
/**
* @param namespace the namespace
*/
TemplateEntry(String namespace)
{
this.namespace = namespace;
this.template = new Template();
this.template.setName(namespace);
this.template.setRuntimeServices(runtimeInstance);
this.counter = 1;
if (globalEntry != null) {
// Inject global macros
this.template.getMacros().putAll(globalEntry.getTemplate().getMacros());
}
}
Template getTemplate()
{
return this.template;
}
String getNamespace()
{
return this.namespace;
}
int getCounter()
{
return this.counter;
}
int incrementCounter()
{
++this.counter;
return this.counter;
}
int decrementCounter()
{
--this.counter;
return this.counter;
}
}
/**
* Used to set it as a Velocity Application Attribute so that Velocity extensions done by XWiki can use it to lookup
* other components.
*/
@Inject
private ComponentManager componentManager;
/**
* Velocity configuration to get the list of configured Velocity properties.
*/
@Inject
private VelocityConfiguration velocityConfiguration;
/**
* Used to create a new context whenever one isn't already provided to the
* {@link #evaluate(Context, Writer, String, Reader)} method.
*/
@Inject
private VelocityContextFactory velocityContextFactory;
@Inject
private Execution execution;
/**
* The logger to use for logging.
*/
@Inject
private Logger logger;
/**
* The actual Velocity runtime.
*/
private RuntimeInstance runtimeInstance;
private TemplateEntry globalEntry;
@Override
public void initialize(Properties overridingProperties) throws XWikiVelocityException
{
RuntimeInstance runtime = new RuntimeInstance();
// Add the Component Manager to allow Velocity extensions to lookup components.
runtime.setApplicationAttribute(ComponentManager.class.getName(), this.componentManager);
// Set up properties
initializeProperties(runtime, this.velocityConfiguration.getProperties(), overridingProperties);
// Set up directives
runtime.loadDirective(TryCatchDirective.class.getName());
try {
runtime.init();
} catch (Exception e) {
throw new XWikiVelocityException("Cannot start the Velocity engine", e);
}
this.runtimeInstance = runtime;
this.globalEntry = new TemplateEntry("");
}
/**
* @param runtime the Velocity engine against which to initialize Velocity properties
* @param configurationProperties the Velocity properties coming from XWiki's configuration
* @param overridingProperties the Velocity properties that override the properties coming from XWiki's
* configuration
*/
private void initializeProperties(RuntimeInstance runtime, Properties configurationProperties,
Properties overridingProperties)
{
// Avoid "unable to find resource 'VM_global_library.vm' in any resource loader." if no
// Velocimacro library is defined. This value is overriden below.
runtime.setProperty(RuntimeConstants.VM_LIBRARY, "");
// Configure Velocity by passing the properties defined in this component's configuration
if (configurationProperties != null) {
for (Enumeration<?> e = configurationProperties.propertyNames(); e.hasMoreElements();) {
String key = e.nextElement().toString();
// Only set a property if it's not overridden by one of the passed properties
if (overridingProperties == null || !overridingProperties.containsKey(key)) {
String value = configurationProperties.getProperty(key);
runtime.setProperty(key, value);
this.logger.debug("Setting property [{}] = [{}]", key, value);
}
}
}
// Override the component's static properties with the ones passed in parameter
if (overridingProperties != null) {
for (Enumeration<?> e = overridingProperties.propertyNames(); e.hasMoreElements();) {
String key = e.nextElement().toString();
String value = overridingProperties.getProperty(key);
runtime.setProperty(key, value);
this.logger.debug("Overriding property [{}] = [{}]", key, value);
}
}
}
@Override
public boolean evaluate(Context context, Writer out, String templateName, String source)
throws XWikiVelocityException
{
return evaluate(context, out, templateName, new StringReader(source));
}
@Override
public boolean evaluate(Context context, Writer out, String namespace, Reader source) throws XWikiVelocityException
{
// Ensure that initialization has been called
if (this.runtimeInstance == null) {
throw new XWikiVelocityException("This Velocity Engine has not yet been initialized. "
+ "You must call its initialize() method before you can use it.");
}
// Save the current resource so that it's not broken by the currently executed one
Resource currentResource;
if (context instanceof VelocityContext) {
currentResource = ((VelocityContext) context).getCurrentResource();
} else {
currentResource = null;
}
try {
TemplateEntry templateEntry;
if (StringUtils.isNotEmpty(namespace)) {
templateEntry = startedUsingMacroNamespaceInternal(namespace);
} else {
templateEntry = this.globalEntry;
}
// Set source
templateEntry.getTemplate().setResourceLoader(new SingletonResourceReader(source));
// Compile the template
templateEntry.getTemplate().process();
// Execute the velocity script
templateEntry.getTemplate().merge(context != null ? context : this.velocityContextFactory.createContext(),
out);
return true;
} catch (StopCommand s) {
// Someone explicitly stopped the script with something like #stop. No reason to make a scene.
return true;
} catch (Exception e) {
throw new XWikiVelocityException("Failed to evaluate content with namespace [" + namespace + "]", e);
} finally {
if (StringUtils.isNotEmpty(namespace)) {
stoppedUsingMacroNamespace(namespace);
}
// Restore the current resource
if (context instanceof VelocityContext) {
((VelocityContext) context).setCurrentResource(currentResource);
}
// Clean the introspection cache to avoid memory leak
cleanIntrospectionCache(context);
}
}
private void cleanIntrospectionCache(Context context)
{
try {
Map introspectionCache = (Map) FieldUtils.readField(context, "introspectionCache", true);
introspectionCache.clear();
} catch (IllegalAccessException e) {
this.logger.warn("Failed to clean the Velocity context introspection cache: ",
ExceptionUtils.getRootCauseMessage(e));
}
}
@Override
@Deprecated
public void clearMacroNamespace(String namespace)
{
// Does not really make much sense anymore since macros are now stored in the execution context
}
@Override
public void startedUsingMacroNamespace(String namespace)
{
startedUsingMacroNamespaceInternal(namespace);
}
private Deque<TemplateEntry> getCurrentTemplates(boolean create)
{
ExecutionContext executionContext = this.execution.getContext();
if (executionContext == null) {
return null;
}
Deque<TemplateEntry> templates = (Deque<TemplateEntry>) executionContext.getProperty(ECONTEXT_TEMPLATES);
if (templates == null && create) {
templates = new LinkedList<>();
if (!executionContext.hasProperty(ECONTEXT_TEMPLATES)) {
executionContext.newProperty(ECONTEXT_TEMPLATES).inherited().declare();
}
executionContext.setProperty(ECONTEXT_TEMPLATES, templates);
}
return templates;
}
private TemplateEntry startedUsingMacroNamespaceInternal(String namespace)
{
Deque<TemplateEntry> templates = getCurrentTemplates(true);
TemplateEntry templateEntry;
if (templates != null) {
// If this is already the current template namespace increment the counter, otherwise push a new
// TemplateEntry
if (!templates.isEmpty() && templates.peek().getNamespace().equals(namespace)) {
templateEntry = templates.peek();
templateEntry.incrementCounter();
} else {
templateEntry = new TemplateEntry(namespace);
templates.push(templateEntry);
}
} else {
// If no execution context can be found create a new template entry
templateEntry = new TemplateEntry(namespace);
}
return templateEntry;
}
@Override
public void stoppedUsingMacroNamespace(String namespace)
{
Deque<TemplateEntry> templates = getCurrentTemplates(true);
if (templates != null) {
if (templates.isEmpty()) {
this.logger.warn("Impossible to pop namespace [{}] because there is no namespace in the stack",
namespace);
} else {
popTemplateEntry(templates, namespace);
}
}
}
private void popTemplateEntry(Deque<TemplateEntry> templates, String namespace)
{
TemplateEntry templateEntry = templates.peek();
if (templateEntry.getNamespace().equals(namespace)) {
if (templateEntry.getCounter() > 1) {
templateEntry.decrementCounter();
} else {
templates.pop();
}
} else {
this.logger.warn("Impossible to pop namespace [{}] because current namespace is [{}]", namespace,
templateEntry.getNamespace());
}
}
} |
package org.framed.orm.ui.command.connectionkinds;
import org.eclipse.draw2d.geometry.Point;
import org.framed.orm.model.Container;
import org.framed.orm.model.Relation;
import org.framed.orm.model.Relationship;
import org.framed.orm.model.RelationshipConstraint;
/**
* Through this command {@link RelationshipConstraint}s can be created(invoked into the model tree).
*
* @author Kay Bierzynski
* */
public class ORMRelationshipConstraintCreateCommand extends ORMRelationCreateCommand {
/**
* The {@link RelationshipConstraint} to be created. The basis class of the
* {@link RelationshipConstraint} is given by a factory.
*/
private RelationshipConstraint relationCons;
/** The {@link Relationship} to which the {@link RelationshipConstraint} belongs to. */
private Relationship relationship;
/**
* This method tests if the conditions for executing this command are fulfilled,
*
* @return true if the parameter target, source, relationCons, arent and relationship are set.
*/
@Override
public boolean canExecute() {
return target != null && source != null && relationCons != null && parent != null
&& relationship != null;
}
/**
* In this method the {@link RelationshipConstrain} is created/ invoked into the
* model tree through setting it's parameter. After that when a {@link RelationshipConstrain}
* already exist beside the {@link RelationshipConstrain} to be invoked all {@link Bendpoint}s
* from this {@link RelationshipConstrain} are added to the created {@link RelationshipConstrain}
* as well. When more as one {@link Relation} exists between the target and the source of the
* {@link RelationshipConstrain} than a {@link Bendpoint} is added to the created
* {@link RelationshipConstrain} to make the {@link RelationshipConstrain} better visibile/
* acessesible to the user.
*
*/
@Override
public void execute() {
relationCons.setSource(source);
relationCons.setTarget(target);
relationCons.setRelationContainer(parent);
relationCons.setRelation(relationship);
int relationCount = getRelationCount();
if (relationship.getRlshipConstraints().size() > 1) {
relationCons.getDim1BP().addAll(relationship.getRlshipConstraints().get(0).getDim1BP());
relationCons.getDim2BP().addAll(relationship.getRlshipConstraints().get(0).getDim2BP());
}
if (relationCount > 1 && relationship.getRlshipConstraints().size() <= 1) {
Point ps = new Point(source.getConstraints().x(), source.getConstraints().y());
Point pt = new Point(target.getConstraints().x(), target.getConstraints().y());
adaptRelationCreation(ps, pt, relationCount);
}
}
/**
* This command is undone through removing the created {@link RelationshipConstrain}
* from the source, the {@link Container}, the {@link Relationship} and the target and through
* deleting all the {@link Bendpoint}s of the {@link RelationshipConstrain}.
*
*/
@Override
public void undo() {
relationCons.getSource().getOutgoingLinks().remove(relationCons);
relationCons.setSource(null);
relationCons.getTarget().getIncomingLinks().remove(relationCons);
relationCons.setTarget(null);
relationCons.setRelationContainer(null);
relationCons.setRelation(null);
relationCons.getDim1BP().clear();
relationCons.getDim2BP().clear();
}
/**
* Setter for the {@link RelationshipConstrain}, which is created/invoked in this command.
*
* @param relation org.framed.orm.model.Relation
* */
@Override
public void setRelation(final Relation relation) {
this.relationCons = (RelationshipConstraint) relation;
}
/**
* Setter for the {@link Relationship} to which the {@link RelationshipConstrain} is added.
*
* @param rlship org.framed.orm.model.Relationship
* */
public void setRelationship(final Relationship rlship) {
this.relationship = rlship;
}
} |
package org.nikkii.http;
import org.nikkii.http.data.RequestData;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* A Basic HTTP Request, All other requests should extend this
*
* @author Nikki
*/
public abstract class HttpRequest implements AutoCloseable {
/**
* The URL String. We aren't using URL objects just so it's easier to manipulate in GET requests, though it'd be a good idea to allow a URL constructor.
*/
protected String url;
/**
* The UserAgent for this request
*/
private String userAgent;
/**
* The connection instance
*/
protected HttpURLConnection connection;
/**
* A map of header elements. This could be done with guava if we wanted to add another dependency...
*/
private Map<String, List<Object>> headers = new HashMap<>();
/**
* A list of request parameters (RequestData is a simple wrapper which allows chaining)
*/
protected RequestData parameters = new RequestData();
/**
* Construct a new HttpRequest from the specified url string
* @param url The URL
*/
public HttpRequest(String url) {
this.url = url;
}
/**
* Called automatically when using getConnection/getResponse* to execute the request
* @throws IOException If an error occurred while executing
*/
public abstract void execute() throws IOException;
/**
* Opens the connection and sets the uesr agent, headers, etc.
* @throws IOException If an error occurred while opening the connection
*/
protected void openConnection() throws IOException {
connection = (HttpURLConnection) new URL(url).openConnection();
if (userAgent != null) {
connection.setRequestProperty("User-Agent", userAgent);
}
if (!headers.isEmpty()) {
for (Map.Entry<String, List<Object>> e : headers.entrySet()) {
for (Object o : e.getValue()) {
connection.addRequestProperty(e.getKey(), o.toString());
}
}
}
}
/**
* Get the connection object. This is useless except when called after execute or getResponse*
* @return The connection object
*/
public HttpURLConnection getConnection() {
return connection;
}
/**
* Get the HTTP response code.
* This will execute the request if it hasn't already.
* @return The response code from the connection
* @throws IOException If an error occurred while executing the request.
*/
public int getResponseCode() throws IOException {
checkConnection();
return connection.getResponseCode();
}
/**
* Gets the HTTP response as an InputStream
* @return The response stream
*/
public InputStream getResponseStream() throws IOException {
checkConnection();
return connection.getInputStream();
}
/**
* Get the HTTP response body as a string.
* This will execute the request if it hasn't already.
* TODO: Do we want to make sure there's no ending \n?
* @return The response string
* @throws IOException If an error occurred while executing the request.
*/
public String getResponseBody() throws IOException {
checkConnection();
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append('\n');
}
}
return builder.toString();
}
/**
* Checks if the connection has been initialized, and if not initialize and execute the request.
* @throws IOException If an error occurred while executing the request
*/
private void checkConnection() throws IOException {
if (connection == null) {
execute();
}
}
/**
* Add a request parameter (GET or POST) to the request
* @param key The parameter name
* @param value The parameter value (Anything with toString, or MultipartFile for a request)
*/
public void addParameter(String key, Object value) {
parameters.put(key, value);
}
/**
* Set the parameter object
* @param parameters The new parameter object
*/
public void setParameters(RequestData parameters) {
this.parameters = parameters;
}
/**
* Add an http request header to this request
* @param name The request header name
* @param value The request header value
*/
public void addHeader(String name, Object value) {
List<Object> list = headers.get(name);
if (list == null) {
headers.put(name, list = new LinkedList<>());
}
list.add(value);
}
/**
* Set the HTTP User agent
* @param userAgent The user agent
*/
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
/**
* Close the connection (used in AutoCloseable)
*/
@Override
public void close() {
connection.disconnect();
}
} |
package org.eclipse.birt.report.designer.internal.ui;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.core.model.schematic.ListBandProxy;
import org.eclipse.birt.report.designer.internal.ui.dialogs.DataColumnBindingDialog;
import org.eclipse.birt.report.designer.internal.ui.dnd.DNDLocation;
import org.eclipse.birt.report.designer.internal.ui.dnd.DNDService;
import org.eclipse.birt.report.designer.internal.ui.dnd.IDropAdapter;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ListBandEditPart;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableCellEditPart;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.TableGroupHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.jface.window.Window;
public class AggDataDropAdapter implements IDropAdapter
{
public static final String TEMPLATE = "DATA_AGG"; //$NON-NLS-1$
public static final String TRANS_NAME = Messages.getString( "AggDataDropAdapter.Trans.Name" ); //$NON-NLS-1$
public int canDrop( Object transfer, Object target, int operation,
DNDLocation location )
{
if ( transfer instanceof Object[] )
{
}
if ( transfer.equals( TEMPLATE ) )
{
if ( target instanceof TableCellEditPart )
{
CellHandle cellHandle = (CellHandle) ( (TableCellEditPart) target ).getModel( );
if ( cellHandle.getContainer( ).getContainer( ) instanceof TableHandle
|| cellHandle.getContainer( ).getContainer( ) instanceof TableGroupHandle )
{
return DNDService.LOGIC_TRUE;
}
else
{
if ( DEUtil.getBindingHolder( (CellHandle) ( (TableCellEditPart) target ).getModel( ) ) != null )
return DNDService.LOGIC_TRUE;
else
return DNDService.LOGIC_FALSE;
}
}
else if ( target instanceof ListBandEditPart )
{
return DNDService.LOGIC_TRUE;
}
}
return DNDService.LOGIC_UNKNOW;
}
public boolean performDrop( Object transfer, Object target, int operation,
DNDLocation location )
{
if ( transfer instanceof Object[] )
{
}
//create data item, and pass it to AggregationDataBindingDialog
//start transaction
SessionHandleAdapter.getInstance( )
.getCommandStack( )
.startTrans( TRANS_NAME );
DataItemHandle dataHandle = DesignElementFactory.getInstance( )
.newDataItem( null );
try
{
if ( target instanceof TableCellEditPart )
{
CellHandle cellHandle = (CellHandle) ( (TableCellEditPart) target ).getModel( );
cellHandle.addElement( dataHandle, CellHandle.CONTENT_SLOT );
}
else if ( target instanceof ListBandEditPart )
{
ListBandProxy cellHandle = (ListBandProxy) ( (ListBandEditPart) target ).getModel( );
cellHandle.getSlotHandle( ).add( dataHandle );
}
DataColumnBindingDialog dialog = new DataColumnBindingDialog( true );
dialog.setInput( dataHandle );
dialog.setAggreate( true );
if ( dialog.open( ) == Window.OK )
{
dataHandle.setResultSetColumn( dialog.getBindingColumn( )
.getName( ) );
SessionHandleAdapter.getInstance( ).getCommandStack( ).commit( );
}
else
{
SessionHandleAdapter.getInstance( )
.getCommandStack( )
.rollback( );
}
}
catch ( Exception e )
{
SessionHandleAdapter.getInstance( ).getCommandStack( ).rollback( );
ExceptionHandler.handle( e );
}
return true;
}
} |
package pointGroups.gui;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import de.jreality.geometry.Primitives;
public class PointPicker
extends JPanel
{
private static final long serialVersionUID = -3642299900579728806L;
protected final UiViewer uiViewer = new UiViewer(this);
public PointPicker() {
super();
setLayout(new BorderLayout());
JButton button3 = new JButton("VIEW");
PointPicker.this.add(button3, BorderLayout.PAGE_END);
uiViewer.setGeometry(Primitives.cylinder(15));
}
public void dispose() {
uiViewer.dispose();
}
} |
package app.intelehealth.client.activities.pastMedicalHistoryActivity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import app.intelehealth.client.R;
import app.intelehealth.client.activities.questionNodeActivity.QuestionsAdapter;
import app.intelehealth.client.app.AppConstants;
import app.intelehealth.client.app.IntelehealthApplication;
import app.intelehealth.client.database.dao.EncounterDAO;
import app.intelehealth.client.database.dao.ImagesDAO;
import app.intelehealth.client.database.dao.ObsDAO;
import app.intelehealth.client.knowledgeEngine.Node;
import app.intelehealth.client.models.dto.ObsDTO;
import app.intelehealth.client.utilities.FileUtils;
import app.intelehealth.client.utilities.SessionManager;
import app.intelehealth.client.utilities.StringUtils;
import app.intelehealth.client.utilities.UuidDictionary;
import app.intelehealth.client.activities.familyHistoryActivity.FamilyHistoryActivity;
import app.intelehealth.client.activities.visitSummaryActivity.VisitSummaryActivity;
import app.intelehealth.client.utilities.exception.DAOException;
import app.intelehealth.client.utilities.pageindicator.ScrollingPagerIndicator;
public class PastMedicalHistoryActivity extends AppCompatActivity implements QuestionsAdapter.FabClickListener {
String patient = "patient";
String patientUuid;
String visitUuid;
String state;
String patientName;
String intentTag;
ArrayList<String> physicalExams;
int lastExpandedPosition = -1;
String mFileName = "patHist.json";
String image_Prefix = "MH";
String imageDir = "Medical History";
String imageName;
File filePath;
SQLiteDatabase localdb, db;
boolean hasLicense = false;
String edit_PatHist = "";
// String mFileName = "DemoHistory.json";
private static final String TAG = PastMedicalHistoryActivity.class.getSimpleName();
Node patientHistoryMap;
// CustomExpandableListAdapter adapter;
//ExpandableListView historyListView;
String patientHistory;
String phistory = "";
boolean flag = false;
SessionManager sessionManager = null;
private String encounterVitals;
private String encounterAdultIntials, EncounterAdultInitial_LatestVisit;
RecyclerView pastMedical_recyclerView;
QuestionsAdapter adapter;
ScrollingPagerIndicator recyclerViewIndicator;
String new_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
sessionManager = new SessionManager(this);
localdb = AppConstants.inteleHealthDatabaseHelper.getWriteDb();
filePath = new File(AppConstants.IMAGE_PATH);
// SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// e = sharedPreferences.edit();
Intent intent = this.getIntent(); // The intent was passed to the activity
if (intent != null) {
patientUuid = intent.getStringExtra("patientUuid");
visitUuid = intent.getStringExtra("visitUuid");
encounterVitals = intent.getStringExtra("encounterUuidVitals");
edit_PatHist = intent.getStringExtra("edit_PatHist");
encounterAdultIntials = intent.getStringExtra("encounterUuidAdultIntial");
EncounterAdultInitial_LatestVisit = intent.getStringExtra("EncounterAdultInitial_LatestVisit");
state = intent.getStringExtra("state");
patientName = intent.getStringExtra("name");
intentTag = intent.getStringExtra("tag");
new_result = getPastMedicalVisitData();
}
boolean past = sessionManager.isReturning();
if (past && edit_PatHist == null) {
MaterialAlertDialogBuilder alertdialog = new MaterialAlertDialogBuilder(this);
//AlertDialog.Builder alertdialog = new AlertDialog.Builder(PastMedicalHistoryActivity.this,R.style.AlertDialogStyle);
View layoutInflater = LayoutInflater.from(PastMedicalHistoryActivity.this)
.inflate(R.layout.past_fam_hist_previous_details, null);
alertdialog.setView(layoutInflater);
TextView textView = layoutInflater.findViewById(R.id.textview_details);
Log.v(TAG, new_result);
textView.setText(Html.fromHtml(new_result));
alertdialog.setTitle(getString(R.string.title_activity_patient_history));
alertdialog.setMessage(getString(R.string.question_update_details));
alertdialog.setPositiveButton(getString(R.string.generic_yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// allow to edit
flag = true;
}
});
alertdialog.setNegativeButton(getString(R.string.generic_no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] columns = {"value", " conceptuuid"};
try {
String medHistSelection = "encounteruuid = ? AND conceptuuid = ? AND voided!='1'";
String[] medHistArgs = {EncounterAdultInitial_LatestVisit, UuidDictionary.RHK_MEDICAL_HISTORY_BLURB};
Cursor medHistCursor = localdb.query("tbl_obs", columns, medHistSelection, medHistArgs, null, null, null);
medHistCursor.moveToLast();
phistory = medHistCursor.getString(medHistCursor.getColumnIndexOrThrow("value"));
medHistCursor.close();
} catch (CursorIndexOutOfBoundsException e) {
phistory = ""; // if medical history does not exist
}
// skip
flag = false;
if (phistory != null && !phistory.isEmpty() && !phistory.equals("null")) {
insertDb(phistory);
}
Intent intent = new Intent(PastMedicalHistoryActivity.this, FamilyHistoryActivity.class);
intent.putExtra("patientUuid", patientUuid);
intent.putExtra("visitUuid", visitUuid);
intent.putExtra("encounterUuidVitals", encounterVitals);
intent.putExtra("encounterUuidAdultIntial", encounterAdultIntials);
intent.putExtra("EncounterAdultInitial_LatestVisit", EncounterAdultInitial_LatestVisit);
intent.putExtra("state", state);
intent.putExtra("name", patientName);
intent.putExtra("tag", intentTag);
// intent.putStringArrayListExtra("exams", physicalExams);
startActivity(intent);
}
});
Dialog builderDialog = alertdialog.show();
builderDialog.setCancelable(false);
builderDialog.setCanceledOnTouchOutside(false);
IntelehealthApplication.setAlertDialogCustomTheme(this, builderDialog);
}
setTitle(getString(R.string.title_activity_patient_history));
setTitle(getTitle() + ": " + patientName);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_past_medical_history);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextAppearance(this, R.style.ToolbarTheme);
toolbar.setTitleTextColor(Color.WHITE);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
recyclerViewIndicator=findViewById(R.id.recyclerViewIndicator);
pastMedical_recyclerView = findViewById(R.id.pastMedical_recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,RecyclerView.HORIZONTAL,false);
pastMedical_recyclerView.setLayoutManager(linearLayoutManager);
pastMedical_recyclerView.setItemAnimator(new DefaultItemAnimator());
PagerSnapHelper helper = new PagerSnapHelper();
helper.attachToRecyclerView(pastMedical_recyclerView);
FloatingActionButton fab = findViewById(R.id.fab);
assert fab != null;
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fabClick();
}
});
if (!sessionManager.getLicenseKey().isEmpty())
hasLicense = true;
if (hasLicense) {
try {
JSONObject currentFile = null;
currentFile = new JSONObject(FileUtils.readFileRoot(mFileName, this));
patientHistoryMap = new Node(currentFile); //Load the patient history mind map
} catch (JSONException e) {
FirebaseCrashlytics.getInstance().recordException(e);
}
} else {
patientHistoryMap = new Node(FileUtils.encodeJSON(this, mFileName)); //Load the patient history mind map
}
/* historyListView = findViewById(R.id.patient_history_expandable_list_view);
adapter = new CustomExpandableListAdapter(this, patientHistoryMap, this.getClass().getSimpleName()); //The adapter might change depending on the activity.
historyListView.setAdapter(adapter);*/
adapter = new QuestionsAdapter(this, patientHistoryMap, pastMedical_recyclerView, this.getClass().getSimpleName(), this, false);
pastMedical_recyclerView.setAdapter(adapter);
recyclerViewIndicator.attachToRecyclerView(pastMedical_recyclerView);
/* historyListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
onListClick(v, groupPosition, childPosition);
return false;
}
});
//Same fix as before, close all other groups when something is clicked.
historyListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
historyListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});*/
}
private void onListClick(View v, int groupPosition, int childPosition) {
Node clickedNode = patientHistoryMap.getOption(groupPosition).getOption(childPosition);
clickedNode.toggleSelected();
//Nodes and the expandable list act funny, so if anything is clicked, a lot of stuff needs to be updated.
if (patientHistoryMap.getOption(groupPosition).anySubSelected()) {
patientHistoryMap.getOption(groupPosition).setSelected(true);
} else {
patientHistoryMap.getOption(groupPosition).setUnselected();
}
adapter.notifyDataSetChanged();
if (clickedNode.getInputType() != null) {
if (!clickedNode.getInputType().equals("camera")) {
imageName = UUID.randomUUID().toString();
Node.handleQuestion(clickedNode, PastMedicalHistoryActivity.this, adapter, null, null);
}
}
Log.i(TAG, String.valueOf(clickedNode.isTerminal()));
if (!clickedNode.isTerminal() && clickedNode.isSelected()) {
imageName = UUID.randomUUID().toString();
Node.subLevelQuestion(clickedNode, PastMedicalHistoryActivity.this, adapter, filePath.toString(), imageName);
}
}
private void fabClick() {
//If nothing is selected, there is nothing to put into the database.
List<String> imagePathList = patientHistoryMap.getImagePathList();
if (imagePathList != null) {
for (String imagePath : imagePathList) {
updateImageDatabase(imagePath);
}
}
if (intentTag != null && intentTag.equals("edit")) {
if (patientHistoryMap.anySubSelected()) {
patientHistory = patientHistoryMap.generateLanguage();
updateDatabase(patientHistory); // update details of patient's visit, when edit button on VisitSummary is pressed
}
// displaying all values in another activity
Intent intent = new Intent(PastMedicalHistoryActivity.this, VisitSummaryActivity.class);
intent.putExtra("patientUuid", patientUuid);
intent.putExtra("visitUuid", visitUuid);
intent.putExtra("encounterUuidVitals", encounterVitals);
intent.putExtra("encounterUuidAdultIntial", encounterAdultIntials);
intent.putExtra("EncounterAdultInitial_LatestVisit", EncounterAdultInitial_LatestVisit);
intent.putExtra("state", state);
intent.putExtra("name", patientName);
intent.putExtra("tag", intentTag);
intent.putExtra("hasPrescription", "false");
startActivity(intent);
} else {
// if(patientHistoryMap.anySubSelected()){
patientHistory = patientHistoryMap.generateLanguage();
if (flag == true) { // only if OK clicked, collect this new info (old patient)
phistory = phistory + patientHistory; // only PMH updated
sessionManager.setReturning(true);
insertDb(phistory);
// however, we concat it here to patientHistory and pass it along to FH, not inserting into db
} else // new patient, directly insert into database
{
insertDb(patientHistory);
}
Intent intent = new Intent(PastMedicalHistoryActivity.this, FamilyHistoryActivity.class);
intent.putExtra("patientUuid", patientUuid);
intent.putExtra("visitUuid", visitUuid);
intent.putExtra("encounterUuidVitals", encounterVitals);
intent.putExtra("encounterUuidAdultIntial", encounterAdultIntials);
intent.putExtra("EncounterAdultInitial_LatestVisit", EncounterAdultInitial_LatestVisit);
intent.putExtra("state", state);
intent.putExtra("name", patientName);
intent.putExtra("tag", intentTag);
// intent.putStringArrayListExtra("exams", physicalExams);
startActivity(intent);
}
}
/**
* This method inserts medical history of patient in database.
*
* @param value variable of type String
* @return long
*/
public boolean insertDb(String value) {
ObsDAO obsDAO = new ObsDAO();
ObsDTO obsDTO = new ObsDTO();
obsDTO.setConceptuuid(UuidDictionary.RHK_MEDICAL_HISTORY_BLURB);
obsDTO.setEncounteruuid(encounterAdultIntials);
obsDTO.setCreator(sessionManager.getCreatorID());
obsDTO.setValue(StringUtils.getValue(value));
boolean isInserted = false;
try {
isInserted = obsDAO.insertObs(obsDTO);
} catch (DAOException e) {
FirebaseCrashlytics.getInstance().recordException(e);
}
return isInserted;
}
private void updateImageDatabase(String imagePath) {
ImagesDAO imagesDAO = new ImagesDAO();
try {
imagesDAO.insertObsImageDatabase(imageName, encounterAdultIntials, "");
} catch (DAOException e) {
FirebaseCrashlytics.getInstance().recordException(e);
}
}
/**
* This method updates medical history of patient in database.
*
* @param string variable of type String
* @return void
*/
private void updateDatabase(String string) {
ObsDTO obsDTO = new ObsDTO();
ObsDAO obsDAO = new ObsDAO();
try {
obsDTO.setConceptuuid(UuidDictionary.RHK_MEDICAL_HISTORY_BLURB);
obsDTO.setEncounteruuid(encounterAdultIntials);
obsDTO.setCreator(sessionManager.getCreatorID());
obsDTO.setValue(string);
obsDTO.setUuid(obsDAO.getObsuuid(encounterAdultIntials, UuidDictionary.RHK_MEDICAL_HISTORY_BLURB));
obsDAO.updateObs(obsDTO);
} catch (DAOException dao) {
FirebaseCrashlytics.getInstance().recordException(dao);
}
EncounterDAO encounterDAO = new EncounterDAO();
try {
encounterDAO.updateEncounterSync("false", encounterAdultIntials);
encounterDAO.updateEncounterModifiedDate(encounterAdultIntials);
} catch (DAOException e) {
FirebaseCrashlytics.getInstance().recordException(e);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Node.TAKE_IMAGE_FOR_NODE) {
if (resultCode == RESULT_OK) {
String mCurrentPhotoPath = data.getStringExtra("RESULT");
patientHistoryMap.setImagePath(mCurrentPhotoPath);
Log.i(TAG, mCurrentPhotoPath);
patientHistoryMap.displayImage(this, filePath.getAbsolutePath(), imageName);
}
}
}
@Override
public void onBackPressed() {
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void fabClickedAtEnd() {
// patientHistoryMap = node;
fabClick();
}
@Override
public void onChildListClickEvent(int groupPos, int childPos, int physExamPos) {
onListClick(null, groupPos, childPos);
}
public void AnimateView(View v) {
int fadeInDuration = 500; // Configure time values here
int timeBetween = 3000;
int fadeOutDuration = 1000;
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator()); // add this
fadeIn.setDuration(fadeInDuration);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator()); // and this
fadeOut.setStartOffset(fadeInDuration + timeBetween);
fadeOut.setDuration(fadeOutDuration);
AnimationSet animation = new AnimationSet(false); // change to false
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
animation.setRepeatCount(1);
if (v != null) {
v.setAnimation(animation);
}
}
public void bottomUpAnimation(View v) {
if (v != null) {
v.setVisibility(View.VISIBLE);
Animation bottomUp = AnimationUtils.loadAnimation(this,
R.anim.bottom_up);
v.startAnimation(bottomUp);
}
}
public String getPastMedicalVisitData() {
String result = "";
db = AppConstants.inteleHealthDatabaseHelper.getWritableDatabase();
// String[] columns = {"value"};
String[] columns = {"value", " conceptuuid"};
try {
String medHistSelection = "encounteruuid = ? AND conceptuuid = ? AND voided!='1'";
String[] medHistArgs = {EncounterAdultInitial_LatestVisit, UuidDictionary.RHK_MEDICAL_HISTORY_BLURB};
Cursor medHistCursor = localdb.query("tbl_obs", columns, medHistSelection, medHistArgs, null, null, null);
medHistCursor.moveToLast();
result = medHistCursor.getString(medHistCursor.getColumnIndexOrThrow("value"));
medHistCursor.close();
} catch (CursorIndexOutOfBoundsException e) {
result = ""; // if medical history does not exist
}
/*
try {
String medHistSelection = "encounteruuid = ? AND conceptuuid = ?";
String[] medHistArgs = {EncounterAdultInitial_LatestVisit, UuidDictionary.RHK_MEDICAL_HISTORY_BLURB};
Cursor medHistCursor = db.query("tbl_obs", columns, medHistSelection, medHistArgs, null, null, null);
medHistCursor.moveToLast();
result = medHistCursor.getString(medHistCursor.getColumnIndexOrThrow("value"));
// patHistory.setValue(medHistText);
// result = medHistText;
if (result != null && !result.isEmpty()) {
// medHistory = patHistory.getValue();
result = result.replace("\"", "");
result = result.replace("\n", "");
do {
result = result.replace(" ", "");
} while (result.contains(" "));
}
else
result = "";
medHistCursor.close();
} catch (CursorIndexOutOfBoundsException e) {
// patHistory.setValue(""); // if medical history does not exist
result = "";
}
*/
// db.setTransactionSuccessful();
db.close();
return result;
}
} |
package seedu.address.ui;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import seedu.address.commons.core.Config;
import seedu.address.commons.core.GuiSettings;
import seedu.address.commons.events.ui.ExitAppRequestEvent;
import seedu.address.logic.Logic;
import seedu.address.model.UserPrefs;
import seedu.address.model.activity.ReadOnlyActivity;
import seedu.address.storage.XmlAddressBookStorage;
/**
* The Main Window. Provides the basic application layout containing
* a menu bar and space where other JavaFX elements can be placed.
*/
public class MainWindow extends UiPart {
private static final String ICON = "/images/lifekeeper.png";
private static final String FXML = "MainWindow.fxml";
public static final int MIN_HEIGHT = 600;
public static final int MIN_WIDTH = 450;
private Logic logic;
// Independent Ui parts residing in this Ui container
private ActivityListPanel activityListPanel;
private OverdueTaskListPanel overdueListPanel;
private ResultDisplay resultDisplay;
private StatusBarFooter statusBarFooter;
private CommandBox commandBox;
private Config config;
private UserPrefs userPrefs;
// Handles to elements of this Ui container
private VBox rootLayout;
private Scene scene;
private String addressBookName;
@FXML
private AnchorPane browserPlaceholder;
@FXML
private AnchorPane commandBoxPlaceholder;
@FXML
private MenuItem helpMenuItem;
@FXML
private AnchorPane activityListPanelPlaceholder;
@FXML
private AnchorPane resultDisplayPlaceholder;
@FXML
private AnchorPane statusbarPlaceholder;
@FXML
private AnchorPane upcomingListPanelPlaceholder;
@FXML
private AnchorPane overdueListDisplayPlaceHolder;
public MainWindow() {
super();
}
@Override
public void setNode(Node node) {
rootLayout = (VBox) node;
}
@Override
public String getFxmlPath() {
return FXML;
}
public static MainWindow load(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
MainWindow mainWindow = UiPartLoader.loadUiPart(primaryStage, new MainWindow());
mainWindow.configure(config.getAppTitle(), config.getLifekeeperName(), config, prefs, logic);
return mainWindow;
}
private void configure(String appTitle, String addressBookName, Config config, UserPrefs prefs,
Logic logic) {
//Set dependencies
this.logic = logic;
this.addressBookName = addressBookName;
this.config = config;
this.userPrefs = prefs;
//Configure the UI
setTitle(appTitle);
setIcon(ICON);
setWindowMinSize();
setWindowDefaultSize(prefs);
scene = new Scene(rootLayout);
primaryStage.setScene(scene);
setAccelerators();
}
private void setAccelerators() {
helpMenuItem.setAccelerator(KeyCombination.valueOf("F1"));
}
void fillInnerParts() {
//fill main activities display panel
activityListPanel = ActivityListPanel.load(primaryStage, getPersonListPlaceholder(), logic.getFilteredPersonList());
//fill dash board
overdueListPanel = OverdueTaskListPanel.load(primaryStage, getOverdueListPlaceholder(), logic.getFilteredOverdueTaskList());
resultDisplay = ResultDisplay.load(primaryStage, getResultDisplayPlaceholder());
statusBarFooter = StatusBarFooter.load(primaryStage, getStatusbarPlaceholder(), userPrefs.getDataFilePath());
commandBox = CommandBox.load(primaryStage, getCommandBoxPlaceholder(), resultDisplay, logic);
}
private AnchorPane getCommandBoxPlaceholder() {
return commandBoxPlaceholder;
}
private AnchorPane getStatusbarPlaceholder() {
return statusbarPlaceholder;
}
private AnchorPane getResultDisplayPlaceholder() {
return resultDisplayPlaceholder;
}
public AnchorPane getPersonListPlaceholder() {
return activityListPanelPlaceholder;
}
public AnchorPane getOverdueListPlaceholder() {
return overdueListDisplayPlaceHolder;
}
public AnchorPane getUpcomingListPlaceholder() {
return upcomingListPanelPlaceholder;
}
public void hide() {
primaryStage.hide();
}
private void setTitle(String appTitle) {
primaryStage.setTitle(appTitle);
}
/**
* Sets the default size based on user preferences.
*/
protected void setWindowDefaultSize(UserPrefs prefs) {
primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight());
primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth());
if (prefs.getGuiSettings().getWindowCoordinates() != null) {
primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX());
primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY());
}
}
private void setWindowMinSize() {
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setMinWidth(MIN_WIDTH);
}
/**
* Returns the current size and the position of the main Window.
*/
public GuiSettings getCurrentGuiSetting() {
return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(),
(int) primaryStage.getX(), (int) primaryStage.getY());
}
@FXML
public void handleHelp() {
HelpWindow helpWindow = HelpWindow.load(primaryStage);
helpWindow.show();
}
public void show() {
primaryStage.show();
}
/**
* Closes the application.
*/
@FXML
private void handleExit() {
raise(new ExitAppRequestEvent());
}
//@@author A0125680H
@FXML
private void handleSaveLoc() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("data/addressbook.xml"));
fileChooser.setFileFilter(new FileNameExtensionFilter("XML File", "xml"));
fileChooser.setAcceptAllFileFilterUsed(false);
int result = fileChooser.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (!selectedFile.getAbsolutePath().endsWith(".xml")) {
selectedFile = new File(selectedFile.getAbsolutePath() + ".xml");
}
XmlAddressBookStorage.setAddressBookFilePath(selectedFile.getAbsolutePath());
resultDisplay.postMessage("New save location: " + selectedFile.getAbsolutePath());
userPrefs.setDataFilePath(selectedFile.getAbsolutePath());
statusBarFooter.setSaveLocation(selectedFile.getAbsolutePath());
}
}
public ActivityListPanel getActivityListPanel() {
return this.activityListPanel;
}
public void refresh() {
activityListPanel.refresh();
}
} |
package org.ovirt.engine.core.bll.validator.storage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.bll.provider.storage.OpenStackVolumeProviderProxy;
import org.ovirt.engine.core.common.businessentities.storage.CinderDisk;
import org.ovirt.engine.core.common.businessentities.storage.CinderVolumeType;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.VolumeClassification;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.DiskDao;
import org.ovirt.engine.core.dao.StorageDomainDao;
import com.woorea.openstack.base.client.OpenStackResponseException;
import com.woorea.openstack.cinder.model.Limits;
public class CinderDisksValidator {
private Iterable<CinderDisk> cinderDisks;
private Map<Guid, OpenStackVolumeProviderProxy> diskProxyMap;
private Map<Guid, CinderStorageRelatedDisksAndProxy> cinderStorageToRelatedDisks;
public CinderDisksValidator(Iterable<CinderDisk> cinderDisks) {
this.cinderDisks = cinderDisks;
this.diskProxyMap = initializeVolumeProviderProxyMap();
}
public CinderDisksValidator(CinderDisk cinderDisk) {
this(Collections.singleton(cinderDisk));
}
private ValidationResult validate(Callable<ValidationResult> callable) {
try {
return callable.call();
} catch (OpenStackResponseException e) {
return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_CINDER,
String.format("$cinderException %1$s", e.getMessage()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public ValidationResult validateCinderDiskLimits() {
return validate(new Callable<ValidationResult>() {
@Override
public ValidationResult call() {
Map<Guid, CinderStorageRelatedDisksAndProxy> relatedCinderDisksByStorageMap =
getRelatedCinderDisksToStorageDomainMap();
Collection<CinderStorageRelatedDisksAndProxy> relatedCinderDisksByStorageCollection =
relatedCinderDisksByStorageMap.values();
for (CinderStorageRelatedDisksAndProxy relatedCinderDisksByStorage : relatedCinderDisksByStorageCollection) {
Limits limits = relatedCinderDisksByStorage.getProxy().getLimits();
int numOfDisks = relatedCinderDisksByStorage.getCinderDisks().size();
if (isLimitExceeded(limits, VolumeClassification.Volume, numOfDisks)) {
String storageName =
getStorageDomainDao().get(relatedCinderDisksByStorage.getStorageDomainId())
.getStorageName();
return new ValidationResult(EngineMessage.CANNOT_ADD_CINDER_DISK_VOLUME_LIMIT_EXCEEDED,
String.format("$maxTotalVolumes %d", limits.getAbsolute().getMaxTotalVolumes()),
String.format("$storageName %s", storageName));
}
}
return ValidationResult.VALID;
}
});
}
public ValidationResult validateCinderDiskSnapshotsLimits() {
return validate(new Callable<ValidationResult>() {
@Override
public ValidationResult call() {
Map<Guid, CinderStorageRelatedDisksAndProxy> relatedCinderDisksByStorageMap =
getRelatedCinderDisksToStorageDomainMap();
Collection<CinderStorageRelatedDisksAndProxy> relatedCinderDisksByStorageCollection =
relatedCinderDisksByStorageMap.values();
for (CinderStorageRelatedDisksAndProxy relatedCinderDisksByStorage : relatedCinderDisksByStorageCollection) {
Limits limits = relatedCinderDisksByStorage.getProxy().getLimits();
int numOfDisks = relatedCinderDisksByStorage.getCinderDisks().size();
if (isLimitExceeded(limits, VolumeClassification.Snapshot, numOfDisks)) {
String storageName =
getStorageDomainDao().get(relatedCinderDisksByStorage.getStorageDomainId())
.getStorageName();
return new ValidationResult(EngineMessage.CANNOT_ADD_CINDER_DISK_SNAPSHOT_LIMIT_EXCEEDED,
String.format("$maxTotalSnapshots %d", limits.getAbsolute().getMaxTotalVolumes()),
String.format("$storageName %s", storageName));
}
}
return ValidationResult.VALID;
}
});
}
private boolean isLimitExceeded(Limits limits, VolumeClassification cinderType, int diskCount) {
if (cinderType == VolumeClassification.Snapshot) {
return (limits.getAbsolute().getTotalSnapshotsUsed() + diskCount >
limits.getAbsolute().getMaxTotalSnapshots());
}
if (cinderType == VolumeClassification.Volume) {
return (limits.getAbsolute().getTotalVolumesUsed() + diskCount >
limits.getAbsolute().getMaxTotalVolumes());
}
return false;
}
private Map<Guid, CinderStorageRelatedDisksAndProxy> getRelatedCinderDisksToStorageDomainMap() {
if (cinderStorageToRelatedDisks == null) {
cinderStorageToRelatedDisks = new HashMap<>();
for (CinderDisk cinderDisk : cinderDisks) {
Guid storageDomainId = cinderDisk.getStorageIds().get(0);
CinderStorageRelatedDisksAndProxy cinderRelatedDisksAndProxy =
cinderStorageToRelatedDisks.get(storageDomainId);
if (cinderRelatedDisksAndProxy == null) {
List<CinderDisk> cinderDisks = new ArrayList<>();
cinderDisks.add(cinderDisk);
OpenStackVolumeProviderProxy proxy = diskProxyMap.get(cinderDisk.getId());
CinderStorageRelatedDisksAndProxy newCinderRelatedDisksAndProxy =
new CinderStorageRelatedDisksAndProxy(storageDomainId, cinderDisks, proxy);
cinderStorageToRelatedDisks.put(storageDomainId, newCinderRelatedDisksAndProxy);
} else {
cinderRelatedDisksAndProxy.getCinderDisks().add(cinderDisk);
}
}
}
return cinderStorageToRelatedDisks;
}
private static class CinderStorageRelatedDisksAndProxy {
private Guid storageDomainId;
private List<CinderDisk> cinderDisks = new ArrayList<>();
private OpenStackVolumeProviderProxy proxy;
public CinderStorageRelatedDisksAndProxy(Guid storageDomainId, List<CinderDisk> cinderDisks, OpenStackVolumeProviderProxy proxy) {
setStorageDomainId(storageDomainId);
setCinderDisks(cinderDisks);
setProxy(proxy);
}
public Guid getStorageDomainId() {
return storageDomainId;
}
public void setStorageDomainId(Guid storageDomainId) {
this.storageDomainId = storageDomainId;
}
public List<CinderDisk> getCinderDisks() {
return cinderDisks;
}
public void setCinderDisks(List<CinderDisk> cinderDisks) {
this.cinderDisks = cinderDisks;
}
public OpenStackVolumeProviderProxy getProxy() {
return proxy;
}
public void setProxy(OpenStackVolumeProviderProxy proxy) {
this.proxy = proxy;
}
}
public ValidationResult validateCinderDisksAlreadyRegistered() {
return validate(new Callable<ValidationResult>() {
@Override
public ValidationResult call() {
for (CinderDisk disk : cinderDisks) {
Disk diskFromDB = getDiskDao().get(disk.getId());
if (diskFromDB != null) {
return new ValidationResult(EngineMessage.CINDER_DISK_ALREADY_REGISTERED,
String.format("$diskAlias %s", diskFromDB.getDiskAlias()));
}
}
return ValidationResult.VALID;
}
});
}
/**
* Validates that the disk's volume type exists in Cinder
* (note that this method validates only against a single disk).
*/
public ValidationResult validateCinderVolumeTypesExist() {
return validate(new Callable<ValidationResult>() {
@Override
public ValidationResult call() {
final CinderDisk disk = cinderDisks.iterator().next();
OpenStackVolumeProviderProxy proxy = diskProxyMap.get(disk.getId());
List<CinderVolumeType> volumeTypes = proxy.getVolumeTypes();
boolean volumeTypeExists = CollectionUtils.exists(volumeTypes, new Predicate() {
@Override
public boolean evaluate(Object o) {
return ((CinderVolumeType) o).getName().equals(disk.getCinderVolumeType());
}
});
if (!volumeTypeExists) {
return new ValidationResult(EngineMessage.CINDER_VOLUME_TYPE_NOT_EXISTS,
String.format("$cinderVolumeType %s", disk.getCinderVolumeType()));
}
return ValidationResult.VALID;
}
});
}
private Map<Guid, OpenStackVolumeProviderProxy> initializeVolumeProviderProxyMap() {
if (diskProxyMap == null) {
diskProxyMap = new HashMap<>();
for (CinderDisk cinderDisk : cinderDisks) {
OpenStackVolumeProviderProxy volumeProviderProxy = getVolumeProviderProxy(cinderDisk);
diskProxyMap.put(cinderDisk.getId(), volumeProviderProxy);
}
}
return diskProxyMap;
}
private OpenStackVolumeProviderProxy getVolumeProviderProxy(CinderDisk cinderDisk) {
if (cinderDisk == null || cinderDisk.getStorageIds().isEmpty()) {
return null;
}
return OpenStackVolumeProviderProxy.getFromStorageDomainId(cinderDisk.getStorageIds().get(0));
}
protected DiskDao getDiskDao() {
return DbFacade.getInstance().getDiskDao();
}
protected StorageDomainDao getStorageDomainDao() {
return DbFacade.getInstance().getStorageDomainDao();
}
} |
package org.opendaylight.bgpcep.bgp.topology.provider;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.io.BaseEncoding;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.protocol.bgp.rib.RibReference;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.DomainName;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.Ipv4InterfaceIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.Ipv6InterfaceIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.IsisAreaIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeFlagBits;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.TopologyIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.ObjectType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.LinkCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.NodeCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.PrefixCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.link._case.LinkDescriptors;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.LinkStateAttribute;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.LinkAttributesCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.NodeAttributesCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.PrefixAttributesCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.link.attributes._case.LinkAttributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.node.attributes._case.NodeAttributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.prefix.attributes._case.PrefixAttributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.routes.LinkstateRoutes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.routes.linkstate.routes.LinkstateRoute;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.routes.linkstate.routes.linkstate.route.Attributes1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.CRouterIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.IsisNodeCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.IsisPseudonodeCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.OspfNodeCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.OspfPseudonodeCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.isis.node._case.IsisNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.isis.pseudonode._case.IsisPseudonode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.ospf.pseudonode._case.OspfPseudonode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.concepts.rev131125.Bandwidth;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.SrlgId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IsoNetId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IsoPseudonodeId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IsoSystemId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.link.attributes.IsisLinkAttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.node.attributes.IsisNodeAttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.node.attributes.isis.node.attributes.IsoBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.srlg.attributes.SrlgValues;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.srlg.attributes.SrlgValuesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.ted.link.attributes.SrlgBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.ted.link.attributes.UnreservedBandwidth;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.ted.link.attributes.UnreservedBandwidthBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.ted.link.attributes.UnreservedBandwidthKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.LinkId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
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.TpId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.link.attributes.DestinationBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.link.attributes.SourceBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.LinkBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.LinkKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.TopologyTypesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Link1;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Link1Builder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Node1;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Node1Builder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.TerminationPoint1;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.TerminationPoint1Builder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.TopologyTypes1;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.TopologyTypes1Builder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.link.attributes.IgpLinkAttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.IgpNodeAttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.igp.node.attributes.Prefix;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.igp.node.attributes.PrefixBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.igp.node.attributes.PrefixKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.termination.point.attributes.IgpTerminationPointAttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.termination.point.attributes.igp.termination.point.attributes.TerminationPointType;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.termination.point.attributes.igp.termination.point.attributes.termination.point.type.IpBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.termination.point.attributes.igp.termination.point.attributes.termination.point.type.UnnumberedBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.Prefix1;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.Prefix1Builder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.link.attributes.OspfLinkAttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.OspfNodeAttributesBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.router.type.AbrBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.router.type.InternalBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.router.type.PseudonodeBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.prefix.attributes.OspfPrefixAttributesBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class LinkstateTopologyBuilder extends AbstractTopologyBuilder<LinkstateRoute> {
private static final String UNHANDLED_OBJECT_CLASS = "Unhandled object class {}";
private static final class TpHolder {
private final Set<LinkId> local = new HashSet<>();
private final Set<LinkId> remote = new HashSet<>();
private final TerminationPoint tp;
private TpHolder(final TerminationPoint tp) {
this.tp = Preconditions.checkNotNull(tp);
}
private synchronized void addLink(final LinkId id, final boolean isRemote) {
if (isRemote) {
this.remote.add(id);
} else {
this.local.add(id);
}
}
private synchronized boolean removeLink(final LinkId id, final boolean isRemote) {
final boolean removed;
if (isRemote) {
removed = this.remote.remove(id);
} else {
removed = this.local.remove(id);
}
if (!removed) {
LOG.warn("Removed non-reference link {} from TP {} isRemote {}", this.tp.getTpId(), id, isRemote);
}
return this.local.isEmpty() && this.remote.isEmpty();
}
private TerminationPoint getTp() {
return this.tp;
}
}
private final class NodeHolder {
private final Map<PrefixKey, Prefix> prefixes = new HashMap<>();
private final Map<TpId, TpHolder> tps = new HashMap<>();
private boolean advertized = false;
private IgpNodeAttributesBuilder inab;
private NodeBuilder nb;
private NodeHolder(final NodeId id) {
this.inab = new IgpNodeAttributesBuilder();
this.nb = new NodeBuilder().setKey(new NodeKey(id)).setNodeId(id);
}
/**
* Synchronized in-core state of a node into the backing store using the transaction
*
* @param trans data modification transaction which to use
* @return True if the node has been purged, false otherwise.
*/
private boolean syncState(final WriteTransaction trans) {
final InstanceIdentifier<Node> nid = getInstanceIdentifier().child(
org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class,
this.nb.getKey());
/*
* Transaction's putOperationalData() does a merge. Force it onto a replace
* by removing the data. If we decide to remove the node -- we just skip the put.
*/
trans.delete(LogicalDatastoreType.OPERATIONAL, nid);
if (!this.advertized) {
if (this.tps.isEmpty() && this.prefixes.isEmpty()) {
LOG.debug("Removing unadvertized unused node {}", this.nb.getNodeId());
return true;
}
LOG.debug("Node {} is still implied by {} TPs and {} prefixes", this.nb.getNodeId(), this.tps.size(), this.prefixes.size());
}
// Re-generate termination points
this.nb.setTerminationPoint(Lists.newArrayList(Collections2.transform(this.tps.values(), new Function<TpHolder, TerminationPoint>() {
@Override
public TerminationPoint apply(final TpHolder input) {
return input.getTp();
}
})));
// Re-generate prefixes
this.inab.setPrefix(Lists.newArrayList(this.prefixes.values()));
// Write the node out
final Node n = this.nb.addAugmentation(Node1.class, new Node1Builder().setIgpNodeAttributes(this.inab.build()).build()).build();
trans.put(LogicalDatastoreType.OPERATIONAL, nid, n);
LOG.debug("Created node {} at {}", n, nid);
return false;
}
private synchronized void removeTp(final TpId tp, final LinkId link, final boolean isRemote) {
final TpHolder h = this.tps.get(tp);
if (h != null) {
if (h.removeLink(link, isRemote)) {
this.tps.remove(tp);
LOG.debug("Removed TP {}", tp);
}
} else {
LOG.warn("Removed non-present TP {} by link {}", tp, link);
}
}
private void addTp(final TerminationPoint tp, final LinkId link, final boolean isRemote) {
TpHolder h = this.tps.get(tp.getTpId());
if (h == null) {
h = new TpHolder(tp);
this.tps.put(tp.getTpId(), h);
}
h.addLink(link, isRemote);
}
private void addPrefix(final Prefix pfx) {
this.prefixes.put(pfx.getKey(), pfx);
}
private void removePrefix(final PrefixCase p) {
this.prefixes.remove(new PrefixKey(p.getPrefixDescriptors().getIpReachabilityInformation()));
}
private void unadvertized() {
this.inab = new IgpNodeAttributesBuilder();
this.nb = new NodeBuilder().setKey(this.nb.getKey()).setNodeId(this.nb.getNodeId());
this.advertized = false;
LOG.debug("Node {} is unadvertized", this.nb.getNodeId());
}
private void advertized(final NodeBuilder nb, final IgpNodeAttributesBuilder inab) {
this.nb = Preconditions.checkNotNull(nb);
this.inab = Preconditions.checkNotNull(inab);
this.advertized = true;
LOG.debug("Node {} is advertized", nb.getNodeId());
}
private Object getNodeId() {
return this.nb.getNodeId();
}
}
private static final Logger LOG = LoggerFactory.getLogger(LinkstateTopologyBuilder.class);
private final Map<NodeId, NodeHolder> nodes = new HashMap<>();
public LinkstateTopologyBuilder(final DataBroker dataProvider, final RibReference locRibReference, final TopologyId topologyId) {
super(dataProvider, locRibReference, topologyId, new TopologyTypesBuilder().addAugmentation(TopologyTypes1.class,
new TopologyTypes1Builder().build()).build());
}
private static LinkId buildLinkId(final UriBuilder base, final LinkCase link) {
return new LinkId(new UriBuilder(base, "link").add(link).toString());
}
private static NodeId buildNodeId(final UriBuilder base,
final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeIdentifier node) {
return new NodeId(new UriBuilder(base, "node").add("", node).toString());
}
private static TpId buildTpId(final UriBuilder base, final TopologyIdentifier topologyIdentifier,
final Ipv4InterfaceIdentifier ipv4InterfaceIdentifier, final Ipv6InterfaceIdentifier ipv6InterfaceIdentifier, final Long id) {
final UriBuilder b = new UriBuilder(base, "tp");
if (topologyIdentifier != null) {
b.add("mt", topologyIdentifier.getValue());
}
if (ipv4InterfaceIdentifier != null) {
b.add("ipv4", ipv4InterfaceIdentifier.getValue());
}
if (ipv6InterfaceIdentifier != null) {
b.add("ipv6", ipv6InterfaceIdentifier.getValue());
}
return new TpId(b.add("id", id).toString());
}
private static TpId buildLocalTpId(final UriBuilder base, final LinkDescriptors linkDescriptors) {
return buildTpId(base, linkDescriptors.getMultiTopologyId(), linkDescriptors.getIpv4InterfaceAddress(),
linkDescriptors.getIpv6InterfaceAddress(), linkDescriptors.getLinkLocalIdentifier());
}
private static TerminationPoint buildTp(final TpId id, final TerminationPointType type) {
final TerminationPointBuilder stpb = new TerminationPointBuilder();
stpb.setKey(new TerminationPointKey(id));
stpb.setTpId(id);
if (type != null) {
stpb.addAugmentation(TerminationPoint1.class, new TerminationPoint1Builder().setIgpTerminationPointAttributes(
new IgpTerminationPointAttributesBuilder().setTerminationPointType(null).build()).build());
}
return stpb.build();
}
private static TerminationPointType getTpType(final Ipv4InterfaceIdentifier ipv4InterfaceIdentifier,
final Ipv6InterfaceIdentifier ipv6InterfaceIdentifier, final Long id) {
// Order of preference: Unnumbered first, then IP
if (id != null) {
LOG.debug("Unnumbered termination point type: {}", id);
return new UnnumberedBuilder().setUnnumberedId(id).build();
}
final IpAddress ip;
if (ipv6InterfaceIdentifier != null) {
ip = new IpAddress(ipv6InterfaceIdentifier);
} else if (ipv4InterfaceIdentifier != null) {
ip = new IpAddress(ipv4InterfaceIdentifier);
} else {
ip = null;
}
if (ip != null) {
LOG.debug("IP termination point type: {}", ip);
return new IpBuilder().setIpAddress(Lists.newArrayList(ip)).build();
}
return null;
}
private static TerminationPoint buildLocalTp(final UriBuilder base, final LinkDescriptors linkDescriptors) {
final TpId id = buildLocalTpId(base, linkDescriptors);
final TerminationPointType t = getTpType(linkDescriptors.getIpv4InterfaceAddress(), linkDescriptors.getIpv6InterfaceAddress(),
linkDescriptors.getLinkLocalIdentifier());
return buildTp(id, t);
}
private static TpId buildRemoteTpId(final UriBuilder base, final LinkDescriptors linkDescriptors) {
return buildTpId(base, linkDescriptors.getMultiTopologyId(), linkDescriptors.getIpv4NeighborAddress(),
linkDescriptors.getIpv6NeighborAddress(), linkDescriptors.getLinkRemoteIdentifier());
}
private static TerminationPoint buildRemoteTp(final UriBuilder base, final LinkDescriptors linkDescriptors) {
final TpId id = buildRemoteTpId(base, linkDescriptors);
final TerminationPointType t = getTpType(linkDescriptors.getIpv4NeighborAddress(), linkDescriptors.getIpv6NeighborAddress(),
linkDescriptors.getLinkRemoteIdentifier());
return buildTp(id, t);
}
private InstanceIdentifier<Link> buildLinkIdentifier(final LinkId id) {
return getInstanceIdentifier().child(
org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link.class,
new LinkKey(id));
}
private static Float bandwidthToFloat(final Bandwidth bandwidth) {
return ByteBuffer.wrap(bandwidth.getValue()).getFloat();
}
private static BigDecimal bandwidthToBigDecimal(final Bandwidth bandwidth) {
return BigDecimal.valueOf(bandwidthToFloat(bandwidth));
}
private static List<UnreservedBandwidth> unreservedBandwidthList(
final List<? extends org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.UnreservedBandwidth> input) {
final List<UnreservedBandwidth> ret = new ArrayList<>(input.size());
for (final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.UnreservedBandwidth i : input) {
ret.add(new UnreservedBandwidthBuilder().setBandwidth(bandwidthToBigDecimal(i.getBandwidth())).setKey(
new UnreservedBandwidthKey(i.getPriority())).build());
}
return ret;
}
private static org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpLinkAttributes1 isisLinkAttributes(
final TopologyIdentifier topologyIdentifier, final LinkAttributes la) {
final org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.link.attributes.isis.link.attributes.TedBuilder tb = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.link.attributes.isis.link.attributes.TedBuilder();
if (la != null) {
if (la.getAdminGroup() != null) {
tb.setColor(la.getAdminGroup().getValue());
}
if (la.getTeMetric() != null) {
tb.setTeDefaultMetric(la.getTeMetric().getValue());
}
if (la.getUnreservedBandwidth() != null) {
tb.setUnreservedBandwidth(unreservedBandwidthList(la.getUnreservedBandwidth()));
}
if (la.getMaxLinkBandwidth() != null) {
tb.setMaxLinkBandwidth(bandwidthToBigDecimal(la.getMaxLinkBandwidth()));
}
if (la.getMaxReservableBandwidth() != null) {
tb.setMaxResvLinkBandwidth(bandwidthToBigDecimal(la.getMaxReservableBandwidth()));
}
if (la.getSharedRiskLinkGroups() != null) {
final List<SrlgValues> srlgs = new ArrayList<>();
for (final SrlgId id : la.getSharedRiskLinkGroups()) {
srlgs.add(new SrlgValuesBuilder().setSrlgValue(id.getValue()).build());
}
tb.setSrlg(new SrlgBuilder().setSrlgValues(srlgs).build());
}
}
final IsisLinkAttributesBuilder ilab = new IsisLinkAttributesBuilder();
ilab.setTed(tb.build());
if (topologyIdentifier != null) {
ilab.setMultiTopologyId(topologyIdentifier.getValue().shortValue());
}
return new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpLinkAttributes1Builder().setIsisLinkAttributes(
ilab.build()).build();
}
private static org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpLinkAttributes1 ospfLinkAttributes(
final TopologyIdentifier topologyIdentifier, final LinkAttributes la) {
final org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.link.attributes.ospf.link.attributes.TedBuilder tb = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.link.attributes.ospf.link.attributes.TedBuilder();
if (la != null) {
if (la.getAdminGroup() != null) {
tb.setColor(la.getAdminGroup().getValue());
}
if (la.getTeMetric() != null) {
tb.setTeDefaultMetric(la.getTeMetric().getValue());
}
if (la.getUnreservedBandwidth() != null) {
tb.setUnreservedBandwidth(unreservedBandwidthList(la.getUnreservedBandwidth()));
}
if (la.getMaxLinkBandwidth() != null) {
tb.setMaxLinkBandwidth(bandwidthToBigDecimal(la.getMaxLinkBandwidth()));
}
if (la.getMaxReservableBandwidth() != null) {
tb.setMaxResvLinkBandwidth(bandwidthToBigDecimal(la.getMaxReservableBandwidth()));
}
if (la.getSharedRiskLinkGroups() != null) {
final List<SrlgValues> srlgs = new ArrayList<>();
for (final SrlgId id : la.getSharedRiskLinkGroups()) {
srlgs.add(new SrlgValuesBuilder().setSrlgValue(id.getValue()).build());
}
tb.setSrlg(new SrlgBuilder().setSrlgValues(srlgs).build());
}
}
final OspfLinkAttributesBuilder ilab = new OspfLinkAttributesBuilder();
ilab.setTed(tb.build());
if (topologyIdentifier != null) {
ilab.setMultiTopologyId(topologyIdentifier.getValue().shortValue());
}
return new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpLinkAttributes1Builder().setOspfLinkAttributes(
ilab.build()).build();
}
private NodeHolder getNode(final NodeId id) {
if (this.nodes.containsKey(id)) {
LOG.debug("Node {} is already present", id);
return this.nodes.get(id);
}
final NodeHolder ret = new NodeHolder(id);
this.nodes.put(id, ret);
return ret;
}
private void putNode(final WriteTransaction trans, final NodeHolder holder) {
if (holder.syncState(trans)) {
this.nodes.remove(holder.getNodeId());
}
}
private static void augmentProtocolId(final LinkstateRoute value, final IgpLinkAttributesBuilder ilab,
final LinkAttributes la, final LinkDescriptors ld) {
switch (value.getProtocolId()) {
case Direct:
case Static:
case Unknown:
break;
case IsisLevel1:
case IsisLevel2:
ilab.addAugmentation(
org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpLinkAttributes1.class,
isisLinkAttributes(ld.getMultiTopologyId(), la));
break;
case Ospf:
ilab.addAugmentation(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpLinkAttributes1.class,
ospfLinkAttributes(ld.getMultiTopologyId(), la));
break;
default:
break;
}
}
private void createLink(final WriteTransaction trans, final UriBuilder base,
final LinkstateRoute value, final LinkCase l, final Attributes attributes) {
// defensive lookup
final LinkAttributes la;
final Attributes1 attr = attributes.getAugmentation(Attributes1.class);
if (attr != null) {
final LinkStateAttribute attrType = attr.getLinkStateAttribute();
if (attrType != null) {
la = ((LinkAttributesCase)attrType).getLinkAttributes();
} else {
LOG.debug("Missing attribute type in link {} route {}, skipping it", l, value);
la = null;
}
} else {
LOG.debug("Missing attributes in link {} route {}, skipping it", l, value);
la = null;
}
final IgpLinkAttributesBuilder ilab = new IgpLinkAttributesBuilder();
if (la != null) {
if (la.getMetric() != null) {
ilab.setMetric(la.getMetric().getValue());
}
ilab.setName(la.getLinkName());
}
augmentProtocolId(value, ilab, la, l.getLinkDescriptors());
final LinkBuilder lb = new LinkBuilder();
lb.setLinkId(buildLinkId(base, l));
lb.addAugmentation(Link1.class, new Link1Builder().setIgpLinkAttributes(ilab.build()).build());
final NodeId srcNode = buildNodeId(base, l.getLocalNodeDescriptors());
LOG.debug("Link {} implies source node {}", l, srcNode);
final NodeId dstNode = buildNodeId(base, l.getRemoteNodeDescriptors());
LOG.debug("Link {} implies destination node {}", l, dstNode);
final TerminationPoint srcTp = buildLocalTp(base, l.getLinkDescriptors());
LOG.debug("Link {} implies source TP {}", l, srcTp);
final TerminationPoint dstTp = buildRemoteTp(base, l.getLinkDescriptors());
LOG.debug("Link {} implies destination TP {}", l, dstTp);
lb.setSource(new SourceBuilder().setSourceNode(srcNode).setSourceTp(srcTp.getTpId()).build());
lb.setDestination(new DestinationBuilder().setDestNode(dstNode).setDestTp(dstTp.getTpId()).build());
final NodeHolder snh = getNode(srcNode);
snh.addTp(srcTp, lb.getLinkId(), false);
LOG.debug("Created TP {} as link source", srcTp);
putNode(trans, snh);
final NodeHolder dnh = getNode(dstNode);
dnh.addTp(dstTp, lb.getLinkId(), true);
LOG.debug("Created TP {} as link destination", dstTp);
putNode(trans, dnh);
final InstanceIdentifier<Link> lid = buildLinkIdentifier(lb.getLinkId());
final Link link = lb.build();
trans.put(LogicalDatastoreType.OPERATIONAL, lid, link);
LOG.debug("Created link {} at {} for {}", link, lid, l);
}
private void removeTp(final WriteTransaction trans, final NodeId node, final TpId tp,
final LinkId link, final boolean isRemote) {
final NodeHolder nh = this.nodes.get(node);
if (nh != null) {
nh.removeTp(tp, link, isRemote);
putNode(trans, nh);
} else {
LOG.warn("Removed non-existent node {}", node);
}
}
private void removeLink(final WriteTransaction trans, final UriBuilder base, final LinkCase l) {
final LinkId id = buildLinkId(base, l);
final InstanceIdentifier<?> lid = buildLinkIdentifier(id);
trans.delete(LogicalDatastoreType.OPERATIONAL, lid);
LOG.debug("Removed link {}", lid);
removeTp(trans, buildNodeId(base, l.getLocalNodeDescriptors()), buildLocalTpId(base, l.getLinkDescriptors()), id, false);
removeTp(trans, buildNodeId(base, l.getRemoteNodeDescriptors()), buildRemoteTpId(base, l.getLinkDescriptors()), id, true);
}
private static List<Short> nodeMultiTopology(final List<TopologyIdentifier> list) {
final List<Short> ret = new ArrayList<>(list.size());
for (final TopologyIdentifier id : list) {
ret.add(id.getValue().shortValue());
}
return ret;
}
private static org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpNodeAttributes1 isisNodeAttributes(
final NodeIdentifier node, final NodeAttributes na) {
final org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.node.attributes.isis.node.attributes.TedBuilder tb = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.node.attributes.isis.node.attributes.TedBuilder();
final IsisNodeAttributesBuilder ab = new IsisNodeAttributesBuilder();
if (na != null) {
if (na.getIpv4RouterId() != null) {
tb.setTeRouterIdIpv4(na.getIpv4RouterId());
}
if (na.getIpv6RouterId() != null) {
tb.setTeRouterIdIpv6(na.getIpv6RouterId());
}
if (na.getTopologyIdentifier() != null) {
ab.setMultiTopologyId(nodeMultiTopology(na.getTopologyIdentifier()));
}
}
final CRouterIdentifier ri = node.getCRouterIdentifier();
if (ri instanceof IsisPseudonodeCase) {
final IsisPseudonode pn = ((IsisPseudonodeCase) ri).getIsisPseudonode();
final IsoBuilder b = new IsoBuilder();
final String systemId = UriBuilder.isoId(pn.getIsIsRouterIdentifier().getIsoSystemId());
b.setIsoSystemId(new IsoSystemId(systemId));
b.setIsoPseudonodeId(new IsoPseudonodeId(BaseEncoding.base16().encode(new byte[] {pn.getPsn().byteValue()})));
ab.setIso(b.build());
if (na != null) {
ab.setNet(toIsoNetIds(na.getIsisAreaId(), systemId));
}
} else if (ri instanceof IsisNodeCase) {
final IsisNode in = ((IsisNodeCase) ri).getIsisNode();
final String systemId = UriBuilder.isoId(in.getIsoSystemId());
ab.setIso(new IsoBuilder().setIsoSystemId(new IsoSystemId(systemId)).build());
if (na != null) {
ab.setNet(toIsoNetIds(na.getIsisAreaId(), systemId));
}
}
ab.setTed(tb.build());
return new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpNodeAttributes1Builder().setIsisNodeAttributes(
ab.build()).build();
}
private static List<IsoNetId> toIsoNetIds(final List<IsisAreaIdentifier> areaIds, final String systemId) {
return Lists.transform(areaIds, new Function<IsisAreaIdentifier, IsoNetId>() {
@Override
public IsoNetId apply(final IsisAreaIdentifier input) {
return new IsoNetId(UriBuilder.toIsoNetId(input, systemId));
}
});
}
private static org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpNodeAttributes1 ospfNodeAttributes(
final NodeIdentifier node, final NodeAttributes na) {
final org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.TedBuilder tb = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.TedBuilder();
final OspfNodeAttributesBuilder ab = new OspfNodeAttributesBuilder();
if (na != null) {
if (na.getIpv4RouterId() != null) {
tb.setTeRouterIdIpv4(na.getIpv4RouterId());
}
if (na.getIpv6RouterId() != null) {
tb.setTeRouterIdIpv6(na.getIpv6RouterId());
}
if (na.getTopologyIdentifier() != null) {
ab.setMultiTopologyId(nodeMultiTopology(na.getTopologyIdentifier()));
}
final CRouterIdentifier ri = node.getCRouterIdentifier();
if (ri instanceof OspfPseudonodeCase) {
final OspfPseudonode pn = ((OspfPseudonodeCase) ri).getOspfPseudonode();
ab.setRouterType(new PseudonodeBuilder().setPseudonode(Boolean.TRUE).build());
ab.setDrInterfaceId(pn.getLanInterface().getValue());
} else if (ri instanceof OspfNodeCase && na.getNodeFlags() != null) {
// TODO: what should we do with in.getOspfRouterId()?
final NodeFlagBits nf = na.getNodeFlags();
if (nf.isAbr() != null) {
ab.setRouterType(new AbrBuilder().setAbr(nf.isAbr()).build());
} else if (nf.isExternal() != null) {
ab.setRouterType(new InternalBuilder().setInternal(!nf.isExternal()).build());
}
}
}
ab.setTed(tb.build());
return new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpNodeAttributes1Builder().setOspfNodeAttributes(
ab.build()).build();
}
private static void augmentProtocolId(final LinkstateRoute value, final IgpNodeAttributesBuilder inab,
final NodeAttributes na, final NodeIdentifier nd) {
switch (value.getProtocolId()) {
case Direct:
case Static:
case Unknown:
break;
case IsisLevel1:
case IsisLevel2:
inab.addAugmentation(
org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpNodeAttributes1.class,
isisNodeAttributes(nd, na));
break;
case Ospf:
inab.addAugmentation(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpNodeAttributes1.class,
ospfNodeAttributes(nd, na));
break;
default:
break;
}
}
private void createNode(final WriteTransaction trans, final UriBuilder base,
final LinkstateRoute value, final NodeCase n, final Attributes attributes) {
final NodeAttributes na;
//defensive lookup
final Attributes1 attr = attributes.getAugmentation(Attributes1.class);
if (attr != null) {
final LinkStateAttribute attrType = attr.getLinkStateAttribute();
if (attrType != null) {
na = ((NodeAttributesCase)attrType).getNodeAttributes();
} else {
LOG.debug("Missing attribute type in node {} route {}, skipping it", n, value);
na = null;
}
} else {
LOG.debug("Missing attributes in node {} route {}, skipping it", n, value);
na = null;
}
final IgpNodeAttributesBuilder inab = new IgpNodeAttributesBuilder();
final List<IpAddress> ids = new ArrayList<>();
if (na != null) {
if (na.getIpv4RouterId() != null) {
ids.add(new IpAddress(na.getIpv4RouterId()));
}
if (na.getIpv6RouterId() != null) {
ids.add(new IpAddress(na.getIpv6RouterId()));
}
if (na.getDynamicHostname() != null) {
inab.setName(new DomainName(na.getDynamicHostname()));
}
}
if (!ids.isEmpty()) {
inab.setRouterId(ids);
}
augmentProtocolId(value, inab, na, n.getNodeDescriptors());
final NodeId nid = buildNodeId(base, n.getNodeDescriptors());
final NodeHolder nh = getNode(nid);
/*
* Eventhough the the holder creates a dummy structure, we need to duplicate it here,
* as that is the API requirement. The reason for it is the possible presence of supporting
* node -- something which the holder does not track.
*/
final NodeBuilder nb = new NodeBuilder();
nb.setNodeId(nid);
nb.setKey(new NodeKey(nb.getNodeId()));
nh.advertized(nb, inab);
putNode(trans, nh);
}
private void removeNode(final WriteTransaction trans, final UriBuilder base, final NodeCase n) {
final NodeId id = buildNodeId(base, n.getNodeDescriptors());
final NodeHolder nh = this.nodes.get(id);
if (nh != null) {
nh.unadvertized();
putNode(trans, nh);
} else {
LOG.warn("Node {} does not have a holder", id);
}
}
private static void augmentProtocolId(final LinkstateRoute value, final PrefixAttributes pa, final PrefixBuilder pb) {
switch (value.getProtocolId()) {
case Direct:
case IsisLevel1:
case IsisLevel2:
case Static:
case Unknown:
break;
case Ospf:
if (pa != null && pa.getOspfForwardingAddress() != null) {
pb.addAugmentation(
Prefix1.class,
new Prefix1Builder().setOspfPrefixAttributes(
new OspfPrefixAttributesBuilder().setForwardingAddress(pa.getOspfForwardingAddress().getIpv4Address()).build()).build());
}
break;
default:
break;
}
}
private void createPrefix(final WriteTransaction trans, final UriBuilder base,
final LinkstateRoute value, final PrefixCase p, final Attributes attributes) {
final IpPrefix ippfx = p.getPrefixDescriptors().getIpReachabilityInformation();
if (ippfx == null) {
LOG.warn("IP reachability not present in prefix {} route {}, skipping it", p, value);
return;
}
final PrefixBuilder pb = new PrefixBuilder();
pb.setKey(new PrefixKey(ippfx));
pb.setPrefix(ippfx);
final PrefixAttributes pa;
// Very defensive lookup
final Attributes1 attr = attributes.getAugmentation(Attributes1.class);
if (attr != null) {
final LinkStateAttribute attrType = attr.getLinkStateAttribute();
if (attrType != null) {
pa = ((PrefixAttributesCase)attrType).getPrefixAttributes();
} else {
LOG.debug("Missing attribute type in IP {} prefix {} route {}, skipping it", ippfx, p, value);
pa = null;
}
} else {
LOG.debug("Missing attributes in IP {} prefix {} route {}, skipping it", ippfx, p, value);
pa = null;
}
if (pa != null) {
pb.setMetric(pa.getPrefixMetric().getValue());
}
augmentProtocolId(value, pa, pb);
final Prefix pfx = pb.build();
/*
* All set, but... the hosting node may not exist, we may need to fake it.
*/
final NodeId node = buildNodeId(base, p.getAdvertisingNodeDescriptors());
final NodeHolder nh = getNode(node);
nh.addPrefix(pfx);
LOG.debug("Created prefix {} for {}", pfx, p);
putNode(trans, nh);
}
private void removePrefix(final WriteTransaction trans, final UriBuilder base, final PrefixCase p) {
final NodeId node = buildNodeId(base, p.getAdvertisingNodeDescriptors());
final NodeHolder nh = this.nodes.get(node);
if (nh != null) {
nh.removePrefix(p);
LOG.debug("Removed prefix {}", p);
putNode(trans, nh);
} else {
LOG.warn("Removing prefix from non-existing node {}", node);
}
}
@Override
protected void createObject(final ReadWriteTransaction trans,
final InstanceIdentifier<LinkstateRoute> id, final LinkstateRoute value) {
final UriBuilder base = new UriBuilder(value);
final ObjectType t = value.getObjectType();
Preconditions.checkArgument(t != null, "Route %s value %s has null object type", id, value);
if (t instanceof LinkCase) {
createLink(trans, base, value, (LinkCase) t, value.getAttributes());
} else if (t instanceof NodeCase) {
createNode(trans, base, value, (NodeCase) t, value.getAttributes());
} else if (t instanceof PrefixCase) {
createPrefix(trans, base, value, (PrefixCase) t, value.getAttributes());
} else {
LOG.debug(UNHANDLED_OBJECT_CLASS, t.getImplementedInterface());
}
}
@Override
protected void removeObject(final ReadWriteTransaction trans,
final InstanceIdentifier<LinkstateRoute> id, final LinkstateRoute value) {
final UriBuilder base = new UriBuilder(value);
final ObjectType t = value.getObjectType();
if (t instanceof LinkCase) {
removeLink(trans, base, (LinkCase) t);
} else if (t instanceof NodeCase) {
removeNode(trans, base, (NodeCase) t);
} else if (t instanceof PrefixCase) {
removePrefix(trans, base, (PrefixCase) t);
} else {
LOG.debug(UNHANDLED_OBJECT_CLASS, t.getImplementedInterface());
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected InstanceIdentifier<LinkstateRoute> getRouteWildcard(final InstanceIdentifier<Tables> tablesId) {
return tablesId.child((Class)LinkstateRoutes.class).child(LinkstateRoute.class);
}
} |
package tigase.server;
import tigase.conf.ConfiguratorAbstract;
import tigase.disco.XMPPService;
import tigase.stats.StatisticsList;
import tigase.sys.TigaseRuntime;
import tigase.util.TigaseStringprepException;
import tigase.util.UpdatesChecker;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.JID;
import tigase.xmpp.PacketErrorTypeException;
import tigase.xmpp.StanzaType;
import static tigase.server.MessageRouterConfig.*;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class MessageRouter
*
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class MessageRouter
extends AbstractMessageReceiver
implements MessageRouterIfc {
// implements XMPPService {
// public static final String INFO_XMLNS =
// "http://jabber.org/protocol/disco#info";
// public static final String ITEMS_XMLNS =
// "http://jabber.org/protocol/disco#items";
private static final Logger log = Logger.getLogger(MessageRouter.class.getName());
private ConfiguratorAbstract config = null;
// private static final long startupTime = System.currentTimeMillis();
// private Set<String> localAddresses = new CopyOnWriteArraySet<String>();
private String disco_name = DISCO_NAME_PROP_VAL;
private boolean disco_show_version = DISCO_SHOW_VERSION_PROP_VAL;
private UpdatesChecker updates_checker = null;
private Map<String, XMPPService> xmppServices = new ConcurrentHashMap<String,
XMPPService>();
private Map<String, ComponentRegistrator> registrators = new ConcurrentHashMap<String,
ComponentRegistrator>();
private Map<String, MessageReceiver> receivers = new ConcurrentHashMap<String,
MessageReceiver>();
private boolean inProperties = false;
private Set<String> connectionManagerNames =
new ConcurrentSkipListSet<String>();
private Map<JID, ServerComponent> components_byId = new ConcurrentHashMap<JID,
ServerComponent>();
private Map<String, ServerComponent> components = new ConcurrentHashMap<String,
ServerComponent>();
/**
* Method description
*
*
* @param component
*/
public void addComponent(ServerComponent component) {
log.log(Level.INFO, "Adding component: ", component.getClass().getSimpleName());
for (ComponentRegistrator registr : registrators.values()) {
if (registr != component) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Adding: {0} component to {1} registrator.",
new Object[] { component.getName(),
registr.getName() });
}
registr.addComponent(component);
} // end of if (reg != component)
} // end of for ()
components.put(component.getName(), component);
components_byId.put(component.getComponentId(), component);
if (component instanceof XMPPService) {
xmppServices.put(component.getName(), (XMPPService) component);
}
}
/**
* Method description
*
*
* @param registr
*/
public void addRegistrator(ComponentRegistrator registr) {
log.log(Level.INFO, "Adding registrator: {0}", registr.getClass().getSimpleName());
registrators.put(registr.getName(), registr);
addComponent(registr);
for (ServerComponent comp : components.values()) {
// if (comp != registr) {
registr.addComponent(comp);
// } // end of if (comp != registr)
} // end of for (ServerComponent comp : components)
}
/**
* Method description
*
*
* @param receiver
*/
public void addRouter(MessageReceiver receiver) {
log.info("Adding receiver: " + receiver.getClass().getSimpleName());
addComponent(receiver);
receivers.put(receiver.getName(), receiver);
}
/**
* Method description
*
*
* @param packet
*
*
*
* @return a value of <code>int</code>
*/
@Override
public int hashCodeForPacket(Packet packet) {
// This is actually quite tricky part. We want to both avoid
// packet reordering and also even packets distribution among
// different threads.
// If packet comes from a connection manager we must use packetFrom
// address. However if the packet comes from SM, PubSub or other similar
// component all packets would end-up in the same queue.
// So, kind of a workaround here....
// TODO: develop a proper solution discovering which components are
// connection managers and use their names here instead of static names.
if ((packet.getPacketFrom() != null) && (packet.getPacketFrom().getLocalpart() !=
null)) {
if (connectionManagerNames.contains(packet.getPacketFrom().getLocalpart())) {
return packet.getPacketFrom().hashCode();
}
}
if ((packet.getPacketTo() != null) && (packet.getPacketTo().getLocalpart() != null)) {
if (connectionManagerNames.contains(packet.getPacketTo().getLocalpart())) {
return packet.getPacketTo().hashCode();
}
}
if (packet.getStanzaTo() != null) {
return packet.getStanzaTo().getBareJID().hashCode();
}
if ((packet.getPacketFrom() != null) &&!getComponentId().equals(packet
.getPacketFrom())) {
// This comes from connection manager so the best way is to get hashcode
// by the connectionId, which is in the getFrom()
return packet.getPacketFrom().hashCode();
}
if ((packet.getPacketTo() != null) &&!getComponentId().equals(packet.getPacketTo())) {
return packet.getPacketTo().hashCode();
}
// If not, then a better way is to get hashCode from the elemTo address
// as this would be by the destination address user name:
return 1;
}
/**
* Method description
*
*
*
*
* @return a value of <code>int</code>
*/
@Override
public int processingInThreads() {
return Runtime.getRuntime().availableProcessors() * 4;
}
/**
* Method description
*
*
*
*
* @return a value of <code>int</code>
*/
@Override
public int processingOutThreads() {
return 1;
}
// private String isToLocalComponent(String jid) {
// String nick = JIDUtils.getNodeNick(jid);
// if (nick == null) {
// return null;
// String host = JIDUtils.getNodeHost(jid);
// if (isLocalDomain(host) && components.get(nick) != null) {
// return nick;
// return null;
// private boolean isLocalDomain(String domain) {
// return localAddresses.contains(domain);
/**
* Method description
*
*
* @param packet
*/
@Override
public void processPacket(Packet packet) {
// We do not process packets with not destination address
// Just dropping them and writing a log message
if (packet.getTo() == null) {
log.log(Level.WARNING, "Packet with TO attribute set to NULL: {0}", packet);
return;
} // end of if (packet.getTo() == null)
// Intentionally comparing to static, final String
// This is kind of a hack to handle packets addressed specifically for the
// SessionManager
// TODO: Replace the hack with a proper solution
// if (packet.getTo() == NULL_ROUTING) {
// log.info("NULL routing, it is normal if server doesn't know how to"
// + " process packet: " + packet.toStringSecure());
// try {
// Packet error =
// Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet,
// "Feature not supported yet.", true);
// addOutPacketNB(error);
// } catch (PacketErrorTypeException e) {
// log.warning("Packet processing exception: " + e);
// return;
// if (log.isLoggable(Level.FINER)) {
// log.finer("Processing packet: " + packet.getElemName()
// + ", type: " + packet.getType());
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing packet: {0}", packet);
}
// Detect inifinite loop if from == to
// Maybe it is not needed anymore...
// There is a need to process packets with the same from and to address
// let't try to relax restriction and block all packets with error type
// 2008-06-16
if (((packet.getType() == StanzaType.error) && (packet.getFrom() != null) && packet
.getFrom().equals(packet.getTo()))) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Possible infinite loop, dropping packet: {0}", packet);
}
return;
}
// Catch and process all service discovery packets here....
// ServerComponent comp = (packet.getStanzaTo() == null)
// ? null
// : getLocalComponent(packet.getStanzaTo());
if (packet.isServiceDisco() && (packet.getType() == StanzaType.get) && (packet
.getStanzaFrom() != null) && ((packet.getStanzaTo() == null) || (isLocalDomain(
packet.getStanzaTo().toString()) &&!isDiscoDisabled(packet.getStanzaTo())))) {
// .getStanzaFrom() != null) && ((packet.getStanzaTo() == null) || ((comp != null) &&
// !(comp instanceof DisableDisco)) || isLocalDomain(packet.getStanzaTo()
// .toString()))) {
Queue<Packet> results = new ArrayDeque<Packet>();
processDiscoQuery(packet, results);
if (results.size() > 0) {
for (Packet res : results) {
// No more recurrential calls!!
addOutPacketNB(res);
} // end of for ()
}
return;
}
// It is not a service discovery packet, we have to find a component to
// process
// the packet. The below block of code is to "quickly" find a component if
// the
// the packet is addressed to the component ID where the component ID is
// either
// of one below:
// 1. component name + "@" + default domain name
// 2. component name + "@" + any virtual host name
// 3. component name + "." + default domain name
// 4. component name + "." + any virtual host name
// TODO: check the efficiency for packets addressed to c2s component
ServerComponent comp = getLocalComponent(packet.getTo());
if (comp != null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "1. Packet will be processed by: {0}, {1}", new Object[] {
comp.getComponentId(),
packet });
}
Queue<Packet> results = new ArrayDeque<Packet>();
if (comp == this) {
// This is addressed to the MessageRouter itself. Has to be processed
// separately to avoid recurential calls by the packet processing
// method.
processPacketMR(packet, results);
} else {
// All other components process the packet the same way.
comp.processPacket(packet, results);
}
if (results.size() > 0) {
for (Packet res : results) {
// No more recurrential calls!!
addOutPacketNB(res);
// processPacket(res);
} // end of for ()
}
// If the component is found the processing ends here as there can be
// only one component with specific ID.
return;
}
// This packet is not processed yet
// The packet can be addressed to just a domain, one of the virtual hosts
// The code below finds all components which handle packets addressed
// to a virtual domains (implement VHostListener and return 'true' from
// handlesLocalDomains() method call)
String host = packet.getTo().getDomain();
ServerComponent[] comps = getComponentsForLocalDomain(host);
if (comps == null) {
// Still no component found, now the most expensive lookup.
// Checking regex routings provided by the component.
comps = getServerComponentsForRegex(packet.getTo().getBareJID().toString());
}
if ((comps == null) &&!isLocalDomain(host)) {
// None of the component want to process the packet.
// If the packet is addressed to non-local domain then it is processed by
// all components dealing with external world, like s2s
comps = getComponentsForNonLocalDomain(host);
}
// Ok, if any component has been found then process the packet in a standard
// way
if (comps != null) {
// Processing packet and handling results out
Queue<Packet> results = new ArrayDeque<Packet>();
for (ServerComponent serverComponent : comps) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "2. Packet will be processed by: {0}, {1}",
new Object[] { serverComponent.getComponentId(),
packet });
}
serverComponent.processPacket(packet, results);
if (results.size() > 0) {
for (Packet res : results) {
// No more recurrential calls!!
addOutPacketNB(res);
// processPacket(res);
} // end of for ()
}
}
} else {
// No components for the packet, sending an error back
if (log.isLoggable(Level.FINEST)) {
log.finest("There is no component for the packet, sending it back");
}
try {
addOutPacketNB(Authorization.SERVICE_UNAVAILABLE.getResponseMessage(packet,
"There is no service found to process your request.", true));
} catch (PacketErrorTypeException e) {
// This packet is to local domain, we don't want to send it out
// drop packet :-(
log.warning("Can't process packet to local domain, dropping..." + packet
.toStringSecure());
}
}
}
/**
* Method description
*
*
* @param packet
* @param results
*/
public void processPacketMR(Packet packet, Queue<Packet> results) {
Iq iq = null;
if (packet instanceof Iq) {
iq = (Iq) packet;
} else {
// Not a command for sure...
log.warning("I expect command (Iq) packet here, instead I got: " + packet
.toString());
return;
}
if (packet.getPermissions() != Permissions.ADMIN) {
try {
Packet res = Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You are not authorized for this action.", true);
results.offer(res);
// processPacket(res);
} catch (PacketErrorTypeException e) {
log.warning("Packet processing exception: " + e);
}
return;
}
if (log.isLoggable(Level.FINEST)) {
log.finest("Command received: " + iq.toString());
}
switch (iq.getCommand()) {
case OTHER :
if (iq.getStrCommand() != null) {
if (iq.getStrCommand().startsWith("controll/")) {
String[] spl = iq.getStrCommand().split("/");
String cmd = spl[1];
if (cmd.equals("stop")) {
Packet result = iq.commandResult(Command.DataType.result);
results.offer(result);
// processPacket(result);
new Timer("Stopping...", true).schedule(new TimerTask() {
@Override
public void run() {
System.exit(0);
}
}, 2000);
}
}
}
break;
default :
break;
}
}
/**
* Method description
*
*
* @param component
*/
public void removeComponent(ServerComponent component) {
for (ComponentRegistrator registr : registrators.values()) {
if (registr != component) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Adding: {0} component to {1} registrator.",
new Object[] { component.getName(),
registr.getName() });
}
registr.deleteComponent(component);
} // end of if (reg != component)
} // end of for ()
components.remove(component.getName());
components_byId.remove(component.getComponentId());
if (component instanceof XMPPService) {
xmppServices.remove(component.getName());
}
}
/**
* Method description
*
*
* @param receiver
*/
public void removeRouter(MessageReceiver receiver) {
log.info("Removing receiver: " + receiver.getClass().getSimpleName());
receivers.remove(receiver.getName());
removeComponent(receiver);
}
/**
* Method description
*
*/
@Override
public void start() {
super.start();
}
/**
* Method description
*
*/
@Override
public void stop() {
Set<String> comp_names = new TreeSet<String>();
comp_names.addAll(components.keySet());
for (String name : comp_names) {
ServerComponent comp = components.remove(name);
if ((comp != this) && (comp != null)) {
comp.release();
}
}
super.stop();
}
/**
* Method description
*
*
* @param params
*
*
*
* @return a value of <code>Map<String,Object></code>
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> defs = super.getDefaults(params);
MessageRouterConfig.getDefaults(defs, params, getName());
return defs;
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
@Override
public String getDiscoCategoryType() {
return "im";
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
@Override
public String getDiscoDescription() {
return disco_name + (disco_show_version
? (" ver. " + XMPPServer.getImplementationVersion())
: "");
}
// public List<Element> getDiscoItems(String node, String jid) {
// return null;
/**
* Method description
*
*
* @param list
*/
@Override
public void getStatistics(StatisticsList list) {
super.getStatistics(list);
list.add(getName(), "Local hostname", getDefHostName().getDomain(), Level.INFO);
TigaseRuntime runtime = TigaseRuntime.getTigaseRuntime();
list.add(getName(), "Uptime", runtime.getUptimeString(), Level.INFO);
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(4);
list.add(getName(), "Load average", format.format(runtime.getLoadAverage()), Level
.FINE);
list.add(getName(), "CPUs no", runtime.getCPUsNumber(), Level.FINEST);
list.add(getName(), "Threads count", runtime.getThreadsNumber(), Level.FINEST);
float cpuUsage = runtime.getCPUUsage();
float heapUsage = runtime.getHeapMemUsage();
float nonHeapUsage = runtime.getNonHeapMemUsage();
list.add(getName(), "CPU usage [%]", cpuUsage, Level.FINE);
list.add(getName(), "HEAP usage [%]", heapUsage, Level.FINE);
list.add(getName(), "NONHEAP usage [%]", nonHeapUsage, Level.FINE);
format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(1);
// if (format instanceof DecimalFormat) {
// DecimalFormat decf = (DecimalFormat)format;
// decf.applyPattern(decf.toPattern()+"%");
list.add(getName(), "CPU usage", format.format(cpuUsage) + "%", Level.INFO);
MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
MemoryUsage nonHeap = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
format = NumberFormat.getIntegerInstance();
if (format instanceof DecimalFormat) {
DecimalFormat decf = (DecimalFormat) format;
decf.applyPattern(decf.toPattern() + " KB");
}
list.add(getName(), "Max Heap mem", format.format(heap.getMax() / 1024), Level.INFO);
list.add(getName(), "Used Heap", format.format(heap.getUsed() / 1024), Level.INFO);
list.add(getName(), "Free Heap", format.format((heap.getMax() - heap.getUsed()) /
1024), Level.FINE);
list.add(getName(), "Max NonHeap mem", format.format(nonHeap.getMax() / 1024), Level
.FINE);
list.add(getName(), "Used NonHeap", format.format(nonHeap.getUsed() / 1024), Level
.FINE);
list.add(getName(), "Free NonHeap", format.format((nonHeap.getMax() - nonHeap
.getUsed()) / 1024), Level.FINE);
}
/**
* Method description
*
*
* @param config
*/
@Override
public void setConfig(ConfiguratorAbstract config) {
components.put(getName(), this);
this.config = config;
addRegistrator(config);
}
/**
* Method description
*
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
if (inProperties) {
return;
} else {
inProperties = true;
} // end of if (inProperties) else
connectionManagerNames.add("c2s");
connectionManagerNames.add("bosh");
connectionManagerNames.add("s2s");
if (props.get(DISCO_SHOW_VERSION_PROP_KEY) != null) {
disco_show_version = (Boolean) props.get(DISCO_SHOW_VERSION_PROP_KEY);
}
if (props.get(DISCO_NAME_PROP_KEY) != null) {
disco_name = (String) props.get(DISCO_NAME_PROP_KEY);
}
try {
super.setProperties(props);
updateServiceDiscoveryItem(getName(), null, getDiscoDescription(), "server", "im",
false);
if (props.size() == 1) {
// If props.size() == 1, it means this is a single property update and
// MR does
// not support it yet.
return;
}
HashSet<String> inactive_msgrec = new HashSet<String>(receivers.keySet());
MessageRouterConfig conf = new MessageRouterConfig(props);
String[] reg_names = conf.getRegistrNames();
for (String name : reg_names) {
inactive_msgrec.remove(name);
// First remove it and later, add it again if still active
ComponentRegistrator cr = registrators.remove(name);
String cls_name = (String) props.get(REGISTRATOR_PROP_KEY + name +
".class");
try {
if ((cr == null) ||!cr.getClass().getName().equals(cls_name)) {
if (cr != null) {
cr.release();
}
cr = conf.getRegistrInstance(name);
cr.setName(name);
} // end of if (cr == null)
addRegistrator(cr);
} catch (Exception e) {
e.printStackTrace();
} // end of try-catch
} // end of for (String name: reg_names)
String[] msgrcv_names = conf.getMsgRcvActiveNames();
for (String name : msgrcv_names) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Loading and registering message receiver: {0}", name);
}
inactive_msgrec.remove(name);
// First remove it and later, add it again if still active
ServerComponent mr = receivers.remove(name);
xmppServices.remove(name);
String cls_name = (String) props.get(MSG_RECEIVERS_PROP_KEY + name + ".class");
try {
// boolean start = false;
if ((mr == null) || ((mr != null) &&!conf.componentClassEquals(cls_name, mr
.getClass()))) {
if (mr != null) {
if (mr instanceof MessageReceiver) {
removeRouter((MessageReceiver) mr);
} else {
removeComponent(mr);
}
mr.release();
}
mr = conf.getMsgRcvInstance(name);
mr.setName(name);
if (mr instanceof MessageReceiver) {
((MessageReceiver) mr).setParent(this);
((MessageReceiver) mr).start();
// start = true;
}
} // end of if (cr == null)
if (mr instanceof MessageReceiver) {
addRouter((MessageReceiver) mr);
} else {
addComponent(mr);
}
System.out.println("Loading component: " + mr.getComponentInfo());
// if (start) {
// ((MessageReceiver) mr).start();
} // end of try
catch (ClassNotFoundException e) {
log.log(Level.WARNING, "class for component = {0} could not be found " +
"- disabling component", name);
// conf.setComponentActive(name, false);
} // end of try
catch (Exception e) {
e.printStackTrace();
} // end of try-catch
} // end of for (String name: reg_names)
// String[] inactive_msgrec = conf.getMsgRcvInactiveNames();
for (String name : inactive_msgrec) {
ServerComponent mr = receivers.remove(name);
xmppServices.remove(name);
if (mr != null) {
try {
if (mr instanceof MessageReceiver) {
removeRouter((MessageReceiver) mr);
} else {
removeComponent(mr);
}
mr.release();
} catch (Exception ex) {
log.log(Level.WARNING, "exception releasing component:", ex);
}
}
}
// for (MessageReceiver mr : tmp_rec.values()) {
// mr.release();
// } // end of for ()
// tmp_rec.clear();
if ((Boolean) props.get(UPDATES_CHECKING_PROP_KEY)) {
installUpdatesChecker((Long) props.get(UPDATES_CHECKING_INTERVAL_PROP_KEY));
} else {
log.log(Level.INFO, "Disabling updates checker.");
stopUpdatesChecker();
}
} finally {
inProperties = false;
} // end of try-finally
for (ServerComponent comp : components.values()) {
log.log(Level.INFO, "Initialization completed notification to: {0}", comp
.getName());
comp.initializationCompleted();
}
// log.info("Initialization completed notification to: " +
// config.getName());
// config.initializationCompleted();
}
/**
* Method description
*
*
* @param def
*
*
*
* @return a value of <code>Integer</code>
*/
@Override
protected Integer getMaxQueueSize(int def) {
return def * 10;
}
private void installUpdatesChecker(long interval) {
stopUpdatesChecker();
updates_checker = new UpdatesChecker(interval, this,
"This is automated message generated by updates checking module.\n" +
" You can disable this function changing configuration option: " + "'/" +
getName() + "/" + UPDATES_CHECKING_PROP_KEY + "' or adjust" +
" updates checking interval time changing option: " + "'/" + getName() + "/" +
UPDATES_CHECKING_INTERVAL_PROP_KEY + "' which" + " now set to " + interval +
" days.");
updates_checker.start();
}
private void processDiscoQuery(final Packet packet, final Queue<Packet> results) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing disco query by: {0}", packet.toStringSecure());
}
JID toJid = packet.getStanzaTo();
JID fromJid = packet.getStanzaFrom();
String node = packet.getAttributeStaticStr(Iq.IQ_QUERY_PATH, "node");
Element query = packet.getElement().getChild("query").clone();
if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, INFO_XMLNS)) {
if (isLocalDomain(toJid.toString()) && (node == null)) {
try {
query = getDiscoInfo(node, (toJid.getLocalpart() == null)
? JID.jidInstance(getName(), toJid.toString(), null)
: toJid, fromJid);
} catch (TigaseStringprepException e) {
log.log(Level.WARNING,
"processing by stringprep throw exception for = {0}@{1}", new Object[] {
getName(),
toJid.toString() });
}
for (XMPPService comp : xmppServices.values()) {
// Buggy custom component may throw exceptions here (NPE most likely)
// which may cause service disco problems for well-behaving components
// too
// So this is kind of a protection
try {
List<Element> features = comp.getDiscoFeatures(fromJid);
if (features != null) {
query.addChildren(features);
}
} catch (Exception e) {
log.log(Level.WARNING, "Component service disco problem: " + comp.getName(),
e);
}
}
} else {
for (XMPPService comp : xmppServices.values()) {
// Buggy custom component may throw exceptions here (NPE most likely)
// which may cause service disco problems for well-behaving components
// too
// So this is kind of a protection
try {
// if (jid.startsWith(comp.getName() + ".")) {
Element resp = comp.getDiscoInfo(node, toJid, fromJid);
if (resp != null) {
query.addChildren(resp.getChildren());
}
} catch (Exception e) {
log.log(Level.WARNING, "Component service disco problem: " + comp.getName(),
e);
}
}
}
}
if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, ITEMS_XMLNS)) {
boolean localDomain = isLocalDomain(toJid.toString());
if (localDomain) {
for (XMPPService comp : xmppServices.values()) {
// Buggy custom component may throw exceptions here (NPE most likely)
// which may cause service disco problems for well-behaving components
// too
// So this is kind of a protection
try {
// if (localDomain || (nick != null && comp.getName().equals(nick)))
List<Element> items = comp.getDiscoItems(node, toJid, fromJid);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,
"Localdomain: {0}, DiscoItems processed by: {1}, items: {2}",
new Object[] { toJid,
comp.getComponentId(),
(items == null)
? null
: items.toString() });
}
if ((items != null) && (items.size() > 0)) {
query.addChildren(items);
}
} catch (Exception e) {
log.log(Level.WARNING, "Component service disco problem: " + comp.getName(),
e);
}
} // end of for ()
} else {
ServerComponent comp = getLocalComponent(toJid);
if ((comp != null) && (comp instanceof XMPPService)) {
List<Element> items = ((XMPPService) comp).getDiscoItems(node, toJid, fromJid);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "DiscoItems processed by: {0}, items: {1}",
new Object[] { comp.getComponentId(), (items == null)
? null
: items.toString() });
}
if ((items != null) && (items.size() > 0)) {
query.addChildren(items);
}
}
}
}
results.offer(packet.okResult(query, 0));
}
private void stopUpdatesChecker() {
if (updates_checker != null) {
updates_checker.interrupt();
updates_checker = null;
}
}
private ServerComponent[] getComponentsForLocalDomain(String domain) {
return vHostManager.getComponentsForLocalDomain(domain);
}
private ServerComponent[] getComponentsForNonLocalDomain(String domain) {
return vHostManager.getComponentsForNonLocalDomain(domain);
}
private ServerComponent getLocalComponent(JID jid) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Called for : {0}", jid);
}
// Fast lookup in the server components to find a candidate
// by the component ID (JID). If the packet is addressed directly
// to the component ID then this is where the processing must happen.
// Normally the component id is: component name + "@" + default hostname
// However the component may "choose" to have any ID.
ServerComponent comp = components_byId.get(jid);
if (comp != null) {
return comp;
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "None compId matches: {0}, for map: {1}", new Object[] { jid,
components_byId });
}
// Note, component ID consists of the component name + default hostname
// which can be different from a virtual host. There might be many
// virtual hosts and the packet can be addressed to the component by
// the component name + virtual host name
// Code below, tries to find a destination by the component name + any
// active virtual hostname.
if (jid.getLocalpart() != null) {
comp = components.get(jid.getLocalpart());
if ((comp != null) && (isLocalDomain(jid.getDomain()) || jid.getDomain().equals(
getDefHostName().getDomain()))) {
return comp;
}
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,
"Still no comp name matches: {0}, for map: {1}, for all VHosts: {3}",
new Object[] { jid,
components, vHostManager.getAllVHosts() });
}
// Instead of a component ID built of: component name + "@" domain name
// Some components have an ID of: component name + "." domain name
// Code below tries to find a packet receiver if the address have the other
// type of form.
int idx = jid.getDomain().indexOf('.');
if (idx > 0) {
String cmpName = jid.getDomain().substring(0, idx);
String basename = jid.getDomain().substring(idx + 1);
comp = components.get(cmpName);
if ((comp != null) && (isLocalDomain(basename) || basename.equals(getDefHostName()
.getDomain()))) {
return comp;
}
}
return null;
}
private ServerComponent[] getServerComponentsForRegex(String id) {
LinkedHashSet<ServerComponent> comps = new LinkedHashSet<ServerComponent>();
for (MessageReceiver mr : receivers.values()) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Checking routings for: " + mr.getName());
}
if (mr.isInRegexRoutings(id)) {
comps.add(mr);
}
}
if (comps.size() > 0) {
return comps.toArray(new ServerComponent[comps.size()]);
} else {
return null;
}
}
private boolean isDiscoDisabled(JID to) {
ServerComponent comp = getLocalComponent(to);
if (comp != null) {
return (comp instanceof DisableDisco);
} else {
ServerComponent[] comps = getComponentsForLocalDomain(to.getDomain());
if (comps != null) {
for (ServerComponent c : comps) {
if (c instanceof DisableDisco) {
return true;
}
}
}
}
return false;
}
}
//~ Formatted in Tigase Code Convention on 13/10/07 |
package org.apache.brooklyn.tosca.a4c.brooklyn;
import alien4cloud.component.repository.CsarFileRepository;
import alien4cloud.component.repository.exception.CSARVersionNotFoundException;
import alien4cloud.model.components.AbstractPropertyValue;
import alien4cloud.model.components.ComplexPropertyValue;
import alien4cloud.model.components.DeploymentArtifact;
import alien4cloud.model.components.ImplementationArtifact;
import alien4cloud.model.components.IndexedArtifactToscaElement;
import alien4cloud.model.components.Interface;
import alien4cloud.model.components.Operation;
import alien4cloud.model.components.ScalarPropertyValue;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.RelationshipTemplate;
import com.google.api.client.repackaged.com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import org.apache.brooklyn.api.catalog.CatalogItem;
import org.apache.brooklyn.api.entity.Entity;
import org.apache.brooklyn.api.entity.EntitySpec;
import org.apache.brooklyn.api.mgmt.ManagementContext;
import org.apache.brooklyn.camp.brooklyn.BrooklynCampConstants;
import org.apache.brooklyn.camp.brooklyn.spi.creation.CampCatalogUtils;
import org.apache.brooklyn.config.ConfigKey;
import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
import org.apache.brooklyn.core.config.ConfigKeys;
import org.apache.brooklyn.entity.software.base.SameServerEntity;
import org.apache.brooklyn.entity.software.base.SoftwareProcess;
import org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess;
import org.apache.brooklyn.entity.stock.BasicApplication;
import org.apache.brooklyn.location.jclouds.JcloudsLocationConfig;
import org.apache.brooklyn.util.collections.MutableList;
import org.apache.brooklyn.util.collections.MutableMap;
import org.apache.brooklyn.util.collections.MutableSet;
import org.apache.brooklyn.util.core.ResourceUtils;
import org.apache.brooklyn.util.core.config.ConfigBag;
import org.apache.brooklyn.util.core.flags.FlagUtils;
import org.apache.brooklyn.util.core.flags.TypeCoercions;
import org.apache.brooklyn.util.os.Os;
import org.apache.brooklyn.util.text.Strings;
import org.apache.commons.lang3.StringUtils;
import org.jclouds.compute.domain.OsFamily;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ToscaNodeToEntityConverter {
private static final Logger log = LoggerFactory.getLogger(ToscaNodeToEntityConverter.class);
private final ManagementContext mgnt;
private String nodeId;
private IndexedArtifactToscaElement indexedNodeTemplate;
private NodeTemplate nodeTemplate;
private CsarFileRepository csarFileRepository;
private String env;
private ToscaNodeToEntityConverter(ManagementContext mgmt) {
this.mgnt = mgmt;
}
public static ToscaNodeToEntityConverter with(ManagementContext mgmt) {
return new ToscaNodeToEntityConverter(mgmt);
}
public ToscaNodeToEntityConverter setNodeId(String nodeId) {
this.nodeId = nodeId;
return this;
}
public ToscaNodeToEntityConverter setNodeTemplate(NodeTemplate nodeTemplate) {
this.nodeTemplate = nodeTemplate;
return this;
}
public ToscaNodeToEntityConverter setIndexedNodeTemplate(IndexedArtifactToscaElement indexedNodeTemplate) {
this.indexedNodeTemplate = indexedNodeTemplate;
return this;
}
public ToscaNodeToEntityConverter setCsarFileRepository(CsarFileRepository csarFileRepository) {
this.csarFileRepository = csarFileRepository;
return this;
}
public EntitySpec<? extends Entity> createSpec(boolean hasMultipleChildren) {
if (this.nodeTemplate == null) {
throw new IllegalStateException("TOSCA node template is missing. You must specify it by using the method #setNodeTemplate(NodeTemplate nodeTemplate)");
}
if (StringUtils.isEmpty(this.nodeId)) {
throw new IllegalStateException("TOSCA node ID is missing. You must specify it by using the method #setNodeId(String nodeId)");
}
EntitySpec<?> spec = null;
CatalogItem catalogItem = CatalogUtils.getCatalogItemOptionalVersion(this.mgnt, this.nodeTemplate.getType());
if (catalogItem != null) {
log.info("Found Brooklyn catalog item that match node type: " + this.nodeTemplate.getType());
spec = (EntitySpec<?>) this.mgnt.getCatalog().createSpec(catalogItem);
} else if (indexedNodeTemplate.getDerivedFrom().contains("tosca.nodes.Compute")) {
spec = hasMultipleChildren ? EntitySpec.create(SameServerEntity.class)
: EntitySpec.create(BasicApplication.class);
} else {
try {
log.info("Found Brooklyn entity that match node type: " + this.nodeTemplate.getType());
spec = EntitySpec.create((Class<? extends Entity>) Class.forName(this.nodeTemplate.getType()));
} catch (ClassNotFoundException e) {
log.info("Cannot find any Brooklyn catalog item nor Brooklyn entities that match node type: " +
this.nodeTemplate.getType() + ". Defaulting to a VanillaSoftwareProcess");
spec = EntitySpec.create(VanillaSoftwareProcess.class);
}
}
// Applying name from the node template or its ID
if (Strings.isNonBlank(this.nodeTemplate.getName())) {
spec.displayName(this.nodeTemplate.getName());
} else {
spec.displayName(this.nodeId);
}
// Add TOSCA node type as a property
spec.configure("tosca.node.type", this.nodeTemplate.getType());
spec.configure("tosca.template.id", this.nodeId);
// Use the nodeId as the camp.template.id to enable DSL lookup
spec.configure(BrooklynCampConstants.PLAN_ID, this.nodeId);
Map<String, AbstractPropertyValue> properties = this.nodeTemplate.getProperties();
// Applying provisioning properties
ConfigBag prov = ConfigBag.newInstance();
prov.putIfNotNull(JcloudsLocationConfig.MIN_RAM, resolve(properties, "mem_size"));
prov.putIfNotNull(JcloudsLocationConfig.MIN_DISK, resolve(properties, "disk_size"));
prov.putIfNotNull(JcloudsLocationConfig.MIN_CORES, TypeCoercions.coerce(resolve(properties, "num_cpus"), Integer.class));
prov.putIfNotNull(JcloudsLocationConfig.OS_FAMILY, TypeCoercions.coerce(resolve(properties, "os_distribution"), OsFamily.class));
prov.putIfNotNull(JcloudsLocationConfig.OS_VERSION_REGEX, (String)resolve(properties, "os_version"));
// TODO: Mapping for "os_arch" and "os_type" are missing
spec.configure(SoftwareProcess.PROVISIONING_PROPERTIES, prov.getAllConfig());
configurePropertiesForSpec(spec, nodeTemplate);
configureRuntimeEnvironment(spec);
// If the entity spec is of type VanillaSoftwareProcess, we assume that it's running. The operations should
// then take care of setting up the correct scripts.
if (spec.getType().isAssignableFrom(VanillaSoftwareProcess.class)) {
spec.configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "true");
spec.configure(VanillaSoftwareProcess.STOP_COMMAND, "true");
spec.configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "true");
Map<String, Object> shellEnvironment = MutableMap.of();
for (Map.Entry<String, ?> entry : nodeTemplate.getProperties().entrySet()) {
if (entry.getValue() instanceof ScalarPropertyValue) {
shellEnvironment.put(entry.getKey().toUpperCase(), ((ScalarPropertyValue) entry.getValue()).getValue());
}
}
spec.configure(SoftwareProcess.SHELL_ENVIRONMENT, shellEnvironment);
}
// Applying operations
final Map<String, Operation> operations = getInterfaceOperations();
if (!operations.isEmpty()) {
if (spec.getType().isAssignableFrom(VanillaSoftwareProcess.class)) {
applyLifecycle(operations, "create", spec, VanillaSoftwareProcess.INSTALL_COMMAND);
applyLifecycle(operations, "configure", spec, VanillaSoftwareProcess.CUSTOMIZE_COMMAND);
applyLifecycle(operations, "start", spec, VanillaSoftwareProcess.LAUNCH_COMMAND);
applyLifecycle(operations, "stop", spec, VanillaSoftwareProcess.STOP_COMMAND);
if (!operations.isEmpty()) {
log.warn("Could not translate some operations for " + this.nodeId + ": " + operations.keySet());
}
}
}
//This is only a fist prototype.
Map<String, Object> propertiesAndTypedValues = MutableMap.of();
//ProcessConfigurationRequirement
for(String requirementId: nodeTemplate.getRequirements().keySet()){
RelationshipTemplate relationshipTemplate =
findRelationshipRequirement(nodeTemplate, requirementId);
if((relationshipTemplate!=null)
&&(relationshipTemplate.getType().equals("tosca.relationships.Configure"))){
Map<String, Object> relationProperties = getTemplatePropertyObjects(relationshipTemplate);
String target = relationshipTemplate.getTarget();
String propName= (String)relationProperties.get("prop.name");
String propCollection= (String)relationProperties.get("prop.collection");
String propValue= managePropertyTargetNode(target,
(String)relationProperties.get("prop.value"));
if(Strings.isBlank(propCollection)&&(Strings.isBlank(propName))){
throw new IllegalStateException("Relationship for Requirement "
+ relationshipTemplate.getRequirementName() + " on NodeTemplate "
+ nodeTemplate.getName() + ". Collection Name or Property Name should" +
" be defined for RelationsType " + relationshipTemplate.getType());
}
Map<String, String> simpleProperty=null;
if(!Strings.isBlank(propName)){
simpleProperty=ImmutableMap.of(propName, propValue);
}
if(simpleProperty==null) {
propertiesAndTypedValues=
ImmutableMap.of(propCollection, ((Object)ImmutableList.of(propValue)));
} else {
propertiesAndTypedValues =
ImmutableMap.of(propCollection, (Object)simpleProperty);
}
}
}
configureConfigKeysSpec(spec, ConfigBag.newInstance(propertiesAndTypedValues));
return spec;
}
private RelationshipTemplate findRelationshipRequirement(NodeTemplate node, String requirementId){
if(node.getRelationships()!=null){
for(Map.Entry<String, RelationshipTemplate> entry: node.getRelationships().entrySet()){
if(entry.getValue().getRequirementName().equals(requirementId)){
return entry.getValue();
}
}
log.warn("Requirement {} is not described by any relationship ", requirementId);
}
return null;
}
private String managePropertyTargetNode(String targetId, String value){
if(!Strings.containsLiteralIgnoreCase(value, "TARGET")){
log.warn("TARGET identifier was not found on value {} in value {}", value);
}
return value.replaceAll("(?i)TARGET", "\\$brooklyn:component(\""+ targetId+"\")");
}
//TODO PROVISION_PROPERTIES should be added to this method.
private void configurePropertiesForSpec(EntitySpec spec, NodeTemplate nodeTemplate){
ConfigBag bag = ConfigBag.newInstance(getTemplatePropertyObjects(nodeTemplate));
// now set configuration for all the items in the bag
configureConfigKeysSpec(spec, bag);
}
private void configureConfigKeysSpec(EntitySpec spec, ConfigBag bag){
Collection<FlagUtils.FlagConfigKeyAndValueRecord> records = findAllFlagsAndConfigKeys(spec, bag);
Set<String> keyNamesUsed = new LinkedHashSet<>();
for (FlagUtils.FlagConfigKeyAndValueRecord r : records) {
if (r.getFlagMaybeValue().isPresent()) {
Optional<Object> resolvedValue = resolveValue(r.getFlagMaybeValue().get(), Optional.<TypeToken>absent());
if (resolvedValue.isPresent()) {
spec.configure(r.getFlagName(), resolvedValue.get());
}
keyNamesUsed.add(r.getFlagName());
}
if (r.getConfigKeyMaybeValue().isPresent()) {
Optional<Object> resolvedValue = resolveValue(r.getConfigKeyMaybeValue().get(), Optional.<TypeToken>of(r.getConfigKey().getTypeToken()));
if (resolvedValue.isPresent()) {
spec.configure(r.getConfigKey(), resolvedValue.get());
}
keyNamesUsed.add(r.getConfigKey().getName());
}
}
// set unused keys as anonymous config keys -
// they aren't flags or known config keys, so must be passed as config keys in order for
// EntitySpec to know what to do with them (as they are passed to the spec as flags)
for (String key : MutableSet.copyOf(bag.getUnusedConfig().keySet())) {
// we don't let a flag with the same name as a config key override the config key
// (that's why we check whether it is used)
if (!keyNamesUsed.contains(key)) {
//Object transformed = new BrooklynComponentTemplateResolver.SpecialFlagsTransformer(loader).apply(bag.getStringKey(key));
spec.configure(ConfigKeys.newConfigKey(Object.class, key.toString()), bag.getStringKey(key));
}
}
}
private Optional<Object> resolveValue(Object unresolvedValue, Optional<TypeToken> desiredType) {
if (unresolvedValue == null) {
return Optional.absent();
}
// The 'dsl' key is arbitrary, but the interpreter requires a map
Map<String, Object> resolvedConfigMap = CampCatalogUtils.getCampPlatform(mgnt).pdp().applyInterpreters(ImmutableMap.of("dsl", unresolvedValue));
return Optional.of(desiredType.isPresent()
? TypeCoercions.coerce(resolvedConfigMap.get("dsl"), desiredType.get())
: resolvedConfigMap.get("dsl"));
}
/**
* Searches for config keys in the type, additional interfaces and the implementation (if specified)
*/
private Collection<FlagUtils.FlagConfigKeyAndValueRecord> findAllFlagsAndConfigKeys(EntitySpec<? extends Entity> spec, ConfigBag bagFlags) {
Set<FlagUtils.FlagConfigKeyAndValueRecord> allKeys = MutableSet.of();
allKeys.addAll(FlagUtils.findAllFlagsAndConfigKeys(null, spec.getType(), bagFlags));
if (spec.getImplementation() != null) {
allKeys.addAll(FlagUtils.findAllFlagsAndConfigKeys(null, spec.getImplementation(), bagFlags));
}
for (Class<?> iface : spec.getAdditionalInterfaces()) {
allKeys.addAll(FlagUtils.findAllFlagsAndConfigKeys(null, iface, bagFlags));
}
return allKeys;
}
private Map<String, Object> getTemplatePropertyObjects(NodeTemplate template) {
return getPropertyObjects(template.getProperties());
}
private Map<String, Object> getTemplatePropertyObjects(RelationshipTemplate template) {
return getPropertyObjects(template.getProperties());
}
private Map<String, Object> getPropertyObjects(Map<String, AbstractPropertyValue> propertyValueMap) {
Map<String, Object> propertyMap = MutableMap.of();
ImmutableSet<String> propertyKeys = ImmutableSet.copyOf(propertyValueMap.keySet());
for (String propertyKey : propertyKeys) {
propertyMap.put(propertyKey,
resolve(propertyValueMap, propertyKey));
}
return propertyMap;
}
protected Map<String, Operation> getInterfaceOperations() {
final Map<String, Operation> operations = MutableMap.of();
if (indexedNodeTemplate.getInterfaces() != null) {
final ImmutableList<String> validInterfaceNames = ImmutableList.of("tosca.interfaces.node.lifecycle.Standard", "Standard", "standard");
final MutableMap<String, Interface> interfaces = MutableMap.copyOf(indexedNodeTemplate.getInterfaces());
for (String validInterfaceName : validInterfaceNames) {
Interface validInterface = interfaces.remove(validInterfaceName);
if (validInterface != null) {
operations.putAll(validInterface.getOperations());
if (!interfaces.isEmpty()) {
log.warn("Could not translate some interfaces for " + this.nodeId + ": " + interfaces.keySet());
}
break;
}
}
}
return operations;
}
protected void applyLifecycle(Map<String, Operation> ops, String opKey, EntitySpec<? extends Entity> spec, ConfigKey<String> cmdKey) {
Operation op = ops.remove(opKey);
if (op == null) {
return;
}
ImplementationArtifact artifact = op.getImplementationArtifact();
if (artifact != null) {
String ref = artifact.getArtifactRef();
if (ref != null) {
String script = null;
// Trying to get the CSAR file based on the artifact reference. If it fails, then we try to get the
// content of the script from any resources
try {
Path csarPath = csarFileRepository.getCSAR(artifact.getArchiveName(), artifact.getArchiveVersion());
script = new ResourceUtils(this).getResourceAsString(csarPath.getParent().toString() + "/expanded/" + ref);
} catch (CSARVersionNotFoundException e) {
script = new ResourceUtils(this).getResourceAsString(ref);
}
spec.configure(cmdKey, env + "\n" + script);
return;
}
log.warn("Unsupported operation implementation for " + opKey + ": " + artifact + " has no ref");
return;
}
log.warn("Unsupported operation implementation for " + opKey + ": " + artifact + " has no impl");
}
protected void configureRuntimeEnvironment(EntitySpec<?> entitySpec) {
if (indexedNodeTemplate.getArtifacts() == null) {
return;
}
final Map<String, String> filesToCopy = MutableMap.of();
final List<String> preInstallCommands = MutableList.of();
final List<String> envCommands = MutableList.of();
for (final Map.Entry<String, DeploymentArtifact> artifactEntry : indexedNodeTemplate.getArtifacts().entrySet()) {
if (artifactEntry.getValue() == null) {
continue;
}
if (!"tosca.artifacts.File".equals(artifactEntry.getValue().getArtifactType())) {
continue;
}
final String destRoot = Os.mergePaths("~", artifactEntry.getValue().getArtifactName());
final String tempRoot = Os.mergePaths("/tmp", artifactEntry.getValue().getArtifactName());
preInstallCommands.add("mkdir -p " + destRoot);
preInstallCommands.add("mkdir -p " + tempRoot);
envCommands.add(String.format("export %s=%s", artifactEntry.getValue().getArtifactName(), destRoot));
try {
Path csarPath = csarFileRepository.getCSAR(artifactEntry.getValue().getArchiveName(), artifactEntry.getValue().getArchiveVersion());
Path resourcesRootPath = Paths.get(csarPath.getParent().toAbsolutePath().toString(), "expanded", artifactEntry.getKey());
Files.walkFileTree(resourcesRootPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String tempDest = Os.mergePaths(tempRoot, file.getFileName().toString());
String finalDest = Os.mergePaths(destRoot, file.getFileName().toString());
filesToCopy.put(file.toAbsolutePath().toString(), tempDest);
preInstallCommands.add(String.format("mv %s %s", tempDest, finalDest));
return FileVisitResult.CONTINUE;
}
});
// Files.find(resourcesRootPath, Integer.MAX_VALUE, new BiPredicate<Path, BasicFileAttributes>() {
// @Override
// public boolean test(Path path, BasicFileAttributes basicFileAttributes) {
// return basicFileAttributes.isRegularFile();
// }).forEach(new Consumer<Path>() {
// @Override
// public void accept(Path file) {
// String tempDest = Os.mergePaths(tempRoot, file.getFileName().toString());
// String finalDest = Os.mergePaths(destRoot, file.getFileName().toString());
// filesToCopy.put(file.toAbsolutePath().toString(), tempDest);
// preInstallCommands.add(String.format("mv %s %s", tempDest, finalDest));
} catch (CSARVersionNotFoundException e) {
log.warn("CSAR " + artifactEntry.getValue().getArtifactName() + ":" + artifactEntry.getValue().getArchiveVersion() + " does not exists", e);
} catch (IOException e) {
log.warn("Cannot parse CSAR resources", e);
}
}
env = Joiner.on("\n").join(envCommands) + "\n";
entitySpec.configure(SoftwareProcess.PRE_INSTALL_FILES, filesToCopy);
entitySpec.configure(SoftwareProcess.PRE_INSTALL_COMMAND, Joiner.on("\n").join(preInstallCommands) + "\n" + env);
}
public static Object resolve(Map<String, AbstractPropertyValue> props, String... keys) {
for (String key: keys) {
AbstractPropertyValue v = props.get(key);
if (v == null) {
continue;
}
if (v instanceof ScalarPropertyValue) {
return ((ScalarPropertyValue)v).getValue();
}
if (v instanceof ComplexPropertyValue){
return ((ComplexPropertyValue)v).getValue();
}
log.warn("Ignoring unsupported property value " + v);
}
return null;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tsdaggregator;
import org.apache.commons.cli.*;
import org.apache.commons.io.input.Tailer;
import org.apache.log4j.Logger;
import org.joda.time.Period;
import org.joda.time.format.ISOPeriodFormat;
import org.joda.time.format.PeriodFormatter;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author brandarp
*/
public class TsdAggregator {
static final Logger _Logger = Logger.getLogger(TsdAggregator.class);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
_Logger.error("Unhandled exception!", throwable);
}
});
Options options = new Options();
options.addOption("f", "file", true, "file to be parsed");
options.addOption("s", "service", true, "service name");
options.addOption("h", "host", true, "host the metrics were generated on");
options.addOption("u", "uri", true, "metrics server uri");
options.addOption("o", "output", true, "output file");
options.addOption("p", "parser", true, "parser to use to parse log lines");
options.addOption("d", "period", true, "aggregation time period in ISO 8601 standard notation (multiple allowed)");
options.addOption("t", "statistic", true, "statistic of aggregation to record (multiple allowed)");
options.addOption("e", "extension", true, "extension of files to parse - uses a union of arguments as a regex (multiple allowed)");
options.addOption("l", "tail", false, "\"tail\" or follow the file and do not terminate");
options.addOption("d", "rrd", false, "create or write to rrd databases");
options.addOption("m", "remet", false, "send data to a local remet server");
CommandLineParser parser = new PosixParser();
CommandLine cl;
try {
cl = parser.parse(options, args);
} catch (ParseException e1) {
printUsage(options);
return;
}
if (!cl.hasOption("f")) {
System.err.println("no file found, must specify file on the command line");
printUsage(options);
return;
}
if (!cl.hasOption("s")) {
System.err.println("service name must be specified");
printUsage(options);
return;
}
if (!cl.hasOption("h")) {
System.err.println("host name must be specified");
printUsage(options);
return;
}
if (!cl.hasOption("u") && !cl.hasOption("o") && !cl.hasOption("remet")) {
System.err.println("metrics server uri or output file not specified");
printUsage(options);
return;
}
Class parserClass = QueryLogLineData.class;
if (cl.hasOption("p")) {
String lineParser = cl.getOptionValue("p");
try {
parserClass = Class.forName(lineParser);
if (!LogLine.class.isAssignableFrom(parserClass)) {
_Logger.error("parser class [" + lineParser + "] does not implement required LogLine interface");
return;
}
} catch (ClassNotFoundException ex) {
_Logger.error("could not find parser class [" + lineParser + "] on classpath");
return;
}
}
String[] periodOptions = {"PT1M", "PT5M", "PT1H"};
if (cl.hasOption("remet")) {
periodOptions = new String[] {"PT1S"};
}
if (cl.hasOption("d")) {
periodOptions = cl.getOptionValues("d");
}
Pattern filter = Pattern.compile(".*");
if (cl.hasOption("e")) {
String[] filters = cl.getOptionValues("e");
StringBuilder builder = new StringBuilder();
int x = 0;
for (String f : filters) {
if (x > 0) {
builder.append(" || ");
}
builder.append("(").append(f).append(")");
}
filter = Pattern.compile(builder.toString(), Pattern.CASE_INSENSITIVE);
}
Boolean tailFile = cl.hasOption("tail") || cl.hasOption("remet");
Set<Statistic> statisticsClasses = new HashSet<Statistic>();
if (cl.hasOption("t")) {
String[] statisticsStrings = cl.getOptionValues("t");
for (String statString : statisticsStrings) {
try {
_Logger.info("Looking up statistic " + statString);
Class statClass = ClassLoader.getSystemClassLoader().loadClass(statString);
Statistic stat;
try {
stat = (Statistic)statClass.newInstance();
statisticsClasses.add(stat);
} catch (InstantiationException ex) {
_Logger.error("Could not instantiate statistic [" + statString + "]", ex);
return;
} catch (IllegalAccessException ex) {
_Logger.error("Could not instantiate statistic [" + statString + "]", ex);
return;
}
if (!Statistic.class.isAssignableFrom(statClass)) {
_Logger.error("Statistic class [" + statString + "] does not implement required Statistic interface");
return;
}
} catch (ClassNotFoundException ex) {
_Logger.error("could not find statistic class [" + statString + "] on classpath");
return;
}
}
} else if (cl.hasOption("remet")) {
statisticsClasses.add(new NStatistic());
statisticsClasses.add(new TP100());
statisticsClasses.add(new TP99());
statisticsClasses.add(new TP90());
statisticsClasses.add(new MeanStatistic());
} else {
statisticsClasses.add(new TP0());
statisticsClasses.add(new TP50());
statisticsClasses.add(new TP100());
statisticsClasses.add(new TP90());
statisticsClasses.add(new TP99());
statisticsClasses.add(new TP99p9());
statisticsClasses.add(new MeanStatistic());
statisticsClasses.add(new NStatistic());
}
String fileName = cl.getOptionValue("f");
String hostName = cl.getOptionValue("h");
String serviceName = cl.getOptionValue("s");
String metricsUri = "";
String outputFile = "";
Boolean outputRRD = false;
if (cl.hasOption("u")) {
metricsUri = cl.getOptionValue("u");
} else if (cl.hasOption("remet")) {
metricsUri = "http://localhost:7090/report";
}
if (cl.hasOption("o")) {
outputFile = cl.getOptionValue("o");
}
if (cl.hasOption("rrd")) {
outputRRD = true;
}
_Logger.info("using file " + fileName);
_Logger.info("using hostname " + hostName);
_Logger.info("using servicename " + serviceName);
_Logger.info("using uri " + metricsUri);
_Logger.info("using output file " + outputFile);
_Logger.info("using filter (" + filter.pattern() + ")");
if (outputRRD) {
_Logger.info("outputting rrd files");
}
Set<Period> periods = new HashSet<Period>();
PeriodFormatter periodParser = ISOPeriodFormat.standard();
for (String p : periodOptions) {
periods.add(periodParser.parsePeriod(p));
}
MultiListener listener = new MultiListener();
if (!metricsUri.equals("") && !options.hasOption("remet")) {
AggregationListener httpListener = new HttpPostListener(metricsUri);
listener.addListener(new BufferingListener(httpListener, 50));
}
if (!metricsUri.equals("") && options.hasOption("remet")) {
AggregationListener httpListener = new HttpPostListener(metricsUri);
//we don't want to buffer remet responses
listener.addListener(httpListener);
}
if (!outputFile.equals("")) {
AggregationListener fileListener = new FileListener(outputFile);
//listener = new BufferingListener(fileListener, 500);
listener.addListener(fileListener);
}
if (outputRRD) {
listener.addListener(new RRDClusterListener());
}
HashMap<String, TSData> aggregations = new HashMap<String, TSData>();
ArrayList<String> files = new ArrayList<String>();
File file = new File(fileName);
if (file.isFile()) {
files.add(fileName);
} else if (file.isDirectory()) {
_Logger.info("File given is a directory, will recursively process");
findFilesRecursive(file, files, filter);
}
for (String f : files) {
try {
_Logger.info("Reading file " + f);
LineProcessor processor = new LineProcessor(parserClass, statisticsClasses, hostName, serviceName, periods, listener, aggregations);
if (tailFile) {
File fileHandle = new File(f);
LogTailerListener tailListener = new LogTailerListener(processor);
Tailer t = Tailer.create(fileHandle, tailListener, 500l, false);
}
else {
//check the first 4 bytes of the file for utf markers
FileInputStream fis = new FileInputStream(f);
byte[] header = new byte[4];
if (fis.read(header) < 4) {
//If there are less than 4 bytes, we should move on
continue;
}
String encoding = "UTF-8";
if (header[0] == -1 && header[1] == -2) {
_Logger.info("Detected UTF-16 encoding");
encoding = "UTF-16";
}
InputStreamReader fileReader = new InputStreamReader(new FileInputStream(f), Charset.forName(encoding));
BufferedReader reader = new BufferedReader(fileReader);
String line;
while ((line = reader.readLine()) != null) {
if (processor.invoke(line))
return;
}
}
//close all aggregations
for (Map.Entry<String, TSData> entry : aggregations.entrySet()) {
entry.getValue().close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long rotationCheck = 30000;
long rotateOn = 60000;
if (options.hasOption("remet")) {
rotationCheck = 500;
rotateOn = 1000;
}
if (tailFile) {
while (true) {
try {
Thread.sleep(rotationCheck);
//_Logger.info("Checking rotations on " + aggregations.size() + " TSData objects");
for (Map.Entry<String, TSData> entry : aggregations.entrySet()) {
//_Logger.info("Check rotate on " + entry.getKey());
entry.getValue().checkRotate(rotateOn);
}
} catch (InterruptedException e) {
_Logger.error("Interrupted!", e);
}
}
}
listener.close();
}
private static void findFilesRecursive(File dir, ArrayList<String> files, Pattern filter) {
String[] list = dir.list();
Arrays.sort(list);
for (String f : list) {
File entry = new File(dir, f);
if (entry.isFile()) {
Matcher m = filter.matcher(entry.getPath());
if (m.find()) {
files.add(entry.getAbsolutePath());
} else {
}
} else if (entry.isDirectory()) {
findFilesRecursive(entry, files, filter);
}
}
}
public static void printUsage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("tsdaggregator", options, true);
}
} |
package at.medevit.elexis.inbox.core.elements;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import at.medevit.elexis.inbox.core.elements.service.ServiceComponent;
import ch.elexis.core.data.events.ElexisEventDispatcher;
import ch.elexis.data.Kontakt;
import ch.elexis.data.LabOrder;
import ch.elexis.data.LabResult;
import ch.elexis.data.Mandant;
import ch.elexis.data.Patient;
public class AddLabInboxElement implements Runnable {
private static Logger logger = LoggerFactory.getLogger(AddLabInboxElement.class);
private static final int MAX_WAIT = 40;
private LabResult labResult;
public AddLabInboxElement(LabResult labResult){
this.labResult = labResult;
}
@Override
public void run(){
// we have to wait for the fields to be set
if (labResult.get(LabResult.PATIENT_ID) == null
|| labResult.get(LabResult.PATIENT_ID).isEmpty()) {
int waitForFields = 0;
while (waitForFields < MAX_WAIT) {
try {
waitForFields++;
Thread.sleep(500);
if (labResult.get(LabResult.PATIENT_ID) != null
&& !labResult.get(LabResult.PATIENT_ID).isEmpty()) {
break;
}
} catch (InterruptedException e) {
// ignore
}
}
if (waitForFields == MAX_WAIT) {
logger
.warn(String.format("Could not get data from result [%s].", labResult.getId()));
return;
}
}
Patient patient = labResult.getPatient();
Kontakt doctor = labResult.getPatient().getStammarzt();
Mandant assignedMandant = loadAssignedMandant(true);
// patient has NO stammarzt
if (doctor == null) {
if (assignedMandant == null) {
// if stammarzt and assigned contact is null use active mandant
assignedMandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
}
} else if ("1".equals(doctor.get(Kontakt.FLD_IS_MANDATOR))) {
// stammarzt is defined
logger.debug("Creating InboxElement for result [" + labResult.getId() + "] and patient "
+ patient.getLabel() + " for mandant " + doctor.getLabel());
ServiceComponent.getService().createInboxElement(patient, doctor, labResult);
}
// an assigned contact was found that is different than the stammarzt
if (assignedMandant != null && !assignedMandant.equals(doctor)) {
logger.debug("Creating InboxElement for result [" + labResult.getId() + "] and patient "
+ patient.getLabel() + " for mandant " + assignedMandant.getLabel());
ServiceComponent.getService().createInboxElement(patient, assignedMandant, labResult);
}
}
private Mandant loadAssignedMandant(boolean retry){
List<LabOrder> orders =
LabOrder.getLabOrders(labResult.getPatient(), null, null, labResult, null, null, null);
if (orders != null && !orders.isEmpty()) {
String mandantId = orders.get(0).get(LabOrder.FLD_MANDANT);
if (mandantId != null && !mandantId.isEmpty()) {
return Mandant.load(mandantId);
}
}
// sometimes the mandant is persisted delayed from another thread - we have to try again to fetch the mandant id
if (retry)
{
try {
Thread.sleep(1500);
return loadAssignedMandant(false);
}
catch (InterruptedException e) {
/* ignore */
}
}
return null;
}
} |
package com.intellij.xml.impl.schema;
import com.intellij.psi.xml.XmlTag;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.util.XmlUtil;
import com.intellij.xml.impl.XmlLangAttributeDescriptor;
import java.util.*;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
/**
* @author Mike
*/
public class ComplexTypeDescriptor extends TypeDescriptor {
private XmlNSDescriptorImpl myDocumentDescriptor;
private XmlTag myTag;
private XmlElementDescriptor[] myElementDescriptors = null;
@NonNls
public static final String PROHIBITED_ATTR_VALUE = "prohibited";
@NonNls
public static final String OTHER_NAMESPACE_ATTR_VALUE = "##other";
public ComplexTypeDescriptor(XmlNSDescriptorImpl documentDescriptor, XmlTag tag) {
myDocumentDescriptor = documentDescriptor;
myTag = tag;
}
public XmlTag getDeclaration(){
return myTag;
}
public XmlElementDescriptor[] getElements() {
if(myElementDescriptors != null) return myElementDescriptors;
Map<String,XmlElementDescriptor> map = new LinkedHashMap<String,XmlElementDescriptor>(5);
collectElements(map, myTag, new HashSet<XmlTag>());
addSubstitutionGroups(map);
filterAbstractElements(map);
return myElementDescriptors = map.values().toArray(
new XmlElementDescriptor[map.values().size()]
);
}
private void addSubstitutionGroups(Map<String, XmlElementDescriptor> result) {
mainLoop: while (true) {
for (Iterator iterator = result.values().iterator(); iterator.hasNext();) {
XmlElementDescriptorImpl descriptor = (XmlElementDescriptorImpl)iterator.next();
final XmlElementDescriptor[] substitutes = myDocumentDescriptor.getSubstitutes(descriptor.getName(), descriptor.getNamespace());
boolean toContinue = false;
for (int i = 0; i < substitutes.length; i++) {
XmlElementDescriptor substitute = substitutes[i];
if (result.get(substitute.getName())==null) {
toContinue = true;
result.put(substitute.getName(),substitute);
}
}
if (toContinue) continue mainLoop;
}
break;
}
}
private void filterAbstractElements(Map<String,XmlElementDescriptor> result) {
for (Iterator<XmlElementDescriptor> iterator = result.values().iterator(); iterator.hasNext();) {
XmlElementDescriptorImpl descriptor = (XmlElementDescriptorImpl)iterator.next();
if (descriptor.isAbstract()) iterator.remove();
}
}
public XmlAttributeDescriptor[] getAttributes() {
List<XmlAttributeDescriptor> result = new ArrayList<XmlAttributeDescriptor>();
collectAttributes(result, myTag, new ArrayList<XmlTag>());
if (myDocumentDescriptor.supportsStdAttributes()) addStdAttributes(result);
return result.toArray(new XmlAttributeDescriptor[result.size()]);
}
private void addStdAttributes(List<XmlAttributeDescriptor> result) {
result.add(new XmlLangAttributeDescriptor());
}
private void collectElements(Map<String,XmlElementDescriptor> result, XmlTag tag, Set<XmlTag> visited) {
if(visited.contains(tag)) return;
visited.add(tag);
if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "element")) {
String nameAttr = tag.getAttributeValue("name");
if (nameAttr != null) {
addElementDescriptor(result, myDocumentDescriptor.createElementDescriptor(tag));
}
else {
String ref = tag.getAttributeValue("ref");
if (ref != null) {
final String local = XmlUtil.findLocalNameByQualifiedName(ref);
final String namespacePrefix = XmlUtil.findPrefixByQualifiedName(ref);
final String namespace = "".equals(namespacePrefix) ?
myDocumentDescriptor.getDefaultNamespace() :
tag.getNamespaceByPrefix(namespacePrefix);
final XmlElementDescriptor element = myDocumentDescriptor.getElementDescriptor(
local,
namespace,
new HashSet<XmlNSDescriptorImpl>(),
true
);
if (element != null) {
addElementDescriptor(result, element);
}
}
}
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "group")) {
String ref = tag.getAttributeValue("ref");
if (ref != null) {
XmlTag groupTag = myDocumentDescriptor.findGroup(ref);
if (groupTag != null) {
XmlTag[] tags = groupTag.getSubTags();
for (int i = 0; i < tags.length; i++) {
XmlTag subTag = tags[i];
collectElements(result, subTag, visited);
}
}
}
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "restriction") ||
XmlNSDescriptorImpl.equalsToSchemaName(tag, "extension")) {
String base = tag.getAttributeValue("base");
if (base != null) {
TypeDescriptor descriptor = myDocumentDescriptor.findTypeDescriptor(
myDocumentDescriptor.getTag(),
base);
if (descriptor instanceof ComplexTypeDescriptor) {
ComplexTypeDescriptor complexTypeDescriptor = (ComplexTypeDescriptor)descriptor;
complexTypeDescriptor.collectElements(result, complexTypeDescriptor.myTag, visited);
}
XmlTag[] tags = tag.getSubTags();
for (int i = 0; i < tags.length; i++) {
XmlTag subTag = tags[i];
collectElements(result, subTag, visited);
}
}
}
else {
XmlTag[] tags = tag.getSubTags();
for (int i = 0; i < tags.length; i++) {
XmlTag subTag = tags[i];
collectElements(result, subTag, visited);
}
}
}
private void addElementDescriptor(Map<String,XmlElementDescriptor> result, XmlElementDescriptor element) {
result.remove(element.getName());
result.put(element.getName(),element);
}
private void collectAttributes(List<XmlAttributeDescriptor> result, XmlTag tag, List<XmlTag> visited) {
if(visited.contains(tag)) return;
visited.add(tag);
if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "element")) {
return;
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "attribute")) {
String use = tag.getAttributeValue("use");
String name = tag.getAttributeValue("name");
if (name != null) {
if (PROHIBITED_ATTR_VALUE.equals(use)) {
removeAttributeDescriptor(result, name);
}
else {
addAttributeDescriptor(result, tag);
}
}
else {
String ref = tag.getAttributeValue("ref");
if (ref != null) {
if (PROHIBITED_ATTR_VALUE.equals(use)) {
removeAttributeDescriptor(result, ref);
}
else {
final String local = XmlUtil.findLocalNameByQualifiedName(ref);
final String namespacePrefix = XmlUtil.findPrefixByQualifiedName(ref);
final String namespace = "".equals(namespacePrefix) ?
myDocumentDescriptor.getDefaultNamespace() :
tag.getNamespaceByPrefix(namespacePrefix);
final XmlAttributeDescriptorImpl attributeDescriptor = myDocumentDescriptor.getAttribute(local, namespace);
if (attributeDescriptor != null) {
if (use != null) {
attributeDescriptor.myUse = use;
}
addAttributeDescriptor(result, attributeDescriptor);
}
}
}
}
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "attributeGroup")) {
String ref = tag.getAttributeValue("ref");
if (ref != null) {
XmlTag groupTag = myDocumentDescriptor.findAttributeGroup(ref);
if (groupTag != null) {
XmlTag[] tags = groupTag.getSubTags();
for (int i = 0; i < tags.length; i++) {
XmlTag subTag = tags[i];
collectAttributes(result, subTag, visited);
}
}
}
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "restriction") ||
XmlNSDescriptorImpl.equalsToSchemaName(tag, "extension")) {
String base = tag.getAttributeValue("base");
if (base != null) {
TypeDescriptor descriptor = myDocumentDescriptor.findTypeDescriptor(
myDocumentDescriptor.getTag(),
base);
if (descriptor instanceof ComplexTypeDescriptor) {
ComplexTypeDescriptor complexTypeDescriptor = (ComplexTypeDescriptor)descriptor;
complexTypeDescriptor.collectAttributes(result, complexTypeDescriptor.myTag, visited);
}
XmlTag[] tags = tag.getSubTags();
for (int i = 0; i < tags.length; i++) {
XmlTag subTag = tags[i];
collectAttributes(result, subTag, visited);
}
}
}
else {
XmlTag[] tags = tag.getSubTags();
for (int i = 0; i < tags.length; i++) {
XmlTag subTag = tags[i];
collectAttributes(result, subTag, visited);
}
}
}
private void removeAttributeDescriptor(List result, String name) {
for (Iterator iterator = result.iterator(); iterator.hasNext();) {
XmlAttributeDescriptorImpl attributeDescriptor = (XmlAttributeDescriptorImpl)iterator.next();
if (attributeDescriptor.getName().equals(name)) {
iterator.remove();
}
}
}
private void addAttributeDescriptor(List<XmlAttributeDescriptor> result, XmlTag tag) {
addAttributeDescriptor(result, myDocumentDescriptor.createAttributeDescriptor(tag));
}
private void addAttributeDescriptor(List<XmlAttributeDescriptor> result, XmlAttributeDescriptor descriptor) {
String name = descriptor.getName();
for (Iterator iterator = result.iterator(); iterator.hasNext();) {
XmlAttributeDescriptorImpl attributeDescriptor = (XmlAttributeDescriptorImpl)iterator.next();
if (attributeDescriptor.getName().equals(name)) {
iterator.remove();
}
}
result.add(descriptor);
}
public boolean canContainTag(String localName, String namespace) {
return _canContainTag(localName, namespace, myTag, new HashSet<XmlTag>(5));
}
private boolean _canContainTag(String localName, String namespace, XmlTag tag,Set<XmlTag> visited) {
if (visited.contains(tag)) return false;
visited.add(tag);
if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "any")) {
if (OTHER_NAMESPACE_ATTR_VALUE.equals(tag.getAttributeValue("namespace"))) {
return namespace == null || !namespace.equals(myDocumentDescriptor.getDefaultNamespace());
}
return true;
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "group")) {
String ref = tag.getAttributeValue("ref");
if (ref != null) {
XmlTag groupTag = myDocumentDescriptor.findGroup(ref);
if (groupTag != null && _canContainTag(localName, namespace, groupTag,visited)) return true;
}
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "restriction") ||
XmlNSDescriptorImpl.equalsToSchemaName(tag, "extension")) {
String base = tag.getAttributeValue("base");
if (base != null) {
TypeDescriptor descriptor = myDocumentDescriptor.findTypeDescriptor(
myDocumentDescriptor.getTag(),
base);
if (descriptor instanceof ComplexTypeDescriptor) {
ComplexTypeDescriptor complexTypeDescriptor = (ComplexTypeDescriptor)descriptor;
if (complexTypeDescriptor.canContainTag(localName, namespace)) return true;
}
}
}
XmlTag[] subTags = tag.getSubTags();
for (int i = 0; i < subTags.length; i++) {
XmlTag subTag = subTags[i];
if (_canContainTag(localName, namespace, subTag, visited)) return true;
}
return false;
}
public boolean canContainAttribute(String attributeName, String namespace) {
return _canContainAttribute(attributeName, namespace, myTag, new THashSet<String>());
}
private boolean _canContainAttribute(String name, String namespace, XmlTag tag, Set<String> visited) {
if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "anyAttribute")) {
String ns = tag.getAttributeValue("namespace");
if (OTHER_NAMESPACE_ATTR_VALUE.equals(ns)) {
return !namespace.equals(myDocumentDescriptor.getDefaultNamespace());
}
return true;
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "attributeGroup")) {
String ref = tag.getAttributeValue("ref");
if (ref != null && !visited.contains(ref)) {
visited.add(ref);
XmlTag groupTag = myDocumentDescriptor.findGroup(ref);
if (groupTag != null) {
if (_canContainAttribute(name, namespace, groupTag,visited)) return true;
}
}
}
else if (XmlNSDescriptorImpl.equalsToSchemaName(tag, "restriction") ||
XmlNSDescriptorImpl.equalsToSchemaName(tag, "extension")) {
String base = tag.getAttributeValue("base");
if (base != null && !visited.contains(base)) {
visited.add(base);
TypeDescriptor descriptor = myDocumentDescriptor.findTypeDescriptor(
myDocumentDescriptor.getTag(),
base);
if (descriptor instanceof ComplexTypeDescriptor) {
ComplexTypeDescriptor complexTypeDescriptor = (ComplexTypeDescriptor)descriptor;
if (complexTypeDescriptor._canContainAttribute(name, namespace,complexTypeDescriptor.getDeclaration(), visited)) return true;
}
}
}
XmlTag[] subTags = tag.getSubTags();
for (int i = 0; i < subTags.length; i++) {
XmlTag subTag = subTags[i];
if (_canContainAttribute(name, namespace, subTag,visited)) return true;
}
return false;
}
} |
package org.eclipse.birt.chart.reportitem.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.DialChart;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.impl.ChartModelHelper;
import org.eclipse.birt.chart.model.type.BubbleSeries;
import org.eclipse.birt.chart.model.type.DifferenceSeries;
import org.eclipse.birt.chart.model.type.GanttSeries;
import org.eclipse.birt.chart.model.type.StockSeries;
import org.eclipse.birt.chart.plugin.ChartEnginePlugin;
import org.eclipse.birt.chart.reportitem.ChartReportItemUtil;
import org.eclipse.birt.chart.reportitem.api.ChartCubeUtil;
import org.eclipse.birt.chart.reportitem.api.ChartItemUtil;
import org.eclipse.birt.chart.reportitem.ui.ChartExpressionButtonUtil.ExpressionDescriptor;
import org.eclipse.birt.chart.reportitem.ui.ChartExpressionButtonUtil.IExpressionDescriptor;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ChartColumnBindingDialog;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ExtendedItemFilterDialog;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ReportItemParametersDialog;
import org.eclipse.birt.chart.reportitem.ui.i18n.Messages;
import org.eclipse.birt.chart.reportitem.ui.views.attributes.provider.ChartCubeFilterHandleProvider;
import org.eclipse.birt.chart.reportitem.ui.views.attributes.provider.ChartFilterProviderDelegate;
import org.eclipse.birt.chart.ui.swt.ColorPalette;
import org.eclipse.birt.chart.ui.swt.ColumnBindingInfo;
import org.eclipse.birt.chart.ui.swt.CustomPreviewTable;
import org.eclipse.birt.chart.ui.swt.DataDefinitionTextManager;
import org.eclipse.birt.chart.ui.swt.DefaultChartDataSheet;
import org.eclipse.birt.chart.ui.swt.SimpleTextTransfer;
import org.eclipse.birt.chart.ui.swt.composites.DataItemCombo;
import org.eclipse.birt.chart.ui.swt.interfaces.IChartDataSheet;
import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider;
import org.eclipse.birt.chart.ui.swt.interfaces.IExpressionButton;
import org.eclipse.birt.chart.ui.swt.interfaces.ISelectDataComponent;
import org.eclipse.birt.chart.ui.swt.interfaces.ISelectDataCustomizeUI;
import org.eclipse.birt.chart.ui.swt.wizard.ChartAdapter;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizard;
import org.eclipse.birt.chart.ui.swt.wizard.data.SelectDataDynamicArea;
import org.eclipse.birt.chart.ui.swt.wizard.preview.ChartLivePreviewThread;
import org.eclipse.birt.chart.ui.swt.wizard.preview.LivePreviewTask;
import org.eclipse.birt.chart.ui.util.ChartUIConstants;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.ui.util.UIHelper;
import org.eclipse.birt.chart.util.ChartExpressionUtil.ExpressionCodec;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase;
import org.eclipse.birt.core.ui.frameworks.taskwizard.interfaces.ITask;
import org.eclipse.birt.report.designer.internal.ui.data.DataService;
import org.eclipse.birt.report.designer.internal.ui.views.ViewsTreeProvider;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.AbstractFilterHandleProvider;
import org.eclipse.birt.report.designer.ui.cubebuilder.action.NewCubeAction;
import org.eclipse.birt.report.designer.ui.dialogs.ColumnBindingDialog;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter;
import org.eclipse.birt.report.designer.ui.util.UIUtil;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.LevelAttributeHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.MultiViewsHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.metadata.IClassInfo;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.MeasureHandle;
import org.eclipse.birt.report.model.elements.interfaces.ITableItemModel;
import org.eclipse.birt.report.model.elements.olap.Level;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
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.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
/**
* Data sheet implementation for Standard Chart
*/
public class StandardChartDataSheet extends DefaultChartDataSheet implements
Listener
{
private static final String KEY_PREVIEW_DATA = "Preview Data"; //$NON-NLS-1$
final protected ExtendedItemHandle itemHandle;
final protected ReportDataServiceProvider dataProvider;
private Button btnInherit = null;
private Button btnUseData = null;
private boolean bIsInheritSelected = true;
private CCombo cmbInherit = null;
private DataItemCombo cmbDataItems = null;
private StackLayout stackLayout = null;
private Composite cmpStack = null;
private Composite cmpCubeTree = null;
private Composite cmpDataPreview = null;
private Composite cmpColumnsList = null;
private CustomPreviewTable tablePreview = null;
private TreeViewer cubeTreeViewer = null;
private Button btnFilters = null;
private Button btnParameters = null;
private Button btnBinding = null;
private String currentData = null;
private String previousData = null;
public static final int SELECT_NONE = 1;
public static final int SELECT_NEXT = 2;
public static final int SELECT_DATA_SET = 4;
public static final int SELECT_DATA_CUBE = 8;
public static final int SELECT_REPORT_ITEM = 16;
public static final int SELECT_NEW_DATASET = 32;
public static final int SELECT_NEW_DATACUBE = 64;
private final int iSupportedDataItems;
private List<Integer> selectDataTypes = new ArrayList<Integer>( );
private Button btnShowDataPreviewA;
private Button btnShowDataPreviewB;
private TableViewer tableViewerColumns;
private Label columnListDescription;
private Label dataPreviewDescription;
protected final ExpressionCodec exprCodec = ChartModelHelper.instance( )
.createExpressionCodec( );
private static final String HEAD_INFO = "HeaderInfo"; //$NON-NLS-1$
private static final String DATA_LIST = "DataList"; //$NON-NLS-1$
private Composite parentComposite;
public StandardChartDataSheet( ExtendedItemHandle itemHandle,
ReportDataServiceProvider dataProvider, int iSupportedDataItems )
{
this.itemHandle = itemHandle;
this.dataProvider = dataProvider;
this.iSupportedDataItems = iSupportedDataItems;
addListener( this );
}
public StandardChartDataSheet( ExtendedItemHandle itemHandle,
ReportDataServiceProvider dataProvider )
{
this( itemHandle, dataProvider, 0 );
}
@Override
public Composite createActionButtons( Composite parent )
{
Composite composite = ChartUIUtil.createCompositeWrapper( parent );
{
composite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_END ) );
}
btnFilters = new Button( composite, SWT.NONE );
{
btnFilters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnFilters.setLayoutData( gridData );
btnFilters.setText( Messages.getString( "StandardChartDataSheet.Label.Filters" ) ); //$NON-NLS-1$
btnFilters.addListener( SWT.Selection, this );
}
btnParameters = new Button( composite, SWT.NONE );
{
btnParameters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnParameters.setLayoutData( gridData );
btnParameters.setText( Messages.getString( "StandardChartDataSheet.Label.Parameters" ) ); //$NON-NLS-1$
btnParameters.addListener( SWT.Selection, this );
}
btnBinding = new Button( composite, SWT.NONE );
{
btnBinding.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnBinding.setLayoutData( gridData );
btnBinding.setText( Messages.getString( "StandardChartDataSheet.Label.DataBinding" ) ); //$NON-NLS-1$
btnBinding.addListener( SWT.Selection, this );
}
setEnabledForButtons( );
return composite;
}
private void setEnabledForButtons( )
{
if ( isCubeMode( ) )
{
boolean inheritXTab = getDataServiceProvider( ).checkState( IDataServiceProvider.INHERIT_CUBE );
if ( inheritXTab )
{
btnFilters.setEnabled( false );
btnBinding.setEnabled( false );
}
else
{
boolean disabled = getDataServiceProvider( ).isInXTabAggrCell( )
|| getDataServiceProvider( ).isInXTabMeasureCell( );
btnFilters.setEnabled( !disabled
&& ( getDataServiceProvider( ).checkState( IDataServiceProvider.HAS_CUBE ) || !getDataServiceProvider( ).isInheritColumnsGroups( ) ) );
btnBinding.setEnabled( ( getDataServiceProvider( ).checkState( IDataServiceProvider.HAS_CUBE ) || !getDataServiceProvider( ).isInheritColumnsGroups( ) )
&& getDataServiceProvider( ).isInvokingSupported( )
|| getDataServiceProvider( ).isSharedBinding( ) );
}
btnParameters.setEnabled( false );
}
else
{
btnFilters.setEnabled( hasDataSet( )
&& !getDataServiceProvider( ).isInheritColumnsGroups( ) );
// Bugzilla#177704 Chart inheriting data from container doesn't
// support parameters due to limitation in DtE
btnParameters.setEnabled( getDataServiceProvider( ).getDataSet( ) != null
&& getDataServiceProvider( ).isInvokingSupported( ) );
btnBinding.setEnabled( hasDataSet( )
&& !getDataServiceProvider( ).isInheritColumnsGroups( )
&& ( getDataServiceProvider( ).isInvokingSupported( ) || getDataServiceProvider( ).isSharedBinding( ) ) );
}
}
private boolean hasDataSet( )
{
return getDataServiceProvider( ).getInheritedDataSet( ) != null
|| getDataServiceProvider( ).getDataSet( ) != null;
}
void fireEvent( Widget widget, int eventType )
{
Event event = new Event( );
event.data = this;
event.widget = widget;
event.type = eventType;
notifyListeners( event );
}
@Override
public Composite createDataDragSource( Composite parent )
{
cmpStack = new Composite( parent, SWT.NONE );
cmpStack.setLayoutData( new GridData( GridData.FILL_BOTH ) );
stackLayout = new StackLayout( );
stackLayout.marginHeight = 0;
stackLayout.marginWidth = 0;
cmpStack.setLayout( stackLayout );
cmpCubeTree = ChartUIUtil.createCompositeWrapper( cmpStack );
cmpDataPreview = ChartUIUtil.createCompositeWrapper( cmpStack );
createColumnsViewerArea( cmpStack );
Label label = new Label( cmpCubeTree, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.CubeTree" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
if ( !dataProvider.isInXTabMeasureCell( )
&& !dataProvider.isInMultiView( ) )
{
// No description if dnd is disabled
Label description = new Label( cmpCubeTree, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
description.setLayoutData( gd );
description.setText( getCubeTreeViewNote( ) );
}
}
cubeTreeViewer = new TreeViewer( cmpCubeTree, SWT.SINGLE
| SWT.H_SCROLL
| SWT.V_SCROLL
| SWT.BORDER );
cubeTreeViewer.getTree( )
.setLayoutData( new GridData( GridData.FILL_BOTH ) );
( (GridData) cubeTreeViewer.getTree( ).getLayoutData( ) ).heightHint = 120;
ViewsTreeProvider provider = new ViewsTreeProvider( ) {
@Override
public Color getBackground( Object element )
{
if ( element instanceof ReportElementHandle )
{
String key = getBindingNameFrom( (ReportElementHandle) element );
return ColorPalette.getInstance( ).getColor( key );
}
return super.getBackground( element );
}
};
cubeTreeViewer.setLabelProvider( provider );
cubeTreeViewer.setContentProvider( provider );
cubeTreeViewer.setInput( getCube( ) );
final DragSource dragSource = new DragSource( cubeTreeViewer.getTree( ),
DND.DROP_COPY );
dragSource.setTransfer( new Transfer[]{
SimpleTextTransfer.getInstance( )
} );
dragSource.addDragListener( new DragSourceListener( ) {
private String text = null;
public void dragFinished( DragSourceEvent event )
{
// TODO Auto-generated method stub
}
public void dragSetData( DragSourceEvent event )
{
event.data = text;
}
public void dragStart( DragSourceEvent event )
{
text = getDraggableCubeExpression( );
if ( text == null )
{
event.doit = false;
}
}
} );
cubeTreeViewer.getTree( ).addListener( SWT.MouseDown, new Listener( ) {
public void handleEvent( Event event )
{
if ( event.button == 3 && event.widget instanceof Tree )
{
Tree tree = (Tree) event.widget;
TreeItem treeItem = tree.getSelection( )[0];
if ( dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
tree.setMenu( null );
}
else
{
tree.setMenu( createMenuManager( getHandleFromSelection( treeItem.getData( ) ) ).createContextMenu( tree ) );
// tree.getMenu( ).setVisible( true );
}
}
}
} );
label = new Label( cmpDataPreview, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.DataPreview" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
if ( !dataProvider.isInXTabMeasureCell( )
&& !dataProvider.isInMultiView( ) )
{
dataPreviewDescription = new Label( cmpDataPreview, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
dataPreviewDescription.setLayoutData( gd );
dataPreviewDescription.setText( Messages.getString( "StandardChartDataSheet.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
}
}
btnShowDataPreviewA = new Button( cmpDataPreview, SWT.CHECK );
btnShowDataPreviewA.setText( Messages.getString( "StandardChartDataSheet.Label.ShowDataPreview" ) ); //$NON-NLS-1$
btnShowDataPreviewA.addListener( SWT.Selection, this );
tablePreview = new CustomPreviewTable( cmpDataPreview, SWT.SINGLE
| SWT.H_SCROLL
| SWT.V_SCROLL
| SWT.FULL_SELECTION );
{
GridData gridData = new GridData( GridData.FILL_BOTH );
gridData.widthHint = 400;
gridData.heightHint = 120;
tablePreview.setLayoutData( gridData );
tablePreview.setHeaderAlignment( SWT.LEFT );
tablePreview.addListener( CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE,
this );
}
updateDragDataSource( );
return cmpStack;
}
/**
* Returns a note for cube tree view.
*
* @return
*/
protected String getCubeTreeViewNote( )
{
return Messages.getString( "StandardChartDataSheet.Label.DragCube" ); //$NON-NLS-1$
}
private void createColumnsViewerArea( Composite parent )
{
cmpColumnsList = ChartUIUtil.createCompositeWrapper( parent );
Label label = new Label( cmpColumnsList, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.DataPreview" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
if ( !dataProvider.isInXTabMeasureCell( ) )
{
columnListDescription = new Label( cmpColumnsList, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
columnListDescription.setLayoutData( gd );
columnListDescription.setText( Messages.getString( "StandardChartDataSheet.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
}
}
btnShowDataPreviewB = new Button( cmpColumnsList, SWT.CHECK );
btnShowDataPreviewB.setText( Messages.getString( "StandardChartDataSheet.Label.ShowDataPreview" ) ); //$NON-NLS-1$
btnShowDataPreviewB.addListener( SWT.Selection, this );
// Add a list to display all columns.
final Table table = new Table( cmpColumnsList, SWT.SINGLE
| SWT.BORDER
| SWT.H_SCROLL
| SWT.V_SCROLL
| SWT.FULL_SELECTION );
GridData gd = new GridData( GridData.FILL_BOTH );
table.setLayoutData( gd );
table.setLinesVisible( true );
tableViewerColumns = new TableViewer( table );
tableViewerColumns.setUseHashlookup( true );
new TableColumn( table, SWT.LEFT );
table.addMouseMoveListener( new MouseMoveListener( ) {
@SuppressWarnings("unchecked")
public void mouseMove( MouseEvent e )
{
if ( !dataProvider.isLivePreviewEnabled( ) )
{
table.setToolTipText( null );
return;
}
String tooltip = null;
TableItem item = ( (Table) e.widget ).getItem( new Point( e.x,
e.y ) );
if ( item != null )
{
List<Object[]> data = (List<Object[]>) tableViewerColumns.getData( KEY_PREVIEW_DATA );
if ( data != null )
{
StringBuilder sb = new StringBuilder( );
int index = ( (Table) e.widget ).indexOf( item );
int i = 0;
for ( ; i < data.size( ); i++ )
{
if ( sb.length( ) > 45 )
{
break;
}
if ( data.get( i )[index] != null )
{
if ( i != 0 )
sb.append( "; " ); //$NON-NLS-1$
sb.append( String.valueOf( data.get( i )[index] ) );
}
}
if ( i == 1 && sb.length( ) > 45 )
{
sb = new StringBuilder( sb.substring( 0, 45 ) );
sb.append( "..." );//$NON-NLS-1$
}
else if ( i < data.size( ) )
{
sb.append( ";..." ); //$NON-NLS-1$
}
tooltip = sb.toString( );
}
}
table.setToolTipText( tooltip );
}
} );
table.addMenuDetectListener( new MenuDetectListener( ) {
public void menuDetected( MenuDetectEvent arg0 )
{
if ( isCubeMode( ) )
{
// share cube
table.setMenu( null );
}
else
{
TableItem item = table.getSelection( )[0];
if ( item == null )
{
tableViewerColumns.getTable( ).select( -1 );
}
// Bind context menu to each header button
boolean isSharingChart = dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY );
if ( item != null && !isSharingChart )
{
if ( table.getMenu( ) != null )
{
table.getMenu( ).dispose( );
}
table.setMenu( createMenuManager( item.getData( ) ).createContextMenu( table ) );
}
else
{
table.setMenu( null );
}
if ( table.getMenu( ) != null && !isSharingChart )
{
table.getMenu( ).setVisible( true );
}
}
}
} );
table.addListener( SWT.Resize, new Listener( ) {
public void handleEvent( Event event )
{
Table table = (Table) event.widget;
int totalWidth = table.getClientArea( ).width;
table.getColumn( 0 ).setWidth( totalWidth );
}
} );
// Set drag/drop.
DragSource ds = new DragSource( table, DND.DROP_COPY | DND.DROP_MOVE );
ds.setTransfer( new Transfer[]{
SimpleTextTransfer.getInstance( )
} );
ColumnNamesTableDragListener dragSourceAdapter = new ColumnNamesTableDragListener( table,
itemHandle );
ds.addDragListener( dragSourceAdapter );
tableViewerColumns.setContentProvider( new IStructuredContentProvider( ) {
/**
* Gets the food items for the list
*
* @param arg0
* the data model
* @return Object[]
*/
public Object[] getElements( Object arg0 )
{
if ( arg0 == null )
return null;
return (ColumnBindingInfo[]) arg0;
}
/**
* Disposes any created resources
*/
public void dispose( )
{
// Do nothing
}
/**
* 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 )
{
// Do nothing
}
} );
tableViewerColumns.setLabelProvider( new ILabelProvider( ) {
/**
* images
*
* @param arg0
* the element
* @return Image
*/
public Image getImage( Object arg0 )
{
String imageName = ( (ColumnBindingInfo) arg0 ).getImageName( );
if ( imageName == null )
return null;
return UIHelper.getImage( imageName );
}
/**
* Gets the text for an element
*
* @param arg0
* the element
* @return String
*/
public String getText( Object arg0 )
{
return ( (ColumnBindingInfo) arg0 ).getName( );
}
/**
* Adds a listener
*
* @param arg0
* the listener
*/
public void addListener( ILabelProviderListener arg0 )
{
// Throw it away
}
/**
* Disposes any resources
*/
public void dispose( )
{
// Nothing to dispose
}
/**
* Returns whether changing the specified property for the specified
* element affect the label
*
* @param arg0
* the element
* @param arg1
* the property
* @return boolean
*/
public boolean isLabelProperty( Object arg0, String arg1 )
{
return false;
}
/**
* Removes a listener
*
* @param arg0
* the listener
*/
public void removeListener( ILabelProviderListener arg0 )
{
// Ignore
}
} );
}
private void updateDragDataSource( )
{
if ( dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{// hide the description if share chart
if ( columnListDescription != null )
{
( (GridData) columnListDescription.getLayoutData( ) ).exclude = true;
columnListDescription.setVisible( false );
cmpColumnsList.layout( );
}
if ( dataPreviewDescription != null )
{
( (GridData) dataPreviewDescription.getLayoutData( ) ).exclude = true;
dataPreviewDescription.setVisible( false );
cmpDataPreview.layout( );
}
}
if ( isCubeMode( ) )
{
if ( getDataServiceProvider( ).checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY ) )
{// share cube
if ( !getDataServiceProvider( ).checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
( (GridData) columnListDescription.getLayoutData( ) ).exclude = false;
columnListDescription.setVisible( true );
columnListDescription.setText( Messages.getString( "StandardChartDataSheet.Label.ShareCrossTab" ) ); //$NON-NLS-1$
cmpColumnsList.layout( );
}
getContext( ).setShowingDataPreview( Boolean.FALSE );
btnShowDataPreviewB.setSelection( false );
btnShowDataPreviewB.setEnabled( false );
stackLayout.topControl = cmpColumnsList;
refreshDataPreviewPane( );
}
else if ( getDataServiceProvider( ).checkState( IDataServiceProvider.INHERIT_CUBE ) )
{// inheritance
stackLayout.topControl = cmpColumnsList;
getContext( ).setShowingDataPreview( Boolean.FALSE );
btnShowDataPreviewB.setSelection( false );
btnShowDataPreviewB.setEnabled( false );
refreshDataPreviewPane( );
}
else
{
stackLayout.topControl = cmpCubeTree;
cubeTreeViewer.setInput( getCube( ) );
}
cmpStack.layout( );
ChartWizard.removeException( ChartWizard.StaChartDSh_dPreview_ID );
return;
}
if ( columnListDescription != null )
{
if ( !dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
( (GridData) columnListDescription.getLayoutData( ) ).exclude = false;
columnListDescription.setVisible( true );
columnListDescription.setText( Messages.getString( "StandardChartDataSheet.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
cmpColumnsList.layout( );
}
}
btnShowDataPreviewB.setEnabled( true );
// Clear data preview setting if current data item was changed.
String pValue = ( previousData == null ) ? "" : previousData; //$NON-NLS-1$
String cValue = ( currentData == null ) ? "" : currentData; //$NON-NLS-1$
if ( !pValue.equals( cValue ) )
{
getContext( ).setShowingDataPreview( null );
}
previousData = currentData;
try
{
// If it is initial state and the columns are equal and greater
// than 6, do not use data preview, just use columns list view.
if ( !getContext( ).isSetShowingDataPreview( )
&& getDataServiceProvider( ).getPreviewHeadersInfo( ).length >= 6 )
{
getContext( ).setShowingDataPreview( Boolean.FALSE );
}
ChartWizard.removeException( ChartWizard.StaChartDSh_gHeaders_ID );
}
catch ( NullPointerException e )
{
// Do not do anything.
}
catch ( ChartException e )
{
ChartWizard.showException( ChartWizard.StaChartDSh_gHeaders_ID,
e.getMessage( ) );
}
btnShowDataPreviewA.setSelection( getContext( ).isShowingDataPreview( ) );
btnShowDataPreviewB.setSelection( getContext( ).isShowingDataPreview( ) );
if ( getContext( ).isShowingDataPreview( ) )
{
stackLayout.topControl = cmpDataPreview;
}
else
{
stackLayout.topControl = cmpColumnsList;
}
refreshDataPreviewPane( );
cmpStack.layout( );
}
/**
* Check if chart is direct consuming cube, should exclude sharing
* cube/inheriting cube/xtab-chart with cube/multiview with cube cases.
*
* @return
*/
private boolean isDirectCubeReference( )
{
boolean bCube = ChartCubeUtil.getBindingCube( itemHandle ) != null;
if ( bCube )
{
int selectedIndex = cmbDataItems.getSelectionIndex( );
if ( selectedIndex < 0 )
{
return false;
}
Integer selectState = selectDataTypes.get( selectedIndex );
return selectState.intValue( ) == SELECT_DATA_CUBE;
}
return false;
}
private void refreshDataPreviewPane( )
{
if ( isDirectCubeReference( ) )
{
return;
}
if ( getContext( ).isShowingDataPreview( ) )
{
refreshTablePreview( );
}
else
{
refreshDataPreview( );
}
}
private void refreshDataPreview( )
{
final boolean isTablePreview = getContext( ).isShowingDataPreview( );
LivePreviewTask lpt = new LivePreviewTask( Messages.getString( "StandardChartDataSheet.Message.RetrieveData" ), //$NON-NLS-1$
null );
// Add a task to retrieve data and bind data to chart.
lpt.addTask( new LivePreviewTask( ) {
public void run( )
{
ColumnBindingInfo[] headers = null;
List<?> dataList = null;
try
{
// Get header and data in other thread.
headers = getDataServiceProvider( ).getPreviewHeadersInfo( );
// Only when live preview is enabled, it retrieves data.
if ( dataProvider.isLivePreviewEnabled( ) )
{
dataList = getPreviewData( );
}
this.setParameter( HEAD_INFO, headers );
this.setParameter( DATA_LIST, dataList );
}
catch ( Exception e )
{
final ColumnBindingInfo[] headerInfo = headers;
final List<?> data = dataList;
// Catch any exception.
final String message = e.getLocalizedMessage( );
Display.getDefault( ).syncExec( new Runnable( ) {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run( )
{
if ( isTablePreview )
{
// Still update table preview in here to ensure
// the
// column headers of table preview can be
// updated
// and user can select expression from table
// preview
// even if there is no preview data.
updateTablePreview( headerInfo, data );
}
else
{
updateColumnsTableViewer( headerInfo, data );
}
ChartWizard.showException( ChartWizard.StaChartDSh_dPreview_ID,
message );
}
} );
}
}
} );
// Add a task to render chart.
lpt.addTask( new LivePreviewTask( ) {
public void run( )
{
final ColumnBindingInfo[] headerInfo = (ColumnBindingInfo[]) this.getParameter( HEAD_INFO );
if ( headerInfo == null )
{
return;
}
final List<?> data = (List<?>) this.getParameter( DATA_LIST );
// Execute UI operation in UI thread.
Display.getDefault( ).syncExec( new Runnable( ) {
public void run( )
{
if ( isTablePreview )
{
updateTablePreview( headerInfo, data );
}
else
{
updateColumnsTableViewer( headerInfo, data );
}
ChartWizard.removeException( ChartWizard.StaChartDSh_dPreview_ID );
}
} );
}
} );
// Add live preview tasks to live preview thread.
( (ChartLivePreviewThread) context.getLivePreviewThread( ) ).setParentShell( parentComposite.getShell( ) );
( (ChartLivePreviewThread) context.getLivePreviewThread( ) ).add( lpt );
}
/**
* @param headerInfo
* @param data
*/
private void updateColumnsTableViewer(
final ColumnBindingInfo[] headerInfo, final List<?> data )
{
if ( tableViewerColumns.getTable( ).isDisposed( ) )
{
return;
}
// Set input.
tableViewerColumns.setInput( headerInfo );
tableViewerColumns.setData( KEY_PREVIEW_DATA, data );
// Make the selected column visible and active.
int index = tablePreview.getCurrentColumnIndex( );
if ( index >= 0 )
{
tableViewerColumns.getTable( ).setFocus( );
tableViewerColumns.getTable( ).select( index );
tableViewerColumns.getTable( ).showSelection( );
}
updateColumnsTableViewerColor( );
}
@Override
public Composite createDataSelector( Composite parent )
{
parentComposite = parent;
// select the only data set
if ( itemHandle.getDataBindingType( ) == ReportItemHandle.DATABINDING_TYPE_NONE
&& itemHandle.getContainer( ) instanceof ModuleHandle )
{
String[] dataSets = dataProvider.getAllDataSets( );
if ( dataProvider.getAllDataCubes( ).length == 0
&& dataSets.length == 1 )
{
dataProvider.setDataSet( dataSets[0] );
}
}
Composite cmpDataSet = ChartUIUtil.createCompositeWrapper( parent );
{
cmpDataSet.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Label label = new Label( cmpDataSet, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.SelectDataSet" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
Composite cmpDetail = new Composite( cmpDataSet, SWT.NONE );
{
GridLayout gridLayout = new GridLayout( 2, false );
gridLayout.marginWidth = 10;
gridLayout.marginHeight = 0;
cmpDetail.setLayout( gridLayout );
cmpDetail.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Composite compRadios = ChartUIUtil.createCompositeWrapper( cmpDetail );
{
GridData gd = new GridData( );
gd.verticalSpan = 2;
compRadios.setLayoutData( gd );
}
btnInherit = new Button( compRadios, SWT.RADIO );
btnInherit.setText( Messages.getString( "StandardChartDataSheet.Label.UseReportData" ) ); //$NON-NLS-1$
btnInherit.addListener( SWT.Selection, this );
btnUseData = new Button( compRadios, SWT.RADIO );
btnUseData.setText( Messages.getString( "StandardChartDataSheet.Label.UseDataSet" ) ); //$NON-NLS-1$
btnUseData.addListener( SWT.Selection, this );
cmbInherit = new CCombo( cmpDetail, SWT.DROP_DOWN
| SWT.READ_ONLY
| SWT.BORDER );
cmbInherit.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
cmbInherit.addListener( SWT.Selection, this );
cmbDataItems = new DataItemCombo( cmpDetail, SWT.DROP_DOWN
| SWT.READ_ONLY
| SWT.BORDER ) {
@Override
public boolean triggerSelection( int index )
{
int selectState = selectDataTypes.get( index ).intValue( );
if ( selectState == SELECT_NEW_DATASET
|| selectState == SELECT_NEW_DATACUBE )
{
return false;
}
return true;
}
@Override
public boolean skipSelection( int index )
{
//skip out of boundary selection
if(index>=0){
int selectState = selectDataTypes.get( index ).intValue( );
if ( selectState == SELECT_NEXT )
{
return true;
}
}
return false;
}
};
cmbDataItems.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
cmbDataItems.addListener( SWT.Selection, this );
cmbDataItems.setVisibleItemCount( 30 );
initDataSelector( );
updatePredefinedQueries( );
checkColBindingForCube( );
if ( dataProvider.checkState( IDataServiceProvider.IN_MULTI_VIEWS ) )
{
autoSelect( false );
}
return cmpDataSet;
}
int invokeNewDataSet( )
{
int count = getDataServiceProvider( ).getAllDataSets( ).length;
DataService.getInstance( ).createDataSet( );
if ( getDataServiceProvider( ).getAllDataSets( ).length == count )
{
// user cancel this operation
return Window.CANCEL;
}
return Window.OK;
}
int invokeEditFilter( )
{
ExtendedItemHandle handle = getItemHandle( );
handle.getModuleHandle( ).getCommandStack( ).startTrans( null );
ExtendedItemFilterDialog page = new ExtendedItemFilterDialog( handle );
AbstractFilterHandleProvider provider = ChartFilterProviderDelegate.createFilterProvider( handle,
handle );
if ( provider instanceof ChartCubeFilterHandleProvider )
{
( (ChartCubeFilterHandleProvider) provider ).setContext( getContext( ) );
}
page.setFilterHandleProvider( provider );
int openStatus = page.open( );
if ( openStatus == Window.OK )
{
handle.getModuleHandle( ).getCommandStack( ).commit( );
}
else
{
handle.getModuleHandle( ).getCommandStack( ).rollback( );
}
return openStatus;
}
int invokeEditParameter( )
{
ReportItemParametersDialog page = new ReportItemParametersDialog( getItemHandle( ) );
return page.open( );
}
int invokeDataBinding( )
{
Shell shell = new Shell( Display.getDefault( ), SWT.DIALOG_TRIM
| SWT.RESIZE
| SWT.APPLICATION_MODAL );
// #194163: Do not register CS help in chart since it's registered in
// super column binding dialog.
// ChartUIUtil.bindHelp( shell,
// ChartHelpContextIds.DIALOG_DATA_SET_COLUMN_BINDING );
ExtendedItemHandle handle = getItemHandle( );
handle.getModuleHandle( ).getCommandStack( ).startTrans( null );
ColumnBindingDialog page = new ChartColumnBindingDialog( handle,
shell,
getContext( ) );
ExpressionProvider ep = new ExpressionProvider( getItemHandle( ) );
ep.addFilter( new ExpressionFilter( ) {
@Override
public boolean select( Object parentElement, Object element )
{
// Remove unsupported expression. See bugzilla#132768
return !( parentElement.equals( ExpressionProvider.BIRT_OBJECTS )
&& element instanceof IClassInfo && ( (IClassInfo) element ).getName( )
.equals( "Total" ) ); //$NON-NLS-1$
}
} );
// Add this filer to disable the reference of DataSet category and Cube
// category.
ep.addFilter( new ExpressionFilter( ) {
@Override
public boolean select( Object parentElement, Object element )
{
if ( !ExpressionFilter.CATEGORY.equals( parentElement ) )
{
return true;
}
if ( element instanceof String )
{
if ( ExpressionProvider.DATASETS.equals( element )
|| ExpressionProvider.CURRENT_CUBE.equals( element ) )
{
return false;
}
return true;
}
return true;
}
} );
page.setExpressionProvider( ep );
// Make all bindings under share binding case read-only.
( (ChartColumnBindingDialog) page ).setReadOnly( getDataServiceProvider( ).isSharedBinding( )
|| getDataServiceProvider( ).isInheritanceOnly( )
|| getDataServiceProvider( ).checkState( IDataServiceProvider.HAS_CUBE ) );
int openStatus = page.open( );
if ( openStatus == Window.OK )
{
handle.getModuleHandle( ).getCommandStack( ).commit( );
updatePredefinedQueries( );
checkColBindingForCube( );
}
else
{
handle.getModuleHandle( ).getCommandStack( ).rollback( );
}
return openStatus;
}
private void initDataSelector( )
{
boolean isInheritingSummaryTable = isInheritingSummaryTable( );
// create Combo items
cmbInherit.setItems( new String[]{
Messages.getString( "StandardChartDataSheet.Combo.InheritColumnsGroups" ), //$NON-NLS-1$
Messages.getString( "StandardChartDataSheet.Combo.InheritColumnsOnly" ) //$NON-NLS-1$
} );
if ( isInheritingSummaryTable )
{
cmbInherit.select( 0 );
getContext( ).setInheritColumnsOnly( true );
}
else if ( dataProvider.isInheritColumnsSet( ) )
{
cmbInherit.select( dataProvider.isInheritColumnsOnly( ) ? 1 : 0 );
}
else
{
// Set default inheritance value
if ( ChartItemUtil.hasAggregation( getChartModel( ) ) )
{
// If aggregations found, set inherit columns only
cmbInherit.select( 1 );
getContext( ).setInheritColumnsOnly( true );
}
else
{
// Default value is set as Inherit groups
cmbInherit.select( 0 );
getContext( ).setInheritColumnsOnly( false );
}
}
cmbInherit.setEnabled( false );
cmbDataItems.setItems( createDataComboItems( ) );
// Select report item reference
// Since handle may have data set or data cube besides reference, always
// check reference first
String sItemRef = getDataServiceProvider( ).getReportItemReference( );
if ( sItemRef != null )
{
btnUseData.setSelection( true );
bIsInheritSelected = false;
cmbDataItems.setText( sItemRef );
currentData = sItemRef;
return;
}
// Select data set
String sDataSet = getDataServiceProvider( ).getDataSet( );
if ( sDataSet != null && !getDataServiceProvider( ).isInheritanceOnly( ) )
{
btnUseData.setSelection( true );
bIsInheritSelected = false;
cmbDataItems.setText( sDataSet );
currentData = sDataSet;
return;
}
// Select data cube
String sDataCube = getDataServiceProvider( ).getDataCube( );
if ( sDataCube != null
&& !getDataServiceProvider( ).isInheritanceOnly( ) )
{
btnUseData.setSelection( true );
bIsInheritSelected = false;
cmbDataItems.setText( sDataCube );
currentData = sDataCube;
return;
}
cmbInherit.setEnabled( !isInheritingSummaryTable
&& getDataServiceProvider( ).getInheritedDataSet( ) != null
&& ChartItemUtil.isContainerInheritable( itemHandle ) );
if ( !cmbInherit.isEnabled( ) )
{
if ( itemHandle.getContainer( ) instanceof MultiViewsHandle
|| itemHandle.getDataBindingReference( ) != null )
{
// If sharing or multi view, set inherit column groups.
cmbInherit.select( 0 );
}
else
{
// If container is grid or anything else, set inherit columns
// only.
cmbInherit.select( 1 );
}
}
btnInherit.setSelection( true );
bIsInheritSelected = true;
if ( getDataServiceProvider( ).isInheritanceOnly( ) )
{
btnUseData.setSelection( false );
btnUseData.setEnabled( false );
}
cmbDataItems.select( 0 );
currentData = null;
cmbDataItems.setEnabled( false );
// Initializes column bindings from container
getDataServiceProvider( ).setDataSet( null );
}
private boolean isInheritingSummaryTable( )
{
if ( ChartItemUtil.isContainerInheritable( itemHandle ) )
{
// Copy aggregations from table container to chart
TableHandle table = null;
DesignElementHandle container = itemHandle.getContainer( );
while ( container != null )
{
if ( container instanceof TableHandle )
{
table = (TableHandle) container;
break;
}
container = container.getContainer( );
}
if ( table != null )
{
return table.getBooleanProperty( ITableItemModel.IS_SUMMARY_TABLE_PROP );
}
}
return false;
}
public void handleEvent( Event event )
{
// When user select expression in drop&down list of live preview
// area, the event will be handled to update related column color.
if ( event.type == IChartDataSheet.EVENT_QUERY )
{
if ( event.detail == IChartDataSheet.DETAIL_UPDATE_COLOR_AND_TEXT )
{
updateColorAndText( );
}
else if ( event.detail == IChartDataSheet.DETAIL_UPDATE_COLOR
&& event.data instanceof ISelectDataComponent )
{
refreshTableColor( );
}
return;
}
// Right click to display the menu. Menu display by clicking
// application key is triggered by os, so do nothing.
// bug 261340, now we use the field doit to indicate whether it's menu
// initialization or event triggering.
if ( event.type == CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE )
{
if ( getDataServiceProvider( ).getDataSet( ) != null
|| getDataServiceProvider( ).getInheritedDataSet( ) != null )
{
if ( event.widget instanceof Button )
{
Button header = (Button) event.widget;
// Bind context menu to each header button
boolean isSharingChart = dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY );
if ( header.getMenu( ) == null && !isSharingChart )
{
header.setMenu( createMenuManager( event.data ).createContextMenu( tablePreview ) );
}
if ( event.doit && !isSharingChart )
{
header.getMenu( ).setVisible( true );
}
}
}
}
else if ( event.type == SWT.Selection )
{
if ( event.widget instanceof MenuItem )
{
MenuItem item = (MenuItem) event.widget;
IAction action = (IAction) item.getData( );
action.setChecked( !action.isChecked( ) );
action.run( );
}
else if ( event.widget == btnFilters )
{
if ( invokeEditFilter( ) == Window.OK )
{
refreshDataPreviewPane( );
// Update preview via event
fireEvent( btnFilters, EVENT_PREVIEW );
}
}
else if ( event.widget == btnParameters )
{
if ( invokeEditParameter( ) == Window.OK )
{
refreshDataPreviewPane( );
// Update preview via event
fireEvent( btnParameters, EVENT_PREVIEW );
}
}
else if ( event.widget == btnBinding )
{
if ( invokeDataBinding( ) == Window.OK )
{
refreshDataPreviewPane( );
// Update preview via event
fireEvent( btnBinding, EVENT_PREVIEW );
}
}
try
{
if ( event.widget == btnInherit )
{
ColorPalette.getInstance( ).restore( );
// Skip when selection is false
if ( !btnInherit.getSelection( ) )
{
return;
}
// Avoid duplicate loading data set.
if ( bIsInheritSelected )
{
return;
}
bIsInheritSelected = true;
getDataServiceProvider( ).setReportItemReference( null );
getDataServiceProvider( ).setDataCube( null );
getDataServiceProvider( ).setDataSet( null );
switchDataSet( );
cmbDataItems.select( 0 );
currentData = null;
cmbDataItems.setEnabled( false );
cmbInherit.setEnabled( !isInheritingSummaryTable( )
&& getDataServiceProvider( ).getInheritedDataSet( ) != null
&& ChartItemUtil.isContainerInheritable( itemHandle ) );
setEnabledForButtons( );
updateDragDataSource( );
updatePredefinedQueries( );
}
else if ( event.widget == btnUseData )
{
// Skip when selection is false
if ( !btnUseData.getSelection( ) )
{
return;
}
// Avoid duplicate loading data set.
if ( !bIsInheritSelected )
{
return;
}
bIsInheritSelected = false;
getDataServiceProvider( ).setReportItemReference( null );
getDataServiceProvider( ).setDataSet( null );
selectDataSet( );
cmbDataItems.setEnabled( true );
cmbInherit.setEnabled( false );
setEnabledForButtons( );
updateDragDataSource( );
updatePredefinedQueries( );
}
else if ( event.widget == cmbInherit )
{
getContext( ).setInheritColumnsOnly( cmbInherit.getSelectionIndex( ) == 1 );
setEnabledForButtons( );
// Fire event to update outside UI
fireEvent( btnBinding, EVENT_QUERY );
refreshDataPreviewPane( );
}
else if ( event.widget == cmbDataItems )
{
ColorPalette.getInstance( ).restore( );
int selectedIndex = cmbDataItems.getSelectionIndex( );
Integer selectState = selectDataTypes.get( selectedIndex );
switch ( selectState.intValue( ) )
{
case SELECT_NONE :
// Inherit data from container
btnInherit.setSelection( true );
btnUseData.setSelection( false );
btnInherit.notifyListeners( SWT.Selection,
new Event( ) );
break;
case SELECT_NEXT :
selectedIndex++;
selectState = selectDataTypes.get( selectedIndex );
cmbDataItems.select( selectedIndex );
break;
}
switch ( selectState.intValue( ) )
{
case SELECT_DATA_SET :
if ( getDataServiceProvider( ).getReportItemReference( ) == null
&& getDataServiceProvider( ).getDataSet( ) != null
&& getDataServiceProvider( ).getDataSet( )
.equals( cmbDataItems.getText( ) ) )
{
return;
}
getDataServiceProvider( ).setDataSet( cmbDataItems.getText( ) );
currentData = cmbDataItems.getText( );
switchDataSet( );
setEnabledForButtons( );
updateDragDataSource( );
break;
case SELECT_DATA_CUBE :
getDataServiceProvider( ).setDataCube( cmbDataItems.getText( ) );
currentData = cmbDataItems.getText( );
// Since cube has no group, it needs to clear group
// flag in category and optional Y of chart model.
clearGrouping( );
updateDragDataSource( );
setEnabledForButtons( );
// Update preview via event
DataDefinitionTextManager.getInstance( )
.refreshAll( );
fireEvent( tablePreview, EVENT_PREVIEW );
break;
case SELECT_REPORT_ITEM :
if ( cmbDataItems.getText( )
.equals( getDataServiceProvider( ).getReportItemReference( ) ) )
{
return;
}
if ( getDataServiceProvider( ).isNoNameItem( cmbDataItems.getText( ) ) )
{
MessageDialog dialog = new MessageDialog( UIUtil.getDefaultShell( ),
org.eclipse.birt.report.designer.nls.Messages.getString( "dataBinding.title.haveNoName" ),//$NON-NLS-1$
null,
org.eclipse.birt.report.designer.nls.Messages.getString( "dataBinding.message.haveNoName" ),//$NON-NLS-1$
MessageDialog.QUESTION,
new String[]{
org.eclipse.birt.report.designer.nls.Messages.getString( "dataBinding.button.OK" )//$NON-NLS-1$
},
0 );
dialog.open( );
btnInherit.setSelection( true );
btnUseData.setSelection( false );
btnInherit.notifyListeners( SWT.Selection,
new Event( ) );
return;
}
getDataServiceProvider( ).setReportItemReference( cmbDataItems.getText( ) );
// TED 10163
// Following calls will revise chart model for
// report item sharing case, in older version of
// chart, it is allowed to set grouping on category
// series when sharing report item, but now it isn't
// allowed, so this calls will revise chart model to
// remove category series grouping flag for the
// case.
ChartReportItemUtil.reviseChartModel( ChartReportItemUtil.REVISE_REFERENCE_REPORT_ITEM,
this.getContext( ).getModel( ),
itemHandle );
// Bugzilla 265077.
if ( this.getDataServiceProvider( )
.checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
ChartAdapter.beginIgnoreNotifications( );
this.getDataServiceProvider( )
.update( ChartUIConstants.COPY_SERIES_DEFINITION,
null );
ChartAdapter.endIgnoreNotifications( );
}
currentData = cmbDataItems.getText( );
// selectDataSet( );
// switchDataSet( cmbDataItems.getText( ) );
// Update preview via event
DataDefinitionTextManager.getInstance( )
.refreshAll( );
fireEvent( tablePreview, EVENT_PREVIEW );
setEnabledForButtons( );
updateDragDataSource( );
break;
case SELECT_NEW_DATASET :
// Bring up the dialog to create a dataset
int result = invokeNewDataSet( );
if ( result == Window.CANCEL )
{
if ( currentData == null )
{
cmbDataItems.select( 0 );
}
else
{
cmbDataItems.setText( currentData );
}
return;
}
cmbDataItems.removeAll( );
cmbDataItems.setItems( createDataComboItems( ) );
// select the newly created data set for user
String[] datasets = getDataServiceProvider( ).getAllDataSets( );
currentData = datasets[datasets.length - 1];
getDataServiceProvider( ).setDataSet( currentData );
cmbDataItems.setText( currentData );
setEnabledForButtons( );
updateDragDataSource( );
break;
case SELECT_NEW_DATACUBE :
if ( getDataServiceProvider( ).getAllDataSets( ).length == 0 )
{
invokeNewDataSet( );
}
int count = getDataServiceProvider( ).getAllDataCubes( ).length;
if ( getDataServiceProvider( ).getAllDataSets( ).length != 0 )
{
new NewCubeAction( ).run( );
}
String[] datacubes = getDataServiceProvider( ).getAllDataCubes( );
cmbDataItems.removeAll( );
cmbDataItems.setItems( createDataComboItems( ) );
if ( datacubes.length == count )
{
if ( currentData == null )
{
cmbDataItems.select( 0 );
}
else
{
cmbDataItems.setText( currentData );
}
return;
}
// select the newly created data cube for user.
currentData = datacubes[datacubes.length - 1];
getDataServiceProvider( ).setDataCube( currentData );
cmbDataItems.setText( currentData );
updateDragDataSource( );
setEnabledForButtons( );
// Update preview via event
DataDefinitionTextManager.getInstance( )
.refreshAll( );
fireEvent( tablePreview, EVENT_PREVIEW );
break;
}
updatePredefinedQueries( );
// autoSelect( true );
}
else if ( event.widget == btnShowDataPreviewA
|| event.widget == btnShowDataPreviewB )
{
Button w = (Button) event.widget;
getContext( ).setShowingDataPreview( Boolean.valueOf( w.getSelection( ) ) );
updateDragDataSource( );
}
checkColBindingForCube( );
ChartWizard.removeException( ChartWizard.StaChartDSh_switch_ID );
}
catch ( ChartException e1 )
{
ChartWizard.showException( ChartWizard.StaChartDSh_switch_ID,
e1.getLocalizedMessage( ) );
}
}
}
/**
* This method clears the flag of category grouping and optional Y grouping.
*/
private void clearGrouping( )
{
SeriesDefinition sd = ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) )
.get( 0 );
if ( sd.getGrouping( ) != null && sd.getGrouping( ).isEnabled( ) )
sd.getGrouping( ).unsetEnabled( );
for ( SeriesDefinition s : ChartUIUtil.getAllOrthogonalSeriesDefinitions( getChartModel( ) ) )
{
if ( s.getQuery( ) != null
&& s.getQuery( ).getGrouping( ) != null
&& s.getQuery( ).getGrouping( ).isEnabled( ) )
s.getQuery( ).getGrouping( ).unsetEnabled( );
}
}
private void autoSelect( boolean force )
{
if ( dataProvider.checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY )
&& !dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
// if only one item,select it for user
Query query = ChartUIUtil.getAllOrthogonalSeriesDefinitions( getContext( ).getModel( ) )
.get( 0 )
.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
Object[] valueExprs = getContext( ).getPredefinedQuery( ChartUIConstants.QUERY_VALUE );
if ( ( force || query.getDefinition( ) == null || query.getDefinition( )
.trim( )
.length( ) == 0 )
&& valueExprs != null
&& valueExprs.length == 1 )
{
boolean isCube = true;
IExpressionDescriptor desc = ExpressionDescriptor.getInstance( valueExprs[0],
isCube );
if ( desc != null )
{
String expr = desc.getExpression( );
query.setDefinition( expr );
if ( dataProvider.update( ChartUIConstants.QUERY_VALUE,
expr ) )
{
Event e = new Event( );
e.type = IChartDataSheet.EVENT_QUERY;
this.notifyListeners( e );
}
if ( force )
{
fireEvent( tablePreview, EVENT_PREVIEW );
}
}
}
}
}
private void selectDataSet( )
{
String currentDS = getDataServiceProvider( ).getDataSet( );
if ( currentDS == null )
{
cmbDataItems.select( 0 );
currentData = null;
}
else
{
cmbDataItems.setText( currentDS );
currentData = currentDS;
}
}
private void refreshTablePreview( )
{
if ( dataProvider.getDataSetFromHandle( ) == null )
{
return;
}
tablePreview.clearContents( );
switchDataTable( );
tablePreview.layout( );
}
private void switchDataSet( ) throws ChartException
{
if ( isCubeMode( ) )
{
return;
}
try
{
// Clear old dataset and preview data
tablePreview.clearContents( );
tableViewerColumns.setInput( null );
tablePreview.createDummyTable( );
tablePreview.layout( );
}
catch ( Throwable t )
{
throw new ChartException( ChartEnginePlugin.ID,
ChartException.DATA_BINDING,
t );
}
DataDefinitionTextManager.getInstance( ).refreshAll( );
// Update preview via event
fireEvent( tablePreview, EVENT_PREVIEW );
}
/**
* Update column headers and data to table.
*
* @param headers
* @param dataList
*/
private void updateTablePreview( final ColumnBindingInfo[] headers,
final List<?> dataList )
{
fireEvent( tablePreview, EVENT_QUERY );
if ( tablePreview.isDisposed( ) )
{
return;
}
if ( headers == null || headers.length == 0 )
{
tablePreview.setEnabled( false );
tablePreview.createDummyTable( );
}
else
{
tablePreview.setEnabled( true );
tablePreview.setColumns( headers );
refreshTableColor( );
// Add data value
if ( dataList != null )
{
for ( Iterator<?> iterator = dataList.iterator( ); iterator.hasNext( ); )
{
String[] dataRow = (String[]) iterator.next( );
for ( int i = 0; i < dataRow.length; i++ )
{
tablePreview.addEntry( dataRow[i], i );
}
}
}
}
tablePreview.layout( );
// Make the selected column visible and active.
int index = tableViewerColumns.getTable( ).getSelectionIndex( );
if ( index >= 0 )
{
tablePreview.moveTo( index );
}
}
private synchronized List<?> getPreviewData( ) throws ChartException
{
return getDataServiceProvider( ).getPreviewData( );
}
private void switchDataTable( )
{
if ( isCubeMode( ) )
{
return;
}
refreshDataPreview( );
}
private void refreshTableColor( )
{
if ( isCubeMode( ) )
{
return;
}
// Reset column color
if ( getContext( ).isShowingDataPreview( ) )
{
for ( int i = 0; i < tablePreview.getColumnNumber( ); i++ )
{
tablePreview.setColumnColor( i, ColorPalette.getInstance( )
.getColor( tablePreview.getColumnHeading( i ) ) );
}
}
else
{
updateColumnsTableViewerColor( );
}
}
private static Collection<TreeItem> getAllItems( TreeItem[] items )
{
List<TreeItem> list = new LinkedList<TreeItem>( );
for ( TreeItem item : items )
{
list.add( item );
list.addAll( getAllItems( item.getItems( ) ) );
}
return list;
}
private static Collection<TreeItem> getAllItems( Tree tree )
{
if ( tree == null )
{
return Collections.emptyList( );
}
List<TreeItem> list = new LinkedList<TreeItem>( );
list.addAll( getAllItems( tree.getItems( ) ) );
return list;
}
private void refreshTreeViewColor( )
{
if ( cubeTreeViewer == null )
{
return;
}
Collection<TreeItem> items = getAllItems( cubeTreeViewer.getTree( ) );
for ( TreeItem item : items )
{
String key = getBindingNameFrom( item );
Color color = ColorPalette.getInstance( ).getColor( key );
item.setBackground( color );
}
cubeTreeViewer.refresh( );
}
private void updateColumnsTableViewerColor( )
{
for ( TableItem item : tableViewerColumns.getTable( ).getItems( ) )
{
ColumnBindingInfo cbi = (ColumnBindingInfo) item.getData( );
Color c = ColorPalette.getInstance( ).getColor( cbi.getName( ) );
if ( c == null )
{
c = Display.getDefault( )
.getSystemColor( SWT.COLOR_LIST_BACKGROUND );
}
item.setBackground( c );
}
}
/**
* Returns actual expression for common and sharing query case.
*
* @param query
* @param expr
* @return
*/
private String getActualExpression( String expr )
{
if ( !dataProvider.checkState( IDataServiceProvider.SHARE_QUERY ) )
{
return expr;
}
// Convert to actual expression.
Object obj = getCurrentColumnHeadObject( );
if ( obj instanceof ColumnBindingInfo )
{
ColumnBindingInfo cbi = (ColumnBindingInfo) obj;
int type = cbi.getColumnType( );
if ( type == ColumnBindingInfo.GROUP_COLUMN
|| type == ColumnBindingInfo.AGGREGATE_COLUMN )
{
return cbi.getExpression( );
}
}
return expr;
}
protected void manageColorAndQuery( Query query, String expr )
{
// If it's not used any more, remove color binding
if ( DataDefinitionTextManager.getInstance( )
.getNumberOfSameDataDefinition( query.getDefinition( ) ) == 1 )
{
ColorPalette.getInstance( ).retrieveColor( query.getDefinition( ) );
}
// Update query, if it is sharing binding case, the specified expression
// will be converted and set to query, else directly set specified
// expression to query.
// DataDefinitionTextManager.getInstance( ).updateQuery( query, expr );
query.setDefinition( getActualExpression( expr ) );
// Refresh all data definition text
DataDefinitionTextManager.getInstance( ).refreshAll( );
// Reset table column color
refreshTableColor( );
refreshTreeViewColor( );
}
/**
* To refresh all color and text
*/
protected void updateColorAndText( )
{
// Refresh all data definition text
DataDefinitionTextManager.getInstance( ).refreshAll( );
// Reset table column color
refreshTableColor( );
refreshTreeViewColor( );
}
private class CategoryXAxisAction extends Action
{
private final IExpressionButton eb;
private final String bindingName;
CategoryXAxisAction( String bindingName )
{
super( getBaseSeriesTitle( getChartModel( ) ) );
SeriesDefinition seriesDefintion = ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) )
.get( 0 );
Query query = seriesDefintion.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
this.bindingName = bindingName;
this.eb = DataDefinitionTextManager.getInstance( )
.findExpressionButton( query );
if ( eb != null )
{
exprCodec.setType( eb.getExpressionType( ) );
exprCodec.setBindingName( bindingName, eb.isCube( ) );
}
setEnabled( eb != null
&& DataDefinitionTextManager.getInstance( )
.isAcceptableExpression( query,
exprCodec.getExpression( ),
dataProvider.isSharedBinding( )
|| dataProvider.isInheritColumnsGroups( ) ) );
}
@Override
public void run( )
{
if ( eb != null )
{
eb.setBindingName( bindingName, true );
}
}
}
private class GroupYSeriesAction extends Action
{
private final IExpressionButton eb;
private final String bindingName;
private final String expr;
GroupYSeriesAction( Query query, String bindingName,
SeriesDefinition seriesDefinition )
{
super( getGroupSeriesTitle( getChartModel( ) ) );
this.bindingName = bindingName;
this.eb = DataDefinitionTextManager.getInstance( )
.findExpressionButton( query );
if ( eb != null )
{
exprCodec.setType( eb.getExpressionType( ) );
exprCodec.setBindingName( bindingName, eb.isCube( ) );
this.expr = exprCodec.getExpression( );
}
else
{
this.expr = null;
}
boolean enabled = eb != null
&& DataDefinitionTextManager.getInstance( )
.isAcceptableExpression( query,
expr,
dataProvider.isSharedBinding( )
|| dataProvider.isInheritColumnsGroups( ) );
setEnabled( enabled );
}
@Override
public void run( )
{
// Use the first group, and copy to the all groups
ChartAdapter.beginIgnoreNotifications( );
ChartUIUtil.setAllGroupingQueryExceptFirst( getChartModel( ), expr );
ChartAdapter.endIgnoreNotifications( );
if ( eb != null )
{
eb.setBindingName( bindingName, true );
}
}
}
private class ValueYSeriesAction extends Action
{
private final Query query;
private final IExpressionButton eb;
private final String bindingName;
ValueYSeriesAction( Query query, String bindingName )
{
super( getOrthogonalSeriesTitle( getChartModel( ) ) );
this.bindingName = bindingName;
this.eb = DataDefinitionTextManager.getInstance( )
.findExpressionButton( query );
this.query = query;
// Grouping expressions can't be set on value series.
boolean enabled = true;
if ( dataProvider.isSharedBinding( )
|| dataProvider.isInheritColumnsGroups( ) )
{
Object obj = getCurrentColumnHeadObject( );
if ( obj instanceof ColumnBindingInfo
&& ( (ColumnBindingInfo) obj ).getColumnType( ) == ColumnBindingInfo.GROUP_COLUMN )
{
enabled = false;
}
}
setEnabled( enabled );
}
@Override
public void run( )
{
if ( eb != null )
{
eb.setBindingName( bindingName, true );
}
else
{
exprCodec.setBindingName( bindingName, isCubeMode( ) );
query.setDefinition( exprCodec.encode( ) );
ColorPalette.getInstance( ).putColor( bindingName );
updateColorAndText( );
}
}
}
Object getCurrentColumnHeadObject( )
{
if ( getContext( ).isShowingDataPreview( ) )
{
return tablePreview.getCurrentColumnHeadObject( );
}
int index = tableViewerColumns.getTable( ).getSelectionIndex( );
if ( index < 0 )
return null;
return tableViewerColumns.getTable( ).getItem( index ).getData( );
}
static class HeaderShowAction extends Action
{
HeaderShowAction( String header )
{
super( header );
setEnabled( false );
}
}
ExtendedItemHandle getItemHandle( )
{
return this.itemHandle;
}
ReportDataServiceProvider getDataServiceProvider( )
{
return this.dataProvider;
}
protected List<Object> getActionsForTableHead( String expr )
{
List<Object> actions = new ArrayList<Object>( 3 );
actions.add( getBaseSeriesMenu( getChartModel( ), expr ) );
actions.add( getOrthogonalSeriesMenu( getChartModel( ), expr ) );
actions.add( getGroupSeriesMenu( getChartModel( ), expr ) );
return actions;
}
protected Object getMenuForMeasure( Chart chart, String expr )
{
return getOrthogonalSeriesMenu( getChartModel( ), expr );
}
protected Object getMenuForDimension( Chart chart, String expr )
{
List<Object> menus = new ArrayList<Object>( 2 );
// bug#220724
if ( ( (Boolean) dataProvider.checkData( ChartUIConstants.QUERY_CATEGORY,
expr ) ).booleanValue( ) )
{
menus.add( getBaseSeriesMenu( getChartModel( ), expr ) );
}
if ( dataProvider.checkState( IDataServiceProvider.MULTI_CUBE_DIMENSIONS )
&& ( (Boolean) dataProvider.checkData( ChartUIConstants.QUERY_OPTIONAL,
expr ) ).booleanValue( ) )
{
menus.add( getGroupSeriesMenu( getChartModel( ), expr ) );
}
return menus;
}
private MenuManager createMenuManager( final Object data )
{
MenuManager menuManager = new MenuManager( );
menuManager.setRemoveAllWhenShown( true );
menuManager.addMenuListener( new IMenuListener( ) {
public void menuAboutToShow( IMenuManager manager )
{
if ( data instanceof ColumnBindingInfo )
{
// Menu for columns table.
addMenu( manager,
new HeaderShowAction( ( (ColumnBindingInfo) data ).getName( ) ) );
// String expr = ExpressionUtil.createJSRowExpression(
// ((ColumnBindingInfo)data).getName( ) );
List<Object> actions = getActionsForTableHead( ( (ColumnBindingInfo) data ).getName( ) );
for ( Object act : actions )
{
addMenu( manager, act );
}
}
else if ( data instanceof Integer )
{
// Menu for table
addMenu( manager,
new HeaderShowAction( tablePreview.getCurrentColumnHeading( ) ) );
String expr = tablePreview.getCurrentColumnHeading( );
List<Object> actions = getActionsForTableHead( expr );
for ( Object act : actions )
{
addMenu( manager, act );
}
}
else if ( data instanceof MeasureHandle )
{
// Menu for Measure
String expr = createCubeExpression( );
if ( expr != null )
{
addMenu( manager,
getMenuForMeasure( getChartModel( ), expr ) );
}
}
else if ( data instanceof LevelHandle )
{
// Menu for Level
String expr = createCubeExpression( );
if ( expr != null )
{
addMenu( manager,
getMenuForDimension( getChartModel( ), expr ) );
}
}
else if ( data instanceof LevelAttributeHandle )
{
// Menu for LevelAttribute
String expr = createCubeExpression( );
if ( expr != null )
{
addMenu( manager,
getMenuForDimension( getChartModel( ), expr ) );
}
}
}
private void addMenu( IMenuManager manager, Object item )
{
if ( item instanceof IAction )
{
manager.add( (IAction) item );
}
else if ( item instanceof IContributionItem )
{
manager.add( (IContributionItem) item );
}
else if ( item instanceof List<?> )
{
for ( Object o : (List<?>) item )
{
addMenu( manager, o );
}
}
// Do not allow customized query in xtab
if ( getDataServiceProvider( ).isPartChart( ) )
{
if ( item instanceof IAction )
{
( (IAction) item ).setEnabled( false );
}
}
}
} );
return menuManager;
}
protected Object getBaseSeriesMenu( Chart chart, String expr )
{
EList<SeriesDefinition> sds = ChartUIUtil.getBaseSeriesDefinitions( chart );
if ( sds.size( ) == 1 )
{
return new CategoryXAxisAction( expr );
}
return null;
}
protected Object getGroupSeriesMenu( Chart chart, String expr )
{
IMenuManager topManager = new MenuManager( getGroupSeriesTitle( getChartModel( ) ) );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chart );
for ( int axisIndex = 0; axisIndex < axisNum; axisIndex++ )
{
List<SeriesDefinition> sds = ChartUIUtil.getOrthogonalSeriesDefinitions( chart,
axisIndex );
if ( !sds.isEmpty( ) )
{
SeriesDefinition sd = sds.get( 0 );
IAction action = new GroupYSeriesAction( sd.getQuery( ),
expr,
sd );
// ONLY USE FIRST GROUPING SERIES FOR CHART ENGINE SUPPORT
// if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simply cascade menu
return action;
}
// action.setText( getSecondMenuText( axisIndex,
// sd.getDesignTimeSeries( ) ) );
// topManager.add( action );
}
}
return topManager;
}
protected Object getOrthogonalSeriesMenu( Chart chart, String expr )
{
IMenuManager topManager = new MenuManager( getOrthogonalSeriesTitle( getChartModel( ) ) );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chart );
for ( int axisIndex = 0; axisIndex < axisNum; axisIndex++ )
{
List<SeriesDefinition> sds = ChartUIUtil.getOrthogonalSeriesDefinitions( chart,
axisIndex );
for ( int i = 0; i < sds.size( ); i++ )
{
Series series = sds.get( i ).getDesignTimeSeries( );
EList<Query> dataDefns = series.getDataDefinition( );
if ( series instanceof StockSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getStockTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof BubbleSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getBubbleTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof DifferenceSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getDifferenceTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof GanttSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getGanttTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else
{
IAction action = new ValueYSeriesAction( dataDefns.get( 0 ),
expr );
if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simplify cascade menu
return action;
}
action.setText( getSecondMenuText( axisIndex, i, series ) );
topManager.add( action );
}
}
}
return topManager;
}
private String getSecondMenuText( int axisIndex, int seriesIndex,
Series series )
{
StringBuffer sb = new StringBuffer( );
if ( ChartUIUtil.getOrthogonalAxisNumber( getChartModel( ) ) > 1 )
{
sb.append( Messages.getString( "StandardChartDataSheet.Label.Axis" ) ); //$NON-NLS-1$
sb.append( axisIndex + 1 );
sb.append( " - " ); //$NON-NLS-1$
}
sb.append( Messages.getString( "StandardChartDataSheet.Label.Series" ) //$NON-NLS-1$
+ ( seriesIndex + 1 )
+ " (" + series.getDisplayName( ) + ")" ); //$NON-NLS-1$ //$NON-NLS-2$
return sb.toString( );
}
private String getBaseSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.UseAsCategoryXAxis" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.UseAsCategorySeries" ); //$NON-NLS-1$
}
private String getOrthogonalSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.PlotAsValueYSeries" ); //$NON-NLS-1$
}
else if ( chart instanceof DialChart )
{
return Messages.getString( "StandardChartDataSheet.Label.PlotAsGaugeValue" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.PlotAsValueSeries" ); //$NON-NLS-1$
}
private String getGroupSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.UseToGroupYSeries" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.UseToGroupValueSeries" ); //$NON-NLS-1$
}
private boolean isCubeMode( )
{
boolean bCube = ChartCubeUtil.getBindingCube( itemHandle ) != null;
if ( bCube )
{
// If current item doesn't support cube, referenced cube should be
// invalid.
return isDataItemSupported( SELECT_DATA_CUBE );
}
return false;
}
private CubeHandle getCube( )
{
return ChartCubeUtil.getBindingCube( itemHandle );
}
private String getBindingNameFrom( ReportElementHandle handle )
{
String expr = null;
ComputedColumnHandle binding = null;
if ( handle instanceof LevelHandle )
{
LevelHandle level = (LevelHandle) handle;
String dimensionName = level.getContainer( )
.getContainer( )
.getName( );
binding = ChartCubeUtil.findLevelBinding( itemHandle,
dimensionName,
level.getName( ) );
}
else if ( handle instanceof MeasureHandle )
{
MeasureHandle measure = (MeasureHandle) handle;
binding = ChartCubeUtil.findMeasureBinding( itemHandle,
measure.getName( ) );
}
if ( binding != null )
{
expr = binding.getName( );
}
return expr;
}
private String getBindingNameFrom( TreeItem treeItem )
{
Object selection = getHandleFromSelection( treeItem.getData( ) );
if ( selection instanceof ReportElementHandle )
{
return getBindingNameFrom( (ReportElementHandle) selection );
}
else if ( selection instanceof LevelAttributeHandle )
{
LevelAttributeHandle la = (LevelAttributeHandle) selection;
LevelHandle level = (LevelHandle) ( (Level) la.getContext( )
.getValueContainer( ) ).getHandle( la.getModule( ) );
String dimensionName = level.getContainer( )
.getContainer( )
.getName( );
ComputedColumnHandle binding = ChartCubeUtil.findLevelAttrBinding( itemHandle,
dimensionName,
level.getName( ),
la.getName( ) );
if ( binding != null )
{
return binding.getName( );
}
}
return null;
}
protected Object getHandleFromSelection( Object selection )
{
if ( selection instanceof LevelHandle
|| selection instanceof MeasureHandle
|| selection instanceof LevelAttributeHandle )
{
return selection;
}
return null;
}
/**
* This method returns a cube expression that is draggable.
*
* @return
*/
protected String getDraggableCubeExpression( )
{
return createCubeExpression( );
}
/**
* Creates the cube expression
*
* @return expression
*/
protected String createCubeExpression( )
{
if ( cubeTreeViewer == null )
{
return null;
}
TreeItem[] selection = cubeTreeViewer.getTree( ).getSelection( );
String expr = null;
if ( selection.length > 0
&& !dataProvider.isSharedBinding( )
&& !dataProvider.isPartChart( ) )
{
TreeItem treeItem = selection[0];
expr = getBindingNameFrom( treeItem );
}
return expr;
}
private boolean isDataItemSupported( int type )
{
return iSupportedDataItems == 0
|| ( iSupportedDataItems & type ) == type;
}
private String[] createDataComboItems( )
{
List<String> items = new ArrayList<String>( );
selectDataTypes.clear( );
if ( isDataItemSupported( SELECT_NONE ) )
{
if ( DEUtil.getDataSetList( itemHandle.getContainer( ) ).size( ) > 0 )
{
items.add( Messages.getString( "ReportDataServiceProvider.Option.Inherits", //$NON-NLS-1$
( (DataSetHandle) DEUtil.getDataSetList( itemHandle.getContainer( ) )
.get( 0 ) ).getName( ) ) );
}
else
{
items.add( ReportDataServiceProvider.OPTION_NONE );
}
selectDataTypes.add( Integer.valueOf( SELECT_NONE ) );
}
if ( isDataItemSupported( SELECT_DATA_SET ) )
{
String[] dataSets = getDataServiceProvider( ).getAllDataSets( );
if ( dataSets.length > 0 )
{
if ( isDataItemSupported( SELECT_NEXT ) )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.DataSets" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEXT ) );
}
for ( int i = 0; i < dataSets.length; i++ )
{
items.add( dataSets[i] );
selectDataTypes.add( Integer.valueOf( SELECT_DATA_SET ) );
}
}
if ( isDataItemSupported( SELECT_NEW_DATASET ) )
{
items.add( Messages.getString( "StandardChartDataSheet.NewDataSet" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEW_DATASET ) );
}
}
if ( isDataItemSupported( SELECT_DATA_CUBE ) )
{
String[] dataCubes = getDataServiceProvider( ).getAllDataCubes( );
if ( dataCubes.length > 0 )
{
if ( isDataItemSupported( SELECT_NEXT ) )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.DataCubes" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEXT ) );
}
for ( int i = 0; i < dataCubes.length; i++ )
{
items.add( dataCubes[i] );
selectDataTypes.add( Integer.valueOf( SELECT_DATA_CUBE ) );
}
}
if ( isDataItemSupported( SELECT_NEW_DATACUBE ) )
{
items.add( Messages.getString( "StandardChartDataSheet.NewDataCube" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEW_DATACUBE ) );
}
}
if ( isDataItemSupported( SELECT_REPORT_ITEM ) )
{
String[] dataRefs = getDataServiceProvider( ).getAllReportItemReferences( );
if ( dataRefs.length > 0 )
{
int curSize = items.size( );
if ( isDataItemSupported( SELECT_NEXT ) )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.ReportItems" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEXT ) );
}
for ( int i = 0; i < dataRefs.length; i++ )
{
// if cube is not supported, do not list the report item
// consuming a cube
if ( !isDataItemSupported( SELECT_DATA_CUBE ) )
{
if ( ( (ReportItemHandle) getDataServiceProvider( ).getReportDesignHandle( )
.findElement( dataRefs[i] ) ).getCube( ) != null )
{
continue;
}
}
items.add( dataRefs[i] );
selectDataTypes.add( Integer.valueOf( SELECT_REPORT_ITEM ) );
}
// didn't add any reportitem reference
if ( items.size( ) == curSize + 1 )
{
items.remove( curSize );
selectDataTypes.remove( curSize );
}
}
}
return items.toArray( new String[items.size( )] );
}
@SuppressWarnings("unchecked")
protected void updatePredefinedQueriesForInheritXTab( )
{
// Get all column bindings.
List<String> dimensionExprs = new ArrayList<String>( );
List<String> measureExprs = new ArrayList<String>( );
ReportItemHandle reportItemHandle = dataProvider.getReportItemHandle( );
for ( Iterator<ComputedColumnHandle> iter = reportItemHandle.getColumnBindings( )
.iterator( ); iter.hasNext( ); )
{
ComputedColumnHandle cch = iter.next( );
ChartItemUtil.loadExpression( exprCodec, cch );
if ( exprCodec.isDimensionExpresion( ) )
{
dimensionExprs.add( cch.getName( ) );
}
else if ( exprCodec.isMeasureExpresion( ) )
{
measureExprs.add( cch.getName( ) );
}
}
String[] valueExprs = measureExprs.toArray( new String[measureExprs.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY, null );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL, null );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
valueExprs );
}
@SuppressWarnings("unchecked")
protected void updatePredefinedQueriesForSharingCube( )
{
// Get all column bindings.
List<String> dimensionExprs = new ArrayList<String>( );
List<String> measureExprs = new ArrayList<String>( );
ReportItemHandle reportItemHandle = dataProvider.getReportItemHandle( );
for ( Iterator<ComputedColumnHandle> iter = reportItemHandle.getColumnBindings( )
.iterator( ); iter.hasNext( ); )
{
ComputedColumnHandle cch = iter.next( );
// String dataExpr = ExpressionUtil.createJSDataExpression(
// cch.getName( ) );
ChartItemUtil.loadExpression( exprCodec, cch );
if ( exprCodec.isDimensionExpresion( ) )
{
dimensionExprs.add( cch.getName( ) );
}
else if ( exprCodec.isMeasureExpresion( ) )
{
// Fixed issue ED 28.
// Underlying code was reverted to the earlier than
// bugzilla 246683, since we have enhanced it to
// support all available measures defined in shared
// item.
// Bugzilla 246683.
// Here if it is sharing with crosstab or
// multi-view, we just put the measure expression
// whose aggregate-ons is most into prepared
// expression query. It will keep correct value to
// shared crosstab or multi-view.
measureExprs.add( cch.getName( ) );
}
else if ( exprCodec.isCubeBinding( true ) )
{
// Just it is under multiple view case, we add those computed measure bindings.
String dataType = cch.getDataType( );
if ( org.eclipse.birt.report.model.api.elements.DesignChoiceConstants.COLUMN_DATA_TYPE_DECIMAL.equals( dataType )
|| org.eclipse.birt.report.model.api.elements.DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT.equals( dataType )
|| org.eclipse.birt.report.model.api.elements.DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER.equals( dataType ) )
{
// It is computed measure binding.
measureExprs.add( cch.getName( ) );
}
}
}
String[] categoryExprs = dimensionExprs.toArray( new String[dimensionExprs.size( )] );
String[] yOptionalExprs = categoryExprs;
String[] valueExprs = measureExprs.toArray( new String[measureExprs.size( )] );
ReportItemHandle referenceHandle = ChartItemUtil.getReportItemReference( itemHandle );
ReportDataServiceProvider rdsp = this.getDataServiceProvider( );
if ( referenceHandle instanceof ExtendedItemHandle
&& rdsp.isChartReportItemHandle( referenceHandle ) )
{
// If the final reference handle is cube with other
// chart, the valid category and Y optional expressions
// only allow those expressions defined in shared chart.
Object referenceCM = ChartItemUtil.getChartFromHandle( (ExtendedItemHandle) referenceHandle );
categoryExprs = rdsp.getSeriesExpressionsFrom( referenceCM,
ChartUIConstants.QUERY_CATEGORY );
yOptionalExprs = rdsp.getSeriesExpressionsFrom( referenceCM,
ChartUIConstants.QUERY_OPTIONAL );
valueExprs = rdsp.getSeriesExpressionsFrom( referenceCM,
ChartUIConstants.QUERY_VALUE );
Chart cm = this.getContext( ).getModel( );
if ( categoryExprs.length > 0 )
{
updateCategoryExpression( cm, categoryExprs[0] );
}
if ( yOptionalExprs.length > 0 )
{
updateYOptionalExpressions( cm, yOptionalExprs[0] );
}
}
else if ( dataProvider.checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY ) )
{
// In sharing query with crosstab, the category
// expression and Y optional expression is decided by
// value series expression, so here set them to null.
// And in UI, when the value series expression is
// selected, it will trigger to set correct category and
// Y optional expressions.
categoryExprs = null;
yOptionalExprs = null;
}
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
categoryExprs );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
yOptionalExprs );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
valueExprs );
}
private void updatePredefinedQueries( )
{
if ( dataProvider.isInXTabMeasureCell( ) )
{
try
{
CrosstabReportItemHandle xtab = ChartCubeUtil.getXtabContainerCell( itemHandle )
.getCrosstab( );
if ( dataProvider.isPartChart( ) )
{
List<String> levels = ChartCubeUtil.getAllLevelsBindingName( xtab );
String[] exprs = levels.toArray( new String[levels.size( )] );
if ( exprs.length == 2 && dataProvider.isInXTabAggrCell( ) )
{
// Only one direction is valid for chart in total cell
if ( ( (ChartWithAxes) getChartModel( ) ).isTransposed( ) )
{
exprs = new String[]{
exprs[1]
};
}
else
{
exprs = new String[]{
exprs[0]
};
}
}
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
exprs );
}
else
{
Iterator<ComputedColumnHandle> columnBindings = ChartItemUtil.getAllColumnBindingsIterator( itemHandle );
List<String> levels = ChartCubeUtil.getAllLevelsBindingName( columnBindings );
String[] exprs = levels.toArray( new String[levels.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
exprs );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
exprs );
columnBindings = ChartItemUtil.getAllColumnBindingsIterator( itemHandle );
List<String> measures = ChartCubeUtil.getAllMeasuresBindingName( columnBindings );
exprs = measures.toArray( new String[measures.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
exprs );
}
}
catch ( BirtException e )
{
WizardBase.displayException( e );
}
}
else
{
if ( getCube( ) == null )
{
try
{
ColumnBindingInfo[] headers = dataProvider.getPreviewHeadersInfo( );
getDataServiceProvider( ).setPredefinedExpressions( headers );
}
catch ( ChartException e )
{
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
null );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
null );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
null );
}
}
else if ( isDataItemSupported( SELECT_DATA_CUBE ) )
{
if ( dataProvider.isInheritanceOnly( )
|| dataProvider.isSharedBinding( ) )
{
updatePredefinedQueriesForSharingCube( );
}
else if ( dataProvider.isInXTabNonAggrCell( )
&& dataProvider.isInheritCube( ) )
{
updatePredefinedQueriesForInheritXTab( );
}
// TODO do we need to handle xtab inheritance case? currently we
// just inherit the cube from xtab essentially
// else if ( ChartXTabUIUtil.isInheritXTabCell( itemHandle ) )
// // Chart in xtab cell and inherits its cube
// List<String> measureExprs = new ArrayList<String>( );
// for ( Iterator<ComputedColumnHandle> iter =
// ChartReportItemUtil.getBindingHolder( itemHandle )
// .getColumnBindings( )
// .iterator( ); iter.hasNext( ); )
// ComputedColumnHandle cch = iter.next( );
// if ( ChartCubeUtil.isMeasureExpresion( cch.getExpression( ) )
// measureExprs.add( ExpressionUtil.createJSDataExpression(
// cch.getName( ) ) );
// String[] valueExprs = measureExprs.toArray( new
// String[measureExprs.size( )] );
// getContext( ).addPredefinedQuery(
// ChartUIConstants.QUERY_CATEGORY,
// null );
// getContext( ).addPredefinedQuery(
// ChartUIConstants.QUERY_OPTIONAL,
// null );
// getContext( ).addPredefinedQuery(
// ChartUIConstants.QUERY_VALUE,
// valueExprs );
else
{
// Updates cube bindings before updating available bindings
// for chart.
getDataServiceProvider( ).update( ChartUIConstants.UPDATE_CUBE_BINDINGS,
null );
Iterator<ComputedColumnHandle> columnBindings = ChartItemUtil.getAllColumnBindingsIterator( itemHandle );
List<String> levels = ChartCubeUtil.getAllLevelsBindingName( columnBindings );
String[] exprs = levels.toArray( new String[levels.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
exprs );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
exprs );
columnBindings = ChartItemUtil.getAllColumnBindingsIterator( itemHandle );
List<String> measures = ChartCubeUtil.getAllMeasuresBindingName( columnBindings );
exprs = measures.toArray( new String[measures.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
exprs );
}
}
}
// Fire event to update predefined queries in outside UI
fireEvent( btnBinding, EVENT_QUERY );
}
/**
* Update Y Optional expression with specified expression if current Y
* optional expression is null or empty.
*
* @param cm
* chart model.
* @param expr
* specified expression.
*/
protected void updateYOptionalExpressions( Chart cm, String expr )
{
this.dataProvider.update( ChartUIConstants.QUERY_OPTIONAL, expr );
}
/**
* Update category expression with specified expression if current category
* expression is null or empty.
*
* @param cm
* chart model.
* @param expr
* specified expression.
*/
protected void updateCategoryExpression( Chart cm, String expr )
{
this.dataProvider.update( ChartUIConstants.QUERY_CATEGORY, expr );
}
@SuppressWarnings("unchecked")
private void checkColBindingForCube( )
{
if ( getCube( ) != null
&& !ChartCubeUtil.checkColumnbindingForCube( DEUtil.getBindingColumnIterator( DEUtil.getBindingHolder( itemHandle ) ) ) )
{
ChartWizard.showException( ChartWizard.StaChartDSh_checCube_ID,
Messages.getString( "StandardChartDataSheet.CheckCubeWarning" ) ); //$NON-NLS-1$
}
else
{
ChartWizard.removeException( ChartWizard.StaChartDSh_checCube_ID );
}
}
@Override
public ISelectDataCustomizeUI createCustomizeUI( ITask task )
{
return new SelectDataDynamicArea( task );
}
@Override
public List<String> getAllValueDefinitions( )
{
List<String> dataDefinitions = new ArrayList<String>( 2 );
for ( SeriesDefinition sd : ChartUIUtil.getAllOrthogonalSeriesDefinitions( getChartModel( ) ) )
{
for ( Query query : sd.getDesignTimeSeries( ).getDataDefinition( ) )
{
String name = exprCodec.getBindingName( query.getDefinition( ) );
if ( name != null )
{
dataDefinitions.add( name );
}
}
}
return dataDefinitions;
}
} |
package org.eclipse.birt.chart.reportitem.ui;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.DialChart;
import org.eclipse.birt.chart.model.attribute.DataType;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.data.SeriesGrouping;
import org.eclipse.birt.chart.model.data.impl.DataFactoryImpl;
import org.eclipse.birt.chart.model.data.impl.SeriesGroupingImpl;
import org.eclipse.birt.chart.model.type.BubbleSeries;
import org.eclipse.birt.chart.model.type.DifferenceSeries;
import org.eclipse.birt.chart.model.type.GanttSeries;
import org.eclipse.birt.chart.model.type.StockSeries;
import org.eclipse.birt.chart.plugin.ChartEnginePlugin;
import org.eclipse.birt.chart.reportitem.ChartReportItemUtil;
import org.eclipse.birt.chart.reportitem.ChartXTabUtil;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ChartColumnBindingDialog;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ExtendedItemFilterDialog;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ReportItemParametersDialog;
import org.eclipse.birt.chart.reportitem.ui.i18n.Messages;
import org.eclipse.birt.chart.reportitem.ui.views.attributes.provider.ChartCubeFilterHandleProvider;
import org.eclipse.birt.chart.reportitem.ui.views.attributes.provider.ChartFilterProviderDelegate;
import org.eclipse.birt.chart.ui.swt.ColorPalette;
import org.eclipse.birt.chart.ui.swt.ColumnBindingInfo;
import org.eclipse.birt.chart.ui.swt.CustomPreviewTable;
import org.eclipse.birt.chart.ui.swt.DataDefinitionTextManager;
import org.eclipse.birt.chart.ui.swt.DefaultChartDataSheet;
import org.eclipse.birt.chart.ui.swt.SimpleTextTransfer;
import org.eclipse.birt.chart.ui.swt.interfaces.IChartDataSheet;
import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider;
import org.eclipse.birt.chart.ui.swt.interfaces.ISelectDataComponent;
import org.eclipse.birt.chart.ui.swt.interfaces.ISelectDataCustomizeUI;
import org.eclipse.birt.chart.ui.swt.wizard.ChartAdapter;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizard;
import org.eclipse.birt.chart.ui.swt.wizard.data.SelectDataDynamicArea;
import org.eclipse.birt.chart.ui.util.ChartUIConstants;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.ui.util.UIHelper;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase;
import org.eclipse.birt.core.ui.frameworks.taskwizard.interfaces.ITask;
import org.eclipse.birt.report.designer.internal.ui.data.DataService;
import org.eclipse.birt.report.designer.internal.ui.views.ViewsTreeProvider;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.AbstractFilterHandleProvider;
import org.eclipse.birt.report.designer.ui.cubebuilder.action.NewCubeAction;
import org.eclipse.birt.report.designer.ui.dialogs.ColumnBindingDialog;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.metadata.IClassInfo;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.MeasureHandle;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
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.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
/**
* Data sheet implementation for Standard Chart
*/
public class StandardChartDataSheet extends DefaultChartDataSheet implements
Listener
{
private static final String KEY_PREVIEW_DATA = "Preview Data"; //$NON-NLS-1$
final private ExtendedItemHandle itemHandle;
final private ReportDataServiceProvider dataProvider;
private Button btnInherit = null;
private Button btnUseData = null;
private boolean bIsInheritSelected = true;
private CCombo cmbInherit = null;
private CCombo cmbDataItems = null;
private StackLayout stackLayout = null;
private Composite cmpStack = null;
private Composite cmpCubeTree = null;
private Composite cmpDataPreview = null;
private Composite cmpColumnsList = null;
private CustomPreviewTable tablePreview = null;
private TreeViewer cubeTreeViewer = null;
private Button btnFilters = null;
private Button btnParameters = null;
private Button btnBinding = null;
private String currentData = null;
private String previousData = null;
public static final int SELECT_NONE = 1;
public static final int SELECT_NEXT = 2;
public static final int SELECT_DATA_SET = 4;
public static final int SELECT_DATA_CUBE = 8;
public static final int SELECT_REPORT_ITEM = 16;
public static final int SELECT_NEW_DATASET = 32;
public static final int SELECT_NEW_DATACUBE = 64;
private final int iSupportedDataItems;
private List<Integer> selectDataTypes = new ArrayList<Integer>( );
private Button btnShowDataPreviewA;
private Button btnShowDataPreviewB;
private TableViewer tableViewerColumns;
private Label columnListDescription;
private Label dataPreviewDescription;
public StandardChartDataSheet( ExtendedItemHandle itemHandle,
ReportDataServiceProvider dataProvider, int iSupportedDataItems )
{
this.itemHandle = itemHandle;
this.dataProvider = dataProvider;
this.iSupportedDataItems = iSupportedDataItems;
addListener( this );
}
public StandardChartDataSheet( ExtendedItemHandle itemHandle,
ReportDataServiceProvider dataProvider )
{
this( itemHandle, dataProvider, 0 );
}
public Composite createActionButtons( Composite parent )
{
Composite composite = ChartUIUtil.createCompositeWrapper( parent );
{
composite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_END ) );
}
btnFilters = new Button( composite, SWT.NONE );
{
btnFilters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnFilters.setLayoutData( gridData );
btnFilters.setText( Messages.getString( "StandardChartDataSheet.Label.Filters" ) ); //$NON-NLS-1$
btnFilters.addListener( SWT.Selection, this );
}
btnParameters = new Button( composite, SWT.NONE );
{
btnParameters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnParameters.setLayoutData( gridData );
btnParameters.setText( Messages.getString( "StandardChartDataSheet.Label.Parameters" ) ); //$NON-NLS-1$
btnParameters.addListener( SWT.Selection, this );
}
btnBinding = new Button( composite, SWT.NONE );
{
btnBinding.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnBinding.setLayoutData( gridData );
btnBinding.setText( Messages.getString( "StandardChartDataSheet.Label.DataBinding" ) ); //$NON-NLS-1$
btnBinding.addListener( SWT.Selection, this );
}
setEnabledForButtons( );
return composite;
}
private void setEnabledForButtons( )
{
if ( isCubeMode( ) )
{
// getDataServiceProvider( ).checkState(
// IDataServiceProvider.SHARE_QUERY )
boolean disabled = getDataServiceProvider( ).isInXTabAggrCell( )
|| getDataServiceProvider( ).isInXTabMeasureCell( );
btnFilters.setEnabled( !disabled );
btnBinding.setEnabled( getDataServiceProvider( ).isInvokingSupported( )
|| getDataServiceProvider( ).isSharedBinding( ) );
btnParameters.setEnabled( false );
}
else
{
btnFilters.setEnabled( hasDataSet( ) );
// Bugzilla#177704 Chart inheriting data from container doesn't
// support parameters due to limitation in DtE
btnParameters.setEnabled( getDataServiceProvider( ).getBoundDataSet( ) != null
&& getDataServiceProvider( ).isInvokingSupported( ) );
btnBinding.setEnabled( hasDataSet( )
&& ( getDataServiceProvider( ).isInvokingSupported( ) || getDataServiceProvider( ).isSharedBinding( ) ) );
}
}
private boolean hasDataSet( )
{
return getDataServiceProvider( ).getReportDataSet( ) != null
|| getDataServiceProvider( ).getBoundDataSet( ) != null;
}
void fireEvent( Widget widget, int eventType )
{
Event event = new Event( );
event.data = this;
event.widget = widget;
event.type = eventType;
notifyListeners( event );
}
public Composite createDataDragSource( Composite parent )
{
cmpStack = new Composite( parent, SWT.NONE );
cmpStack.setLayoutData( new GridData( GridData.FILL_BOTH ) );
stackLayout = new StackLayout( );
stackLayout.marginHeight = 0;
stackLayout.marginWidth = 0;
cmpStack.setLayout( stackLayout );
cmpCubeTree = ChartUIUtil.createCompositeWrapper( cmpStack );
cmpDataPreview = ChartUIUtil.createCompositeWrapper( cmpStack );
createColumnsViewerArea( cmpStack );
Label label = new Label( cmpCubeTree, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.CubeTree" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
if ( !dataProvider.isInXTabMeasureCell( )
&& !dataProvider.isInMultiView( ) )
{
// No description if dnd is disabled
Label description = new Label( cmpCubeTree, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
description.setLayoutData( gd );
description.setText( Messages.getString( "StandardChartDataSheet.Label.DragCube" ) ); //$NON-NLS-1$
}
}
cubeTreeViewer = new TreeViewer( cmpCubeTree, SWT.SINGLE
| SWT.H_SCROLL
| SWT.V_SCROLL
| SWT.BORDER );
cubeTreeViewer.getTree( )
.setLayoutData( new GridData( GridData.FILL_BOTH ) );
( (GridData) cubeTreeViewer.getTree( ).getLayoutData( ) ).heightHint = 120;
ViewsTreeProvider provider = new ViewsTreeProvider( );
cubeTreeViewer.setLabelProvider( provider );
cubeTreeViewer.setContentProvider( provider );
cubeTreeViewer.setInput( getCube( ) );
final DragSource dragSource = new DragSource( cubeTreeViewer.getTree( ),
DND.DROP_COPY );
dragSource.setTransfer( new Transfer[]{
SimpleTextTransfer.getInstance( )
} );
dragSource.addDragListener( new DragSourceListener( ) {
private String text = null;
public void dragFinished( DragSourceEvent event )
{
// TODO Auto-generated method stub
}
public void dragSetData( DragSourceEvent event )
{
event.data = text;
}
public void dragStart( DragSourceEvent event )
{
text = createCubeExpression( );
if ( text == null )
{
event.doit = false;
}
}
} );
cubeTreeViewer.getTree( ).addListener( SWT.MouseDown, new Listener( ) {
public void handleEvent( Event event )
{
if ( event.button == 3 && event.widget instanceof Tree )
{
Tree tree = (Tree) event.widget;
TreeItem treeItem = tree.getSelection( )[0];
if ( treeItem.getData( ) instanceof LevelHandle
|| treeItem.getData( ) instanceof MeasureHandle )
{
if ( dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY ))
{
tree.setMenu( null );
}
else
{
tree.setMenu( createMenuManager( treeItem.getData( ) ).createContextMenu( tree ) );
// tree.getMenu( ).setVisible( true );
}
}
else
{
tree.setMenu( null );
}
}
}
} );
label = new Label( cmpDataPreview, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.DataPreview" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
if ( !dataProvider.isInXTabMeasureCell( )
&& !dataProvider.isInMultiView( ) )
{
dataPreviewDescription = new Label( cmpDataPreview, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
dataPreviewDescription.setLayoutData( gd );
dataPreviewDescription.setText( Messages.getString( "StandardChartDataSheet.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
}
}
btnShowDataPreviewA = new Button( cmpDataPreview, SWT.CHECK );
btnShowDataPreviewA.setText( Messages.getString("StandardChartDataSheet.Label.ShowDataPreview") ); //$NON-NLS-1$
btnShowDataPreviewA.addListener( SWT.Selection, this );
tablePreview = new CustomPreviewTable( cmpDataPreview, SWT.SINGLE
| SWT.H_SCROLL
| SWT.V_SCROLL
| SWT.FULL_SELECTION );
{
GridData gridData = new GridData( GridData.FILL_BOTH );
gridData.widthHint = 400;
gridData.heightHint = 120;
tablePreview.setLayoutData( gridData );
tablePreview.setHeaderAlignment( SWT.LEFT );
tablePreview.addListener( CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE,
this );
}
updateDragDataSource( );
return cmpStack;
}
private void createColumnsViewerArea( Composite parent )
{
cmpColumnsList = ChartUIUtil.createCompositeWrapper( parent );
Label label = new Label( cmpColumnsList, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.DataPreview" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
if ( !dataProvider.isInXTabMeasureCell( ) )
{
columnListDescription = new Label( cmpColumnsList, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
columnListDescription.setLayoutData( gd );
columnListDescription.setText( Messages.getString( "StandardChartDataSheet.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
}
}
btnShowDataPreviewB = new Button( cmpColumnsList, SWT.CHECK );
btnShowDataPreviewB.setText( Messages.getString("StandardChartDataSheet.Label.ShowDataPreview") ); //$NON-NLS-1$
btnShowDataPreviewB.addListener( SWT.Selection, this );
// Add a list to display all columns.
final Table table = new Table( cmpColumnsList, SWT.SINGLE
| SWT.BORDER
| SWT.H_SCROLL
| SWT.V_SCROLL
| SWT.FULL_SELECTION);
GridData gd = new GridData( GridData.FILL_BOTH );
table.setLayoutData( gd );
table.setLinesVisible( true );
tableViewerColumns = new TableViewer( table );
tableViewerColumns.setUseHashlookup( true );
new TableColumn( table, SWT.LEFT );
table.addMouseMoveListener( new MouseMoveListener() {
public void mouseMove( MouseEvent e )
{
if ( !dataProvider.isLivePreviewEnabled( ) )
{
table.setToolTipText( null );
return;
}
String tooltip = null;
TableItem item = ((Table)e.widget).getItem( new Point( e.x, e.y ) );
if ( item != null )
{
List<Object[]> data = (List<Object[]> ) tableViewerColumns.getData( KEY_PREVIEW_DATA );
if ( data != null )
{
StringBuilder sb = new StringBuilder( );
int index = ( (Table) e.widget ).indexOf( item );
int i = 0;
for ( ; i < data.size( ); i++ )
{
if ( sb.length( ) > 45 )
{
break;
}
if ( data.get( i )[index] != null )
{
if ( i != 0 )
sb.append( "; " ); //$NON-NLS-1$
sb.append( String.valueOf( data.get( i )[index] ) );
}
}
if ( i == 1 && sb.length( ) > 45 )
{
sb = new StringBuilder( sb.substring( 0, 45 ) );
sb.append( "..." );//$NON-NLS-1$
}
else if ( i < data.size( ) )
{
sb.append( ";..." ); //$NON-NLS-1$
}
tooltip = sb.toString( );
}
}
table.setToolTipText( tooltip );
}} );
table.addMouseListener( new MouseAdapter() {
public void mouseDown( MouseEvent e )
{
if ( e.button == 3 )
{
if ( isCubeMode( ) )
{
// share cube
table.setMenu( null );
}
else
{
TableItem item = ( (Table) e.widget ).getItem( new Point( e.x,
e.y ) );
if ( item == null )
{
tableViewerColumns.getTable( ).select( -1 );
}
// Bind context menu to each header button
boolean isSharingChart = dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY );
if ( item != null && !isSharingChart )
{
if ( table.getMenu( ) != null )
{
table.getMenu( ).dispose( );
}
table.setMenu( createMenuManager( item.getData( ) ).createContextMenu( table ) );
}
else
{
table.setMenu( null );
}
if ( table.getMenu( ) != null && !isSharingChart )
{
table.getMenu( ).setVisible( true );
}
}
}
}
} ) ;
table.addListener( SWT.Resize, new Listener( ) {
public void handleEvent( Event event )
{
Table table = (Table) event.widget;
int totalWidth = table.getClientArea( ).width;
table.getColumn( 0 ).setWidth( totalWidth );
}
} );
// Set drag/drop.
DragSource ds = new DragSource( table, DND.DROP_COPY | DND.DROP_MOVE);
ds.setTransfer( new Transfer[]{
SimpleTextTransfer.getInstance( )
} );
ColumnNamesTableDragListener dragSourceAdapter = new ColumnNamesTableDragListener( table,
itemHandle );
ds.addDragListener( dragSourceAdapter );
tableViewerColumns.setContentProvider( new IStructuredContentProvider() {
/**
* Gets the food items for the list
*
* @param arg0
* the data model
* @return Object[]
*/
public Object[] getElements(Object arg0) {
if ( arg0 == null )
return null;
return (ColumnBindingInfo[])arg0;
}
/**
* Disposes any created resources
*/
public void dispose() {
// Do nothing
}
/**
* 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) {
// Do nothing
}
} );
tableViewerColumns.setLabelProvider( new ILabelProvider() {
/**
* images
*
* @param arg0
* the element
* @return Image
*/
public Image getImage(Object arg0) {
String imageName = ((ColumnBindingInfo) arg0).getImageName( );
if ( imageName == null )
return null;
return UIHelper.getImage( imageName );
}
/**
* Gets the text for an element
*
* @param arg0
* the element
* @return String
*/
public String getText(Object arg0) {
return ((ColumnBindingInfo) arg0).getName();
}
/**
* Adds a listener
*
* @param arg0
* the listener
*/
public void addListener(ILabelProviderListener arg0) {
// Throw it away
}
/**
* Disposes any resources
*/
public void dispose() {
// Nothing to dispose
}
/**
* Returns whether changing the specified property for the specified element
* affect the label
*
* @param arg0
* the element
* @param arg1
* the property
* @return boolean
*/
public boolean isLabelProperty(Object arg0, String arg1) {
return false;
}
/**
* Removes a listener
*
* @param arg0
* the listener
*/
public void removeListener(ILabelProviderListener arg0) {
// Ignore
}
} );
}
private void updateDragDataSource( )
{
if ( dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{// hide the description if share chart
if ( columnListDescription != null )
{
( (GridData) columnListDescription.getLayoutData( ) ).exclude = true;
columnListDescription.setVisible( false );
cmpColumnsList.layout( );
}
if ( dataPreviewDescription != null )
{
( (GridData) dataPreviewDescription.getLayoutData( ) ).exclude = true;
dataPreviewDescription.setVisible( false );
cmpDataPreview.layout( );
}
}
if ( isCubeMode( ) )
{
if ( getDataServiceProvider( ).checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY ) )
{// share cube
if ( !getDataServiceProvider( ).checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
( (GridData) columnListDescription.getLayoutData( ) ).exclude = false;
columnListDescription.setVisible( true );
columnListDescription.setText( Messages.getString("StandardChartDataSheet.Label.ShareCrossTab") ); //$NON-NLS-1$
cmpColumnsList.layout( );
}
getContext( ).setShowingDataPreview( Boolean.FALSE );
btnShowDataPreviewB.setSelection( false );
btnShowDataPreviewB.setEnabled( false );
stackLayout.topControl = cmpColumnsList;
refreshDataPreviewPane( );
}
else
{
stackLayout.topControl = cmpCubeTree;
cubeTreeViewer.setInput( getCube( ) );
}
cmpStack.layout( );
return;
}
if ( columnListDescription != null )
{
if ( !dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
( (GridData) columnListDescription.getLayoutData( ) ).exclude = false;
columnListDescription.setVisible( true );
columnListDescription.setText( Messages.getString( "StandardChartDataSheet.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
cmpColumnsList.layout( );
}
}
btnShowDataPreviewB.setEnabled( true );
// Clear data preview setting if current data item was changed.
String pValue = ( previousData == null ) ? "" : previousData; //$NON-NLS-1$
String cValue = ( currentData == null ) ? "" : currentData; //$NON-NLS-1$
if ( !pValue.equals( cValue ) )
{
getContext( ).setShowingDataPreview( null );
}
previousData = currentData;
try
{
// If it is initial state and the columns are equal and greater
// than 6, do not use data preview, just use columns list view.
if ( !getContext( ).isSetShowingDataPreview( )
&& getDataServiceProvider( ).getPreviewHeadersInfo( ).length >= 6 )
{
getContext().setShowingDataPreview( Boolean.FALSE );
}
ChartWizard.removeException( ChartWizard.StaChartDSh_gHeaders_ID );
}
catch ( NullPointerException e )
{
// Do not do anything.
}
catch ( ChartException e )
{
ChartWizard.showException( ChartWizard.StaChartDSh_gHeaders_ID,
e.getMessage( ) );
}
btnShowDataPreviewA.setSelection( getContext().isShowingDataPreview( ) );
btnShowDataPreviewB.setSelection( getContext().isShowingDataPreview( ) );
if ( getContext().isShowingDataPreview( ) )
{
stackLayout.topControl = cmpDataPreview;
}
else
{
stackLayout.topControl = cmpColumnsList;
}
refreshDataPreviewPane( );
cmpStack.layout( );
}
private void refreshDataPreviewPane( )
{
if ( getContext().isShowingDataPreview( ) )
{
refreshTablePreview( );
}
else
{
refreshColumnsListView( );
}
}
private void refreshColumnsListView( )
{
// if ( dataProvider.getDataSetFromHandle( ) == null )
// return;
// if ( isCubeMode( ) )
// 1. Create a runnable.
Runnable runnable = new Runnable( ) {
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public void run( )
{
ColumnBindingInfo[] headers = null;
List<?> dataList = null;
try
{
// Get header and data in other thread.
headers = getDataServiceProvider( ).getPreviewHeadersInfo( );
// Only when live preview is enabled, it retrieves data.
if ( dataProvider.isLivePreviewEnabled( ) )
{
dataList = getPreviewData( );
}
final ColumnBindingInfo[] headerInfo = headers;
final List<?> data = dataList;
// Execute UI operation in UI thread.
Display.getDefault( ).syncExec( new Runnable( ) {
public void run( )
{
updateColumnsTableViewer( headerInfo, data );
ChartWizard.removeException( ChartWizard.StaChartDSh_dPreview_ID );
}
} );
}
catch ( Exception e )
{
final ColumnBindingInfo[] headerInfo = headers;
final List<?> data = dataList;
// Catch any exception.
final String message = e.getLocalizedMessage( );
Display.getDefault( ).syncExec( new Runnable( ) {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run( )
{
updateColumnsTableViewer( headerInfo, data );
ChartWizard.showException( ChartWizard.StaChartDSh_dPreview_ID,
message );
}
} );
}
}
};
// 2. Run it.
new Thread( runnable ).start( );
}
/**
* @param headerInfo
* @param data
*/
private void updateColumnsTableViewer(
final ColumnBindingInfo[] headerInfo,
final List<?> data )
{
// Set input.
tableViewerColumns.setInput( headerInfo );
tableViewerColumns.setData( KEY_PREVIEW_DATA, data );
// Make the selected column visible and active.
int index = tablePreview.getCurrentColumnIndex( );
if ( index >= 0 )
{
tableViewerColumns.getTable( ).setFocus( );
tableViewerColumns.getTable( ).select( index );
tableViewerColumns.getTable( ).showSelection( );
}
updateColumnsTableViewerColor( );
}
public Composite createDataSelector( Composite parent )
{
Composite cmpDataSet = ChartUIUtil.createCompositeWrapper( parent );
{
cmpDataSet.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Label label = new Label( cmpDataSet, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.SelectDataSet" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
Composite cmpDetail = new Composite( cmpDataSet, SWT.NONE );
{
GridLayout gridLayout = new GridLayout( 2, false );
gridLayout.marginWidth = 10;
gridLayout.marginHeight = 0;
cmpDetail.setLayout( gridLayout );
cmpDetail.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Composite compRadios = ChartUIUtil.createCompositeWrapper( cmpDetail );
{
GridData gd = new GridData( );
gd.verticalSpan = 2;
compRadios.setLayoutData( gd );
}
btnInherit = new Button( compRadios, SWT.RADIO );
btnInherit.setText( Messages.getString( "StandardChartDataSheet.Label.UseReportData" ) ); //$NON-NLS-1$
btnInherit.addListener( SWT.Selection, this );
btnUseData = new Button( compRadios, SWT.RADIO );
btnUseData.setText( Messages.getString( "StandardChartDataSheet.Label.UseDataSet" ) ); //$NON-NLS-1$
btnUseData.addListener( SWT.Selection, this );
cmbInherit = new CCombo( cmpDetail, SWT.DROP_DOWN
| SWT.READ_ONLY
| SWT.BORDER );
cmbInherit.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
cmbInherit.addListener( SWT.Selection, this );
cmbDataItems = new CCombo( cmpDetail, SWT.DROP_DOWN
| SWT.READ_ONLY
| SWT.BORDER );
cmbDataItems.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
cmbDataItems.addListener( SWT.Selection, this );
initDataSelector( );
updatePredefinedQueries( );
checkColBindingForCube( );
if ( dataProvider.checkState( IDataServiceProvider.IN_MULTI_VIEWS ) )
{
autoSelect( false );
}
return cmpDataSet;
}
int invokeNewDataSet( )
{
DataService.getInstance( ).createDataSet( );
// Due to the limitation of the action execution, always return ok
return Window.OK;
}
int invokeEditFilter( )
{
ExtendedItemHandle handle = getItemHandle( );
handle.getModuleHandle( ).getCommandStack( ).startTrans( null );
ExtendedItemFilterDialog page = new ExtendedItemFilterDialog( handle );
AbstractFilterHandleProvider provider = ChartFilterProviderDelegate.createFilterProvider( handle,
handle );
if ( provider instanceof ChartCubeFilterHandleProvider )
{
( (ChartCubeFilterHandleProvider) provider ).setContext( getContext( ) );
}
page.setFilterHandleProvider( provider );
int openStatus = page.open( );
if ( openStatus == Window.OK )
{
handle.getModuleHandle( ).getCommandStack( ).commit( );
}
else
{
handle.getModuleHandle( ).getCommandStack( ).rollback( );
}
return openStatus;
}
int invokeEditParameter( )
{
ReportItemParametersDialog page = new ReportItemParametersDialog( getItemHandle( ) );
return page.open( );
}
int invokeDataBinding( )
{
Shell shell = new Shell( Display.getDefault( ), SWT.DIALOG_TRIM
| SWT.RESIZE
| SWT.APPLICATION_MODAL );
// #194163: Do not register CS help in chart since it's registered in
// super column binding dialog.
// ChartUIUtil.bindHelp( shell,
// ChartHelpContextIds.DIALOG_DATA_SET_COLUMN_BINDING );
ExtendedItemHandle handle = getItemHandle( );
handle.getModuleHandle( ).getCommandStack( ).startTrans( null );
ColumnBindingDialog page = new ChartColumnBindingDialog( handle,
shell,
getContext( ) );
ExpressionProvider ep = new ExpressionProvider( getItemHandle( ) );
ep.addFilter( new ExpressionFilter( ) {
public boolean select( Object parentElement, Object element )
{
// Remove unsupported expression. See bugzilla#132768
return !( parentElement.equals( ExpressionProvider.BIRT_OBJECTS )
&& element instanceof IClassInfo && ( (IClassInfo) element ).getName( )
.equals( "Total" ) ); //$NON-NLS-1$
}
} );
page.setExpressionProvider( ep );
// Make all bindings under share binding case read-only.
( (ChartColumnBindingDialog) page ).setReadOnly( getDataServiceProvider( ).isSharedBinding( )
|| getDataServiceProvider( ).isInheritanceOnly( ) );
int openStatus = page.open( );
if ( openStatus == Window.OK )
{
handle.getModuleHandle( ).getCommandStack( ).commit( );
updatePredefinedQueries( );
checkColBindingForCube( );
}
else
{
handle.getModuleHandle( ).getCommandStack( ).rollback( );
}
return openStatus;
}
private void initDataSelector( )
{
// create Combo items
cmbInherit.setItems( new String[]{
Messages.getString( "StandardChartDataSheet.Combo.InheritColumnsGroups" ), //$NON-NLS-1$
Messages.getString( "StandardChartDataSheet.Combo.InheritColumnsOnly" ) //$NON-NLS-1$
} );
if ( dataProvider.isInheritColumnsSet( ) )
{
cmbInherit.select( dataProvider.isInheritColumnsOnly( ) ? 1 : 0 );
}
else
{
// Set default inheritance value
if ( ChartReportItemUtil.hasAggregation( getChartModel( ) ) )
{
// If aggregations found, set inherit columns only
cmbInherit.select( 1 );
getContext( ).setInheritColumnsOnly( true );
}
else
{
// Default value is set as Inherit groups
cmbInherit.select( 0 );
getContext( ).setInheritColumnsOnly( false );
}
}
cmbInherit.setEnabled( false );
cmbDataItems.setItems( createDataComboItems( ) );
cmbDataItems.setVisibleItemCount( cmbDataItems.getItemCount( ) );
// Select report item reference
// Since handle may have data set or data cube besides reference, always
// check reference first
String sItemRef = getDataServiceProvider( ).getReportItemReference( );
if ( sItemRef != null )
{
btnUseData.setSelection( true );
bIsInheritSelected = false;
cmbDataItems.setText( sItemRef );
currentData = sItemRef;
return;
}
// Select data set
String sDataSet = getDataServiceProvider( ).getBoundDataSet( );
if ( sDataSet != null && !getDataServiceProvider( ).isInheritanceOnly( ) )
{
btnUseData.setSelection( true );
bIsInheritSelected = false;
cmbDataItems.setText( sDataSet );
currentData = sDataSet;
if ( sDataSet != null )
{
switchDataTable( );
}
return;
}
// Select data cube
String sDataCube = getDataServiceProvider( ).getDataCube( );
if ( sDataCube != null
&& !getDataServiceProvider( ).isInheritanceOnly( ) )
{
btnUseData.setSelection( true );
bIsInheritSelected = false;
cmbDataItems.setText( sDataCube );
currentData = sDataCube;
return;
}
cmbInherit.setEnabled( getDataServiceProvider( ).getReportDataSet( ) != null
&& ChartReportItemUtil.isContainerInheritable( itemHandle ) );
if ( !cmbInherit.isEnabled( ) )
{
// If container is not inheritable, set inherit column groups.
cmbInherit.select( 0 );
}
btnInherit.setSelection( true );
bIsInheritSelected = true;
if ( getDataServiceProvider( ).isInheritanceOnly( ) )
{
btnUseData.setSelection( false );
btnUseData.setEnabled( false );
}
cmbDataItems.select( 0 );
currentData = null;
cmbDataItems.setEnabled( false );
// Initializes column bindings from container
getDataServiceProvider( ).setDataSet( null );
String reportDataSet = getDataServiceProvider( ).getReportDataSet( );
if ( reportDataSet != null )
{
switchDataTable( );
}
}
public void handleEvent( Event event )
{
if ( event.data instanceof ISelectDataComponent )
{
// When user select expression in drop&down list of live preview
// area, the event will be handled to update related column color.
if ( event.type == IChartDataSheet.EVENT_QUERY
&& event.detail == IChartDataSheet.DETAIL_UPDATE_COLOR )
{
refreshTableColor( );
}
return;
}
// Right click to display the menu. Menu display by clicking
// application key is triggered by os, so do nothing.
// bug 261340, now we use the field doit to indicate whether it's menu
// initialization or event triggering.
if ( event.type == CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE )
{
if ( getDataServiceProvider( ).getBoundDataSet( ) != null
|| getDataServiceProvider( ).getReportDataSet( ) != null )
{
if ( event.widget instanceof Button )
{
Button header = (Button) event.widget;
// Bind context menu to each header button
boolean isSharingChart = dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY );
if ( header.getMenu( ) == null && !isSharingChart)
{
header.setMenu( createMenuManager( event.data ).createContextMenu( tablePreview ) );
}
if ( event.doit && !isSharingChart )
{
header.getMenu( ).setVisible( true );
}
}
}
}
else if ( event.type == SWT.Selection )
{
if ( event.widget instanceof MenuItem )
{
MenuItem item = (MenuItem) event.widget;
IAction action = (IAction) item.getData( );
action.setChecked( !action.isChecked( ) );
action.run( );
}
else if ( event.widget == btnFilters )
{
if ( invokeEditFilter( ) == Window.OK )
{
refreshDataPreviewPane( );
// Update preview via event
fireEvent( btnFilters, EVENT_PREVIEW );
}
}
else if ( event.widget == btnParameters )
{
if ( invokeEditParameter( ) == Window.OK )
{
refreshDataPreviewPane( );
// Update preview via event
fireEvent( btnParameters, EVENT_PREVIEW );
}
}
else if ( event.widget == btnBinding )
{
if ( invokeDataBinding( ) == Window.OK )
{
refreshDataPreviewPane( );
// Update preview via event
fireEvent( btnBinding, EVENT_PREVIEW );
}
}
try
{
if ( event.widget == btnInherit )
{
ColorPalette.getInstance( ).restore( );
// Skip when selection is false
if ( !btnInherit.getSelection( ) )
{
return;
}
// Avoid duplicate loading data set.
if ( bIsInheritSelected )
{
return;
}
bIsInheritSelected = true;
getDataServiceProvider( ).setReportItemReference( null );
getDataServiceProvider( ).setDataSet( null );
switchDataSet( null );
cmbDataItems.select( 0 );
currentData = null;
cmbDataItems.setEnabled( false );
cmbInherit.setEnabled( getDataServiceProvider( ).getReportDataSet( ) != null
&& ChartReportItemUtil.isContainerInheritable( itemHandle ) );
setEnabledForButtons( );
updateDragDataSource( );
updatePredefinedQueries( );
}
else if ( event.widget == btnUseData )
{
// Skip when selection is false
if ( !btnUseData.getSelection( ) )
{
return;
}
// Avoid duplicate loading data set.
if ( !bIsInheritSelected )
{
return;
}
bIsInheritSelected = false;
getDataServiceProvider( ).setReportItemReference( null );
getDataServiceProvider( ).setDataSet( null );
selectDataSet( );
cmbDataItems.setEnabled( true );
cmbInherit.setEnabled( false );
setEnabledForButtons( );
updateDragDataSource( );
updatePredefinedQueries( );
}
else if ( event.widget == cmbInherit )
{
getContext( ).setInheritColumnsOnly( cmbInherit.getSelectionIndex( ) == 1 );
// Fire event to update outside UI
fireEvent( btnBinding, EVENT_QUERY );
refreshDataPreviewPane( );
}
else if ( event.widget == cmbDataItems )
{
ColorPalette.getInstance( ).restore( );
int selectedIndex = cmbDataItems.getSelectionIndex( );
Integer selectState = selectDataTypes.get( selectedIndex );
switch ( selectState.intValue( ) )
{
case SELECT_NONE :
// Inherit data from container
btnInherit.setSelection( true );
btnUseData.setSelection( false );
btnInherit.notifyListeners( SWT.Selection,
new Event( ) );
break;
case SELECT_NEXT :
selectedIndex++;
selectState = selectDataTypes.get( selectedIndex );
cmbDataItems.select( selectedIndex );
break;
}
switch ( selectState.intValue( ) )
{
case SELECT_DATA_SET :
if ( getDataServiceProvider( ).getReportItemReference( ) == null
&& getDataServiceProvider( ).getBoundDataSet( ) != null
&& getDataServiceProvider( ).getBoundDataSet( )
.equals( cmbDataItems.getText( ) ) )
{
return;
}
getDataServiceProvider( ).setDataSet( cmbDataItems.getText( ) );
currentData = cmbDataItems.getText( );
switchDataSet( cmbDataItems.getText( ) );
setEnabledForButtons( );
updateDragDataSource( );
break;
case SELECT_DATA_CUBE :
getDataServiceProvider( ).setDataCube( cmbDataItems.getText( ) );
currentData = cmbDataItems.getText( );
updateDragDataSource( );
setEnabledForButtons( );
// Update preview via event
DataDefinitionTextManager.getInstance( )
.refreshAll( );
fireEvent( tablePreview, EVENT_PREVIEW );
break;
case SELECT_REPORT_ITEM :
if ( cmbDataItems.getText( )
.equals( getDataServiceProvider( ).getReportItemReference( ) ) )
{
return;
}
getDataServiceProvider( ).setReportItemReference( cmbDataItems.getText( ) );
// TED 10163
// Following calls will revise chart model for
// report item sharing case, in older version of
// chart, it is allowed to set grouping on category
// series when sharing report item, but now it isn't
// allowed, so this calls will revise chart model to
// remove category series grouping flag for the
// case.
ChartReportItemUtil.reviseChartModel( ChartReportItemUtil.REVISE_REFERENCE_REPORT_ITEM,
this.getContext( ).getModel( ),
itemHandle );
// Bugzilla 265077.
if ( this.getDataServiceProvider( ).checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
ChartAdapter.beginIgnoreNotifications( );
this.getDataServiceProvider( )
.update( ChartUIConstants.COPY_SERIES_DEFINITION, null );
ChartAdapter.endIgnoreNotifications( );
}
currentData = cmbDataItems.getText( );
// selectDataSet( );
// switchDataSet( cmbDataItems.getText( ) );
// Update preview via event
DataDefinitionTextManager.getInstance( )
.refreshAll( );
fireEvent( tablePreview, EVENT_PREVIEW );
setEnabledForButtons( );
updateDragDataSource( );
break;
case SELECT_NEW_DATASET :
// Bring up the dialog to create a dataset
int result = invokeNewDataSet( );
if ( result == Window.CANCEL )
{
return;
}
cmbDataItems.removeAll( );
cmbDataItems.setItems( createDataComboItems( ) );
cmbDataItems.setVisibleItemCount( cmbDataItems.getItemCount( ) );
if ( currentData == null )
{
cmbDataItems.select( 0 );
}
else
{
cmbDataItems.setText( currentData );
}
break;
case SELECT_NEW_DATACUBE :
if ( getDataServiceProvider( ).getAllDataSets( ).length == 0 )
{
invokeNewDataSet( );
}
if ( getDataServiceProvider( ).getAllDataSets( ).length != 0 )
{
new NewCubeAction( ).run( );
}
cmbDataItems.removeAll( );
cmbDataItems.setItems( createDataComboItems( ) );
cmbDataItems.setVisibleItemCount( cmbDataItems.getItemCount( ) );
if ( currentData == null )
{
cmbDataItems.select( 0 );
}
else
{
cmbDataItems.setText( currentData );
}
break;
}
updatePredefinedQueries( );
autoSelect( true );
}
else if ( event.widget == btnShowDataPreviewA || event.widget == btnShowDataPreviewB )
{
Button w = (Button) event.widget;
getContext().setShowingDataPreview( Boolean.valueOf( w.getSelection( ) ) );
updateDragDataSource( );
}
if ( event.widget == btnInherit || event.widget == cmbDataItems )
{
List<SeriesDefinition> sds = ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) );
if ( sds != null && sds.size( ) > 0 )
{
SeriesDefinition base = sds.get( 0 );
if ( selectDataTypes.get( cmbDataItems.getSelectionIndex( ) )
.intValue( ) == SELECT_DATA_SET
&& !ChartUIConstants.TYPE_GANTT.equals( getChartModel( ).getType( ) ) )
{
if ( base.getGrouping( ) == null )
{
base.setGrouping( SeriesGroupingImpl.create( ) );
}
base.getGrouping( ).setEnabled( true );
}
else
{
if ( base.getGrouping( ) != null )
{
base.getGrouping( ).setEnabled( false );
}
}
}
}
checkColBindingForCube( );
ChartWizard.removeException( ChartWizard.StaChartDSh_switch_ID );
}
catch ( ChartException e1 )
{
ChartWizard.showException( ChartWizard.StaChartDSh_switch_ID,
e1.getLocalizedMessage( ) );
}
}
}
private void autoSelect( boolean force )
{
if ( dataProvider.checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY )
&& !dataProvider.checkState( IDataServiceProvider.SHARE_CHART_QUERY ) )
{
// if only one item,select it for user
Query query = ChartUIUtil.getAllOrthogonalSeriesDefinitions( getContext( ).getModel( ) )
.get( 0 )
.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
Object[] valueExprs = getContext( ).getPredefinedQuery( ChartUIConstants.QUERY_VALUE );
if ( ( force || query.getDefinition( ) == null || query.getDefinition( )
.trim( )
.length( ) == 0 )
&& valueExprs != null && valueExprs.length == 1 )
{
String text = valueExprs[0].toString( );
query.setDefinition( text );
if ( dataProvider.update( ChartUIConstants.QUERY_VALUE, text ) )
{
Event e = new Event( );
e.type = IChartDataSheet.EVENT_QUERY;
this.notifyListeners( e );
}
if ( force )
{
fireEvent( tablePreview, EVENT_PREVIEW );
}
}
}
}
private void selectDataSet( )
{
String currentDS = getDataServiceProvider( ).getBoundDataSet( );
if ( currentDS == null )
{
cmbDataItems.select( 0 );
currentData = null;
}
else
{
cmbDataItems.setText( currentDS );
currentData = currentDS;
}
}
private void refreshTablePreview( )
{
if ( dataProvider.getDataSetFromHandle( ) == null )
{
return;
}
tablePreview.clearContents( );
switchDataTable( );
tablePreview.layout( );
}
private void switchDataSet( String datasetName ) throws ChartException
{
if ( isCubeMode( ) )
{
return;
}
try
{
// Clear old dataset and preview data
tablePreview.clearContents( );
tableViewerColumns.setInput( null );
// Try to get report data set
if ( datasetName == null )
{
datasetName = getDataServiceProvider( ).getReportDataSet( );
}
if ( datasetName != null )
{
switchDataTable( );
}
else
{
tablePreview.createDummyTable( );
}
tablePreview.layout( );
}
catch ( Throwable t )
{
throw new ChartException( ChartEnginePlugin.ID,
ChartException.DATA_BINDING,
t );
}
DataDefinitionTextManager.getInstance( ).refreshAll( );
// Update preview via event
fireEvent( tablePreview, EVENT_PREVIEW );
}
/**
* Update column headers and data to table.
*
* @param headers
* @param dataList
*/
private void updateTablePreview( final ColumnBindingInfo[] headers,
final List<?> dataList )
{
fireEvent( tablePreview, EVENT_QUERY );
if ( tablePreview.isDisposed( ) )
{
return;
}
if ( headers == null || headers.length == 0 )
{
tablePreview.setEnabled( false );
tablePreview.createDummyTable( );
}
else
{
tablePreview.setEnabled( true );
tablePreview.setColumns( headers );
refreshTableColor( );
// Add data value
if ( dataList != null )
{
for ( Iterator<?> iterator = dataList.iterator( ); iterator.hasNext( ); )
{
String[] dataRow = (String[]) iterator.next( );
for ( int i = 0; i < dataRow.length; i++ )
{
tablePreview.addEntry( dataRow[i], i );
}
}
}
}
tablePreview.layout( );
// Make the selected column visible and active.
int index = tableViewerColumns.getTable( ).getSelectionIndex( );
if ( index >= 0 )
{
tablePreview.moveTo( index );
}
}
private synchronized List<?> getPreviewData( ) throws ChartException
{
return getDataServiceProvider( ).getPreviewData( );
}
private void switchDataTable( )
{
if ( isCubeMode( ) )
{
return;
}
// 1. Create a runnable.
Runnable runnable = new Runnable( ) {
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public void run( )
{
ColumnBindingInfo[] headers = null;
List<?> dataList = null;
try
{
// Get header and data in other thread.
headers = getDataServiceProvider( ).getPreviewHeadersInfo( );
dataList = getPreviewData( );
final ColumnBindingInfo[] headerInfo = headers;
final List<?> data = dataList;
// Execute UI operation in UI thread.
Display.getDefault( ).syncExec( new Runnable( ) {
public void run( )
{
updateTablePreview( headerInfo, data );
ChartWizard.removeException( ChartWizard.StaChartDSh_dPreview_ID );
}
} );
}
catch ( Exception e )
{
final ColumnBindingInfo[] headerInfo = headers;
final List<?> data = dataList;
// Catch any exception.
final String message = e.getMessage( );
Display.getDefault( ).syncExec( new Runnable( ) {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run( )
{
// Still update table preview in here to ensure the
// column headers of table preview can be updated
// and user can select expression from table preview
// even if there is no preview data.
updateTablePreview( headerInfo, data );
ChartWizard.showException( ChartWizard.StaChartDSh_dPreview_ID,
message );
}
} );
}
}
};
// 2. Run it.
new Thread( runnable ).start( );
}
private void refreshTableColor( )
{
if ( isCubeMode( ) )
{
return;
}
// Reset column color
if ( getContext( ).isShowingDataPreview( ) )
{
for ( int i = 0; i < tablePreview.getColumnNumber( ); i++ )
{
tablePreview.setColumnColor( i,
ColorPalette.getInstance( )
.getColor( ExpressionUtil.createJSRowExpression( tablePreview.getColumnHeading( i ) ) ) );
}
}
else
{
updateColumnsTableViewerColor( );
}
}
private void updateColumnsTableViewerColor( )
{
for ( TableItem item : tableViewerColumns.getTable( ).getItems( ) )
{
ColumnBindingInfo cbi = (ColumnBindingInfo) item.getData( );
Color c = ColorPalette.getInstance( )
.getColor( ExpressionUtil.createJSRowExpression( cbi.getName( ) ) );
if ( c == null )
{
c = Display.getDefault( )
.getSystemColor( SWT.COLOR_LIST_BACKGROUND );
}
item.setBackground( c );
}
}
/**
* Returns actual expression for common and sharing query case.
*
* @param query
* @param expr
* @return
*/
private String getActualExpression( String expr )
{
if ( !dataProvider.checkState( IDataServiceProvider.SHARE_QUERY ) )
{
return expr;
}
// Convert to actual expression.
Object obj = getCurrentColumnHeadObject( );
if ( obj instanceof ColumnBindingInfo )
{
ColumnBindingInfo cbi = (ColumnBindingInfo) obj;
int type = cbi.getColumnType( );
if ( type == ColumnBindingInfo.GROUP_COLUMN
|| type == ColumnBindingInfo.AGGREGATE_COLUMN )
{
return cbi.getExpression( );
}
}
return expr;
}
protected void manageColorAndQuery( Query query, String expr )
{
// If it's not used any more, remove color binding
if ( DataDefinitionTextManager.getInstance( )
.getNumberOfSameDataDefinition( query.getDefinition( ) ) == 1 )
{
ColorPalette.getInstance( ).retrieveColor( query.getDefinition( ) );
}
// Update query, if it is sharing binding case, the specified expression
// will be converted and set to query, else directly set specified
// expression to query.
// DataDefinitionTextManager.getInstance( ).updateQuery( query, expr );
query.setDefinition( getActualExpression( expr ) );
DataDefinitionTextManager.getInstance( ).updateText( query );
// Reset table column color
refreshTableColor( );
// Refresh all data definition text
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
/**
* @param queryType
* @param query
* @param expr
* @param seriesDefinition
* @since 2.5
*/
protected void manageColorAndQuery( String queryType, Query query, String expr,
SeriesDefinition seriesDefinition )
{
// If it's not used any more, remove color binding
if ( dataProvider.getNumberOfSameDataDefinition( query.getDefinition( ) ) == 1 )
{
ColorPalette.getInstance( ).retrieveColor( query.getDefinition( ) );
}
// Update query, if it is sharing binding case, the specified expression
// will be converted and set to query, else directly set specified
// expression to query.
updateQuery( queryType, query, expr, seriesDefinition );
// 236018--add the logic of register color with display expression
// as it does in the input text refreshing, since the text may not be
// shown at current.
ColorPalette.getInstance( ).putColor( expr );
DataDefinitionTextManager.getInstance( ).updateText( query );
// Reset table column color
refreshTableColor( );
// Refresh all data definition text
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
private void updateQuery( String queryType, Query query, String expr,
SeriesDefinition seriesDefinition )
{
String actualExpr = expr;
if ( dataProvider.checkState( IDataServiceProvider.SHARE_QUERY )
|| dataProvider.checkState( IDataServiceProvider.INHERIT_COLUMNS_GROUPS ) )
{
boolean isGroupOrAggr = false;
// Convert to actual expression.
Object obj = getCurrentColumnHeadObject( );
if ( obj instanceof ColumnBindingInfo )
{
ColumnBindingInfo cbi = (ColumnBindingInfo) obj;
int type = cbi.getColumnType( );
if ( type == ColumnBindingInfo.GROUP_COLUMN
|| type == ColumnBindingInfo.AGGREGATE_COLUMN )
{
actualExpr = cbi.getExpression( );
isGroupOrAggr = true;
}
}
// Update group state.
if ( seriesDefinition != null
&& ( queryType.equals( ChartUIConstants.QUERY_CATEGORY ) || queryType.equals( ChartUIConstants.QUERY_VALUE ) ) )
{
seriesDefinition.getGrouping( ).setEnabled( isGroupOrAggr );
}
}
if ( ChartUIConstants.QUERY_VALUE.equals( queryType ) )
{
if ( !dataProvider.checkState( IDataServiceProvider.SHARE_QUERY )
&& dataProvider.checkState( IDataServiceProvider.HAS_DATA_SET ) )
{
if ( dataProvider.getDataType( actualExpr ) == DataType.DATE_TIME_LITERAL )
{
ChartAdapter.beginIgnoreNotifications( );
if ( query.getGrouping( ) == null )
{
query.setGrouping( DataFactoryImpl.init( )
.createSeriesGrouping( ) );
}
SeriesGrouping group = query.getGrouping( );
group.setEnabled( true );
group.setAggregateExpression( "First" ); //$NON-NLS-1$
ChartAdapter.endIgnoreNotifications( );
}
}
}
query.setDefinition( actualExpr );
}
class CategoryXAxisAction extends Action
{
Query query;
String expr;
private SeriesDefinition seriesDefintion;
CategoryXAxisAction( String expr )
{
super( getBaseSeriesTitle( getChartModel( ) ) );
seriesDefintion = ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) )
.get( 0 );
this.query = seriesDefintion.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
this.expr = expr;
setEnabled( DataDefinitionTextManager.getInstance( )
.isAcceptableExpression( query,
expr,
dataProvider.isSharedBinding( ) ) );
}
public void run( )
{
manageColorAndQuery( ChartUIConstants.QUERY_CATEGORY,
query,
expr,
seriesDefintion );
}
}
class GroupYSeriesAction extends Action
{
Query query;
String expr;
private SeriesDefinition seriesDefinition;
GroupYSeriesAction( Query query, String expr,
SeriesDefinition seriesDefinition )
{
super( getGroupSeriesTitle( getChartModel( ) ) );
this.seriesDefinition = seriesDefinition;
this.query = query;
this.expr = expr;
setEnabled( DataDefinitionTextManager.getInstance( )
.isAcceptableExpression( query,
expr,
dataProvider.isSharedBinding( ) ) );
}
public void run( )
{
// Use the first group, and copy to the all groups
ChartAdapter.beginIgnoreNotifications( );
ChartUIUtil.setAllGroupingQueryExceptFirst( getChartModel( ), expr );
ChartAdapter.endIgnoreNotifications( );
manageColorAndQuery( ChartUIConstants.QUERY_OPTIONAL,
query,
expr,
seriesDefinition );
}
}
class ValueYSeriesAction extends Action
{
Query query;
String expr;
ValueYSeriesAction( Query query, String expr )
{
super( getOrthogonalSeriesTitle( getChartModel( ) ) );
this.query = query;
this.expr = expr;
// Grouping expressions can't be set on value series.
boolean enabled = true;
if ( dataProvider.checkState( IDataServiceProvider.SHARE_QUERY ) )
{
Object obj = getCurrentColumnHeadObject( );
if ( obj instanceof ColumnBindingInfo
&& ( (ColumnBindingInfo) obj ).getColumnType( ) == ColumnBindingInfo.GROUP_COLUMN )
{
enabled = false;
}
}
setEnabled( enabled );
}
public void run( )
{
manageColorAndQuery( ChartUIConstants.QUERY_VALUE,
query,
expr,
null );
}
}
Object getCurrentColumnHeadObject()
{
if ( getContext( ).isShowingDataPreview( ) )
{
return tablePreview.getCurrentColumnHeadObject( );
}
int index = tableViewerColumns.getTable( ).getSelectionIndex( );
if ( index < 0 )
return null;
return tableViewerColumns.getTable( ).getItem( index ).getData( );
}
static class HeaderShowAction extends Action
{
HeaderShowAction( String header )
{
super( header );
setEnabled( false );
}
}
ExtendedItemHandle getItemHandle( )
{
return this.itemHandle;
}
ReportDataServiceProvider getDataServiceProvider( )
{
return this.dataProvider;
}
protected List<Object> getActionsForTableHead( String expr )
{
List<Object> actions = new ArrayList<Object>( 3 );
actions.add( getBaseSeriesMenu( getChartModel( ), expr ) );
actions.add( getOrthogonalSeriesMenu( getChartModel( ), expr ) );
actions.add( getGroupSeriesMenu( getChartModel( ), expr ) );
return actions;
}
private MenuManager createMenuManager( final Object data )
{
MenuManager menuManager = new MenuManager( );
menuManager.setRemoveAllWhenShown( true );
menuManager.addMenuListener( new IMenuListener( ) {
public void menuAboutToShow( IMenuManager manager )
{
if ( data instanceof ColumnBindingInfo )
{
// Menu for columns table.
addMenu( manager,
new HeaderShowAction( ((ColumnBindingInfo)data).getName( ) ) );
String expr = ExpressionUtil.createJSRowExpression( ((ColumnBindingInfo)data).getName( ) );
List<Object> actions = getActionsForTableHead( expr );
for ( Object act : actions )
{
addMenu( manager, act );
}
}
else if ( data instanceof Integer )
{
// Menu for table
addMenu( manager,
new HeaderShowAction( tablePreview.getCurrentColumnHeading( ) ) );
String expr = ExpressionUtil.createJSRowExpression( tablePreview.getCurrentColumnHeading( ) );
List<Object> actions = getActionsForTableHead( expr );
for ( Object act : actions )
{
addMenu( manager, act );
}
}
else if ( data instanceof MeasureHandle )
{
// Menu for Measure
String expr = createCubeExpression( );
if ( expr != null )
{
addMenu( manager,
getOrthogonalSeriesMenu( getChartModel( ), expr ) );
}
}
else if ( data instanceof LevelHandle )
{
// Menu for Level
String expr = createCubeExpression( );
if ( expr != null )
{
// bug#220724
if ( ( (Boolean) dataProvider.checkData( ChartUIConstants.QUERY_CATEGORY,
expr ) ).booleanValue( ) )
{
addMenu( manager,
getBaseSeriesMenu( getChartModel( ),
expr ) );
}
if ( dataProvider.checkState( IDataServiceProvider.MULTI_CUBE_DIMENSIONS )
&& ( (Boolean) dataProvider.checkData( ChartUIConstants.QUERY_OPTIONAL,
expr ) ).booleanValue( ) )
{
addMenu( manager,
getGroupSeriesMenu( getChartModel( ),
expr ) );
}
}
}
}
private void addMenu( IMenuManager manager, Object item )
{
if ( item instanceof IAction )
{
manager.add( (IAction) item );
}
else if ( item instanceof IContributionItem )
{
manager.add( (IContributionItem) item );
}
// Do not allow customized query in xtab
if ( getDataServiceProvider( ).isPartChart( ) )
{
if ( item instanceof IAction )
{
( (IAction) item ).setEnabled( false );
}
}
}
} );
return menuManager;
}
private Object getBaseSeriesMenu( Chart chart, String expr )
{
EList<SeriesDefinition> sds = ChartUIUtil.getBaseSeriesDefinitions( chart );
if ( sds.size( ) == 1 )
{
return new CategoryXAxisAction( expr );
}
return null;
}
private Object getGroupSeriesMenu( Chart chart, String expr )
{
IMenuManager topManager = new MenuManager( getGroupSeriesTitle( getChartModel( ) ) );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chart );
for ( int axisIndex = 0; axisIndex < axisNum; axisIndex++ )
{
List<SeriesDefinition> sds = ChartUIUtil.getOrthogonalSeriesDefinitions( chart,
axisIndex );
if ( !sds.isEmpty( ) )
{
SeriesDefinition sd = sds.get( 0 );
IAction action = new GroupYSeriesAction( sd.getQuery( ),
expr,
sd );
// ONLY USE FIRST GROUPING SERIES FOR CHART ENGINE SUPPORT
// if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simply cascade menu
return action;
}
// action.setText( getSecondMenuText( axisIndex,
// sd.getDesignTimeSeries( ) ) );
// topManager.add( action );
}
}
return topManager;
}
private Object getOrthogonalSeriesMenu( Chart chart, String expr )
{
IMenuManager topManager = new MenuManager( getOrthogonalSeriesTitle( getChartModel( ) ) );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chart );
for ( int axisIndex = 0; axisIndex < axisNum; axisIndex++ )
{
List<SeriesDefinition> sds = ChartUIUtil.getOrthogonalSeriesDefinitions( chart,
axisIndex );
for ( int i = 0; i < sds.size( ); i++ )
{
Series series = sds.get( i ).getDesignTimeSeries( );
EList<Query> dataDefns = series.getDataDefinition( );
if ( series instanceof StockSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getStockTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof BubbleSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getBubbleTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof DifferenceSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getDifferenceTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof GanttSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getGanttTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else
{
IAction action = new ValueYSeriesAction( dataDefns.get( 0 ),
expr );
if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simplify cascade menu
return action;
}
action.setText( getSecondMenuText( axisIndex, i, series ) );
topManager.add( action );
}
}
}
return topManager;
}
private String getSecondMenuText( int axisIndex, int seriesIndex,
Series series )
{
StringBuffer sb = new StringBuffer( );
if ( ChartUIUtil.getOrthogonalAxisNumber( getChartModel( ) ) > 1 )
{
sb.append( Messages.getString( "StandardChartDataSheet.Label.Axis" ) ); //$NON-NLS-1$
sb.append( axisIndex + 1 );
sb.append( " - " ); //$NON-NLS-1$
}
sb.append( Messages.getString( "StandardChartDataSheet.Label.Series" ) //$NON-NLS-1$
+ ( seriesIndex + 1 )
+ " (" + series.getDisplayName( ) + ")" ); //$NON-NLS-1$ //$NON-NLS-2$
return sb.toString( );
}
private String getBaseSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.UseAsCategoryXAxis" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.UseAsCategorySeries" ); //$NON-NLS-1$
}
private String getOrthogonalSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.PlotAsValueYSeries" ); //$NON-NLS-1$
}
else if ( chart instanceof DialChart )
{
return Messages.getString( "StandardChartDataSheet.Label.PlotAsGaugeValue" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.PlotAsValueSeries" ); //$NON-NLS-1$
}
private String getGroupSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.UseToGroupYSeries" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.UseToGroupValueSeries" ); //$NON-NLS-1$
}
private boolean isCubeMode( )
{
boolean bCube = ChartXTabUtil.getBindingCube( itemHandle ) != null;
if ( bCube )
{
// If current item doesn't support cube, referenced cube should be
// invalid.
return isDataItemSupported( SELECT_DATA_CUBE );
}
return false;
}
private CubeHandle getCube( )
{
return ChartXTabUtil.getBindingCube( itemHandle );
}
/**
* Creates the cube expression
*
* @return expression
*/
private String createCubeExpression( )
{
if ( cubeTreeViewer == null )
{
return null;
}
TreeItem[] selection = cubeTreeViewer.getTree( ).getSelection( );
String expr = null;
if ( selection.length > 0
&& !dataProvider.isSharedBinding( )
&& !dataProvider.isPartChart( ) )
{
TreeItem treeItem = selection[0];
ComputedColumnHandle binding = null;
if ( treeItem.getData( ) instanceof LevelHandle )
{
binding = ChartXTabUtil.findBinding( itemHandle,
ChartXTabUtil.createDimensionExpression( (LevelHandle) treeItem.getData( ) ) );
}
else if ( treeItem.getData( ) instanceof MeasureHandle )
{
binding = ChartXTabUtil.findBinding( itemHandle,
ChartXTabUtil.createMeasureExpression( (MeasureHandle) treeItem.getData( ) ) );
}
if ( binding != null )
{
expr = ExpressionUtil.createJSDataExpression( binding.getName( ) );
}
}
return expr;
}
private boolean isDataItemSupported( int type )
{
return iSupportedDataItems == 0
|| ( iSupportedDataItems & type ) == type;
}
private String[] createDataComboItems( )
{
List<String> items = new ArrayList<String>( );
selectDataTypes.clear( );
if ( isDataItemSupported( SELECT_NONE ) )
{
if ( DEUtil.getDataSetList( itemHandle.getContainer( ) )
.size( ) > 0 )
{
items.add( Messages.getString( "ReportDataServiceProvider.Option.Inherits", //$NON-NLS-1$
( (DataSetHandle) DEUtil.getDataSetList( itemHandle.getContainer( ) )
.get( 0 ) ).getName( ) ) );
}
else
{
items.add( ReportDataServiceProvider.OPTION_NONE );
}
selectDataTypes.add( Integer.valueOf( SELECT_NONE ) );
}
if ( isDataItemSupported( SELECT_DATA_SET ) )
{
String[] dataSets = getDataServiceProvider( ).getAllDataSets( );
if ( dataSets.length > 0 )
{
if ( isDataItemSupported( SELECT_NEXT ) )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.DataSets" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEXT ) );
}
for ( int i = 0; i < dataSets.length; i++ )
{
items.add( dataSets[i] );
selectDataTypes.add( Integer.valueOf( SELECT_DATA_SET ) );
}
}
if ( isDataItemSupported( SELECT_NEW_DATASET ) )
{
items.add( Messages.getString( "StandardChartDataSheet.NewDataSet" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEW_DATASET ) );
}
}
if ( isDataItemSupported( SELECT_DATA_CUBE ) )
{
String[] dataCubes = getDataServiceProvider( ).getAllDataCubes( );
if ( dataCubes.length > 0 )
{
if ( isDataItemSupported( SELECT_NEXT ) )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.DataCubes" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEXT ) );
}
for ( int i = 0; i < dataCubes.length; i++ )
{
items.add( dataCubes[i] );
selectDataTypes.add( Integer.valueOf( SELECT_DATA_CUBE ) );
}
}
if ( isDataItemSupported( SELECT_NEW_DATACUBE ) )
{
items.add( Messages.getString( "StandardChartDataSheet.NewDataCube" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEW_DATACUBE ) );
}
}
if ( isDataItemSupported( SELECT_REPORT_ITEM ) )
{
String[] dataRefs = getDataServiceProvider( ).getAllReportItemReferences( );
if ( dataRefs.length > 0 )
{
int curSize = items.size( );
if ( isDataItemSupported( SELECT_NEXT ) )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.ReportItems" ) ); //$NON-NLS-1$
selectDataTypes.add( Integer.valueOf( SELECT_NEXT ) );
}
for ( int i = 0; i < dataRefs.length; i++ )
{
// if cube is not supported, do not list the report item
// consuming a cube
if ( !isDataItemSupported( SELECT_DATA_CUBE ) )
{
if ( ( (ReportItemHandle) getDataServiceProvider( ).getReportDesignHandle( )
.findElement( dataRefs[i] ) ).getCube( ) != null )
{
continue;
}
}
items.add( dataRefs[i] );
selectDataTypes.add( Integer.valueOf( SELECT_REPORT_ITEM ) );
}
// didn't add any reportitem reference
if ( items.size( ) == curSize + 1 )
{
items.remove( curSize );
selectDataTypes.remove( curSize );
}
}
}
return items.toArray( new String[items.size( )] );
}
private void updatePredefinedQueries( )
{
if ( dataProvider.isInXTabMeasureCell( ) )
{
try
{
CrosstabReportItemHandle xtab = ChartXTabUtil.getXtabContainerCell( itemHandle )
.getCrosstab( );
if ( dataProvider.isPartChart( ) )
{
List<String> levels = ChartXTabUtil.getAllLevelsBindingExpression( xtab );
String[] exprs = levels.toArray( new String[levels.size( )] );
if ( exprs.length == 2 && dataProvider.isInXTabAggrCell( ) )
{
// Only one direction is valid for chart in total cell
if ( ( (ChartWithAxes) getChartModel( ) ).isTransposed( ) )
{
exprs = new String[]{
exprs[1]
};
}
else
{
exprs = new String[]{
exprs[0]
};
}
}
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
exprs );
}
else
{
Iterator<ComputedColumnHandle> columnBindings = ChartXTabUtil.getAllColumnBindingsIterator( itemHandle );
List<String> levels = ChartXTabUtil.getAllLevelsBindingExpression( columnBindings );
String[] exprs = levels.toArray( new String[levels.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
exprs );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
exprs );
columnBindings = ChartXTabUtil.getAllColumnBindingsIterator( itemHandle );
List<String> measures = ChartXTabUtil.getAllMeasuresBindingExpression( columnBindings );
exprs = measures.toArray( new String[measures.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
exprs );
}
}
catch ( BirtException e )
{
WizardBase.displayException( e );
}
}
else
{
if ( getCube( ) == null )
{
try
{
ColumnBindingInfo[] headers = dataProvider.getPreviewHeadersInfo( );
getDataServiceProvider( ).setPredefinedExpressions( headers );
}
catch ( ChartException e )
{
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
null );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
null );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
null );
}
}
else if ( isDataItemSupported( SELECT_DATA_CUBE ) )
{
if ( dataProvider.isInheritanceOnly( )
|| dataProvider.isSharedBinding( ) )
{
// Get all column bindings.
List<String> dimensionExprs = new ArrayList<String>( );
List<String> measureExprs = new ArrayList<String>( );
ReportItemHandle reportItemHandle = dataProvider.getReportItemHandle( );
for ( Iterator<ComputedColumnHandle> iter = reportItemHandle.getColumnBindings( )
.iterator( ); iter.hasNext( ); )
{
ComputedColumnHandle cch = iter.next( );
String dataExpr = ExpressionUtil.createJSDataExpression( cch.getName( ) );
if ( ChartXTabUtil.isDimensionExpresion( cch.getExpression( ) ) )
{
dimensionExprs.add( dataExpr );
}
else if ( ChartXTabUtil.isMeasureExpresion( cch.getExpression( ) ) )
{
// Fixed issue ED 28.
// Underlying code was reverted to the earlier than
// bugzilla 246683, since we have enhanced it to
// support all available measures defined in shared
// item.
// Bugzilla 246683.
// Here if it is sharing with crosstab or
// multi-view, we just put the measure expression
// whose aggregate-ons is most into prepared
// expression query. It will keep correct value to
// shared crosstab or multi-view.
measureExprs.add( dataExpr );
}
}
String[] categoryExprs = dimensionExprs.toArray( new String[dimensionExprs.size( )] );
String[] yOptionalExprs = categoryExprs;
String[] valueExprs = measureExprs.toArray( new String[measureExprs.size( )] );
ReportItemHandle referenceHandle = ChartReportItemUtil.getReportItemReference( itemHandle );
ReportDataServiceProvider rdsp = this.getDataServiceProvider( );
if ( referenceHandle instanceof ExtendedItemHandle
&& rdsp.isChartReportItemHandle( referenceHandle ) )
{
// If the final reference handle is cube with other
// chart, the valid category and Y optional expressions
// only allow those expressions defined in shared chart.
Object referenceCM = rdsp.getChartFromHandle( (ExtendedItemHandle) referenceHandle );
categoryExprs = rdsp.getSeriesExpressionsFrom( referenceCM, ChartUIConstants.QUERY_CATEGORY );
yOptionalExprs = rdsp.getSeriesExpressionsFrom( referenceCM, ChartUIConstants.QUERY_OPTIONAL );
valueExprs = rdsp.getSeriesExpressionsFrom( referenceCM, ChartUIConstants.QUERY_VALUE );
Chart cm = this.getContext( ).getModel( );
if ( categoryExprs.length > 0 )
{
updateCategoryExpression( cm, categoryExprs[0] );
}
if ( yOptionalExprs.length > 0 )
{
updateYOptionalExpressions( cm, yOptionalExprs[0] );
}
}
else if ( dataProvider.checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY ) )
{
// In sharing query with crosstab, the category
// expression and Y optional expression is decided by
// value series expression, so here set them to null.
// And in UI, when the value series expression is
// selected, it will trigger to set correct category and
// Y optional expressions.
categoryExprs = null;
yOptionalExprs = null;
}
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
categoryExprs );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
yOptionalExprs );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
valueExprs );
}
// TODO do we need to handle xtab inheritance case? currently we
// just inherit the cube from xtab essentially
// else if ( ChartXTabUIUtil.isInheritXTabCell( itemHandle ) )
// // Chart in xtab cell and inherits its cube
// List<String> measureExprs = new ArrayList<String>( );
// for ( Iterator<ComputedColumnHandle> iter = ChartReportItemUtil.getBindingHolder( itemHandle )
// .getColumnBindings( )
// .iterator( ); iter.hasNext( ); )
// ComputedColumnHandle cch = iter.next( );
// if ( ChartXTabUtil.isMeasureExpresion( cch.getExpression( ) ) )
// measureExprs.add( ExpressionUtil.createJSDataExpression( cch.getName( ) ) );
// String[] valueExprs = measureExprs.toArray( new String[measureExprs.size( )] );
// getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
// null );
// getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
// null );
// getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
// valueExprs );
else
{
Iterator<ComputedColumnHandle> columnBindings = ChartXTabUtil.getAllColumnBindingsIterator( itemHandle );
List<String> levels = ChartXTabUtil.getAllLevelsBindingExpression( columnBindings );
String[] exprs = levels.toArray( new String[levels.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
exprs );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
exprs );
columnBindings = ChartXTabUtil.getAllColumnBindingsIterator( itemHandle );
List<String> measures = ChartXTabUtil.getAllMeasuresBindingExpression( columnBindings );
exprs = measures.toArray( new String[measures.size( )] );
getContext( ).addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
exprs );
}
}
}
// Fire event to update predefined queries in outside UI
fireEvent( btnBinding, EVENT_QUERY );
}
/**
* Update Y Optional expression with specified expression if current Y
* optional expression is null or empty.
*
* @param cm
* chart model.
* @param expr
* specified expression.
*/
private void updateYOptionalExpressions( Chart cm, String expr )
{
this.dataProvider.update( ChartUIConstants.QUERY_OPTIONAL, expr );
}
/**
* Update category expression with specified expression if current category
* expression is null or empty.
*
* @param cm
* chart model.
* @param expr
* specified expression.
*/
private void updateCategoryExpression( Chart cm, String expr )
{
this.dataProvider.update( ChartUIConstants.QUERY_CATEGORY, expr );
}
private void checkColBindingForCube( )
{
if ( getCube( ) != null
&& !ChartXTabUIUtil.checkColumnbindingForCube( DEUtil.getBindingColumnIterator( DEUtil.getBindingHolder( itemHandle ) ) ) )
{
ChartWizard.showException( ChartWizard.StaChartDSh_checCube_ID,
Messages.getString("StandardChartDataSheet.CheckCubeWarning") ); //$NON-NLS-1$
}
else
{
ChartWizard.removeException( ChartWizard.StaChartDSh_checCube_ID );
}
}
@Override
public ISelectDataCustomizeUI createCustomizeUI( ITask task )
{
return new SelectDataDynamicArea( task );
}
} |
package com.yahoo.vespa.hosted.controller.api.integration.configserver;
import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.NodeList;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.NodeMembership;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.NodeRepositoryNode;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.NodeState;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A minimal interface to the node repository, providing only the operations used by the controller.
*
* @author mpolden
*/
public interface NodeRepository {
void addNodes(ZoneId zone, Collection<NodeRepositoryNode> nodes);
void deleteNode(ZoneId zone, String hostname);
void setState(ZoneId zone, NodeState nodeState, String nodename);
NodeRepositoryNode getNode(ZoneId zone, String hostname);
NodeList listNodes(ZoneId zone);
NodeList listNodes(ZoneId zone, ApplicationId application);
/** List all nodes in given zone */
default List<Node> list(ZoneId zone) {
return listNodes(zone).nodes().stream()
.map(NodeRepository::toNode)
.collect(Collectors.toUnmodifiableList());
}
/** List all nodes in zone owned by given application */
default List<Node> list(ZoneId zone, ApplicationId application) {
return listNodes(zone, application).nodes().stream()
.map(NodeRepository::toNode)
.collect(Collectors.toUnmodifiableList());
}
/** List all nodes in states, in zone owned by given application */
default List<Node> list(ZoneId zone, ApplicationId application, Set<Node.State> states) {
return list(zone, application).stream()
.filter(node -> states.contains(node.state()))
.collect(Collectors.toList());
}
/** Upgrade all nodes of given type to a new version */
void upgrade(ZoneId zone, NodeType type, Version version);
/** Upgrade OS for all nodes of given type to a new version */
void upgradeOs(ZoneId zone, NodeType type, Version version);
/** Requests firmware checks on all hosts in the given zone. */
void requestFirmwareCheck(ZoneId zone);
/** Cancels firmware checks on all hosts in the given zone. */
void cancelFirmwareCheck(ZoneId zone);
private static Node toNode(NodeRepositoryNode node) {
var application = Optional.ofNullable(node.getOwner())
.map(owner -> ApplicationId.from(owner.getTenant(), owner.getApplication(),
owner.getInstance()));
return new Node(com.yahoo.config.provision.HostName.from(node.getHostname()),
fromJacksonState(node.getState()),
fromJacksonType(node.getType()),
application,
versionFrom(node.getVespaVersion()),
versionFrom(node.getWantedVespaVersion()),
versionFrom(node.getCurrentOsVersion()),
versionFrom(node.getWantedOsVersion()),
fromBoolean(node.getAllowedToBeDown()),
toInt(node.getCurrentRestartGeneration()),
toInt(node.getRestartGeneration()),
toInt(node.getCurrentRebootGeneration()),
toInt(node.getRebootGeneration()),
toDouble(node.getMinCpuCores()),
toDouble(node.getMinMainMemoryAvailableGb()),
toDouble(node.getMinDiskAvailableGb()),
toDouble(node.getBandwidthGbps()),
toBoolean(node.getFastDisk()),
toInt(node.getCost()),
node.getCanonicalFlavor(),
clusterIdOf(node.getMembership()),
clusterTypeOf(node.getMembership()));
}
private static String clusterIdOf(NodeMembership nodeMembership) {
return nodeMembership == null ? "" : nodeMembership.clusterid;
}
private static Node.ClusterType clusterTypeOf(NodeMembership nodeMembership) {
if (nodeMembership == null) return Node.ClusterType.unknown;
switch (nodeMembership.clustertype) {
case "admin": return Node.ClusterType.admin;
case "content": return Node.ClusterType.content;
case "container": return Node.ClusterType.container;
}
return Node.ClusterType.unknown;
}
// Convert Jackson type to config.provision type
private static NodeType fromJacksonType(com.yahoo.vespa.hosted.controller.api.integration.noderepository.NodeType nodeType) {
switch (nodeType) {
case tenant: return NodeType.tenant;
case host: return NodeType.host;
case proxy: return NodeType.proxy;
case proxyhost: return NodeType.proxyhost;
case config: return NodeType.config;
case confighost: return NodeType.confighost;
default: throw new IllegalArgumentException("Unknown type: " + nodeType);
}
}
private static com.yahoo.vespa.hosted.controller.api.integration.configserver.Node.State fromJacksonState(NodeState state) {
switch (state) {
case provisioned: return Node.State.provisioned;
case ready: return Node.State.ready;
case reserved: return Node.State.reserved;
case active: return Node.State.active;
case inactive: return Node.State.inactive;
case dirty: return Node.State.dirty;
case failed: return Node.State.failed;
case parked: return Node.State.parked;
}
return Node.State.unknown;
}
private static Node.ServiceState fromBoolean(Boolean allowedDown) {
return (allowedDown == null)
? Node.ServiceState.unorchestrated
: allowedDown ? Node.ServiceState.allowedDown : Node.ServiceState.expectedUp;
}
private static boolean toBoolean(Boolean b) {
return b == null ? false : b;
}
private static double toDouble(Double d) {
return d == null ? 0 : d;
}
private static int toInt(Integer i) {
return i == null ? 0 : i;
}
private static Version versionFrom(String s) {
return s == null ? Version.emptyVersion : Version.fromString(s);
}
} |
package org.datavaultplatform.webapp.controllers.admin;
import java.security.Principal;
import org.datavaultplatform.common.model.*;
import org.datavaultplatform.common.request.CreateVault;
import org.datavaultplatform.common.request.CreateRetentionPolicy;
import org.datavaultplatform.common.response.VaultInfo;
import org.datavaultplatform.common.response.VaultsData;
import org.datavaultplatform.webapp.services.RestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.RequestParam;
@Controller
public class AdminPendingVaultsController {
private static final Logger logger = LoggerFactory.getLogger(AdminPendingVaultsController.class);
private static final int MAX_RECORDS_PER_PAGE = 10;
private RestService restService;
public void setRestService(RestService restService) {
this.restService = restService;
}
@RequestMapping(value = "/admin/pendingVaults", method = RequestMethod.GET)
public String searchPendingVaults(ModelMap model,
@RequestParam(value = "query", defaultValue = "") String query,
@RequestParam(value = "sort", defaultValue = "creationTime") String sort,
@RequestParam(value = "order", defaultValue = "desc") String order,
@RequestParam(value = "pageId", defaultValue = "1") int pageId) throws Exception {
model.addAttribute("activePageId", pageId);
// calculate offset which is passed to the service to fetch records from that row Id
int offset = (pageId-1) * MAX_RECORDS_PER_PAGE;
VaultsData savedVaultsData = restService.searchPendingVaults(query, sort, order, offset, MAX_RECORDS_PER_PAGE, false);
VaultsData confirmedVaultsData = restService.searchPendingVaults(query, sort, order, offset, MAX_RECORDS_PER_PAGE, true);
int savedRecordsTotal = savedVaultsData.getRecordsFiltered();
int confirmedRecordsTotal = confirmedVaultsData.getRecordsFiltered();
model.addAttribute("savedVaultsTotal", savedRecordsTotal);
model.addAttribute("confirmedVaultsTotal", confirmedRecordsTotal);
return "admin/pendingVaults/index";
}
@RequestMapping(value = "/admin/pendingVaults/saved", method = RequestMethod.GET)
public String searchSavedPendingVaults(ModelMap model,
@RequestParam(value = "query", defaultValue = "") String query,
@RequestParam(value = "sort", defaultValue = "creationTime") String sort,
@RequestParam(value = "order", defaultValue = "desc") String order,
@RequestParam(value = "pageId", defaultValue = "1") int pageId) throws Exception {
model.addAttribute("activePageId", pageId);
// calculate offset which is passed to the service to fetch records from that row Id
int offset = (pageId-1) * MAX_RECORDS_PER_PAGE;
VaultsData filteredVaultsData = restService.searchPendingVaults(query, sort, order, offset, MAX_RECORDS_PER_PAGE, false);
int filteredRecordsTotal = filteredVaultsData.getRecordsFiltered();
this.createModelMap(model,filteredRecordsTotal, filteredVaultsData, query, offset, sort, order);
return "admin/pendingVaults/saved";
}
@RequestMapping(value = "/admin/pendingVaults/confirmed", method = RequestMethod.GET)
public String searchConfirmedPendingVaults(ModelMap model,
@RequestParam(value = "query", defaultValue = "") String query,
@RequestParam(value = "sort", defaultValue = "creationTime") String sort,
@RequestParam(value = "order", defaultValue = "desc") String order,
@RequestParam(value = "pageId", defaultValue = "1") int pageId) throws Exception {
model.addAttribute("activePageId", pageId);
// calculate offset which is passed to the service to fetch records from that row Id
int offset = (pageId-1) * MAX_RECORDS_PER_PAGE;
VaultsData filteredVaultsData = restService.searchPendingVaults(query, sort, order, offset, MAX_RECORDS_PER_PAGE, true);
int filteredRecordsTotal = filteredVaultsData.getRecordsFiltered();
this.createModelMap(model,filteredRecordsTotal, filteredVaultsData, query, offset, sort, order);
return "admin/pendingVaults/confirmed";
}
private ModelMap createModelMap(ModelMap model, int filteredRecordsTotal, VaultsData filteredVaultsData,
String query, int offset, String sort, String order) {
int numberOfPages = (int)Math.ceil((double)filteredRecordsTotal/MAX_RECORDS_PER_PAGE);
model.addAttribute("numberOfPages", numberOfPages);
model.addAttribute("pendingVaults", filteredVaultsData.getData());
model.addAttribute("query", query);
boolean isFiltered = query != null && !query.equals("");
model.addAttribute("recordsInfo",
constructTableRecordsInfo(
offset,
filteredVaultsData.getRecordsTotal(),
filteredRecordsTotal,
filteredVaultsData.getData().size(),
isFiltered
) );
// Pass the sort and order
if (sort == null) sort = "";
model.addAttribute("sort", sort);
model.addAttribute("order", order);
String otherOrder = order.equals("asc")?"desc":"asc";
model.addAttribute("ordername", "name".equals(sort)?otherOrder:"asc");
return model;
}
@RequestMapping(value = "/admin/pendingVaults/summary/{pendingVaultId}", method = RequestMethod.GET)
public String getVault(ModelMap model, @PathVariable("pendingVaultId") String vaultID, Principal principal) {
logger.info("VaultID:'" + vaultID + "'");
VaultInfo pendingVault = restService.getPendingVault(vaultID);
logger.info("pendingVault.id:'" + pendingVault.getID() + "'");
model.addAttribute("pendingVault", pendingVault);
CreateRetentionPolicy createRetentionPolicy = null;
if (pendingVault.getPolicyID() != null) {
createRetentionPolicy = restService.getRetentionPolicy(pendingVault.getPolicyID());
}
model.addAttribute("createRetentionPolicy", createRetentionPolicy);
Group group = restService.getGroup(pendingVault.getGroupID());
model.addAttribute("group", group);
return "admin/pendingVaults/summary";
}
@RequestMapping(value = "/admin/pendingVaults/upgrade/{pendingVaultId}", method = RequestMethod.GET)
public String upgradeVault(@PathVariable("pendingVaultId") String pendingVaultID) {
// need to either pass in create vault or get vaultnfo from the pending id param
// and convert it to create vault object like in VaultController.getPendingVault
VaultInfo pendingVault = restService.getPendingVault(pendingVaultID);
CreateVault cv = pendingVault.convertToCreate();
logger.info("Attempting to upgrade pending vault to full vault");
VaultInfo newVault = restService.addVault(cv);
logger.info("Completed upgrading pending vault to full vault");
//need to add full vault datacreators, roles etc.
// any other new info too pure stuff billing etc.
// then delete the pending vault
restService.deletePendingVault(cv.getPendingID());
String vaultUrl = "/vaults/" + newVault.getID() + "/";
return "redirect:" + vaultUrl;
}
/*
@RequestMapping(value = "/admin/pendingVaults/addVault/{pendingVaultId}", method = RequestMethod.GET)
public String addVault(@PathVariable("pendingVaultId") String pendingVaultID,
@RequestParam("reviewDate") String reviewDateString) {
logger.info("pendingVaultID: " + pendingVaultID);
logger.info("reviewDateString: " + reviewDateString);
try {
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date reviewDate = new SimpleDateFormat("dd-MMM-yyy").parse(reviewDateString);
boolean vaultAdded = restService.addVaultForPendingVault(pendingVaultID, reviewDate);
logger.info("vaultAdded: " + vaultAdded);
} catch(ParseException pe ) {
logger.info("Parse error: " + pe);
}
// if ("cancel".equals(action)) {
// return "redirect:/admin/pendingVaults";
// }
return "redirect:/admin/pendingVaults";
}
*/
/*
@RequestMapping(value = "/admin/pendingVaults/delete/{pendingVaultId}", method = RequestMethod.GET)
public String deletePendingVault(@PathVariable("pendingVaultId") String pendingVaultID) {
logger.info("pendingVaultID: " + pendingVaultID);
PendingVault pendingVault = restService.getPendingVaultRecord(vaultID);
model.addAttribute("pendingVault", pendingVault);
return "redirect:/admin/pendingVaults";
}*/
@RequestMapping(value = "/admin/pendingVaults/{pendingVaultID}", method = RequestMethod.GET)
public String deletePendingVault(ModelMap model, @PathVariable("pendingVaultID") String pendingVaultID) throws Exception {
restService.deletePendingVault(pendingVaultID);
return "redirect:/admin/pendingVaults";
}
private String constructTableRecordsInfo(int offset, int recordsTotal, int filteredRecords, int numberOfRecordsonPage, boolean isFiltered) {
StringBuilder recordsInfo = new StringBuilder();
recordsInfo.append("Showing ").append(offset + 1).append(" - ").append(offset + numberOfRecordsonPage);
if(isFiltered) {
recordsInfo.append(" pending vaults of ").append(filteredRecords)
.append(" (").append("filtered from ").append(recordsTotal).append(" total pending vaults)");
} else {
recordsInfo.append(" pending vaults of ").append(recordsTotal);
}
return recordsInfo.toString();
}
} |
package org.geomajas.puregwt.client.map.layer;
import java.util.ArrayList;
import java.util.List;
import org.geomajas.configuration.client.ClientLayerInfo;
import org.geomajas.configuration.client.ClientMapInfo;
import org.geomajas.configuration.client.ClientRasterLayerInfo;
import org.geomajas.configuration.client.ClientVectorLayerInfo;
import org.geomajas.puregwt.client.event.LayerAddedEvent;
import org.geomajas.puregwt.client.event.LayerDeselectedEvent;
import org.geomajas.puregwt.client.event.LayerOrderChangedEvent;
import org.geomajas.puregwt.client.event.LayerRemovedEvent;
import org.geomajas.puregwt.client.event.LayerSelectedEvent;
import org.geomajas.puregwt.client.event.LayerSelectionHandler;
import org.geomajas.puregwt.client.map.MapEventBus;
import org.geomajas.puregwt.client.map.ViewPort;
import com.google.inject.Inject;
/**
* Default implementation of the {@link LayersModel} interface.
*
* @author Pieter De Graef
*/
public final class LayersModelImpl implements LayersModel {
private ClientMapInfo mapInfo;
private ViewPort viewPort;
private MapEventBus eventBus;
/**
* An ordered list of layers. The drawing order on the map is as follows: the first layer will be placed at the
* bottom, the last layer on top.
*/
private List<Layer> layers = new ArrayList<Layer>();
@Inject
private LayerFactory layerFactory;
// Constructors:
@Inject
private LayersModelImpl() {
}
// MapModel implementation:
/**
* Initialization method for the layers model.
*
* @param mapInfo
* The configuration object from which this model should build itself.
* @param viewPort
* The view port that is associated with the same map this layer model belongs to.
* @param eventBus
* Event bus that governs all event related to this layers model.
*/
public void initialize(ClientMapInfo mapInfo, ViewPort viewPort, MapEventBus eventBus) {
this.mapInfo = mapInfo;
this.viewPort = viewPort;
this.eventBus = eventBus;
// Add a layer selection handler that allows only one selected layer at a time:
eventBus.addLayerSelectionHandler(new LayerSelectionHandler() {
public void onSelectLayer(LayerSelectedEvent event) {
for (Layer layer : layers) {
if (layer.isSelected() && !layer.equals(event.getLayer())) {
layer.setSelected(false);
}
}
}
public void onDeselectLayer(LayerDeselectedEvent event) {
}
});
// Create all the layers:
layers = new ArrayList<Layer>();
for (ClientLayerInfo layerInfo : mapInfo.getLayers()) {
Layer layer = createLayer(layerInfo);
addLayer(layer);
}
}
/** {@inheritDoc} */
public boolean addLayer(Layer layer) {
if (layer == null) {
throw new IllegalArgumentException("Layer is null.");
}
if (getLayer(layer.getId()) == null) {
layers.add(layer);
if (layer instanceof AbstractLayer) {
AbstractLayer aLayer = (AbstractLayer) layer;
aLayer.setViewPort(viewPort);
aLayer.setEventBus(eventBus);
}
eventBus.fireEvent(new LayerAddedEvent(layer));
return true;
}
return false;
}
private Layer createLayer(ClientLayerInfo layerInfo) {
ServerLayer<?> layer = null;
switch (layerInfo.getLayerType()) {
case RASTER:
layer = layerFactory.createRasterLayer((ClientRasterLayerInfo) layerInfo, viewPort, eventBus);
break;
default:
layer = layerFactory.createVectorLayer((ClientVectorLayerInfo) layerInfo, viewPort, eventBus);
break;
}
if (!mapInfo.getLayers().contains(layer.getLayerInfo())) {
mapInfo.getLayers().add(layer.getLayerInfo());
}
return layer;
}
public boolean removeLayer(String id) {
Layer layer = getLayer(id);
if (layer != null) {
int index = getLayerPosition(layer);
layers.remove(layer);
if (layer instanceof ServerLayer) {
ServerLayer<?> serverLayer = (ServerLayer<?>) layer;
mapInfo.getLayers().remove(serverLayer.getLayerInfo());
}
eventBus.fireEvent(new LayerRemovedEvent(layer, index));
return true;
}
return false;
}
/**
* Get a single layer by its identifier.
*
* @param id
* The layers unique identifier within this map.
* @return Returns the layer, or null if it could not be found.
*/
public Layer getLayer(String id) {
if (id == null) {
throw new IllegalArgumentException("Null ID passed to the getLayer method.");
}
for (Layer layer : layers) {
if (id.equals(layer.getId())) {
return layer;
}
}
return null;
}
/**
* Return the total number of layers within this map.
*
* @return The layer count.
*/
public int getLayerCount() {
return layers.size();
}
public boolean moveLayer(Layer layer, int index) {
int currentIndex = getLayerPosition(layer);
// Check the new index:
if (index < 0) {
index = 0;
} else if (index > layers.size() - 1) {
index = layers.size() - 1;
}
if (currentIndex < 0 || currentIndex == index) {
return false;
}
ClientLayerInfo layerInfo = null;
int newIndexMapInfo = -1;
// Check if both the layer with whom the specified layer will swap (concerning the ordering) and
// the specified layer are server layers. If so their position in the mapInfo.getLayers() must also be swapped
if (layer instanceof ServerLayer && layers.get(index) instanceof ServerLayer) {
ServerLayer<?> serverLayer = (ServerLayer<?>) layer;
layerInfo = serverLayer.getLayerInfo();
int idx = 0;
for (ClientLayerInfo layerInMapInfo : mapInfo.getLayers()) {
if (layerInMapInfo.getId().equals(layerInfo.getId())) {
if (index > currentIndex) {
newIndexMapInfo = idx + 1;
} else {
newIndexMapInfo = idx - 1;
}
break; // Stop when found
}
idx++;
}
}
// Index might have been altered; check again if it is really a change:
if (currentIndex == index) {
return false;
}
// First remove the layer from the list:
layers.remove(layer);
// Change the order:
layers.add(index, layer);
if (layerInfo != null && newIndexMapInfo >= 0) {
mapInfo.getLayers().remove(layerInfo); // remove from mapInfo.layers
mapInfo.getLayers().add(newIndexMapInfo, layerInfo); // put back (changed order)
}
// Send out the correct event:
eventBus.fireEvent(new LayerOrderChangedEvent(currentIndex, index));
return true;
}
public boolean moveLayerUp(Layer layer) {
return moveLayer(layer, getLayerPosition(layer) + 1);
}
public boolean moveLayerDown(Layer layer) {
return moveLayer(layer, getLayerPosition(layer) - 1);
}
/**
* Get the position of a certain layer in this map model.
*
* @param layer
* The layer to return the position for.
* @return Returns the position of the layer in the map. This position determines layer order. If the layer was not
* found, than -1 is returned.
*/
public int getLayerPosition(Layer layer) {
if (layer == null) {
throw new IllegalArgumentException("Null value passed to the getLayerPosition method.");
}
for (int i = 0; i < layers.size(); i++) {
if (layer.getId().equals(layers.get(i).getId())) {
return i;
}
}
return -1;
}
/**
* Return the layer at a certain index. If the index can't be found, null is returned.
*
* @param index
* The specified index.
* @return Returns the layer, or null if the index can't be found.
*/
public Layer getLayer(int index) {
return layers.get(index);
}
/**
* Return the currently selected layer within this map model.
*
* @return Returns the selected layer, or null if no layer is selected.
*/
public Layer getSelectedLayer() {
if (layers != null) {
for (Layer layer : layers) {
if (layer.isSelected()) {
return layer;
}
}
}
return null;
}
} |
package org.jfree.chart.annotations;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.jfree.chart.axis.CategoryAnchor;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.util.HashUtilities;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleEdge;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.category.CategoryDataset;
/**
* A line annotation that can be placed on a {@link CategoryPlot}.
*/
public class CategoryLineAnnotation implements CategoryAnnotation,
Cloneable, PublicCloneable, Serializable {
/** For serialization. */
static final long serialVersionUID = 3477740483341587984L;
/** The category for the start of the line. */
private Comparable category1;
/** The value for the start of the line. */
private double value1;
/** The category for the end of the line. */
private Comparable category2;
/** The value for the end of the line. */
private double value2;
/** The line color. */
private transient Paint paint = Color.black;
/** The line stroke. */
private transient Stroke stroke = new BasicStroke(1.0f);
/**
* Creates a new annotation that draws a line between (category1, value1)
* and (category2, value2).
*
* @param category1 the category (<code>null</code> not permitted).
* @param value1 the value.
* @param category2 the category (<code>null</code> not permitted).
* @param value2 the value.
* @param paint the line color (<code>null</code> not permitted).
* @param stroke the line stroke (<code>null</code> not permitted).
*/
public CategoryLineAnnotation(Comparable category1, double value1,
Comparable category2, double value2,
Paint paint, Stroke stroke) {
if (category1 == null) {
throw new IllegalArgumentException("Null 'category1' argument.");
}
if (category2 == null) {
throw new IllegalArgumentException("Null 'category2' argument.");
}
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.category1 = category1;
this.value1 = value1;
this.category2 = category2;
this.value2 = value2;
this.paint = paint;
this.stroke = stroke;
}
/**
* Returns the category for the start of the line.
*
* @return The category for the start of the line (never <code>null</code>).
*
* @see #setCategory1(Comparable)
*/
public Comparable getCategory1() {
return this.category1;
}
/**
* Sets the category for the start of the line.
*
* @param category the category (<code>null</code> not permitted).
*
* @see #getCategory1()
*/
public void setCategory1(Comparable category) {
if (category == null) {
throw new IllegalArgumentException("Null 'category' argument.");
}
this.category1 = category;
}
/**
* Returns the y-value for the start of the line.
*
* @return The y-value for the start of the line.
*
* @see #setValue1(double)
*/
public double getValue1() {
return this.value1;
}
/**
* Sets the y-value for the start of the line.
*
* @param value the value.
*
* @see #getValue1()
*/
public void setValue1(double value) {
this.value1 = value;
}
/**
* Returns the category for the end of the line.
*
* @return The category for the end of the line (never <code>null</code>).
*
* @see #setCategory2(Comparable)
*/
public Comparable getCategory2() {
return this.category2;
}
/**
* Sets the category for the end of the line.
*
* @param category the category (<code>null</code> not permitted).
*
* @see #getCategory2()
*/
public void setCategory2(Comparable category) {
if (category == null) {
throw new IllegalArgumentException("Null 'category' argument.");
}
this.category2 = category;
}
/**
* Returns the y-value for the end of the line.
*
* @return The y-value for the end of the line.
*
* @see #setValue2(double)
*/
public double getValue2() {
return this.value2;
}
/**
* Sets the y-value for the end of the line.
*
* @param value the value.
*
* @see #getValue2()
*/
public void setValue2(double value) {
this.value2 = value;
}
/**
* Returns the paint used to draw the connecting line.
*
* @return The paint (never <code>null</code>).
*
* @see #setPaint(Paint)
*/
public Paint getPaint() {
return this.paint;
}
/**
* Sets the paint used to draw the connecting line.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPaint()
*/
public void setPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.paint = paint;
}
/**
* Returns the stroke used to draw the connecting line.
*
* @return The stroke (never <code>null</code>).
*
* @see #setStroke(Stroke)
*/
public Stroke getStroke() {
return this.stroke;
}
/**
* Sets the stroke used to draw the connecting line.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getStroke()
*/
public void setStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.stroke = stroke;
}
/**
* Draws the annotation.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param dataArea the data area.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param rendererIndex the renderer index.
* @param info the plot info (<code>null</code> permitted).
*/
public void draw(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea,
CategoryAxis domainAxis, ValueAxis rangeAxis,
int rendererIndex, PlotRenderingInfo info) {
CategoryDataset dataset = plot.getDataset();
int catIndex1 = dataset.getColumnIndex(this.category1);
int catIndex2 = dataset.getColumnIndex(this.category2);
int catCount = dataset.getColumnCount();
double lineX1 = 0.0f;
double lineY1 = 0.0f;
double lineX2 = 0.0f;
double lineY2 = 0.0f;
PlotOrientation orientation = plot.getOrientation();
RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(
plot.getDomainAxisLocation(), orientation);
RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(
plot.getRangeAxisLocation(), orientation);
if (orientation == PlotOrientation.HORIZONTAL) {
lineY1 = domainAxis.getCategoryJava2DCoordinate(
CategoryAnchor.MIDDLE, catIndex1, catCount, dataArea,
domainEdge);
lineX1 = rangeAxis.valueToJava2D(this.value1, dataArea, rangeEdge);
lineY2 = domainAxis.getCategoryJava2DCoordinate(
CategoryAnchor.MIDDLE, catIndex2, catCount, dataArea,
domainEdge);
lineX2 = rangeAxis.valueToJava2D(this.value2, dataArea, rangeEdge);
}
else if (orientation == PlotOrientation.VERTICAL) {
lineX1 = domainAxis.getCategoryJava2DCoordinate(
CategoryAnchor.MIDDLE, catIndex1, catCount, dataArea,
domainEdge);
lineY1 = rangeAxis.valueToJava2D(this.value1, dataArea, rangeEdge);
lineX2 = domainAxis.getCategoryJava2DCoordinate(
CategoryAnchor.MIDDLE, catIndex2, catCount, dataArea,
domainEdge);
lineY2 = rangeAxis.valueToJava2D(this.value2, dataArea, rangeEdge);
}
g2.setPaint(this.paint);
g2.setStroke(this.stroke);
g2.drawLine((int) lineX1, (int) lineY1, (int) lineX2, (int) lineY2);
}
/**
* Tests this object for equality with another.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CategoryLineAnnotation)) {
return false;
}
CategoryLineAnnotation that = (CategoryLineAnnotation) obj;
if (!this.category1.equals(that.getCategory1())) {
return false;
}
if (this.value1 != that.getValue1()) {
return false;
}
if (!this.category2.equals(that.getCategory2())) {
return false;
}
if (this.value2 != that.getValue2()) {
return false;
}
if (!PaintUtilities.equal(this.paint, that.paint)) {
return false;
}
if (!ObjectUtilities.equal(this.stroke, that.stroke)) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
public int hashCode() {
int result = 193;
result = 37 * result + this.category1.hashCode();
long temp = Double.doubleToLongBits(this.value1);
result = 37 * result + (int) (temp ^ (temp >>> 32));
result = 37 * result + this.category2.hashCode();
temp = Double.doubleToLongBits(this.value2);
result = 37 * result + (int) (temp ^ (temp >>> 32));
result = 37 * result + HashUtilities.hashCodeForPaint(this.paint);
result = 37 * result + this.stroke.hashCode();
return result;
}
/**
* Returns a clone of the annotation.
*
* @return A clone.
*
* @throws CloneNotSupportedException this class will not throw this
* exception, but subclasses (if any) might.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.paint, stream);
SerialUtilities.writeStroke(this.stroke, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.paint = SerialUtilities.readPaint(stream);
this.stroke = SerialUtilities.readStroke(stream);
}
} |
package org.geomajas.puregwt.example.base.client;
import org.geomajas.geometry.Bbox;
import org.geomajas.puregwt.example.base.client.page.sample.SamplePage;
import org.geomajas.puregwt.example.base.client.resource.ShowcaseResource;
import org.geomajas.puregwt.example.base.client.sample.ShowcaseSampleDefinition;
import org.geomajas.puregwt.example.base.client.widget.ShowcaseDialogBox;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.inject.client.Ginjector;
import com.google.gwt.user.client.Window;
/**
* Entry point and main class for PureGWT example application.
*
* @author Pieter De Graef
*/
public class ExampleBase implements EntryPoint {
// private static final GeomajasGinjector GEOMAJASINJECTOR = GWT.create(GeomajasGinjector.class);
private static Ginjector ginjector;
private static final ShowcaseResource RESOURCE = GWT.create(ShowcaseResource.class);
private static final ShowcaseLayout LAYOUT = new ShowcaseLayout();
public static final Bbox BBOX_ITALY = new Bbox(868324, 4500612, 1174072, 1174072);
public static final Bbox BBOX_AFRICA = new Bbox(-2915614, -4324501, 9392582, 9392582);
public void onModuleLoad() {
// Prepare styling:
RESOURCE.css().ensureInjected();
}
public static ShowcaseLayout getLayout() {
return LAYOUT;
}
public static Ginjector getInjector() {
return ginjector;
}
public static void setInjector(Ginjector injector) {
ginjector = injector;
}
public static ShowcaseResource getShowcaseResource() {
return RESOURCE;
}
public static void showSample(ShowcaseSampleDefinition sample) {
ShowcaseDialogBox dialogBox = new ShowcaseDialogBox();
dialogBox.setAnimationEnabled(true);
dialogBox.setAutoHideEnabled(false);
dialogBox.setModal(true);
dialogBox.setGlassEnabled(true);
dialogBox.setText(sample.getTitle());
SamplePage page = new SamplePage();
int width = Window.getClientWidth() - 200;
int height = Window.getClientHeight() - 160;
page.setSize(width + "px", height + "px");
page.setSamplePanelFactory(sample);
dialogBox.setWidget(page);
dialogBox.center();
dialogBox.show();
}
} |
package org.fedorahosted.flies.adapter.properties;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.fedorahosted.flies.LocaleId;
import org.fedorahosted.flies.rest.dto.Document;
import org.fedorahosted.flies.rest.dto.Resource;
import org.fedorahosted.flies.rest.dto.SimpleComment;
import org.fedorahosted.flies.rest.dto.TextFlow;
import org.fedorahosted.flies.rest.dto.TextFlowTarget;
import org.fedorahosted.flies.rest.dto.TextFlowTarget.ContentState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
/**
* A PropReader. NOT THREADSAFE.
*
* @author <a href="mailto:sflaniga@redhat.com">Sean Flanigan</a>
* @version $Revision: 1.1 $
*/
public class PropReader {
public static final String PROP_CONTENT_TYPE = "text/plain";
private static final Logger log = LoggerFactory.getLogger(PropReader.class);
// private final MessageDigest md5;
// public PropReader() {
// try {
// this.md5 = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
public void extractAll(Document doc, File basePropertiesFile,
String[] locales) throws IOException {
InputStream baseInput = new BufferedInputStream(
new FileInputStream(basePropertiesFile));
try {
// System.out.println("processing base " + basePropertiesFile);
extractTemplate(doc, new InputSource(baseInput));
for (String locale : locales) {
File localeFile = new File(dropExtension(basePropertiesFile
.toString())
+ "_" + locale + ".properties");
if (!localeFile.exists())
continue;
// System.out.println("processing " + localeFile);
InputStream localeInput = new BufferedInputStream(new FileInputStream(localeFile));
try {
extractTarget(doc, new InputSource(localeInput), new LocaleId(
locale));
} finally {
localeInput.close();
}
}
} finally {
baseInput.close();
}
}
private String dropExtension(String f) {
return f.substring(0, f.length() - ".properties".length());
}
// pre: template already extracted
public void extractTarget(Document doc, InputSource inputSource,
LocaleId localeId) throws IOException {
Map<String, TextFlow> textFlowMap = new HashMap<String, TextFlow>();
for (Resource resource : doc.getResources(true)) {
if (resource instanceof TextFlow) {
TextFlow textFlow = (TextFlow) resource;
textFlowMap.put(textFlow.getId(), textFlow);
}
}
Properties props = loadProps(inputSource);
for (String key : props.stringPropertyNames()) {
String val = props.getProperty(key);
String id = getID(key, val);
TextFlow textFlow = textFlowMap.get(id);
if (textFlow == null) {
log.warn("Property with key {} in locale {} has no corresponding source in {}",
new Object[]{key, localeId, doc.getId()});
continue;
}
TextFlowTarget textFlowTarget = new TextFlowTarget(); // TODO might
// need id,
// version
textFlowTarget.setContent(val);
textFlowTarget.setId(id);
textFlowTarget.setLang(localeId);
textFlowTarget.setState(ContentState.New);
// textFlowTarget.setVersion(version)
textFlow.addTarget(textFlowTarget);
}
}
// TODO allowing Readers (via InputSource) might be a bad idea
public void extractTemplate(Document doc, InputSource inputSource)
throws IOException {
List<Resource> resources = doc.getResources(true);
Properties props = loadProps(inputSource);
for (String key : props.stringPropertyNames()) {
String val = props.getProperty(key);
String id = getID(key, val);
TextFlow textFlow = new TextFlow(id);
textFlow.setContent(val);
// FIXME fix OpenProps, then put this in:
// textFlow.getComments().getComments().add(new SimpleComment(null, props.getComment(key)));
// textFlow.setLang(LocaleId.EN);
resources.add(textFlow);
}
}
// private String generateHash(String key){
// try {
// md5.reset();
// return new String(Hex.encodeHex(md5.digest(key.getBytes("UTF-8"))));
// } catch (Exception exc) {
// throw new RuntimeException(exc);
private String getID(String key, String val) {
// return generateHash(val); // TODO or just use key??
return key;
}
private Properties loadProps(InputSource inputSource) throws IOException {
Properties props = new Properties();
InputStream byteStream = inputSource.getByteStream();
// NB unlike SAX, we prefer the bytestream over the charstream
if (byteStream != null) {
props.load(byteStream);
} else {
Reader reader = inputSource.getCharacterStream();
props.load(reader);
}
return props;
}
} |
package org.apache.batik.refimpl.transcoder;
import java.awt.Color;
import org.apache.batik.util.awt.image.codec.PNGImageEncoder;
import org.apache.batik.util.awt.image.codec.PNGEncodeParam;
import org.apache.batik.util.awt.image.codec.ImageEncoder;
import org.apache.batik.transcoder.TranscodingHints;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.SinglePixelPackedSampleModel;
import java.io.IOException;
import java.io.OutputStream;
/**
* An <tt>ImageTranscoder</tt> that produces a png image. The default
* background color is transparent.
*
* @author <a href="mailto:vincent.hardy@eng.sun.com">Vincent Hardy</a>
* @version $Id$
*/
public class PngTranscoder extends ImageTranscoder {
/**
* Constructs a new png transcoder.
*/
public PngTranscoder(){
}
/**
* Creates a new image of type ARGB with the specified dimension.
* @param w the width of the image
* @param h the height of the image
*/
public BufferedImage createImage(int w, int h) {
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
return bi;
}
/**
* Writes the specified image as a png to the specified ouput stream.
* @param img the image to write
* @param ostream the output stream where to write the image
*/
public void writeImage(BufferedImage img, OutputStream ostream)
throws IOException {
PNGEncodeParam.RGB params =
(PNGEncodeParam.RGB)PNGEncodeParam.getDefaultEncodeParam(img);
params.setBackgroundRGB(new int[] { 255, 255, 255 });
// This is a trick so that viewers which do not support
// the alpha channel will see a white background (and not
// a black one).
int w = img.getWidth(), h = img.getHeight();
DataBufferInt biDB = (DataBufferInt)img.getRaster().getDataBuffer();
int scanStride = ((SinglePixelPackedSampleModel)img.getSampleModel()).getScanlineStride();
int dbOffset = biDB.getOffset();
int pixels[] = biDB.getBankData()[0];
int p = dbOffset;
int adjust = scanStride - w;
int a=0, r=0, g=0, b=0, pel=0;
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
pel = pixels[p];
a = (pel >> 24) & 0xff;
r = (pel >> 16) & 0xff;
g = (pel >> 8 ) & 0xff;
b = pel & 0xff;
r = (255*(255 -a) + a*r)/255;
g = (255*(255 -a) + a*g)/255;
b = (255*(255 -a) + a*b)/255;
pixels[p++] =
(a<<24 & 0xff000000) |
(r<<16 & 0xff0000) |
(g<<8 & 0xff00) |
(b & 0xff);
}
p += adjust;
}
PNGImageEncoder pngEncoder = new PNGImageEncoder(ostream, params);
pngEncoder.encode(img);
}
/**
* Returns the png mime type <tt>image/png</tt>.
*/
public String getMimeType() {
return "image/png";
}
} |
package org.ovirt.engine.ui.uicommonweb.models.vms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.AddVmFromScratchParameters;
import org.ovirt.engine.core.common.action.AddVmFromTemplateParameters;
import org.ovirt.engine.core.common.action.AddVmTemplateParameters;
import org.ovirt.engine.core.common.action.AttachEntityToTagParameters;
import org.ovirt.engine.core.common.action.ChangeDiskCommandParameters;
import org.ovirt.engine.core.common.action.ChangeVMClusterParameters;
import org.ovirt.engine.core.common.action.HibernateVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmToServerParameters;
import org.ovirt.engine.core.common.action.MoveVmParameters;
import org.ovirt.engine.core.common.action.RemoveVmParameters;
import org.ovirt.engine.core.common.action.RunVmOnceParams;
import org.ovirt.engine.core.common.action.RunVmParams;
import org.ovirt.engine.core.common.action.ShutdownVmParameters;
import org.ovirt.engine.core.common.action.StopVmParameters;
import org.ovirt.engine.core.common.action.StopVmTypeEnum;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VmManagementParametersBase;
import org.ovirt.engine.core.common.action.VmOperationParameterBase;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.common.businessentities.MigrationSupport;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.businessentities.UsbPolicy;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.VmOsType;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VmType;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.queries.GetVmByVmIdParameters;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.ObservableCollection;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.searchbackend.SearchObjects;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Cloner;
import org.ovirt.engine.ui.uicommonweb.DataProvider;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.TagsEqualityComparer;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ISupportSystemTreeContext;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel;
import org.ovirt.engine.ui.uicommonweb.models.configure.ChangeCDModel;
import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel;
import org.ovirt.engine.ui.uicommonweb.models.tags.TagListModel;
import org.ovirt.engine.ui.uicommonweb.models.tags.TagModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.VmBaseListModel;
import org.ovirt.engine.ui.uicommonweb.models.userportal.AttachCdModel;
import org.ovirt.engine.ui.uicompat.Assembly;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.ResourceManager;
public class VmListModel extends VmBaseListModel<VM> implements ISupportSystemTreeContext
{
private UICommand privateNewServerCommand;
public UICommand getNewServerCommand()
{
return privateNewServerCommand;
}
private void setNewServerCommand(UICommand value)
{
privateNewServerCommand = value;
}
private UICommand privateNewDesktopCommand;
public UICommand getNewDesktopCommand()
{
return privateNewDesktopCommand;
}
private void setNewDesktopCommand(UICommand value)
{
privateNewDesktopCommand = value;
}
private UICommand privateEditCommand;
public UICommand getEditCommand()
{
return privateEditCommand;
}
private void setEditCommand(UICommand value)
{
privateEditCommand = value;
}
private UICommand privateRemoveCommand;
public UICommand getRemoveCommand()
{
return privateRemoveCommand;
}
private void setRemoveCommand(UICommand value)
{
privateRemoveCommand = value;
}
private UICommand privateRunCommand;
public UICommand getRunCommand()
{
return privateRunCommand;
}
private void setRunCommand(UICommand value)
{
privateRunCommand = value;
}
private UICommand privatePauseCommand;
public UICommand getPauseCommand()
{
return privatePauseCommand;
}
private void setPauseCommand(UICommand value)
{
privatePauseCommand = value;
}
private UICommand privateStopCommand;
public UICommand getStopCommand()
{
return privateStopCommand;
}
private void setStopCommand(UICommand value)
{
privateStopCommand = value;
}
private UICommand privateShutdownCommand;
public UICommand getShutdownCommand()
{
return privateShutdownCommand;
}
private void setShutdownCommand(UICommand value)
{
privateShutdownCommand = value;
}
private UICommand privateCancelMigrateCommand;
public UICommand getCancelMigrateCommand() {
return privateCancelMigrateCommand;
}
private void setCancelMigrateCommand(UICommand value) {
privateCancelMigrateCommand = value;
}
private UICommand privateMigrateCommand;
public UICommand getMigrateCommand()
{
return privateMigrateCommand;
}
private void setMigrateCommand(UICommand value)
{
privateMigrateCommand = value;
}
private UICommand privateNewTemplateCommand;
public UICommand getNewTemplateCommand()
{
return privateNewTemplateCommand;
}
private void setNewTemplateCommand(UICommand value)
{
privateNewTemplateCommand = value;
}
private UICommand privateRunOnceCommand;
public UICommand getRunOnceCommand()
{
return privateRunOnceCommand;
}
private void setRunOnceCommand(UICommand value)
{
privateRunOnceCommand = value;
}
private UICommand privateExportCommand;
public UICommand getExportCommand()
{
return privateExportCommand;
}
private void setExportCommand(UICommand value)
{
privateExportCommand = value;
}
private UICommand privateMoveCommand;
public UICommand getMoveCommand()
{
return privateMoveCommand;
}
private void setMoveCommand(UICommand value)
{
privateMoveCommand = value;
}
private UICommand privateRetrieveIsoImagesCommand;
public UICommand getRetrieveIsoImagesCommand()
{
return privateRetrieveIsoImagesCommand;
}
private void setRetrieveIsoImagesCommand(UICommand value)
{
privateRetrieveIsoImagesCommand = value;
}
private UICommand privateGuideCommand;
public UICommand getGuideCommand()
{
return privateGuideCommand;
}
private void setGuideCommand(UICommand value)
{
privateGuideCommand = value;
}
private UICommand privateChangeCdCommand;
public UICommand getChangeCdCommand()
{
return privateChangeCdCommand;
}
private void setChangeCdCommand(UICommand value)
{
privateChangeCdCommand = value;
}
private UICommand privateAssignTagsCommand;
public UICommand getAssignTagsCommand()
{
return privateAssignTagsCommand;
}
private void setAssignTagsCommand(UICommand value)
{
privateAssignTagsCommand = value;
}
private Model errorWindow;
public Model getErrorWindow()
{
return errorWindow;
}
public void setErrorWindow(Model value)
{
if (errorWindow != value)
{
errorWindow = value;
OnPropertyChanged(new PropertyChangedEventArgs("ErrorWindow")); //$NON-NLS-1$
}
}
private ConsoleModel defaultConsoleModel;
public ConsoleModel getDefaultConsoleModel()
{
return defaultConsoleModel;
}
public void setDefaultConsoleModel(ConsoleModel value)
{
if (defaultConsoleModel != value)
{
defaultConsoleModel = value;
OnPropertyChanged(new PropertyChangedEventArgs("DefaultConsoleModel")); //$NON-NLS-1$
}
}
private ConsoleModel additionalConsoleModel;
public ConsoleModel getAdditionalConsoleModel()
{
return additionalConsoleModel;
}
public void setAdditionalConsoleModel(ConsoleModel value)
{
if (additionalConsoleModel != value)
{
additionalConsoleModel = value;
OnPropertyChanged(new PropertyChangedEventArgs("AdditionalConsoleModel")); //$NON-NLS-1$
}
}
private boolean hasAdditionalConsoleModel;
public boolean getHasAdditionalConsoleModel()
{
return hasAdditionalConsoleModel;
}
public void setHasAdditionalConsoleModel(boolean value)
{
if (hasAdditionalConsoleModel != value)
{
hasAdditionalConsoleModel = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasAdditionalConsoleModel")); //$NON-NLS-1$
}
}
public ObservableCollection<ChangeCDModel> isoImages;
public ObservableCollection<ChangeCDModel> getIsoImages()
{
return isoImages;
}
private void setIsoImages(ObservableCollection<ChangeCDModel> value)
{
if ((isoImages == null && value != null) || (isoImages != null && !isoImages.equals(value)))
{
isoImages = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsoImages")); //$NON-NLS-1$
}
}
// get { return SelectedItems == null ? new object[0] : SelectedItems.Cast<VM>().Select(a =>
// a.vm_guid).Cast<object>().ToArray(); }
protected Object[] getSelectedKeys()
{
if (getSelectedItems() == null)
{
return new Object[0];
}
Object[] keys = new Object[getSelectedItems().size()];
for (int i = 0; i < getSelectedItems().size(); i++)
{
keys[i] = ((VM) getSelectedItems().get(i)).getId();
}
return keys;
}
private Object privateGuideContext;
public Object getGuideContext()
{
return privateGuideContext;
}
public void setGuideContext(Object value)
{
privateGuideContext = value;
}
private VM privatecurrentVm;
public VM getcurrentVm()
{
return privatecurrentVm;
}
public void setcurrentVm(VM value)
{
privatecurrentVm = value;
}
private final HashMap<Guid, ArrayList<ConsoleModel>> cachedConsoleModels;
private HashMap<Version, ArrayList<String>> privateCustomPropertiesKeysList;
private HashMap<Version, ArrayList<String>> getCustomPropertiesKeysList() {
return privateCustomPropertiesKeysList;
}
private void setCustomPropertiesKeysList(HashMap<Version, ArrayList<String>> value) {
privateCustomPropertiesKeysList = value;
}
public VmListModel()
{
setTitle(ConstantsManager.getInstance().getConstants().virtualMachinesTitle());
setHashName("virtual_machines"); //$NON-NLS-1$
setDefaultSearchString("Vms:"); //$NON-NLS-1$
setSearchString(getDefaultSearchString());
setSearchObjects(new String[] { SearchObjects.VM_OBJ_NAME, SearchObjects.VM_PLU_OBJ_NAME });
setAvailableInModes(ApplicationMode.VirtOnly);
cachedConsoleModels = new HashMap<Guid, ArrayList<ConsoleModel>>();
setNewServerCommand(new UICommand("NewServer", this)); //$NON-NLS-1$
setNewDesktopCommand(new UICommand("NewDesktop", this)); //$NON-NLS-1$
setEditCommand(new UICommand("Edit", this)); //$NON-NLS-1$
setRemoveCommand(new UICommand("Remove", this)); //$NON-NLS-1$
setRunCommand(new UICommand("Run", this, true)); //$NON-NLS-1$
setPauseCommand(new UICommand("Pause", this)); //$NON-NLS-1$
setStopCommand(new UICommand("Stop", this)); //$NON-NLS-1$
setShutdownCommand(new UICommand("Shutdown", this)); //$NON-NLS-1$
setMigrateCommand(new UICommand("Migrate", this)); //$NON-NLS-1$
setCancelMigrateCommand(new UICommand("CancelMigration", this)); //$NON-NLS-1$
setNewTemplateCommand(new UICommand("NewTemplate", this)); //$NON-NLS-1$
setRunOnceCommand(new UICommand("RunOnce", this)); //$NON-NLS-1$
setExportCommand(new UICommand("Export", this)); //$NON-NLS-1$
setMoveCommand(new UICommand("Move", this)); //$NON-NLS-1$
setGuideCommand(new UICommand("Guide", this)); //$NON-NLS-1$
setRetrieveIsoImagesCommand(new UICommand("RetrieveIsoImages", this)); //$NON-NLS-1$
setChangeCdCommand(new UICommand("ChangeCD", this)); //$NON-NLS-1$
setAssignTagsCommand(new UICommand("AssignTags", this)); //$NON-NLS-1$
setIsoImages(new ObservableCollection<ChangeCDModel>());
ChangeCDModel tempVar = new ChangeCDModel();
tempVar.setTitle(ConstantsManager.getInstance().getConstants().retrievingCDsTitle());
getIsoImages().add(tempVar);
UpdateActionAvailability();
getSearchNextPageCommand().setIsAvailable(true);
getSearchPreviousPageCommand().setIsAvailable(true);
if (getCustomPropertiesKeysList() == null) {
AsyncDataProvider.GetCustomPropertiesList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel model = (VmListModel) target;
if (returnValue != null)
{
model.setCustomPropertiesKeysList(new HashMap<Version, ArrayList<String>>());
HashMap<Version, String> dictionary = (HashMap<Version, String>) returnValue;
for (Map.Entry<Version, String> keyValuePair : dictionary.entrySet())
{
model.getCustomPropertiesKeysList().put(keyValuePair.getKey(),
new ArrayList<String>());
for (String s : keyValuePair.getValue().split("[;]", -1)) //$NON-NLS-1$
{
model.getCustomPropertiesKeysList().get(keyValuePair.getKey()).add(s);
}
}
}
}
}));
}
// Call 'IsCommandCompatible' for precaching
AsyncDataProvider.IsCommandCompatible(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
}
}), null, null, null);
}
private void AssignTags()
{
if (getWindow() != null)
{
return;
}
TagListModel model = new TagListModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().assignTagsTitle());
model.setHashName("assign_tags_vms"); //$NON-NLS-1$
GetAttachedTagsToSelectedVMs(model);
UICommand tempVar = new UICommand("OnAssignTags", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
public Map<Guid, Boolean> attachedTagsToEntities;
public ArrayList<org.ovirt.engine.core.common.businessentities.tags> allAttachedTags;
public int selectedItemsCounter;
private void GetAttachedTagsToSelectedVMs(TagListModel model)
{
ArrayList<Guid> vmIds = new ArrayList<Guid>();
for (Object item : getSelectedItems())
{
VM vm = (VM) item;
vmIds.add(vm.getId());
}
attachedTagsToEntities = new HashMap<Guid, Boolean>();
allAttachedTags = new ArrayList<org.ovirt.engine.core.common.businessentities.tags>();
selectedItemsCounter = 0;
for (Guid id : vmIds)
{
AsyncDataProvider.GetAttachedTagsToVm(new AsyncQuery(new Object[] { this, model },
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
VmListModel vmListModel = (VmListModel) array[0];
TagListModel tagListModel = (TagListModel) array[1];
vmListModel.allAttachedTags.addAll((ArrayList<org.ovirt.engine.core.common.businessentities.tags>) returnValue);
vmListModel.selectedItemsCounter++;
if (vmListModel.selectedItemsCounter == vmListModel.getSelectedItems().size())
{
PostGetAttachedTags(vmListModel, tagListModel);
}
}
}),
id);
}
}
private void PostGetAttachedTags(VmListModel vmListModel, TagListModel tagListModel)
{
if (vmListModel.getLastExecutedCommand() == getAssignTagsCommand())
{
ArrayList<org.ovirt.engine.core.common.businessentities.tags> attachedTags =
Linq.Distinct(vmListModel.allAttachedTags, new TagsEqualityComparer());
for (org.ovirt.engine.core.common.businessentities.tags tag : attachedTags)
{
int count = 0;
for (org.ovirt.engine.core.common.businessentities.tags tag2 : vmListModel.allAttachedTags)
{
if (tag2.gettag_id().equals(tag.gettag_id()))
{
count++;
}
}
vmListModel.attachedTagsToEntities.put(tag.gettag_id(), count == vmListModel.getSelectedItems().size());
}
tagListModel.setAttachedTagsToEntities(vmListModel.attachedTagsToEntities);
}
else if (StringHelper.stringsEqual(vmListModel.getLastExecutedCommand().getName(), "OnAssignTags")) //$NON-NLS-1$
{
vmListModel.PostOnAssignTags(tagListModel.getAttachedTagsToEntities());
}
}
private void OnAssignTags()
{
TagListModel model = (TagListModel) getWindow();
GetAttachedTagsToSelectedVMs(model);
}
public void PostOnAssignTags(Map<Guid, Boolean> attachedTags)
{
TagListModel model = (TagListModel) getWindow();
ArrayList<Guid> vmIds = new ArrayList<Guid>();
for (Object item : getSelectedItems())
{
VM vm = (VM) item;
vmIds.add(vm.getId());
}
// prepare attach/detach lists
ArrayList<Guid> tagsToAttach = new ArrayList<Guid>();
ArrayList<Guid> tagsToDetach = new ArrayList<Guid>();
if (model.getItems() != null && ((ArrayList<TagModel>) model.getItems()).size() > 0)
{
ArrayList<TagModel> tags = (ArrayList<TagModel>) model.getItems();
TagModel rootTag = tags.get(0);
TagModel.RecursiveEditAttachDetachLists(rootTag, attachedTags, tagsToAttach, tagsToDetach);
}
ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>();
for (Guid a : tagsToAttach)
{
parameters.add(new AttachEntityToTagParameters(a, vmIds));
}
Frontend.RunMultipleAction(VdcActionType.AttachVmsToTag, parameters);
parameters = new ArrayList<VdcActionParametersBase>();
for (Guid a : tagsToDetach)
{
parameters.add(new AttachEntityToTagParameters(a, vmIds));
}
Frontend.RunMultipleAction(VdcActionType.DetachVmFromTag, parameters);
Cancel();
}
private void Guide()
{
VmGuideModel model = new VmGuideModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().newVirtualMachineGuideMeTitle());
model.setHashName("new_virtual_machine_-_guide_me"); //$NON-NLS-1$
if (getGuideContext() == null) {
VM vm = (VM) getSelectedItem();
setGuideContext(vm.getId());
}
AsyncDataProvider.GetVmById(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
VmGuideModel model = (VmGuideModel) vmListModel.getWindow();
model.setEntity(returnValue);
UICommand tempVar = new UICommand("Cancel", vmListModel); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().configureLaterTitle());
tempVar.setIsDefault(true);
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
}), (Guid) getGuideContext());
}
@Override
protected void InitDetailModels()
{
super.InitDetailModels();
ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>();
list.add(new VmGeneralModel());
list.add(new VmInterfaceListModel());
list.add(new VmDiskListModel());
list.add(new VmSnapshotListModel());
list.add(new VmEventListModel());
list.add(new VmAppListModel());
list.add(new PermissionListModel());
setDetailModels(list);
}
@Override
public boolean IsSearchStringMatch(String searchString)
{
return searchString.trim().toLowerCase().startsWith("vm"); //$NON-NLS-1$
}
@Override
protected void SyncSearch()
{
SearchParameters tempVar = new SearchParameters(getSearchString(), SearchType.VM);
tempVar.setMaxCount(getSearchPageSize());
super.SyncSearch(VdcQueryType.Search, tempVar);
}
@Override
protected void AsyncSearch()
{
super.AsyncSearch();
setAsyncResult(Frontend.RegisterSearch(getSearchString(), SearchType.VM, getSearchPageSize()));
setItems(getAsyncResult().getData());
}
private void UpdateConsoleModels()
{
List tempVar = getSelectedItems();
List selectedItems = (tempVar != null) ? tempVar : new ArrayList();
Object tempVar2 = getSelectedItem();
VM vm = (VM) ((tempVar2 instanceof VM) ? tempVar2 : null);
if (vm == null || selectedItems.size() > 1)
{
setDefaultConsoleModel(null);
setAdditionalConsoleModel(null);
setHasAdditionalConsoleModel(false);
}
else
{
if (!cachedConsoleModels.containsKey(vm.getId()))
{
SpiceConsoleModel spiceConsoleModel = new SpiceConsoleModel();
spiceConsoleModel.getErrorEvent().addListener(this);
VncConsoleModel vncConsoleModel = new VncConsoleModel();
vncConsoleModel.setModel(this);
RdpConsoleModel rdpConsoleModel = new RdpConsoleModel();
cachedConsoleModels.put(vm.getId(),
new ArrayList<ConsoleModel>(Arrays.asList(new ConsoleModel[] {
spiceConsoleModel, vncConsoleModel, rdpConsoleModel })));
}
ArrayList<ConsoleModel> cachedModels = cachedConsoleModels.get(vm.getId());
for (ConsoleModel a : cachedModels)
{
a.setEntity(null);
a.setEntity(vm);
}
setDefaultConsoleModel(vm.getdisplay_type() == DisplayType.vnc ? cachedModels.get(1) : cachedModels.get(0));
if (DataProvider.IsWindowsOsType(vm.getvm_os()))
{
for (ConsoleModel a : cachedModels)
{
if (a instanceof RdpConsoleModel)
{
setAdditionalConsoleModel(a);
break;
}
}
setHasAdditionalConsoleModel(true);
}
else
{
setAdditionalConsoleModel(null);
setHasAdditionalConsoleModel(false);
}
}
}
public ArrayList<ConsoleModel> GetConsoleModelsByVmGuid(Guid vmGuid)
{
if (cachedConsoleModels != null && cachedConsoleModels.containsKey(vmGuid))
{
return cachedConsoleModels.get(vmGuid);
}
return null;
}
private void NewDesktop()
{
NewInternal(VmType.Desktop);
}
private void NewServer()
{
NewInternal(VmType.Server);
}
private void NewInternal(VmType vmType)
{
if (getWindow() != null)
{
return;
}
UnitVmModel model = new UnitVmModel(new NewVmModelBehavior());
model.setTitle(ConstantsManager.getInstance()
.getMessages()
.newVmTitle(vmType == VmType.Server ? ConstantsManager.getInstance().getConstants().serverVmType()
: ConstantsManager.getInstance().getConstants().desktopVmType()));
model.setHashName("new_" + (vmType == VmType.Server ? "server" : "desktop")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
model.setIsNew(true);
model.setVmType(vmType);
model.setCustomPropertiesKeysList(getCustomPropertiesKeysList());
setWindow(model);
model.Initialize(getSystemTreeSelectedItem());
// Ensures that the default provisioning is "Clone" for a new server and "Thin" for a new desktop.
boolean selectValue = model.getVmType() == VmType.Server;
model.getProvisioning().setEntity(selectValue);
UICommand tempVar = new UICommand("OnSave", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void Edit()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
UnitVmModel model = new UnitVmModel(new ExistingVmModelBehavior(vm));
model.setVmType(vm.getvm_type());
setWindow(model);
model.setTitle(ConstantsManager.getInstance()
.getMessages()
.editVmTitle(vm.getvm_type() == VmType.Server ? ConstantsManager.getInstance()
.getConstants()
.serverVmType()
: ConstantsManager.getInstance().getConstants().desktopVmType()));
model.setHashName("edit_" + (vm.getvm_type() == VmType.Server ? "server" : "desktop")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
model.setCustomPropertiesKeysList(getCustomPropertiesKeysList());
model.Initialize(this.getSystemTreeSelectedItem());
// TODO:
// VDSGroup cluster = null;
// if (model.Cluster.Items == null)
// model.Commands.Add(
// new UICommand("Cancel", this)
// Title = "Cancel",
// IsCancel = true
// return;
UICommand tempVar = new UICommand("OnSave", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void remove()
{
if (getWindow() != null)
{
return;
}
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().removeVirtualMachinesTitle());
model.setHashName("remove_virtual_machine"); //$NON-NLS-1$
model.setMessage(ConstantsManager.getInstance().getConstants().virtualMachinesMsg());
// model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name);
ArrayList<String> list = new ArrayList<String>();
for (Object selectedItem : getSelectedItems())
{
VM a = (VM) selectedItem;
list.add(a.getvm_name());
}
model.setItems(list);
UICommand tempVar = new UICommand("OnRemove", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void Move()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
MoveDiskModel model = new MoveDiskModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().moveVirtualMachineTitle());
model.setHashName("move_virtual_machine"); //$NON-NLS-1$
model.setIsSourceStorageDomainNameAvailable(true);
model.setEntity(this);
model.StartProgress(null);
AsyncDataProvider.GetVmDiskList(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
MoveDiskModel moveDiskModel = (MoveDiskModel) vmListModel.getWindow();
LinkedList<DiskImage> disks = (LinkedList<DiskImage>) returnValue;
ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>();
diskImages.addAll(disks);
moveDiskModel.init(diskImages);
}
}), vm.getId(), true);
}
@Override
protected String thereIsNoExportDomainBackupEntityAttachExportDomainToVmsDcMsg() {
return ConstantsManager.getInstance()
.getConstants()
.thereIsNoExportDomainBackupVmAttachExportDomainToVmsDcMsg();
}
@Override
protected VdcQueryType getEntityExportDomain() {
return VdcQueryType.GetVmsFromExportDomain;
}
@Override
protected String entityResideOnSeveralDCsMakeSureTheExportedVMResideOnSameDcMsg() {
return ConstantsManager.getInstance()
.getConstants()
.vmsResideOnSeveralDCsMakeSureTheExportedVMResideOnSameDcMsg();
}
protected boolean entitiesSelectedOnDifferentDataCenters()
{
ArrayList<VM> vms = new ArrayList<VM>();
for (Object selectedItem : getSelectedItems())
{
VM a = (VM) selectedItem;
vms.add(a);
}
Map<NGuid, ArrayList<VM>> t = new HashMap<NGuid, ArrayList<VM>>();
for (VM a : vms)
{
if (!t.containsKey(a.getstorage_pool_id()))
{
t.put(a.getstorage_pool_id(), new ArrayList<VM>());
}
ArrayList<VM> list = t.get(a.getstorage_pool_id());
list.add(a);
}
return t.size() > 1;
}
protected String extractNameFromEntity(VM entity) {
return entity.getvm_name();
}
protected boolean entititesEqualsNullSafe(VM e1, VM e2) {
return e1.getId().equals(e2.getId());
}
@Override
protected String composeEntityOnStorage(String entities) {
return ConstantsManager.getInstance()
.getMessages()
.vmsAlreadyExistOnTargetExportDomain(entities);
}
@Override
protected Iterable<VM> asIterableReturnValue(Object returnValue) {
return (List<VM>) returnValue;
}
private void GetTemplatesNotPresentOnExportDomain()
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
AsyncDataProvider.GetDataCentersByStorageDomain(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
ArrayList<storage_pool> storagePools =
(ArrayList<storage_pool>) returnValue;
storage_pool storagePool = storagePools.size() > 0 ? storagePools.get(0) : null;
vmListModel.PostGetTemplatesNotPresentOnExportDomain(storagePool);
}
}), storageDomainId);
}
private void PostGetTemplatesNotPresentOnExportDomain(storage_pool storagePool)
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
if (storagePool != null)
{
AsyncDataProvider.GetAllTemplatesFromExportDomain(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
HashMap<VmTemplate, ArrayList<DiskImage>> templatesDiskSet =
(HashMap<VmTemplate, ArrayList<DiskImage>>) returnValue;
HashMap<String, ArrayList<String>> templateDic =
new HashMap<String, ArrayList<String>>();
// check if relevant templates are already there
for (Object selectedItem : vmListModel.getSelectedItems())
{
VM vm = (VM) selectedItem;
boolean hasMatch = false;
for (VmTemplate a : templatesDiskSet.keySet())
{
if (vm.getvmt_guid().equals(a.getId()))
{
hasMatch = true;
break;
}
}
if (!vm.getvmt_guid().equals(NGuid.Empty) && !hasMatch)
{
if (!templateDic.containsKey(vm.getvmt_name()))
{
templateDic.put(vm.getvmt_name(), new ArrayList<String>());
}
templateDic.get(vm.getvmt_name()).add(vm.getvm_name());
}
}
String tempStr;
ArrayList<String> tempList;
ArrayList<String> missingTemplates = new ArrayList<String>();
for (Map.Entry<String, ArrayList<String>> keyValuePair : templateDic.entrySet())
{
tempList = keyValuePair.getValue();
tempStr = "Template " + keyValuePair.getKey() + " (for "; //$NON-NLS-1$ //$NON-NLS-2$
int i;
for (i = 0; i < tempList.size() - 1; i++)
{
tempStr += tempList.get(i) + ", "; //$NON-NLS-1$
}
tempStr += tempList.get(i) + ")"; //$NON-NLS-1$
missingTemplates.add(tempStr);
}
vmListModel.PostExportGetMissingTemplates(missingTemplates);
}
}),
storagePool.getId(),
storageDomainId);
}
}
private void PostExportGetMissingTemplates(ArrayList<String> missingTemplatesFromVms)
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>();
model.StopProgress();
for (Object a : getSelectedItems())
{
VM vm = (VM) a;
MoveVmParameters parameter = new MoveVmParameters(vm.getId(), storageDomainId);
parameter.setForceOverride((Boolean) model.getForceOverride().getEntity());
parameter.setCopyCollapse((Boolean) model.getCollapseSnapshots().getEntity());
parameter.setTemplateMustExists(true);
parameters.add(parameter);
}
if (!(Boolean) model.getCollapseSnapshots().getEntity())
{
if ((missingTemplatesFromVms == null || missingTemplatesFromVms.size() > 0))
{
ConfirmationModel confirmModel = new ConfirmationModel();
setConfirmWindow(confirmModel);
confirmModel.setTitle(ConstantsManager.getInstance()
.getConstants()
.templatesNotFoundOnExportDomainTitle());
confirmModel.setHashName("template_not_found_on_export_domain"); //$NON-NLS-1$
confirmModel.setMessage(missingTemplatesFromVms == null ? ConstantsManager.getInstance()
.getConstants()
.couldNotReadTemplatesFromExportDomainMsg()
: ConstantsManager.getInstance()
.getConstants()
.theFollowingTemplatesAreMissingOnTargetExportDomainMsg());
confirmModel.setItems(missingTemplatesFromVms);
UICommand tempVar = new UICommand("OnExportNoTemplates", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
confirmModel.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("CancelConfirmation", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
confirmModel.getCommands().add(tempVar2);
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.ExportVm, parameters,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
}
else
{
if (model.getProgress() != null)
{
return;
}
for (VdcActionParametersBase item : parameters)
{
MoveVmParameters parameter = (MoveVmParameters) item;
parameter.setTemplateMustExists(false);
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.ExportVm, parameters,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
}
public void OnExport()
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
if (!model.Validate())
{
return;
}
model.StartProgress(null);
GetTemplatesNotPresentOnExportDomain();
}
private void OnExportNoTemplates()
{
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
if (model.getProgress() != null)
{
return;
}
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
MoveVmParameters parameters = new MoveVmParameters(a.getId(), storageDomainId);
parameters.setForceOverride((Boolean) model.getForceOverride().getEntity());
parameters.setCopyCollapse((Boolean) model.getCollapseSnapshots().getEntity());
parameters.setTemplateMustExists(false);
list.add(parameters);
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.ExportVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
private void RunOnce()
{
VM vm = (VM) getSelectedItem();
RunOnceModel model = new RunOnceModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().runVirtualMachinesTitle());
model.setHashName("run_virtual_machine"); //$NON-NLS-1$
model.getAttachIso().setEntity(false);
model.getAttachFloppy().setEntity(false);
model.getRunAsStateless().setEntity(vm.getis_stateless());
model.getRunAndPause().setEntity(false);
model.setHwAcceleration(true);
// passing Kernel parameters
model.getKernel_parameters().setEntity(vm.getkernel_params());
model.getKernel_path().setEntity(vm.getkernel_url());
model.getInitrd_path().setEntity(vm.getinitrd_url());
// Custom Properties
model.getCustomPropertySheet()
.setKeyValueString(this.getCustomPropertiesKeysList()
.get(vm.getvds_group_compatibility_version()));
model.getCustomPropertySheet().setEntity(vm.getCustomProperties());
model.setCustomPropertiesKeysList(this.getCustomPropertiesKeysList()
.get(vm.getvds_group_compatibility_version()));
model.setIsLinux_Unassign_UnknownOS(DataProvider.IsLinuxOsType(vm.getvm_os())
|| vm.getvm_os() == VmOsType.Unassigned || vm.getvm_os() == VmOsType.Other);
model.getIsLinuxOptionsAvailable().setEntity(model.getIsLinux_Unassign_UnknownOS());
model.setIsWindowsOS(DataProvider.IsWindowsOsType(vm.getvm_os()));
model.getIsVmFirstRun().setEntity(!vm.getis_initialized());
model.getSysPrepDomainName().setSelectedItem(vm.getvm_domain());
RunOnceUpdateDisplayProtocols(vm);
RunOnceUpdateFloppy(vm, new ArrayList<String>());
RunOnceUpdateImages(vm);
RunOnceUpdateDomains();
RunOnceUpdateBootSequence(vm);
UICommand tempVar = new UICommand("OnRunOnce", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void RunOnceUpdateDisplayProtocols(VM vm)
{
RunOnceModel model = (RunOnceModel) getWindow();
EntityModel tempVar = new EntityModel();
tempVar.setTitle(ConstantsManager.getInstance().getConstants().VNCTitle());
tempVar.setEntity(DisplayType.vnc);
EntityModel vncProtocol = tempVar;
EntityModel tempVar2 = new EntityModel();
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().spiceTitle());
tempVar2.setEntity(DisplayType.qxl);
EntityModel qxlProtocol = tempVar2;
boolean isVncSelected = vm.getdefault_display_type() == DisplayType.vnc;
model.getDisplayConsole_Vnc_IsSelected().setEntity(isVncSelected);
model.getDisplayConsole_Spice_IsSelected().setEntity(!isVncSelected);
ArrayList<EntityModel> items = new ArrayList<EntityModel>();
items.add(vncProtocol);
items.add(qxlProtocol);
model.getDisplayProtocol().setItems(items);
model.getDisplayProtocol().setSelectedItem(isVncSelected ? vncProtocol : qxlProtocol);
}
private void RunOnceUpdateBootSequence(VM vm)
{
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object ReturnValue)
{
VmListModel vmListModel = (VmListModel) model;
RunOnceModel runOnceModel = (RunOnceModel) vmListModel.getWindow();
boolean hasNics =
((ArrayList<VmNetworkInterface>) ((VdcQueryReturnValue) ReturnValue).getReturnValue()).size() > 0;
if (!hasNics)
{
BootSequenceModel bootSequenceModel = runOnceModel.getBootSequence();
bootSequenceModel.getNetworkOption().setIsChangable(false);
bootSequenceModel.getNetworkOption()
.getChangeProhibitionReasons()
.add("Virtual Machine must have at least one network interface defined to boot from network."); //$NON-NLS-1$
}
}
};
Frontend.RunQuery(VdcQueryType.GetVmInterfacesByVmId, new GetVmByVmIdParameters(vm.getId()), _asyncQuery);
}
private void RunOnceUpdateDomains()
{
RunOnceModel model = (RunOnceModel) getWindow();
// Update Domain list
AsyncDataProvider.GetDomainList(new AsyncQuery(model,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
RunOnceModel runOnceModel = (RunOnceModel) target;
List<String> domains = (List<String>) returnValue;
String oldDomain = (String) runOnceModel.getSysPrepDomainName().getSelectedItem();
if (oldDomain != null && !oldDomain.equals("") && !domains.contains(oldDomain)) //$NON-NLS-1$
{
domains.add(0, oldDomain);
}
runOnceModel.getSysPrepDomainName().setItems(domains);
String selectedDomain = (oldDomain != null) ? oldDomain : Linq.FirstOrDefault(domains);
if (!StringHelper.stringsEqual(selectedDomain, "")) //$NON-NLS-1$
{
runOnceModel.getSysPrepDomainName().setSelectedItem(selectedDomain);
}
}
}), true);
}
public void RunOnceUpdateFloppy(VM vm, ArrayList<String> images)
{
RunOnceModel model = (RunOnceModel) getWindow();
if (DataProvider.IsWindowsOsType(vm.getvm_os()))
{
// Add a pseudo floppy disk image used for Windows' sysprep.
if (!vm.getis_initialized())
{
images.add(0, "[sysprep]"); //$NON-NLS-1$
model.getAttachFloppy().setEntity(true);
}
else
{
images.add("[sysprep]"); //$NON-NLS-1$
}
}
model.getFloppyImage().setItems(images);
if (model.getFloppyImage().getIsChangable() && model.getFloppyImage().getSelectedItem() == null)
{
model.getFloppyImage().setSelectedItem(Linq.FirstOrDefault(images));
}
}
private void RunOnceUpdateImages(VM vm) {
AsyncQuery _asyncQuery2 = new AsyncQuery();
_asyncQuery2.setModel(this);
_asyncQuery2.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model2, Object result)
{
VmListModel vmListModel2 = (VmListModel) model2;
VM selectedVM = (VM) vmListModel2.getSelectedItem();
ArrayList<String> images = (ArrayList<String>) result;
vmListModel2.RunOnceUpdateFloppy(selectedVM, images);
}
};
AsyncDataProvider.GetFloppyImageList(_asyncQuery2, vm.getstorage_pool_id());
AsyncQuery getImageListQuery = new AsyncQuery();
getImageListQuery.setModel(this);
getImageListQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result)
{
VmListModel vmListModel1 = (VmListModel) model1;
RunOnceModel runOnceModel = (RunOnceModel) vmListModel1.getWindow();
ArrayList<String> images = (ArrayList<String>) result;
runOnceModel.getIsoImage().setItems(images);
if (runOnceModel.getIsoImage().getIsChangable()
&& runOnceModel.getIsoImage().getSelectedItem() == null)
{
runOnceModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images));
}
}
};
AsyncDataProvider.GetIrsImageList(getImageListQuery, vm.getstorage_pool_id());
}
private void OnRunOnce()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
Cancel();
return;
}
RunOnceModel model = (RunOnceModel) getWindow();
if (!model.Validate())
{
return;
}
BootSequenceModel bootSequenceModel = model.getBootSequence();
RunVmOnceParams tempVar = new RunVmOnceParams();
tempVar.setVmId(vm.getId());
tempVar.setBootSequence(bootSequenceModel.getSequence());
tempVar.setDiskPath((Boolean) model.getAttachIso().getEntity() ? (String) model.getIsoImage().getSelectedItem()
: ""); //$NON-NLS-1$
tempVar.setFloppyPath(model.getFloppyImagePath());
tempVar.setKvmEnable(model.getHwAcceleration());
tempVar.setRunAndPause((Boolean) model.getRunAndPause().getEntity());
tempVar.setAcpiEnable(true);
tempVar.setRunAsStateless((Boolean) model.getRunAsStateless().getEntity());
tempVar.setReinitialize(model.getReinitialize());
tempVar.setCustomProperties(model.getCustomPropertySheet().getEntity());
RunVmOnceParams param = tempVar;
// kernel params
if (model.getKernel_path().getEntity() != null)
{
param.setkernel_url((String) model.getKernel_path().getEntity());
}
if (model.getKernel_parameters().getEntity() != null)
{
param.setkernel_params((String) model.getKernel_parameters().getEntity());
}
if (model.getInitrd_path().getEntity() != null)
{
param.setinitrd_url((String) model.getInitrd_path().getEntity());
}
// Sysprep params
if (model.getSysPrepDomainName().getSelectedItem() != null)
{
param.setSysPrepDomainName(model.getSysPrepSelectedDomainName().getEntity().equals("") ? (String) model.getSysPrepSelectedDomainName() //$NON-NLS-1$
.getEntity()
: (String) model.getSysPrepDomainName().getSelectedItem());
}
if (model.getSysPrepUserName().getEntity() != null)
{
param.setSysPrepUserName((String) model.getSysPrepUserName().getEntity());
}
if (model.getSysPrepPassword().getEntity() != null)
{
param.setSysPrepPassword((String) model.getSysPrepPassword().getEntity());
}
EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem();
param.setUseVnc((DisplayType) displayProtocolSelectedItem.getEntity() == DisplayType.vnc);
if ((Boolean) model.getDisplayConsole_Vnc_IsSelected().getEntity()
|| (Boolean) model.getDisplayConsole_Spice_IsSelected().getEntity())
{
param.setUseVnc((Boolean) model.getDisplayConsole_Vnc_IsSelected().getEntity());
}
Frontend.RunAction(VdcActionType.RunVmOnce, param,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
}
}, this);
Cancel();
}
private void NewTemplate()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
UnitVmModel model = new UnitVmModel(new NewTemplateVmModelBehavior(vm));
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().newTemplateTitle());
model.setHashName("new_template"); //$NON-NLS-1$
model.setIsNew(true);
model.setVmType(vm.getvm_type());
model.Initialize(getSystemTreeSelectedItem());
UICommand tempVar = new UICommand("OnNewTemplate", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void OnNewTemplate()
{
UnitVmModel model = (UnitVmModel) getWindow();
VM vm = (VM) getSelectedItem();
if (vm == null)
{
Cancel();
return;
}
if (model.getProgress() != null)
{
return;
}
if (!model.Validate())
{
model.setIsValid(false);
}
else
{
String name = (String) model.getName().getEntity();
// Check name unicitate.
AsyncDataProvider.IsTemplateNameUnique(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
boolean isNameUnique = (Boolean) returnValue;
if (!isNameUnique)
{
UnitVmModel VmModel = (UnitVmModel) vmListModel.getWindow();
VmModel.getInvalidityReasons().clear();
VmModel.getName()
.getInvalidityReasons()
.add(ConstantsManager.getInstance()
.getConstants()
.nameMustBeUniqueInvalidReason());
VmModel.getName().setIsValid(false);
VmModel.setIsValid(false);
}
else
{
vmListModel.PostNameUniqueCheck();
}
}
}),
name);
}
}
public void PostNameUniqueCheck()
{
UnitVmModel model = (UnitVmModel) getWindow();
VM vm = (VM) getSelectedItem();
VM tempVar = new VM();
tempVar.setId(vm.getId());
tempVar.setvm_type(model.getVmType());
if (model.getQuota().getSelectedItem() != null) {
tempVar.setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId());
}
tempVar.setvm_os((VmOsType) model.getOSType().getSelectedItem());
tempVar.setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem());
tempVar.setAllowConsoleReconnect((Boolean) model.getAllowConsoleReconnect().getEntity());
tempVar.setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem() : ""); //$NON-NLS-1$
tempVar.setvm_mem_size_mb((Integer) model.getMemSize().getEntity());
tempVar.setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity());
tempVar.setvds_group_id(((VDSGroup) model.getCluster().getSelectedItem()).getId());
tempVar.settime_zone(model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null ? ((Map.Entry<String, String>) model.getTimeZone()
.getSelectedItem()).getKey()
: ""); //$NON-NLS-1$
tempVar.setnum_of_sockets((Integer) model.getNumOfSockets().getEntity());
tempVar.setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity()
/ (Integer) model.getNumOfSockets().getEntity());
tempVar.setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem());
tempVar.setis_auto_suspend(false);
tempVar.setis_stateless((Boolean) model.getIsStateless().getEntity());
tempVar.setdefault_boot_sequence(model.getBootSequence());
tempVar.setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity());
tempVar.setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem() : ""); //$NON-NLS-1$
tempVar.setinitrd_url(vm.getinitrd_url());
tempVar.setkernel_url(vm.getkernel_url());
tempVar.setkernel_params(vm.getkernel_params());
VM newvm = tempVar;
EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem();
newvm.setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity());
EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem();
newvm.setpriority((Integer) prioritySelectedItem.getEntity());
AddVmTemplateParameters addVmTemplateParameters =
new AddVmTemplateParameters(newvm,
(String) model.getName().getEntity(),
(String) model.getDescription().getEntity());
addVmTemplateParameters.setPublicUse((Boolean) model.getIsTemplatePublic().getEntity());
addVmTemplateParameters.setDiskInfoDestinationMap(
model.getDisksAllocationModel()
.getImageToDestinationDomainMap((Boolean) model.getDisksAllocationModel()
.getIsSingleStorageDomain()
.getEntity()));
model.StartProgress(null);
Frontend.RunAction(VdcActionType.AddVmTemplate, addVmTemplateParameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
private void Migrate()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
if (getWindow() != null)
{
return;
}
MigrateModel model = new MigrateModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().migrateVirtualMachinesTitle());
model.setHashName("migrate_virtual_machine"); //$NON-NLS-1$
model.setVmsOnSameCluster(true);
model.setIsAutoSelect(true);
model.setVmList(Linq.<VM> Cast(getSelectedItems()));
AsyncDataProvider.GetUpHostListByCluster(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
VmListModel vmListModel = (VmListModel) target;
vmListModel.PostMigrateGetUpHosts((ArrayList<VDS>) returnValue);
}
}), vm.getvds_group_name());
}
private void CancelMigration()
{
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems()) {
VM a = (VM) item;
list.add(new VmOperationParameterBase(a.getId()));
}
Frontend.RunMultipleAction(VdcActionType.CancelMigrateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(
FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void PostMigrateGetUpHosts(ArrayList<VDS> hosts)
{
MigrateModel model = (MigrateModel) getWindow();
NGuid run_on_vds = null;
boolean allRunOnSameVds = true;
for (Object item : getSelectedItems())
{
VM a = (VM) item;
if (!a.getvds_group_id().equals(((VM) getSelectedItems().get(0)).getvds_group_id()))
{
model.setVmsOnSameCluster(false);
}
if (run_on_vds == null)
{
run_on_vds = a.getrun_on_vds().getValue();
}
else if (allRunOnSameVds && !run_on_vds.equals(a.getrun_on_vds().getValue()))
{
allRunOnSameVds = false;
}
}
model.setIsHostSelAvailable(model.getVmsOnSameCluster() && hosts.size() > 0);
if (model.getVmsOnSameCluster() && allRunOnSameVds)
{
VDS runOnSameVDS = null;
for (VDS host : hosts)
{
if (host.getId().equals(run_on_vds))
{
runOnSameVDS = host;
}
}
hosts.remove(runOnSameVDS);
}
if (hosts.isEmpty())
{
model.setIsHostSelAvailable(false);
if (allRunOnSameVds)
{
model.setNoSelAvailable(true);
UICommand tempVar = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().close());
tempVar.setIsDefault(true);
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
}
else
{
model.getHosts().setItems(hosts);
model.getHosts().setSelectedItem(Linq.FirstOrDefault(hosts));
UICommand tempVar2 = new UICommand("OnMigrate", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar2.setIsDefault(true);
model.getCommands().add(tempVar2);
UICommand tempVar3 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar3.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar3.setIsCancel(true);
model.getCommands().add(tempVar3);
}
}
private void OnMigrate()
{
MigrateModel model = (MigrateModel) getWindow();
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
if (model.getIsAutoSelect())
{
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new MigrateVmParameters(true, a.getId()));
}
Frontend.RunMultipleAction(VdcActionType.MigrateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
MigrateModel localModel = (MigrateModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
else
{
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
if (a.getrun_on_vds().getValue().equals(((VDS) model.getHosts().getSelectedItem()).getId()))
{
continue;
}
list.add(new MigrateVmToServerParameters(true, a.getId(), ((VDS) model.getHosts()
.getSelectedItem()).getId()));
}
Frontend.RunMultipleAction(VdcActionType.MigrateVmToServer, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
MigrateModel localModel = (MigrateModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
}
private void Shutdown()
{
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().shutdownVirtualMachinesTitle());
model.setHashName("shut_down_virtual_machine"); //$NON-NLS-1$
model.setMessage(ConstantsManager.getInstance()
.getConstants()
.areYouSureYouWantToShutDownTheFollowingVirtualMachinesMsg());
// model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name);
ArrayList<String> items = new ArrayList<String>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
items.add(a.getvm_name());
}
model.setItems(items);
UICommand tempVar = new UICommand("OnShutdown", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void OnShutdown()
{
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null)
{
return;
}
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new ShutdownVmParameters(a.getId(), true));
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.ShutdownVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
private void stop()
{
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().stopVirtualMachinesTitle());
model.setHashName("stop_virtual_machine"); //$NON-NLS-1$
model.setMessage(ConstantsManager.getInstance()
.getConstants()
.areYouSureYouWantToStopTheFollowingVirtualMachinesMsg());
// model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name);
ArrayList<String> items = new ArrayList<String>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
items.add(a.getvm_name());
}
model.setItems(items);
UICommand tempVar = new UICommand("OnStop", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void OnStop()
{
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null)
{
return;
}
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new StopVmParameters(a.getId(), StopVmTypeEnum.NORMAL));
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.StopVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
private void Pause()
{
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new HibernateVmParameters(a.getId()));
}
Frontend.RunMultipleAction(VdcActionType.HibernateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void Run()
{
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
// use sysprep iff the vm is not initialized and vm has Win OS
boolean reinitialize = !a.getis_initialized() && DataProvider.IsWindowsOsType(a.getvm_os());
RunVmParams tempVar = new RunVmParams(a.getId());
tempVar.setReinitialize(reinitialize);
list.add(tempVar);
}
Frontend.RunMultipleAction(VdcActionType.RunVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void OnRemove()
{
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null)
{
return;
}
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object item : getSelectedItems())
{
VM a = (VM) item;
list.add(new RemoveVmParameters(a.getId(), false));
}
model.StartProgress(null);
Frontend.RunMultipleAction(VdcActionType.RemoveVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.StopProgress();
Cancel();
}
}, model);
}
private void ChangeCD()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
return;
}
AttachCdModel model = new AttachCdModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().changeCDTitle());
model.setHashName("change_cd"); //$NON-NLS-1$
AttachCdModel attachCdModel = (AttachCdModel) getWindow();
ArrayList<String> images1 =
new ArrayList<String>(Arrays.asList(new String[] { "No CDs" })); //$NON-NLS-1$
attachCdModel.getIsoImage().setItems(images1);
attachCdModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images1));
AsyncQuery getIrsImageListCallback = new AsyncQuery();
getIrsImageListCallback.setModel(this);
getIrsImageListCallback.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object result)
{
VmListModel vmListModel2 = (VmListModel) model;
AttachCdModel _attachCdModel = (AttachCdModel) vmListModel2.getWindow();
ArrayList<String> images = (ArrayList<String>) result;
if (images.size() > 0)
{
images.add(0, ConsoleModel.EjectLabel);
_attachCdModel.getIsoImage().setItems(images);
}
if (_attachCdModel.getIsoImage().getIsChangable())
{
_attachCdModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images));
}
}
};
AsyncDataProvider.GetIrsImageList(getIrsImageListCallback, vm.getstorage_pool_id());
UICommand tempVar = new UICommand("OnChangeCD", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void OnChangeCD()
{
VM vm = (VM) getSelectedItem();
if (vm == null)
{
Cancel();
return;
}
AttachCdModel model = (AttachCdModel) getWindow();
if (model.getProgress() != null)
{
return;
}
String isoName =
(StringHelper.stringsEqual(model.getIsoImage().getSelectedItem().toString(), ConsoleModel.EjectLabel)) ? "" //$NON-NLS-1$
: model.getIsoImage().getSelectedItem().toString();
model.StartProgress(null);
Frontend.RunAction(VdcActionType.ChangeDisk, new ChangeDiskCommandParameters(vm.getId(), isoName),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
AttachCdModel attachCdModel = (AttachCdModel) result.getState();
attachCdModel.StopProgress();
Cancel();
}
}, model);
}
private void OnSave()
{
UnitVmModel model = (UnitVmModel) getWindow();
VM selectedItem = (VM) getSelectedItem();
if (model.getIsNew() == false && selectedItem == null)
{
Cancel();
return;
}
setcurrentVm(model.getIsNew() ? new VM() : (VM) Cloner.clone(selectedItem));
if (!model.Validate())
{
return;
}
String name = (String) model.getName().getEntity();
// Check name unicitate.
if (!DataProvider.IsVmNameUnique(name) && name.compareToIgnoreCase(getcurrentVm().getvm_name()) != 0)
{
model.getName().setIsValid(false);
model.getName()
.getInvalidityReasons()
.add(ConstantsManager.getInstance().getConstants().nameMustBeUniqueInvalidReason());
model.setIsGeneralTabValid(false);
return;
}
// Save changes.
VmTemplate template = (VmTemplate) model.getTemplate().getSelectedItem();
getcurrentVm().setvm_type(model.getVmType());
getcurrentVm().setvmt_guid(template.getId());
getcurrentVm().setvm_name(name);
if (model.getQuota().getSelectedItem() != null) {
getcurrentVm().setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId());
}
getcurrentVm().setvm_os((VmOsType) model.getOSType().getSelectedItem());
getcurrentVm().setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem());
getcurrentVm().setAllowConsoleReconnect((Boolean) model.getAllowConsoleReconnect().getEntity());
getcurrentVm().setvm_description((String) model.getDescription().getEntity());
getcurrentVm().setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem()
: ""); //$NON-NLS-1$
getcurrentVm().setvm_mem_size_mb((Integer) model.getMemSize().getEntity());
getcurrentVm().setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity());
Guid newClusterID = ((VDSGroup) model.getCluster().getSelectedItem()).getId();
getcurrentVm().setvds_group_id(newClusterID);
getcurrentVm().settime_zone((model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null) ? ((Map.Entry<String, String>) model.getTimeZone()
.getSelectedItem()).getKey()
: ""); //$NON-NLS-1$
getcurrentVm().setnum_of_sockets((Integer) model.getNumOfSockets().getEntity());
getcurrentVm().setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity()
/ (Integer) model.getNumOfSockets().getEntity());
getcurrentVm().setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem());
getcurrentVm().setis_auto_suspend(false);
getcurrentVm().setis_stateless((Boolean) model.getIsStateless().getEntity());
getcurrentVm().setdefault_boot_sequence(model.getBootSequence());
getcurrentVm().setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem()
: ""); //$NON-NLS-1$
getcurrentVm().setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity());
getcurrentVm().setinitrd_url((String) model.getInitrd_path().getEntity());
getcurrentVm().setkernel_url((String) model.getKernel_path().getEntity());
getcurrentVm().setkernel_params((String) model.getKernel_parameters().getEntity());
getcurrentVm().setCustomProperties(model.getCustomPropertySheet().getEntity());
EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem();
getcurrentVm().setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity());
EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem();
getcurrentVm().setpriority((Integer) prioritySelectedItem.getEntity());
getcurrentVm().setCpuPinning((String) model.getCpuPinning()
.getEntity());
VDS defaultHost = (VDS) model.getDefaultHost().getSelectedItem();
if ((Boolean) model.getIsAutoAssign().getEntity())
{
getcurrentVm().setdedicated_vm_for_vds(null);
}
else
{
getcurrentVm().setdedicated_vm_for_vds(defaultHost.getId());
}
getcurrentVm().setMigrationSupport(MigrationSupport.MIGRATABLE);
if ((Boolean) model.getRunVMOnSpecificHost().getEntity())
{
getcurrentVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST);
}
else if ((Boolean) model.getDontMigrateVM().getEntity())
{
getcurrentVm().setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE);
}
if (model.getIsNew())
{
if (getcurrentVm().getvmt_guid().equals(NGuid.Empty))
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunAction(VdcActionType.AddVmFromScratch, new AddVmFromScratchParameters(getcurrentVm(),
new ArrayList<DiskImage>(),
NGuid.Empty),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
vmListModel.setGuideContext(returnValueBase.getActionReturnValue());
vmListModel.UpdateActionAvailability();
vmListModel.getGuideCommand().Execute();
}
}
}, this);
}
else
{
if (model.getProgress() != null)
{
return;
}
if ((Boolean) model.getProvisioning().getEntity())
{
model.StartProgress(null);
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result1)
{
VmListModel vmListModel = (VmListModel) model1;
ArrayList<DiskImage> templateDisks = (ArrayList<DiskImage>) result1;
UnitVmModel unitVmModel = (UnitVmModel) vmListModel.getWindow();
HashMap<Guid, DiskImage> imageToDestinationDomainMap =
unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap();
ArrayList<storage_domains> activeStorageDomains =
unitVmModel.getDisksAllocationModel().getActiveStorageDomains();
HashMap<Guid, DiskImage> dict = unitVmModel.getDisksAllocationModel()
.getImageToDestinationDomainMap((Boolean) unitVmModel.getDisksAllocationModel()
.getIsSingleStorageDomain()
.getEntity());
for (DiskImage templateDisk : templateDisks)
{
DiskModel disk = null;
for (DiskModel a : unitVmModel.getDisksAllocationModel().getDisks())
{
if (templateDisk.getId().equals(a.getDisk().getId()))
{
disk = a;
break;
}
}
storage_domains storageDomain =
Linq.getStorageById(
imageToDestinationDomainMap.get(templateDisk.getId())
.getstorage_ids()
.get(0), activeStorageDomains);
if (disk != null) {
dict.get(templateDisk.getId())
.setvolume_type((VolumeType) disk.getVolumeType()
.getSelectedItem());
dict.get(templateDisk.getId())
.setvolume_format(DataProvider.GetDiskVolumeFormat(
(VolumeType) disk.getVolumeType().getSelectedItem(),
storageDomain.getstorage_type()));
}
}
storage_domains storageDomain =
(storage_domains) unitVmModel.getDisksAllocationModel()
.getStorageDomain().getSelectedItem();
AddVmFromTemplateParameters parameters =
new AddVmFromTemplateParameters(vmListModel.getcurrentVm(),
dict, storageDomain.getId());
Frontend.RunAction(VdcActionType.AddVmFromTemplate, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel1 = (VmListModel) result.getState();
vmListModel1.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel1.Cancel();
}
}
},
vmListModel);
}
};
AsyncDataProvider.GetTemplateDiskList(_asyncQuery, template.getId());
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
HashMap<Guid, DiskImage> imageToDestinationDomainMap =
model.getDisksAllocationModel().getImageToDestinationDomainMap();
storage_domains storageDomain =
((storage_domains) model.getDisksAllocationModel().getStorageDomain().getSelectedItem());
VmManagementParametersBase params = new VmManagementParametersBase(getcurrentVm());
params.setDiskInfoDestinationMap(
model.getDisksAllocationModel()
.getImageToDestinationDomainMap((Boolean) model.getDisksAllocationModel()
.getIsSingleStorageDomain()
.getEntity()));
Frontend.RunAction(VdcActionType.AddVm, params,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
}
}
else // Update existing VM -> consists of editing VM cluster, and if succeeds - editing VM:
{
if (model.getProgress() != null)
{
return;
}
// runEditVM: should be true if Cluster hasn't changed or if
// Cluster has changed and Editing it in the Backend has succeeded:
Guid oldClusterID = selectedItem.getvds_group_id();
if (oldClusterID.equals(newClusterID) == false)
{
ChangeVMClusterParameters parameters =
new ChangeVMClusterParameters(newClusterID, getcurrentVm().getId());
model.StartProgress(null);
Frontend.RunAction(VdcActionType.ChangeVMCluster, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
Frontend.RunAction(VdcActionType.UpdateVm,
new VmManagementParametersBase(vmListModel.getcurrentVm()),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result1) {
VmListModel vmListModel1 = (VmListModel) result1.getState();
vmListModel1.getWindow().StopProgress();
VdcReturnValueBase retVal = result1.getReturnValue();
boolean isSucceeded = retVal.getSucceeded();
if (retVal != null && isSucceeded)
{
vmListModel1.Cancel();
}
}
},
vmListModel);
}
else
{
vmListModel.getWindow().StopProgress();
}
}
}, this);
}
else
{
if (model.getProgress() != null)
{
return;
}
model.StartProgress(null);
Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(getcurrentVm()),
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VmListModel vmListModel = (VmListModel) result.getState();
vmListModel.getWindow().StopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded())
{
vmListModel.Cancel();
}
}
}, this);
}
}
}
private void RetrieveIsoImages()
{
Object tempVar = getSelectedItem();
VM vm = (VM) ((tempVar instanceof VM) ? tempVar : null);
if (vm == null)
{
return;
}
Guid storagePoolId = vm.getstorage_pool_id();
getIsoImages().clear();
ChangeCDModel tempVar2 = new ChangeCDModel();
tempVar2.setTitle(ConsoleModel.EjectLabel);
ChangeCDModel ejectModel = tempVar2;
ejectModel.getExecutedEvent().addListener(this);
getIsoImages().add(ejectModel);
ArrayList<String> list = new ArrayList<String>();
ChangeCDModel tempVar4 = new ChangeCDModel();
tempVar4.setTitle(ConstantsManager.getInstance().getConstants().noCDsTitle());
getIsoImages().add(tempVar4);
}
private void changeCD(Object sender, EventArgs e)
{
ChangeCDModel model = (ChangeCDModel) sender;
// TODO: Patch!
String isoName = model.getTitle();
if (StringHelper.stringsEqual(isoName, "No CDs")) //$NON-NLS-1$
{
return;
}
Object tempVar = getSelectedItem();
VM vm = (VM) ((tempVar instanceof VM) ? tempVar : null);
if (vm == null)
{
return;
}
Frontend.RunMultipleAction(VdcActionType.ChangeDisk,
new ArrayList<VdcActionParametersBase>(Arrays.asList(new VdcActionParametersBase[] { new ChangeDiskCommandParameters(vm.getId(),
StringHelper.stringsEqual(isoName, ConsoleModel.EjectLabel) ? "" : isoName) })), //$NON-NLS-1$
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
}
},
null);
}
public void Cancel()
{
Frontend.Unsubscribe();
CancelConfirmation();
setGuideContext(null);
setWindow(null);
UpdateActionAvailability();
}
private void CancelConfirmation()
{
setConfirmWindow(null);
}
public void CancelError()
{
setErrorWindow(null);
}
@Override
protected void OnSelectedItemChanged()
{
super.OnSelectedItemChanged();
UpdateActionAvailability();
UpdateConsoleModels();
}
@Override
protected void SelectedItemsChanged()
{
super.SelectedItemsChanged();
UpdateActionAvailability();
UpdateConsoleModels();
}
@Override
protected void SelectedItemPropertyChanged(Object sender, PropertyChangedEventArgs e)
{
super.SelectedItemPropertyChanged(sender, e);
if (e.PropertyName.equals("status")) //$NON-NLS-1$
{
UpdateActionAvailability();
}
else if (e.PropertyName.equals("display_type")) //$NON-NLS-1$
{
UpdateConsoleModels();
}
}
private void UpdateActionAvailability()
{
List items =
getSelectedItems() != null && getSelectedItem() != null ? getSelectedItems()
: new ArrayList();
getEditCommand().setIsExecutionAllowed(isEditCommandExecutionAllowed(items));
getRemoveCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RemoveVm));
getRunCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RunVm));
getPauseCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.HibernateVm));
getShutdownCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ShutdownVm));
getStopCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.StopVm));
getMigrateCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.MigrateVm));
getCancelMigrateCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.CancelMigrateVm));
getNewTemplateCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.AddVmTemplate));
getRunOnceCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RunVmOnce));
getExportCommand().setIsExecutionAllowed(items.size() > 0
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ExportVm));
getMoveCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.MoveVm));
getRetrieveIsoImagesCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ChangeDisk));
getChangeCdCommand().setIsExecutionAllowed(items.size() == 1
&& VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ChangeDisk));
getAssignTagsCommand().setIsExecutionAllowed(items.size() > 0);
getGuideCommand().setIsExecutionAllowed(getGuideContext() != null
|| (getSelectedItem() != null && getSelectedItems() != null && getSelectedItems().size() == 1));
}
/**
* Return true if and only if one elemnt is selected, and this element is not a part of any pool.
*/
private boolean isEditCommandExecutionAllowed(List items) {
if (items == null) {
return false;
}
if (items.size() != 1) {
return false;
}
VM selectedItem = (VM) items.get(0);
return selectedItem.getVmPoolId() == null;
}
@Override
public void eventRaised(Event ev, Object sender, EventArgs args)
{
super.eventRaised(ev, sender, args);
if (ev.equals(ChangeCDModel.ExecutedEventDefinition))
{
changeCD(sender, args);
}
else if (ev.equals(ConsoleModel.ErrorEventDefinition) && sender instanceof SpiceConsoleModel)
{
SpiceConsoleModel_Error(sender, (ErrorCodeEventArgs) args);
}
}
private void SpiceConsoleModel_Error(Object sender, ErrorCodeEventArgs e)
{
ResourceManager rm =
new ResourceManager("UICommon.Resources.RdpErrors.RdpErrors", Assembly.GetExecutingAssembly()); //$NON-NLS-1$
ConfirmationModel model = new ConfirmationModel();
if (getErrorWindow() == null)
{
setErrorWindow(model);
}
model.setTitle(ConstantsManager.getInstance().getConstants().consoleDisconnectedTitle());
model.setHashName("console_disconnected"); //$NON-NLS-1$
model.setMessage(ConstantsManager.getInstance()
.getMessages()
.errConnectingVmUsingSpiceMsg(rm.GetString("E" + e.getErrorCode()))); //$NON-NLS-1$
rm.ReleaseAllResources();
UICommand tempVar = new UICommand("CancelError", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().close());
tempVar.setIsDefault(true);
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
@Override
public void ExecuteCommand(UICommand command)
{
super.ExecuteCommand(command);
if (command == getNewServerCommand())
{
NewServer();
}
else if (command == getNewDesktopCommand())
{
NewDesktop();
}
else if (command == getEditCommand())
{
Edit();
}
else if (command == getRemoveCommand())
{
remove();
}
else if (command == getRunCommand())
{
Run();
}
else if (command == getPauseCommand())
{
Pause();
}
else if (command == getStopCommand())
{
stop();
}
else if (command == getShutdownCommand())
{
Shutdown();
}
else if (command == getMigrateCommand())
{
Migrate();
}
else if (command == getNewTemplateCommand())
{
NewTemplate();
}
else if (command == getRunOnceCommand())
{
RunOnce();
}
else if (command == getExportCommand())
{
Export(ConstantsManager.getInstance().getConstants().exportVirtualMachineTitle());
}
else if (command == getMoveCommand())
{
Move();
}
else if (command == getGuideCommand())
{
Guide();
}
else if (command == getRetrieveIsoImagesCommand())
{
RetrieveIsoImages();
}
else if (command == getChangeCdCommand())
{
ChangeCD();
}
else if (command == getAssignTagsCommand())
{
AssignTags();
}
else if (StringHelper.stringsEqual(command.getName(), "OnAssignTags")) //$NON-NLS-1$
{
OnAssignTags();
}
else if (StringHelper.stringsEqual(command.getName(), "Cancel")) //$NON-NLS-1$
{
Cancel();
}
else if (StringHelper.stringsEqual(command.getName(), "OnSave")) //$NON-NLS-1$
{
OnSave();
}
else if (StringHelper.stringsEqual(command.getName(), "OnRemove")) //$NON-NLS-1$
{
OnRemove();
}
else if (StringHelper.stringsEqual(command.getName(), "OnExport")) //$NON-NLS-1$
{
OnExport();
}
else if (StringHelper.stringsEqual(command.getName(), "OnExportNoTemplates")) //$NON-NLS-1$
{
OnExportNoTemplates();
}
else if (StringHelper.stringsEqual(command.getName(), "CancelConfirmation")) //$NON-NLS-1$
{
CancelConfirmation();
}
else if (StringHelper.stringsEqual(command.getName(), "CancelError")) //$NON-NLS-1$
{
CancelError();
}
else if (StringHelper.stringsEqual(command.getName(), "OnRunOnce")) //$NON-NLS-1$
{
OnRunOnce();
}
else if (StringHelper.stringsEqual(command.getName(), "OnNewTemplate")) //$NON-NLS-1$
{
OnNewTemplate();
}
else if (StringHelper.stringsEqual(command.getName(), "OnMigrate")) //$NON-NLS-1$
{
OnMigrate();
}
else if (command == getCancelMigrateCommand())
{
CancelMigration();
}
else if (StringHelper.stringsEqual(command.getName(), "OnShutdown")) //$NON-NLS-1$
{
OnShutdown();
}
else if (StringHelper.stringsEqual(command.getName(), "OnStop")) //$NON-NLS-1$
{
OnStop();
}
else if (StringHelper.stringsEqual(command.getName(), "OnChangeCD")) //$NON-NLS-1$
{
OnChangeCD();
}
else if (command.getName().equals("closeVncInfo")) { //$NON-NLS-1$
setWindow(null);
}
}
private SystemTreeItemModel systemTreeSelectedItem;
@Override
public SystemTreeItemModel getSystemTreeSelectedItem()
{
return systemTreeSelectedItem;
}
@Override
public void setSystemTreeSelectedItem(SystemTreeItemModel value)
{
systemTreeSelectedItem = value;
OnPropertyChanged(new PropertyChangedEventArgs("SystemTreeSelectedItem")); //$NON-NLS-1$
}
@Override
protected String getListName() {
return "VmListModel"; //$NON-NLS-1$
}
@Override
protected Guid extractStoragePoolIdNullSafe(VM entity) {
return entity.getstorage_pool_id();
}
} |
package ca.uhn.fhir.jpa.dao.r4;
import ca.uhn.fhir.jpa.dao.DaoConfig;
import ca.uhn.fhir.jpa.model.entity.ModelConfig;
import ca.uhn.fhir.jpa.model.entity.ResourceIndexedSearchParamToken;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.rest.api.server.IBundleProvider;
import ca.uhn.fhir.rest.param.*;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException;
import ca.uhn.fhir.util.TestUtil;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.*;
import org.hl7.fhir.r4.model.Appointment.AppointmentStatus;
import org.hl7.fhir.r4.model.Enumerations.AdministrativeGender;
import org.junit.*;
import org.mockito.internal.util.collections.ListUtil;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.List;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class FhirResourceDaoR4SearchCustomSearchParamTest extends BaseJpaR4Test {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirResourceDaoR4SearchCustomSearchParamTest.class);
@After
public void after() {
myDaoConfig.setValidateSearchParameterExpressionsOnSave(new DaoConfig().isValidateSearchParameterExpressionsOnSave());
}
@Before
public void beforeDisableResultReuse() {
myDaoConfig.setReuseCachedSearchResultsForMillis(null);
myModelConfig.setDefaultSearchParamsCanBeOverridden(new ModelConfig().isDefaultSearchParamsCanBeOverridden());
}
@Test
public void testCreateInvalidNoBase() {
SearchParameter fooSp = new SearchParameter();
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
fooSp.setTitle("FOO SP");
fooSp.setExpression("Patient.gender");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
try {
mySearchParameterDao.create(fooSp, mySrd);
fail();
} catch (UnprocessableEntityException e) {
assertEquals("SearchParameter.base is missing", e.getMessage());
}
}
@Test
@Ignore
public void testCreateInvalidParamInvalidResourceName() {
SearchParameter fooSp = new SearchParameter();
fooSp.addBase("Patient");
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
fooSp.setTitle("FOO SP");
fooSp.setExpression("PatientFoo.gender");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
try {
mySearchParameterDao.create(fooSp, mySrd);
fail();
} catch (UnprocessableEntityException e) {
assertEquals("Invalid SearchParameter.expression value \"PatientFoo.gender\": Unknown resource name \"PatientFoo\" (this name is not known in FHIR version \"R4\")", e.getMessage());
}
}
@Test
public void testCreateInvalidParamNoPath() {
SearchParameter fooSp = new SearchParameter();
fooSp.addBase("Patient");
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
fooSp.setTitle("FOO SP");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
try {
mySearchParameterDao.create(fooSp, mySrd);
fail();
} catch (UnprocessableEntityException e) {
assertEquals("SearchParameter.expression is missing", e.getMessage());
}
}
@Test
@Ignore
public void testCreateInvalidParamNoResourceName() {
SearchParameter fooSp = new SearchParameter();
fooSp.addBase("Patient");
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
fooSp.setTitle("FOO SP");
fooSp.setExpression("gender");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
try {
mySearchParameterDao.create(fooSp, mySrd);
fail();
} catch (UnprocessableEntityException e) {
assertEquals("Invalid SearchParameter.expression value \"gender\". Must start with a resource name", e.getMessage());
}
}
@Test
public void testCreateInvalidParamParamNullStatus() {
SearchParameter fooSp = new SearchParameter();
fooSp.addBase("Patient");
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
fooSp.setTitle("FOO SP");
fooSp.setExpression("Patient.gender");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(null);
try {
mySearchParameterDao.create(fooSp, mySrd);
fail();
} catch (UnprocessableEntityException e) {
assertEquals("SearchParameter.status is missing or invalid", e.getMessage());
}
}
@Test
public void testCreateSearchParameterOnSearchParameterDoesntCauseEndlessReindexLoop() {
SearchParameter fooSp = new SearchParameter();
fooSp.setCode("foo");
fooSp.addBase("SearchParameter");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
fooSp.setTitle("FOO SP");
fooSp.setExpression("SearchParameter.code");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(fooSp, mySrd);
assertEquals(1, myResourceReindexingSvc.forceReindexingPass());
myResourceReindexingSvc.forceReindexingPass();
myResourceReindexingSvc.forceReindexingPass();
myResourceReindexingSvc.forceReindexingPass();
myResourceReindexingSvc.forceReindexingPass();
assertEquals(0, myResourceReindexingSvc.forceReindexingPass());
}
@Test
public void testCustomReferenceParameter() throws Exception {
SearchParameter sp = new SearchParameter();
sp.addBase("Patient");
sp.setCode("myDoctor");
sp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.REFERENCE);
sp.setTitle("My Doctor");
sp.setExpression("Patient.extension('http://fmcna.com/myDoctor').value.as(Reference)");
sp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
sp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(sp);
mySearchParamRegistry.forceRefresh();
org.hl7.fhir.r4.model.Practitioner pract = new org.hl7.fhir.r4.model.Practitioner();
pract.setId("A");
pract.addName().setFamily("PRACT");
myPractitionerDao.update(pract);
Patient pat = myFhirCtx.newJsonParser().parseResource(Patient.class, loadClasspath("/r4/custom_resource_patient.json"));
IIdType pid = myPatientDao.create(pat, mySrd).getId().toUnqualifiedVersionless();
SearchParameterMap params = new SearchParameterMap();
params.add("myDoctor", new ReferenceParam("A"));
IBundleProvider outcome = myPatientDao.search(params);
List<String> ids = toUnqualifiedVersionlessIdValues(outcome);
ourLog.info("IDS: " + ids);
assertThat(ids, contains(pid.getValue()));
}
@Test
public void testIndexIntoBundle() {
SearchParameter sp = new SearchParameter();
sp.addBase("Bundle");
sp.setCode("messageid");
sp.setType(Enumerations.SearchParamType.TOKEN);
sp.setTitle("Message ID");
sp.setExpression("Bundle.entry.resource.as(MessageHeader).id");
sp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
sp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(sp));
mySearchParameterDao.create(sp);
mySearchParamRegistry.forceRefresh();
MessageHeader messageHeader = new MessageHeader();
messageHeader.setId("123");
Bundle bundle = new Bundle();
bundle.setType(Bundle.BundleType.MESSAGE);
bundle.addEntry()
.setResource(messageHeader);
ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle));
myBundleDao.create(bundle);
SearchParameterMap params = new SearchParameterMap();
params.add("messageid", new TokenParam("123"));
IBundleProvider outcome = myBundleDao.search(params);
List<String> ids = toUnqualifiedVersionlessIdValues(outcome);
ourLog.info("IDS: " + ids);
assertThat(ids, not(empty()));
}
@Test
public void testExtensionWithNoValueIndexesWithoutFailure() {
SearchParameter eyeColourSp = new SearchParameter();
eyeColourSp.addBase("Patient");
eyeColourSp.setCode("eyecolour");
eyeColourSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
eyeColourSp.setTitle("Eye Colour");
eyeColourSp.setExpression("Patient.extension('http://acme.org/eyecolour')");
eyeColourSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
eyeColourSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(eyeColourSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient p1 = new Patient();
p1.setActive(true);
p1.addExtension().setUrl("http:
IIdType p1id = myPatientDao.create(p1).getId().toUnqualifiedVersionless();
}
@Test
public void testIncludeExtensionReferenceAsRecurse() {
SearchParameter attendingSp = new SearchParameter();
attendingSp.addBase("Patient");
attendingSp.setCode("attending");
attendingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.REFERENCE);
attendingSp.setTitle("Attending");
attendingSp.setExpression("Patient.extension('http://acme.org/attending')");
attendingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
attendingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
attendingSp.getTarget().add(new CodeType("Practitioner"));
IIdType spId = mySearchParameterDao.create(attendingSp, mySrd).getId().toUnqualifiedVersionless();
mySearchParamRegistry.forceRefresh();
Practitioner p1 = new Practitioner();
p1.addName().setFamily("P1");
IIdType p1id = myPractitionerDao.create(p1).getId().toUnqualifiedVersionless();
Patient p2 = new Patient();
p2.addName().setFamily("P2");
p2.addExtension().setUrl("http://acme.org/attending").setValue(new Reference(p1id));
IIdType p2id = myPatientDao.create(p2).getId().toUnqualifiedVersionless();
Appointment app = new Appointment();
app.addParticipant().getActor().setReference(p2id.getValue());
IIdType appId = myAppointmentDao.create(app).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.addInclude(new Include("Appointment:patient", true));
map.addInclude(new Include("Patient:attending", true));
results = myAppointmentDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(appId.getValue(), p2id.getValue(), p1id.getValue()));
}
@Test
public void testOverrideAndDisableBuiltInSearchParametersWithOverridingDisabled() {
myModelConfig.setDefaultSearchParamsCanBeOverridden(false);
SearchParameter memberSp = new SearchParameter();
memberSp.setCode("member");
memberSp.addBase("Group");
memberSp.setType(Enumerations.SearchParamType.REFERENCE);
memberSp.setExpression("Group.member.entity");
memberSp.setStatus(Enumerations.PublicationStatus.RETIRED);
mySearchParameterDao.create(memberSp, mySrd);
SearchParameter identifierSp = new SearchParameter();
identifierSp.setCode("identifier");
identifierSp.addBase("Group");
identifierSp.setType(Enumerations.SearchParamType.TOKEN);
identifierSp.setExpression("Group.identifier");
identifierSp.setStatus(Enumerations.PublicationStatus.RETIRED);
mySearchParameterDao.create(identifierSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient p = new Patient();
p.addName().addGiven("G");
IIdType pid = myPatientDao.create(p).getId().toUnqualifiedVersionless();
Group g = new Group();
g.addIdentifier().setSystem("urn:foo").setValue("bar");
g.addMember().getEntity().setReferenceElement(pid);
myGroupDao.create(g);
assertThat(myResourceLinkDao.findAll(), not(empty()));
assertThat(ListUtil.filter(myResourceIndexedSearchParamTokenDao.findAll(), new ListUtil.Filter<ResourceIndexedSearchParamToken>() {
@Override
public boolean isOut(ResourceIndexedSearchParamToken object) {
return !object.getResourceType().equals("Group") || object.isMissing();
}
}), not(empty()));
}
@Test
public void testOverrideAndDisableBuiltInSearchParametersWithOverridingEnabled() {
myModelConfig.setDefaultSearchParamsCanBeOverridden(true);
SearchParameter memberSp = new SearchParameter();
memberSp.setCode("member");
memberSp.addBase("Group");
memberSp.setType(Enumerations.SearchParamType.REFERENCE);
memberSp.setExpression("Group.member.entity");
memberSp.setStatus(Enumerations.PublicationStatus.RETIRED);
mySearchParameterDao.create(memberSp, mySrd);
SearchParameter identifierSp = new SearchParameter();
identifierSp.setCode("identifier");
identifierSp.addBase("Group");
identifierSp.setType(Enumerations.SearchParamType.TOKEN);
identifierSp.setExpression("Group.identifier");
identifierSp.setStatus(Enumerations.PublicationStatus.RETIRED);
mySearchParameterDao.create(identifierSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient p = new Patient();
p.addName().addGiven("G");
IIdType pid = myPatientDao.create(p).getId().toUnqualifiedVersionless();
Group g = new Group();
g.addIdentifier().setSystem("urn:foo").setValue("bar");
g.addMember().getEntity().setReferenceElement(pid);
myGroupDao.create(g);
assertThat(myResourceLinkDao.findAll(), empty());
assertThat(ListUtil.filter(myResourceIndexedSearchParamTokenDao.findAll(), new ListUtil.Filter<ResourceIndexedSearchParamToken>() {
@Override
public boolean isOut(ResourceIndexedSearchParamToken object) {
return !object.getResourceType().equals("Group") || object.isMissing();
}
}), empty());
}
/**
* See #863
*/
@Test
public void testParamWithMultipleBases() {
SearchParameter sp = new SearchParameter();
sp.setUrl("http://clinicalcloud.solutions/fhir/SearchParameter/request-reason");
sp.setName("reason");
sp.setStatus(Enumerations.PublicationStatus.ACTIVE);
sp.setCode("reason");
sp.addBase("MedicationRequest");
sp.addBase("ServiceRequest");
sp.setType(Enumerations.SearchParamType.REFERENCE);
sp.setExpression("MedicationRequest.reasonReference | ServiceRequest.reasonReference");
sp.addTarget("Condition");
sp.addTarget("Observation");
mySearchParameterDao.create(sp);
mySearchParamRegistry.forceRefresh();
Condition condition = new Condition();
condition.getCode().setText("A condition");
String conditionId = myConditionDao.create(condition).getId().toUnqualifiedVersionless().getValue();
MedicationRequest mr = new MedicationRequest();
mr.addReasonReference().setReference(conditionId);
String mrId = myMedicationRequestDao.create(mr).getId().toUnqualifiedVersionless().getValue();
ServiceRequest pr = new ServiceRequest();
pr.addReasonReference().setReference(conditionId);
myServiceRequestDao.create(pr);
SearchParameterMap map = new SearchParameterMap();
map.setLoadSynchronous(true);
map.add("reason", new ReferenceParam(conditionId));
List<String> results = toUnqualifiedVersionlessIdValues(myMedicationRequestDao.search(map));
assertThat(results.toString(), results, contains(mrId));
}
/**
* See #863
*/
@Test
public void testParamWithMultipleBasesToken() {
SearchParameter sp = new SearchParameter();
sp.setUrl("http://clinicalcloud.solutions/fhir/SearchParameter/request-reason");
sp.setName("reason");
sp.setStatus(Enumerations.PublicationStatus.ACTIVE);
sp.setCode("reason");
sp.addBase("MedicationRequest");
sp.addBase("ServiceRequest");
sp.setType(Enumerations.SearchParamType.TOKEN);
sp.setExpression("MedicationRequest.reasonCode | ServiceRequest.reasonCode");
mySearchParameterDao.create(sp);
mySearchParamRegistry.forceRefresh();
MedicationRequest mr = new MedicationRequest();
mr.addReasonCode().addCoding().setSystem("foo").setCode("bar");
String mrId = myMedicationRequestDao.create(mr).getId().toUnqualifiedVersionless().getValue();
ServiceRequest pr = new ServiceRequest();
pr.addReasonCode().addCoding().setSystem("foo").setCode("bar");
myServiceRequestDao.create(pr);
SearchParameterMap map = new SearchParameterMap();
map.setLoadSynchronous(true);
map.add("reason", new TokenParam("foo", "bar"));
List<String> results = toUnqualifiedVersionlessIdValues(myMedicationRequestDao.search(map));
assertThat(results, contains(mrId));
}
@Test
public void testRejectSearchParamWithInvalidExpression() {
SearchParameter threadIdSp = new SearchParameter();
threadIdSp.addBase("Communication");
threadIdSp.setCode("has-attachments");
threadIdSp.setType(Enumerations.SearchParamType.REFERENCE);
threadIdSp.setExpression("Communication.payload[1].contentAttachment is not null");
threadIdSp.setXpathUsage(SearchParameter.XPathUsageType.NORMAL);
threadIdSp.setStatus(Enumerations.PublicationStatus.ACTIVE);
try {
mySearchParameterDao.create(threadIdSp, mySrd);
fail();
} catch (UnprocessableEntityException e) {
assertThat(e.getMessage(), startsWith("Invalid SearchParameter.expression value \"Communication.payload[1].contentAttachment is not null\""));
}
}
@Test
public void testSearchForExtensionReferenceWithNonMatchingTarget() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("sibling");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.REFERENCE);
siblingSp.setTitle("Sibling");
siblingSp.setExpression("Patient.extension('http://acme.org/sibling')");
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
siblingSp.getTarget().add(new CodeType("Organization"));
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient p1 = new Patient();
p1.addName().setFamily("P1");
IIdType p1id = myPatientDao.create(p1).getId().toUnqualifiedVersionless();
Patient p2 = new Patient();
p2.addName().setFamily("P2");
p2.addExtension().setUrl("http://acme.org/sibling").setValue(new Reference(p1id));
IIdType p2id = myPatientDao.create(p2).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
// Search by ref
map = new SearchParameterMap();
map.add("sibling", new ReferenceParam(p1id.getValue()));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, empty());
// Search by chain
map = new SearchParameterMap();
map.add("sibling", new ReferenceParam("name", "P1"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, empty());
}
@Test
public void testSearchForExtensionReferenceWithTarget() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("sibling");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.REFERENCE);
siblingSp.setTitle("Sibling");
siblingSp.setExpression("Patient.extension('http://acme.org/sibling')");
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
siblingSp.getTarget().add(new CodeType("Patient"));
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient p1 = new Patient();
p1.addName().setFamily("P1");
IIdType p1id = myPatientDao.create(p1).getId().toUnqualifiedVersionless();
Patient p2 = new Patient();
p2.addName().setFamily("P2");
p2.addExtension().setUrl("http://acme.org/sibling").setValue(new Reference(p1id));
IIdType p2id = myPatientDao.create(p2).getId().toUnqualifiedVersionless();
Appointment app = new Appointment();
app.addParticipant().getActor().setReference(p2id.getValue());
IIdType appid = myAppointmentDao.create(app).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
// Search by ref
map = new SearchParameterMap();
map.add("sibling", new ReferenceParam(p1id.getValue()));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
// Search by chain
map = new SearchParameterMap();
map.add("sibling", new ReferenceParam("name", "P1"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
// Search by two level chain
map = new SearchParameterMap();
map.add("patient", new ReferenceParam("sibling.name", "P1"));
results = myAppointmentDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, containsInAnyOrder(appid.getValue()));
}
@Test
public void testSearchForExtensionReferenceWithoutTarget() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("sibling");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.REFERENCE);
siblingSp.setTitle("Sibling");
siblingSp.setExpression("Patient.extension('http://acme.org/sibling')");
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient p1 = new Patient();
p1.addName().setFamily("P1");
IIdType p1id = myPatientDao.create(p1).getId().toUnqualifiedVersionless();
Patient p2 = new Patient();
p2.addName().setFamily("P2");
p2.addExtension().setUrl("http://acme.org/sibling").setValue(new Reference(p1id));
IIdType p2id = myPatientDao.create(p2).getId().toUnqualifiedVersionless();
Appointment app = new Appointment();
app.addParticipant().getActor().setReference(p2id.getValue());
IIdType appid = myAppointmentDao.create(app).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
// Search by ref
map = new SearchParameterMap();
map.add("sibling", new ReferenceParam(p1id.getValue()));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
// Search by chain
map = new SearchParameterMap();
map.add("sibling", new ReferenceParam("name", "P1"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
// Search by two level chain
map = new SearchParameterMap();
map.add("patient", new ReferenceParam("sibling.name", "P1"));
results = myAppointmentDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, containsInAnyOrder(appid.getValue()));
}
@Test
public void testSearchForExtensionToken() {
SearchParameter eyeColourSp = new SearchParameter();
eyeColourSp.addBase("Patient");
eyeColourSp.setCode("eyecolour");
eyeColourSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
eyeColourSp.setTitle("Eye Colour");
eyeColourSp.setExpression("Patient.extension('http://acme.org/eyecolour')");
eyeColourSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
eyeColourSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(eyeColourSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient p1 = new Patient();
p1.setActive(true);
p1.addExtension().setUrl("http://acme.org/eyecolour").setValue(new CodeType("blue"));
IIdType p1id = myPatientDao.create(p1).getId().toUnqualifiedVersionless();
Patient p2 = new Patient();
p2.setActive(true);
p2.addExtension().setUrl("http://acme.org/eyecolour").setValue(new CodeType("green"));
IIdType p2id = myPatientDao.create(p2).getId().toUnqualifiedVersionless();
// Try with custom gender SP
SearchParameterMap map = new SearchParameterMap();
map.add("eyecolour", new TokenParam(null, "blue"));
IBundleProvider results = myPatientDao.search(map);
List<String> foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p1id.getValue()));
}
@Test
public void testSearchForExtensionTwoDeepCodeableConcept() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
siblingSp.getTarget().add(new CodeType("Organization"));
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new CodeableConcept().addCoding(new Coding().setSystem("foo").setCode("bar")));
IIdType p2id = myPatientDao.create(patient).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new TokenParam("foo", "bar"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
}
@Test
public void testSearchForExtensionTwoDeepCoding() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
siblingSp.getTarget().add(new CodeType("Organization"));
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new Coding().setSystem("foo").setCode("bar"));
IIdType p2id = myPatientDao.create(patient).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new TokenParam("foo", "bar"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
}
@Test
public void testSearchForExtensionTwoDeepDate() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.DATE);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Appointment apt = new Appointment();
apt.setStatus(AppointmentStatus.ARRIVED);
IIdType aptId = myAppointmentDao.create(apt).getId().toUnqualifiedVersionless();
Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new DateType("2012-01-02"));
IIdType p2id = myPatientDao.create(patient).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new DateParam("2012-01-02"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
}
@Test
public void testSearchForExtensionTwoDeepDecimal() {
final SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.NUMBER);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
txTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus theArg0) {
mySearchParameterDao.create(siblingSp, mySrd);
}
});
txTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus theArg0) {
mySearchParamRegistry.forceRefresh();
}
});
final Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new DecimalType("2.1"));
IIdType p2id = txTemplate.execute(new TransactionCallback<IIdType>() {
@Override
public IIdType doInTransaction(TransactionStatus theArg0) {
return myPatientDao.create(patient).getId().toUnqualifiedVersionless();
}
});
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new NumberParam("2.1"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
}
@Test
public void testSearchForExtensionTwoDeepNumber() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.NUMBER);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new IntegerType(5));
IIdType p2id = myPatientDao.create(patient).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new NumberParam("5"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
}
@Test
public void testSearchForExtensionTwoDeepReference() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.REFERENCE);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
siblingSp.getTarget().add(new CodeType("Appointment"));
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Appointment apt = new Appointment();
apt.setStatus(AppointmentStatus.ARRIVED);
IIdType aptId = myAppointmentDao.create(apt).getId().toUnqualifiedVersionless();
Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new Reference(aptId.getValue()));
IIdType p2id = myPatientDao.create(patient).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new ReferenceParam(aptId.getValue()));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
}
@Test
public void testSearchForExtensionTwoDeepReferenceWithoutType() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.REFERENCE);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Appointment apt = new Appointment();
apt.setStatus(AppointmentStatus.ARRIVED);
IIdType aptId = myAppointmentDao.create(apt).getId().toUnqualifiedVersionless();
Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new Reference(aptId.getValue()));
IIdType p2id = myPatientDao.create(patient).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new ReferenceParam(aptId.getValue()));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
}
@Test
public void testSearchForExtensionTwoDeepReferenceWrongType() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.REFERENCE);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
siblingSp.getTarget().add(new CodeType("Observation"));
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Appointment apt = new Appointment();
apt.setStatus(AppointmentStatus.ARRIVED);
IIdType aptId = myAppointmentDao.create(apt).getId().toUnqualifiedVersionless();
Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new Reference(aptId.getValue()));
IIdType p2id = myPatientDao.create(patient).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new ReferenceParam(aptId.getValue()));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, empty());
}
@Test
public void testSearchForExtensionTwoDeepString() {
SearchParameter siblingSp = new SearchParameter();
siblingSp.addBase("Patient");
siblingSp.setCode("foobar");
siblingSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.STRING);
siblingSp.setTitle("FooBar");
siblingSp.setExpression("Patient.extension('http:
siblingSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
siblingSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
mySearchParameterDao.create(siblingSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient patient = new Patient();
patient.addName().setFamily("P2");
Extension extParent = patient
.addExtension()
.setUrl("http://acme.org/foo");
extParent
.addExtension()
.setUrl("http://acme.org/bar")
.setValue(new StringType("HELLOHELLO"));
IIdType p2id = myPatientDao.create(patient).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
map = new SearchParameterMap();
map.add("foobar", new StringParam("hello"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(p2id.getValue()));
}
@Test
public void testSearchForStringOnIdentifier() {
SearchParameter fooSp = new SearchParameter();
fooSp.addBase("Patient");
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.STRING);
fooSp.setTitle("FOO SP");
fooSp.setExpression("Patient.identifier.value");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
IIdType spId = mySearchParameterDao.create(fooSp, mySrd).getId().toUnqualifiedVersionless();
mySearchParamRegistry.forceRefresh();
Patient pat = new Patient();
pat.addIdentifier().setSystem("FOO123").setValue("BAR678");
pat.setGender(AdministrativeGender.MALE);
IIdType patId = myPatientDao.create(pat, mySrd).getId().toUnqualifiedVersionless();
Patient pat2 = new Patient();
pat.setGender(AdministrativeGender.FEMALE);
myPatientDao.create(pat2, mySrd).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
// Partial match
map = new SearchParameterMap();
map.add("foo", new StringParam("bar"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(patId.getValue()));
// Non match
map = new SearchParameterMap();
map.add("foo", new StringParam("zzz"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, empty());
}
@Test
public void testSearchForStringOnIdentifierWithSpecificSystem() {
SearchParameter fooSp = new SearchParameter();
fooSp.addBase("Patient");
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.STRING);
fooSp.setTitle("FOO SP");
fooSp.setExpression("Patient.identifier.where(system = 'http://AAA').value");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
IIdType spId = mySearchParameterDao.create(fooSp, mySrd).getId().toUnqualifiedVersionless();
mySearchParamRegistry.forceRefresh();
Patient pat = new Patient();
pat.addIdentifier().setSystem("http://AAA").setValue("BAR678");
pat.setGender(AdministrativeGender.MALE);
IIdType patId = myPatientDao.create(pat, mySrd).getId().toUnqualifiedVersionless();
Patient pat2 = new Patient();
pat2.addIdentifier().setSystem("http://BBB").setValue("BAR678");
pat2.setGender(AdministrativeGender.FEMALE);
myPatientDao.create(pat2, mySrd).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
// Partial match
map = new SearchParameterMap();
map.add("foo", new StringParam("bar"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(patId.getValue()));
// Non match
map = new SearchParameterMap();
map.add("foo", new StringParam("zzz"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, empty());
}
@Test
public void testSearchParameterDescendsIntoContainedResource() {
SearchParameter sp = new SearchParameter();
sp.addBase("Observation");
sp.setCode("specimencollectedtime");
sp.setType(Enumerations.SearchParamType.DATE);
sp.setTitle("Observation Specimen Collected Time");
sp.setExpression("Observation.specimen.resolve().receivedTime");
sp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
sp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(sp));
mySearchParameterDao.create(sp);
mySearchParamRegistry.forceRefresh();
Specimen specimen = new Specimen();
specimen.setId("#FOO");
specimen.setReceivedTimeElement(new DateTimeType("2011-01-01"));
Observation o = new Observation();
o.setId("O1");
o.getContained().add(specimen);
o.setStatus(Observation.ObservationStatus.FINAL);
o.setSpecimen(new Reference("#FOO"));
ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(o));
myObservationDao.update(o);
specimen = new Specimen();
specimen.setId("#FOO");
specimen.setReceivedTimeElement(new DateTimeType("2011-01-03"));
o = new Observation();
o.setId("O2");
o.getContained().add(specimen);
o.setStatus(Observation.ObservationStatus.FINAL);
o.setSpecimen(new Reference("#FOO"));
myObservationDao.update(o);
SearchParameterMap params = new SearchParameterMap();
params.add("specimencollectedtime", new DateParam("2011-01-01"));
IBundleProvider outcome = myObservationDao.search(params);
List<String> ids = toUnqualifiedVersionlessIdValues(outcome);
ourLog.info("IDS: " + ids);
assertThat(ids, contains("Observation/O1"));
}
@Test
public void testSearchWithCustomParam() {
SearchParameter fooSp = new SearchParameter();
fooSp.addBase("Patient");
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
fooSp.setTitle("FOO SP");
fooSp.setExpression("Patient.gender");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.ACTIVE);
IIdType spId = mySearchParameterDao.create(fooSp, mySrd).getId().toUnqualifiedVersionless();
mySearchParamRegistry.forceRefresh();
Patient pat = new Patient();
pat.setGender(AdministrativeGender.MALE);
IIdType patId = myPatientDao.create(pat, mySrd).getId().toUnqualifiedVersionless();
Patient pat2 = new Patient();
pat.setGender(AdministrativeGender.FEMALE);
IIdType patId2 = myPatientDao.create(pat2, mySrd).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
// Try with custom gender SP
map = new SearchParameterMap();
map.add("foo", new TokenParam(null, "male"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(patId.getValue()));
// Try with normal gender SP
map = new SearchParameterMap();
map.add("gender", new TokenParam(null, "male"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(patId.getValue()));
// Delete the param
mySearchParameterDao.delete(spId, mySrd);
mySearchParamRegistry.forceRefresh();
myResourceReindexingSvc.forceReindexingPass();
// Try with custom gender SP
map = new SearchParameterMap();
map.add("foo", new TokenParam(null, "male"));
try {
myPatientDao.search(map).size();
fail();
} catch (InvalidRequestException e) {
assertEquals("Unknown search parameter foo for resource type Patient", e.getMessage());
}
}
@Test
public void testSearchWithCustomParamDraft() {
SearchParameter fooSp = new SearchParameter();
fooSp.addBase("Patient");
fooSp.setCode("foo");
fooSp.setType(org.hl7.fhir.r4.model.Enumerations.SearchParamType.TOKEN);
fooSp.setTitle("FOO SP");
fooSp.setExpression("Patient.gender");
fooSp.setXpathUsage(org.hl7.fhir.r4.model.SearchParameter.XPathUsageType.NORMAL);
fooSp.setStatus(org.hl7.fhir.r4.model.Enumerations.PublicationStatus.DRAFT);
mySearchParameterDao.create(fooSp, mySrd);
mySearchParamRegistry.forceRefresh();
Patient pat = new Patient();
pat.setGender(AdministrativeGender.MALE);
IIdType patId = myPatientDao.create(pat, mySrd).getId().toUnqualifiedVersionless();
Patient pat2 = new Patient();
pat.setGender(AdministrativeGender.FEMALE);
IIdType patId2 = myPatientDao.create(pat2, mySrd).getId().toUnqualifiedVersionless();
SearchParameterMap map;
IBundleProvider results;
List<String> foundResources;
// Try with custom gender SP (should find nothing)
map = new SearchParameterMap();
map.add("foo", new TokenParam(null, "male"));
try {
myPatientDao.search(map).size();
fail();
} catch (InvalidRequestException e) {
assertEquals("Unknown search parameter foo for resource type Patient", e.getMessage());
}
// Try with normal gender SP
map = new SearchParameterMap();
map.add("gender", new TokenParam(null, "male"));
results = myPatientDao.search(map);
foundResources = toUnqualifiedVersionlessIdValues(results);
assertThat(foundResources, contains(patId.getValue()));
}
@AfterClass
public static void afterClassClearContext() {
TestUtil.clearAllStaticFieldsForUnitTest();
}
} |
package com.github.ibole.infrastructure.cache.session.redis;
import com.github.ibole.infrastructure.cache.redis.RedisSimpleTempalte;
import com.github.ibole.infrastructure.common.serialization.KryoSerializationUtil;
import com.google.common.base.Strings;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
public class RedisSessionManager {
public static final String SESSION_PREFIX = "SESSION:";
public static final String SESSION_ID_PREFIX = SESSION_PREFIX + "RJSID_";
public static final String SESSION_ID_COOKIE = "RSESSIONID";
public static final int DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS = 1800;
public static final int DEFAULT_MAX_UPDATER_INTERVAL_TIME = 500;
// Session(ms)
private int expirationUpdateInterval;
// Session(second)
private int sessionTimeOut;
private RedisSimpleTempalte redisClient;
public RedisSessionManager() {
this.expirationUpdateInterval = 600;
this.sessionTimeOut = 1800;
}
public RedisSessionManager(String host, String port, String password) {
this(host, port, password, 1800);
}
/**
* Constructor.
* @param host String
* @param port String
* @param password String
* @param sessionTimeOut int
*/
public RedisSessionManager(String host, String port, String password, int sessionTimeOut) {
this.expirationUpdateInterval = DEFAULT_MAX_UPDATER_INTERVAL_TIME;
this.sessionTimeOut =
sessionTimeOut == 0 ? DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS : sessionTimeOut;
this.redisClient = new RedisSimpleTempalte(host, Integer.parseInt(port), password);
}
public RedisSimpleTempalte getRedisClient() {
return this.redisClient;
}
public void setExpirationUpdateInterval(int expirationUpdateInterval) {
this.expirationUpdateInterval = expirationUpdateInterval;
}
public void setMaxInactiveInterval(int sessionTimeOut) {
this.sessionTimeOut = sessionTimeOut;
}
/**
* Session.
* @param request RedisHttpServletRequestWrapper
* @param response HttpServletResponse
* @param requestEventSubject RequestEventSubject
* @param create boolean
* @return RedisHttpSession RedisHttpSession
*
*/
public RedisHttpSession createSession(RedisHttpServletRequestWrapper request,
HttpServletResponse response, RequestEventSubject requestEventSubject, boolean create) {
String sessionId = getRequestedSessionId(request);
RedisHttpSession session = null;
// SeeionIDSession
if ((Strings.isNullOrEmpty(sessionId)) && (!(create))) {
return null;
}
// SessionIDRedisSession
if (!Strings.isNullOrEmpty(sessionId)) {
session = loadSession(sessionId);
}
// Session,Session
if ((session == null) && (create)) {
session = createEmptySession(request, response);
}
// Session
if (session != null) {
attachEvent(session, request, response, requestEventSubject);
}
return session;
}
/**
* RequestCookiesSessionId.
*/
private String getRequestedSessionId(HttpServletRequestWrapper request) {
Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0) {
return null;
}
for (Cookie cookie : cookies) {
if (SESSION_ID_COOKIE.equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
/**
* Session.
*
* @param session RedisHttpSession
*/
private void saveSession(RedisHttpSession session) {
String sessionid = generateSessionKey(session.id);
try {
// Session
if (session.expired) {
// CacheUtil.removeKey(session.id);
// Redis
this.getRedisClient().del(sessionid);
} else {
// Session
// CacheUtil.put(session.id, session);
// RedisSession
this.getRedisClient().set(sessionid,
KryoSerializationUtil.getInstance().serialize(session), this.sessionTimeOut);
}
} catch (Exception e) {
throw new SessionException(e);
}
}
/**
* SessionRequest.
*
* @param session RedisHttpSession
* @param request HttpServletRequestWrapper
* @param response HttpServletResponse
* @param requestEventSubject RequestEventSubject
*/
private void attachEvent(final RedisHttpSession session, final HttpServletRequestWrapper request,
final HttpServletResponse response, RequestEventSubject requestEventSubject) {
session.setListener(new RedisSessionListener() {
public void onInvalidated(RedisHttpSession session) {
// Cookies
saveCookie(session, request, response);
// RedisSession
saveSession(session);
}
});
requestEventSubject.attach(new RequestEventObserver() {
public void completed(HttpServletRequest servletRequest, HttpServletResponse response) {
int updateInterval = (int) (System.currentTimeMillis() - session.lastAccessedTime);
// SessionSessionRedis
// Session Redis
if (session.isNew == false
&& session.isDirty == false && updateInterval < expirationUpdateInterval) {
return;
}
// SessionRedis
if (session.expired) {
return;
}
session.lastAccessedTime = System.currentTimeMillis();
saveSession(session);
}
});
}
/**
* Session.
*
* @param request RedisHttpServletRequestWrapper
* @param response HttpServletResponse
* @return RedisHttpSession RedisHttpSession
*/
private RedisHttpSession createEmptySession(RedisHttpServletRequestWrapper request,
HttpServletResponse response) {
RedisHttpSession session = new RedisHttpSession();
session.id = createSessionId();
session.creationTime = System.currentTimeMillis();
session.maxInactiveInterval = this.sessionTimeOut;
session.isNew = true;
saveCookie(session, request, response);
return session;
}
private String createSessionId() {
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
private void saveCookie(RedisHttpSession session, HttpServletRequestWrapper request,
HttpServletResponse response) {
if (session.isNew == false && session.expired == false) {
return;
}
Cookie cookie = new Cookie(SESSION_ID_COOKIE, null);
cookie.setPath(request.getContextPath());
// SessionCookies
if (session.expired) {
cookie.setMaxAge(0);
// SessionSessionID
} else if (session.isNew) {
cookie.setValue(session.getId());
}
response.addCookie(cookie);
}
/**
* RedisSession.
*
* @param sessionId String
* @return RedisHttpSession RedisHttpSession
*/
private RedisHttpSession loadSession(String sessionId) {
RedisHttpSession session = null;
byte[] bytes = getRedisClient().getByte(generateSessionKey(sessionId));
if (bytes != null) {
session = KryoSerializationUtil.getInstance().deserialize(bytes);
}
// Session
if (session != null) {
session.isNew = false;
session.isDirty = false;
}
return session;
}
private static String generateSessionKey(String sessionId) {
return SESSION_ID_PREFIX.concat(sessionId);
}
} |
package org.jaulp.wicket.base.components.labeled.examples;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.jaulp.test.objects.Gender;
import org.jaulp.test.objects.Person;
import org.jaulp.wicket.base.mainbase.BasePage;
import org.jaulp.wicket.components.labeled.checkbox.LabeledCheckboxPanel;
import org.jaulp.wicket.components.labeled.textarea.LabeledTextAreaPanel;
import org.jaulp.wicket.components.labeled.textfield.LabeledTextfieldPanel;
public class LabeledHomePage extends BasePage {
private static final long serialVersionUID = 1L;
private Person person;
public LabeledHomePage(final PageParameters parameters) {
super(parameters);
person = new Person();
person.setGender(Gender.UNDEFINED);
person.setName("");
person.setAbout("");
person.setMarried(false);
final CompoundPropertyModel<Person> cpModel = new CompoundPropertyModel<Person>(
person);
final Form<Person> form =
new Form<Person>("form", cpModel);
add(form);
LabeledTextfieldPanel<Person> nameTextField = new LabeledTextfieldPanel<Person>("name", cpModel, Model.of("Name:"));
form.add(nameTextField);
LabeledTextAreaPanel<Person> about = new LabeledTextAreaPanel<Person>("about", cpModel, Model.of("About:"));
form.add(about);
LabeledCheckboxPanel<Person> married = new LabeledCheckboxPanel<Person>("married", cpModel, Model.of("Married:"));
form.add(married);
// Create submit button for the form
final Button submitButton = new Button("submitButton") {
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
info("Person:"+person.toString());
}
};
form.add(submitButton);
add(new FeedbackPanel("feedbackpanel"));
}
} |
package net.resheim.eclipse.timekeeper.ui.preferences;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import net.resheim.eclipse.timekeeper.db.TimekeeperPlugin;
import net.resheim.eclipse.timekeeper.db.report.ReportTemplate;
import net.resheim.eclipse.timekeeper.db.report.ReportTemplate.Type;
/**
* This preference page allows for setting up various report templates.
*
* @author Torkild U. Resheim
* @since 2.0
*/
public class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private List list;
/** List of templates that can be modified */
private Map<String, ReportTemplate> templates;
private SourceViewer sourceViewer;
/** The currently selected template */
private ReportTemplate selectedTemplate;
/** Name of the default template */
private String defaultTemplate;
private Button defaultTemplateButton;
private Combo templateTypeButton;
public TemplatePreferencePage() {
}
@SuppressWarnings("unchecked")
@Override
public Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
container.setLayout(new GridLayout(4, false));
list = new List(container, SWT.BORDER);
list.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 3));
list.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
int[] selectedItems = list.getSelectionIndices();
for (int i : selectedItems) {
Optional<ReportTemplate> o = templates.values().stream()
.filter(t -> t.getName().equals(list.getItem(i)))
.findFirst();
if (o.isPresent()) {
select(o.get());
}
}
}
});
Button addButton = new Button(container, SWT.NONE);
addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
addButton.setText("Add");
addButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ReportTemplate template = new ReportTemplate("Template #" + (templates.size() + 1),
ReportTemplate.Type.TEXT, "");
templates.put(template.getName(),template);
updateListAndSelect(template);
}
});
Button removeButton = new Button(container, SWT.NONE);
removeButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
removeButton.setText("Remove");
removeButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (selectedTemplate != null) {
templates.remove(selectedTemplate.getName());
updateListAndSelect(null);
}
}
});
Button duplicateButton = new Button(container, SWT.NONE);
duplicateButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
duplicateButton.setText("Duplicate");
Label lblNewLabel = new Label(container, SWT.NONE);
lblNewLabel.setText("Template code:");
// spacers
new Label(container, SWT.NONE);
new Label(container, SWT.NONE);
new Label(container, SWT.NONE);
int styles = SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION;
CompositeRuler cr = new CompositeRuler();
LineNumberRulerColumn lnrc = new LineNumberRulerColumn();
cr.addDecorator(0, lnrc);
sourceViewer = new SourceViewer(container, cr, styles);
StyledText styledText = sourceViewer.getTextWidget();
styledText.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, true, 3, 1));
sourceViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
Document document = new Document();
sourceViewer.setDocument(document);
sourceViewer.configure(new SourceViewerConfiguration());
Font font = JFaceResources.getFont(JFaceResources.TEXT_FONT);
sourceViewer.getTextWidget().setFont(font);
document.addDocumentListener(new IDocumentListener() {
@Override
public void documentChanged(DocumentEvent event) {
if (selectedTemplate != null) {
selectedTemplate.setCode(sourceViewer.getDocument().get());
}
}
@Override
public void documentAboutToBeChanged(DocumentEvent event) {
}
});
// spacer
new Label(container, SWT.NONE);
Label label = new Label(container, SWT.NONE);
label.setText("Content type:");
templateTypeButton = new Combo(container, SWT.READ_ONLY);
templateTypeButton.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
templateTypeButton.setText("Type");
templateTypeButton.setItems("HTML", "Plain Text", "Rich Text Format");
templateTypeButton.select(0);
templateTypeButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
switch (templateTypeButton.getSelectionIndex()) {
case 0:
selectedTemplate.setType(Type.HTML);
break;
case 1:
selectedTemplate.setType(Type.TEXT);
break;
case 2:
selectedTemplate.setType(Type.RTF);
break;
}
}
});
defaultTemplateButton = new Button(container, SWT.CHECK);
defaultTemplateButton.setText("Use as default template");
defaultTemplateButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
defaultTemplate = selectedTemplate.getName();
}
});
// spacer
new Label(container, SWT.NONE);
// clear out all the privately kept templates
templates = new HashMap<>();
// and load the contents from the current preferences
IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, TimekeeperPlugin.BUNDLE_ID);
defaultTemplate = store.getString(TimekeeperPlugin.PREF_DEFAULT_TEMPLATE);
// not exactly the most future-proof method, but it will suffice
byte[] decoded = Base64.getDecoder().decode(store.getString(TimekeeperPlugin.PREF_REPORT_TEMPLATES));
ByteArrayInputStream bis = new ByteArrayInputStream(decoded);
try {
ObjectInputStream ois = new ObjectInputStream(bis);
java.util.List<ReportTemplate> rt = (java.util.List<ReportTemplate>) ois.readObject();
for (ReportTemplate t : rt) {
templates.put(t.getName(), t);
}
java.util.List<String> names = templates.values().stream().map(t -> t.getName()).sorted()
.collect(Collectors.toList());
list.setItems(names.toArray(new String[names.size()]));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return container;
}
/**
* Initialize the preference page.
*/
public void init(IWorkbench workbench) {
}
@SuppressWarnings("unchecked")
@Override
protected void performDefaults() {
// load _default_ templates to a list
IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, TimekeeperPlugin.BUNDLE_ID);
byte[] decoded = Base64.getDecoder().decode(store.getDefaultString(TimekeeperPlugin.PREF_REPORT_TEMPLATES));
ByteArrayInputStream bis = new ByteArrayInputStream(decoded);
try {
ObjectInputStream ois = new ObjectInputStream(bis);
java.util.List<ReportTemplate> defaults = (java.util.List<ReportTemplate>) ois.readObject();
// remove all privately kept templates
templates.clear();
// and add the default ones to the list
for (ReportTemplate t : defaults) {
templates.put(t.getName(), t);
}
updateListAndSelect(selectedTemplate);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
defaultTemplate = store.getDefaultString(TimekeeperPlugin.PREF_DEFAULT_TEMPLATE);
}
@Override
public boolean performOk() {
IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, TimekeeperPlugin.BUNDLE_ID);
// serialize the list of templates to a string and store it in the preferences
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out)) {
java.util.List<ReportTemplate> saveTemplates = new ArrayList<>();
templates.values().forEach(t -> saveTemplates.add(t));
oos.writeObject(saveTemplates);
String encoded = Base64.getEncoder().encodeToString(out.toByteArray());
store.setValue(TimekeeperPlugin.PREF_REPORT_TEMPLATES, encoded);
} catch (IOException e) {
e.printStackTrace();
return false;
}
// specify which template is the default
store.setDefault(TimekeeperPlugin.PREF_DEFAULT_TEMPLATE, defaultTemplate);
return true;
}
private void updateListAndSelect(ReportTemplate template) {
// create a list of sorted template names
java.util.List<String> collected = templates
.values()
.stream()
.map(t -> t.getName())
.sorted()
.collect(Collectors.toList());
String[] array = collected.toArray(new String[collected.size()]);
list.setItems(array);
select(template);
}
/**
* Handle that the specified template has been selected.
*
* @param template
* the selected template
*/
private void select(ReportTemplate template) {
boolean found = false;
defaultTemplateButton.setSelection(false);
// select the specified template
if (template != null) {
for (int i = 0; i < list.getItems().length; i++) {
String name = list.getItem(i);
if (name.equals(template.getName())) {
found = true;
list.select(i);
selectedTemplate = template;
sourceViewer.getDocument().set(templates.get(name).getCode());
sourceViewer.moveFocusToWidgetToken();
if (name.equals(defaultTemplate)) {
defaultTemplateButton.setSelection(true);
}
switch (selectedTemplate.getType()) {
case HTML:
templateTypeButton.select(0);
break;
case TEXT:
templateTypeButton.select(1);
break;
case RTF:
templateTypeButton.select(3);
break;
}
}
}
}
// clear the source viewer
if (template == null || !found) {
selectedTemplate = null;
sourceViewer.getDocument().set("");
}
}
} |
package org.openmole.ui.plugin.builder;
import org.openmole.core.model.plan.IPlan;
import org.openmole.core.implementation.data.DataSet;
import org.openmole.core.structuregenerator.ComplexNode;
import org.openmole.core.structuregenerator.PrototypeNode;
import org.openmole.core.implementation.capsule.ExplorationTaskCapsule;
import org.openmole.core.implementation.capsule.TaskCapsule;
import org.openmole.core.implementation.data.Prototype;
import org.openmole.core.implementation.mole.Mole;
import org.openmole.core.implementation.plan.Factor;
import org.openmole.core.implementation.transition.ExplorationTransition;
import org.openmole.core.model.capsule.IExplorationTaskCapsule;
import org.openmole.core.model.capsule.IGenericTaskCapsule;
import org.openmole.core.model.data.IPrototype;
import org.openmole.core.model.domain.IDomain;
import org.openmole.core.model.plan.IFactor;
import org.openmole.core.model.task.IExplorationTask;
import org.openmole.core.model.task.ITask;
import org.openmole.commons.exception.InternalProcessingError;
import org.openmole.commons.exception.UserBadDataError;
import org.openmole.core.implementation.task.ExplorationTask;
import static org.openmole.ui.plugin.transitionfactory.TransitionFactory.buildChain;
import org.openmole.core.implementation.mole.FixedEnvironmentStrategy;
public class Builder {
public IPrototype buildPrototype(String name, Class type) {
return new Prototype(name, type);
}
public DataSet buildDataSet(IPrototype...prototypes){
return new DataSet(prototypes);
}
public TaskCapsule buildTaskCapsule(ITask task) {
return new TaskCapsule(task);
}
public Mole buildMole(ITask... tasks) throws UserBadDataError, InternalProcessingError, InterruptedException {
return new Mole(buildChain(tasks).getFirstCapsule());
}
public Mole buildMole(IGenericTaskCapsule taskCapsule) throws UserBadDataError, InternalProcessingError, InterruptedException {
return new Mole(taskCapsule);
}
public FixedEnvironmentStrategy buildFixedEnvironmentStrategy() throws InternalProcessingError{
return new FixedEnvironmentStrategy();
}
public final ExplorationBuilder exploration = new ExplorationBuilder();
public class ExplorationBuilder {
public IFactor buildFactor(IPrototype prototype, IDomain domain) {
return new Factor(prototype, domain);
}
public IExplorationTask buildExplorationTask(String name,IPlan plan) throws UserBadDataError, InternalProcessingError{
return new ExplorationTask(name,plan);
}
public ExplorationTaskCapsule buildExplorationTaskCapsule(IExplorationTask task) {
return new ExplorationTaskCapsule(task);
}
public TaskCapsule buildExplorationTransition(IExplorationTaskCapsule explorationCapsule, ITask exploredTask) {
TaskCapsule exploredCapsule = new TaskCapsule(exploredTask);
new ExplorationTransition(explorationCapsule, exploredCapsule);
return exploredCapsule;
}
}
public final StructureBuilder structure = new StructureBuilder();
public class StructureBuilder {
public PrototypeNode buildPrototypeNode(String name, Class type) {
return new PrototypeNode(new Prototype(name, type));
}
public ComplexNode buildComplexNode(String name) {
return new ComplexNode(name);
}
public ComplexNode buildComplexNode(String name, ComplexNode parent) {
return new ComplexNode(name, parent);
}
}
} |
package checker.framework.errorcentric.view.views;
import java.util.Set;
import org.eclipse.core.commands.operations.IOperationHistory;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;
import checker.framework.change.propagator.ActionableMarkerResolution;
import checker.framework.change.propagator.ShadowProject;
import checker.framework.change.propagator.ShadowProjectFactory;
import checker.framework.errorcentric.propagator.commands.InferCommandHandler;
import checker.framework.errorcentric.propagator.commands.InferNullnessCommandHandler;
import checker.framework.errorcentric.view.Activator;
import checker.framework.quickfixes.descriptors.Fixer;
import com.google.common.base.Optional;
/**
* This sample class demonstrates how to plug-in a new workbench view. The view
* shows data obtained from the model. The sample creates a dummy model on the
* fly, but a real implementation would connect to the model available either in
* this or another plug-in (e.g. the workspace). The view is connected to the
* model using a content provider.
* <p>
* The view uses a label provider to define how model objects should be
* presented in the view. Each view can present the same model objects using
* different labels and icons, if needed. Alternatively, a single label provider
* can be shared between views in order to ensure that objects of the same type
* are presented in the same way everywhere.
* <p>
*/
public class ErrorCentricView extends ViewPart implements TreeUpdater {
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "checker.framework.errorcentric.view.views.ErrorCentricView";
private TreeViewer viewer;
private DrillDownAdapter drillDownAdapter;
private Action refreshAction;
private Action doubleClickAction;
private TreeObject invisibleRoot;
private IJavaProject javaProject;
private ChangeUndoRedoSupporter changeUndoRedoSupporter;
private ChangeStateViewer changeStateViewer;
/**
* The constructor.
*/
public ErrorCentricView() {
}
private TreeObject initializeInput() {
invisibleRoot = new TreeObject("");
if (InferCommandHandler.checkerID == null) {
return null;
}
if (!InferCommandHandler.selectedJavaProject.isPresent()) {
return null;
}
javaProject = InferCommandHandler.selectedJavaProject.get();
ShadowProject shadowProject = new ShadowProjectFactory(javaProject)
.get();
shadowProject.runChecker(InferCommandHandler.checkerID);
Set<ActionableMarkerResolution> resolutions = shadowProject
.getResolutions();
invisibleRoot.addChildren(AddedErrorTreeNode.createTreeNodesFrom(
resolutions, this));
return invisibleRoot;
}
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
public void createPartControl(Composite parent) {
viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
drillDownAdapter = new DrillDownAdapter(viewer);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setSorter(new NameSorter());
viewer.setInput(initializeInput());
viewer.getTree().setLinesVisible(true);
makeActions();
hookContextMenu();
hookDoubleClickAction();
hookSelectionAction();
contributeToActionBars();
changeStateViewer = new ChangeStateViewer(viewer);
initializeChangeUndoRedoSupporter();
}
private void initializeChangeUndoRedoSupporter() {
IWorkbench workbench = getSite().getWorkbenchWindow().getWorkbench();
IOperationHistory operationHistory = workbench.getOperationSupport()
.getOperationHistory();
changeUndoRedoSupporter = new ChangeUndoRedoSupporter(operationHistory,
changeStateViewer);
changeUndoRedoSupporter.initialize();
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
ErrorCentricView.this.fillContextMenu(manager);
}
});
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, viewer);
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(refreshAction);
}
private void fillContextMenu(IMenuManager manager) {
manager.add(refreshAction);
manager.add(new Separator());
drillDownAdapter.addNavigationActions(manager);
// Other plug-ins can contribute there actions here
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(refreshAction);
manager.add(new Separator());
drillDownAdapter.addNavigationActions(manager);
}
private void makeActions() {
refreshAction = new Action() {
public void run() {
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(initializeInput());
}
};
refreshAction.setText("Refresh");
refreshAction.setToolTipText("Recomputes the error/change tree.");
refreshAction.setImageDescriptor(ImageDescriptor
.createFromImage(Activator.getImageDescriptor(
"icons/refresh.gif").createImage()));
doubleClickAction = new Action() {
public void run() {
Optional<TreeObject> selectedTreeObject = getSelectedTreeObject(viewer
.getSelection());
if (selectedTreeObject.isPresent()
&& changeStateViewer.isDisabled(selectedTreeObject
.get())) {
return;
}
Optional<MarkerResolutionTreeNode> resolution = getSelectedMarkResolution(selectedTreeObject);
if (resolution.isPresent()) {
final MarkerResolutionTreeNode resolutionTreeNode = resolution
.get();
Job job = new Job("Applying resolution") {
@Override
protected IStatus run(IProgressMonitor monitor) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
changeUndoRedoSupporter
.applyUndoableChange(resolutionTreeNode);
}
});
return Status.OK_STATUS;
}
};
job.setRule(ResourcesPlugin.getWorkspace().getRoot());
job.setPriority(Job.INTERACTIVE);
job.schedule();
}
Optional<ErrorTreeNode> error = getSelectedError(selectedTreeObject);
if (error.isPresent()) {
ErrorTreeNode errorTreeNode = error.get();
errorTreeNode.reveal();
}
}
};
}
private Optional<MarkerResolutionTreeNode> getSelectedMarkResolution(
Optional<TreeObject> optionalTreeObject) {
Optional<MarkerResolutionTreeNode> optionalMarkerTreeNode = Optional
.absent();
if (optionalTreeObject.isPresent()) {
if (optionalTreeObject.isPresent()) {
TreeObject treeObject = optionalTreeObject.get();
if (treeObject instanceof MarkerResolutionTreeNode) {
optionalMarkerTreeNode = Optional
.of((MarkerResolutionTreeNode) treeObject);
}
}
}
return optionalMarkerTreeNode;
}
private Optional<ErrorTreeNode> getSelectedError(
Optional<TreeObject> optionalTreeObject) {
Optional<ErrorTreeNode> optionalMarkerTreeNode = Optional.absent();
if (optionalTreeObject.isPresent()) {
if (optionalTreeObject.isPresent()) {
TreeObject treeObject = optionalTreeObject.get();
if (treeObject instanceof ErrorTreeNode) {
optionalMarkerTreeNode = Optional
.of((ErrorTreeNode) treeObject);
}
}
}
return optionalMarkerTreeNode;
}
private Optional<TreeObject> getSelectedTreeObject(ISelection selection) {
Object selectedObject = ((IStructuredSelection) selection)
.getFirstElement();
if (selectedObject instanceof TreeObject) {
return Optional.of((TreeObject) selectedObject);
}
return Optional.absent();
}
private void hookDoubleClickAction() {
viewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
doubleClickAction.run();
}
});
}
private void hookSelectionAction() {
viewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
Optional<TreeObject> selectedTreeObject = getSelectedTreeObject(event
.getSelection());
if (selectedTreeObject.isPresent()) {
if (changeStateViewer.isDisabled(selectedTreeObject.get())) {
return;
}
Optional<MarkerResolutionTreeNode> optionalResolution = getSelectedMarkResolution(selectedTreeObject);
if (optionalResolution.isPresent()) {
MarkerResolutionTreeNode resolutionTreeNode = optionalResolution
.get();
IJavaProject javaProject = InferNullnessCommandHandler.selectedJavaProject
.get();
Fixer fixer = resolutionTreeNode.getResolution()
.createFixer(javaProject);
selectAndReveal(fixer);
viewer.setLabelProvider(new DecoratingLabelProvider(
new ViewLabelProvider(),
new FixedErrorDecorator(resolutionTreeNode)));
} else {
viewer.setLabelProvider(new ViewLabelProvider());
}
}
}
private void selectAndReveal(Fixer fixer) {
new CodeSnippetRevealer().reveal(fixer.getCompilationUnit(),
fixer.getOffset(), fixer.getLength());
}
});
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
viewer.getControl().setFocus();
}
@Override
public void update(final TreeObject node) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
viewer.refresh();
}
});
}
} |
package com.opengamma.financial.analytics.model.forex.option.black;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.time.calendar.Clock;
import javax.time.calendar.ZonedDateTime;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.option.definition.ForexOptionDataBundle;
import com.opengamma.analytics.financial.model.option.definition.SmileDeltaTermStructureDataBundle;
import com.opengamma.analytics.financial.model.option.definition.YieldCurveWithBlackForexTermStructureBundle;
import com.opengamma.analytics.financial.model.volatility.curve.BlackForexTermStructureParameters;
import com.opengamma.analytics.financial.model.volatility.surface.SmileDeltaTermStructureParametersStrikeInterpolation;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.AbstractFunction;
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.ValueProperties;
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.analytics.conversion.ForexSecurityConverter;
import com.opengamma.financial.analytics.model.InstrumentTypeProperties;
import com.opengamma.financial.analytics.model.InterpolatedDataProperties;
import com.opengamma.financial.analytics.model.forex.ForexVisitors;
import com.opengamma.financial.currency.CurrencyPair;
import com.opengamma.financial.currency.CurrencyPairs;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.financial.security.option.FXDigitalOptionSecurity;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXDigitalOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.UnorderedCurrencyPair;
import com.opengamma.util.tuple.ObjectsPair;
import com.opengamma.util.tuple.Pair;
public abstract class FXOptionBlackFunction extends AbstractFunction.NonCompiledInvoker {
/** The name of the calculation method */
public static final String BLACK_METHOD = "BlackMethod";
/** Property name for the put curve */
public static final String PUT_CURVE = "PutCurve";
/** Property name for the call curve */
public static final String CALL_CURVE = "CallCurve";
/** Property name for the put curve calculation configuration */
public static final String PUT_CURVE_CALC_CONFIG = "PutCurveCalculationConfig";
/** Property name for the receive curve calculation configuration */
public static final String CALL_CURVE_CALC_CONFIG = "CallCurveCalculationConfig";
private final String _valueRequirementName;
public FXOptionBlackFunction(final String valueRequirementName) {
ArgumentChecker.notNull(valueRequirementName, "value requirement name");
_valueRequirementName = valueRequirementName;
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
final Clock snapshotClock = executionContext.getValuationClock();
final ZonedDateTime now = snapshotClock.zonedDateTime();
final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
final ValueRequirement desiredValue = desiredValues.iterator().next();
final String putCurveName = desiredValue.getConstraint(PUT_CURVE);
final String callCurveName = desiredValue.getConstraint(CALL_CURVE);
final String surfaceName = desiredValue.getConstraint(ValuePropertyNames.SURFACE);
final String putCurveConfig = desiredValue.getConstraint(PUT_CURVE_CALC_CONFIG);
final String callCurveConfig = desiredValue.getConstraint(CALL_CURVE_CALC_CONFIG);
final String interpolatorName = desiredValue.getConstraint(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
final String leftExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
final String rightExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
final Object baseQuotePairsObject = inputs.getValue(ValueRequirementNames.CURRENCY_PAIRS);
if (baseQuotePairsObject == null) {
throw new OpenGammaRuntimeException("Could not get base/quote pair data");
}
final CurrencyPairs baseQuotePairs = (CurrencyPairs) baseQuotePairsObject;
final String fullPutCurveName = putCurveName + "_" + putCurrency.getCode();
final String fullCallCurveName = callCurveName + "_" + callCurrency.getCode();
final YieldAndDiscountCurve putFundingCurve = getCurve(inputs, putCurrency, putCurveName, putCurveConfig);
final YieldAndDiscountCurve callFundingCurve = getCurve(inputs, callCurrency, callCurveName, callCurveConfig);
final YieldAndDiscountCurve[] curves;
final Map<String, Currency> curveCurrency = new HashMap<String, Currency>();
curveCurrency.put(fullPutCurveName, putCurrency);
curveCurrency.put(fullCallCurveName, callCurrency);
final InstrumentDefinition<?> definition = security.accept(new ForexSecurityConverter(baseQuotePairs));
final String[] allCurveNames;
final Currency ccy1;
final Currency ccy2;
final Object spotObject = inputs.getValue(ValueRequirementNames.SPOT_RATE);
if (spotObject == null) {
throw new OpenGammaRuntimeException("Could not get spot requirement");
}
final double spot = (Double) spotObject;
final CurrencyPair baseQuotePair = baseQuotePairs.getCurrencyPair(putCurrency, callCurrency);
if (baseQuotePair == null) {
throw new OpenGammaRuntimeException("Could not get base/quote pair for currency pair (" + putCurrency + ", " + callCurrency + ")");
}
if (baseQuotePair.getBase().equals(putCurrency)) { // To get Base/quote in market standard order.
ccy1 = putCurrency;
ccy2 = callCurrency;
curves = new YieldAndDiscountCurve[] {putFundingCurve, callFundingCurve};
allCurveNames = new String[] {fullPutCurveName, fullCallCurveName};
} else {
curves = new YieldAndDiscountCurve[] {callFundingCurve, putFundingCurve};
allCurveNames = new String[] {fullCallCurveName, fullPutCurveName};
ccy1 = callCurrency;
ccy2 = putCurrency;
}
final InstrumentDerivative fxOption = definition.toDerivative(now, allCurveNames);
final YieldCurveBundle yieldCurves = new YieldCurveBundle(allCurveNames, curves);
final ValueRequirement fxVolatilitySurfaceRequirement = getSurfaceRequirement(surfaceName, putCurrency, callCurrency, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
final Object volatilitySurfaceObject = inputs.getValue(fxVolatilitySurfaceRequirement);
if (volatilitySurfaceObject == null) {
throw new OpenGammaRuntimeException("Could not get " + fxVolatilitySurfaceRequirement);
}
final FXMatrix fxMatrix = new FXMatrix(ccy1, ccy2, spot);
final ValueProperties.Builder properties = getResultProperties(target, desiredValue, baseQuotePair);
final ValueSpecification spec = new ValueSpecification(getValueRequirementName(), target.toSpecification(), properties.get());
final YieldCurveBundle curvesWithFX = new YieldCurveBundle(fxMatrix, curveCurrency, yieldCurves.getCurvesMap());
final ObjectsPair<Currency, Currency> currencyPair = Pair.of(ccy1, ccy2);
if (volatilitySurfaceObject instanceof SmileDeltaTermStructureParametersStrikeInterpolation) {
final SmileDeltaTermStructureParametersStrikeInterpolation smiles = (SmileDeltaTermStructureParametersStrikeInterpolation) volatilitySurfaceObject;
final SmileDeltaTermStructureDataBundle smileBundle = new SmileDeltaTermStructureDataBundle(curvesWithFX, smiles, currencyPair);
return getResult(fxOption, smileBundle, target, desiredValues, inputs, spec, executionContext);
}
final BlackForexTermStructureParameters termStructure = (BlackForexTermStructureParameters) volatilitySurfaceObject;
final YieldCurveWithBlackForexTermStructureBundle flatData = new YieldCurveWithBlackForexTermStructureBundle(curvesWithFX, termStructure, currencyPair);
return getResult(fxOption, flatData, target, desiredValues, inputs, spec, executionContext);
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.SECURITY;
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
if (target.getType() != ComputationTargetType.SECURITY) {
return false;
}
return target.getSecurity() instanceof FXOptionSecurity
|| target.getSecurity() instanceof FXBarrierOptionSecurity
|| target.getSecurity() instanceof FXDigitalOptionSecurity
|| target.getSecurity() instanceof NonDeliverableFXOptionSecurity
|| target.getSecurity() instanceof NonDeliverableFXDigitalOptionSecurity;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties.Builder properties = getResultProperties(target);
return Collections.singleton(new ValueSpecification(getValueRequirementName(), target.toSpecification(), properties.get()));
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> putCurveNames = constraints.getValues(PUT_CURVE);
if (putCurveNames == null || putCurveNames.size() != 1) {
return null;
}
final Set<String> callCurveNames = constraints.getValues(CALL_CURVE);
if (callCurveNames == null || callCurveNames.size() != 1) {
return null;
}
final Set<String> putCurveCalculationConfigs = constraints.getValues(PUT_CURVE_CALC_CONFIG);
if (putCurveCalculationConfigs == null || putCurveCalculationConfigs.size() != 1) {
return null;
}
final Set<String> callCurveCalculationConfigs = constraints.getValues(CALL_CURVE_CALC_CONFIG);
if (callCurveCalculationConfigs == null || callCurveCalculationConfigs.size() != 1) {
return null;
}
final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
if (surfaceNames == null || surfaceNames.size() != 1) {
return null;
}
final Set<String> interpolatorNames = constraints.getValues(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
if (interpolatorNames == null || interpolatorNames.size() != 1) {
return null;
}
final Set<String> leftExtrapolatorNames = constraints.getValues(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
if (leftExtrapolatorNames == null || leftExtrapolatorNames.size() != 1) {
return null;
}
final Set<String> rightExtrapolatorNames = constraints.getValues(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
if (rightExtrapolatorNames == null || rightExtrapolatorNames.size() != 1) {
return null;
}
final String putCurveName = putCurveNames.iterator().next();
final String callCurveName = callCurveNames.iterator().next();
final String putCurveCalculationConfig = putCurveCalculationConfigs.iterator().next();
final String callCurveCalculationConfig = callCurveCalculationConfigs.iterator().next();
final String surfaceName = surfaceNames.iterator().next();
final String interpolatorName = interpolatorNames.iterator().next();
final String leftExtrapolatorName = leftExtrapolatorNames.iterator().next();
final String rightExtrapolatorName = rightExtrapolatorNames.iterator().next();
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
final ValueRequirement putFundingCurve = getCurveRequirement(putCurveName, putCurrency, putCurveCalculationConfig);
final ValueRequirement callFundingCurve = getCurveRequirement(callCurveName, callCurrency, callCurveCalculationConfig);
final ValueRequirement fxVolatilitySurface = getSurfaceRequirement(surfaceName, putCurrency, callCurrency, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(putCurrency, callCurrency);
final ValueRequirement spotRequirement = new ValueRequirement(ValueRequirementNames.SPOT_RATE, currencyPair);
final ValueRequirement pairQuoteRequirement = new ValueRequirement(ValueRequirementNames.CURRENCY_PAIRS, ComputationTargetType.PRIMITIVE, currencyPair.getUniqueId());
return Sets.newHashSet(putFundingCurve, callFundingCurve, fxVolatilitySurface, spotRequirement, pairQuoteRequirement);
}
protected abstract ValueProperties.Builder getResultProperties(final ComputationTarget target);
protected abstract ValueProperties.Builder getResultProperties(final ComputationTarget target, final ValueRequirement desiredValue, final CurrencyPair baseQuotePair);
//TODO clumsy. Push the execute() method down into the functions and have getDerivative() and getData() methods
protected abstract Set<ComputedValue> getResult(final InstrumentDerivative forex, final ForexOptionDataBundle<?> data, final ComputationTarget target,
final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final ValueSpecification spec, final FunctionExecutionContext executionContext);
protected static ValueRequirement getCurveRequirement(final String curveName, final Currency currency, final String curveCalculationConfigName) {
final ValueProperties.Builder properties = ValueProperties.builder()
.with(ValuePropertyNames.CURVE, curveName)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName);
return new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetType.PRIMITIVE, currency.getUniqueId(), properties.get());
}
protected static ValueRequirement getSurfaceRequirement(final String surfaceName, final Currency putCurrency, final Currency callCurrency,
final String interpolatorName, final String leftExtrapolatorName, final String rightExtrapolatorName) {
final ValueProperties surfaceProperties = ValueProperties.builder()
.with(ValuePropertyNames.SURFACE, surfaceName)
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName)
.get();
final UnorderedCurrencyPair currenciesTarget = UnorderedCurrencyPair.of(putCurrency, callCurrency);
return new ValueRequirement(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, currenciesTarget, surfaceProperties);
}
protected static YieldAndDiscountCurve getCurve(final FunctionInputs inputs, final Currency currency, final String curveName, final String curveCalculationConfig) {
final Object curveObject = inputs.getValue(getCurveRequirement(curveName, currency, curveCalculationConfig));
if (curveObject == null) {
throw new OpenGammaRuntimeException("Could not get " + curveName + " curve");
}
final YieldAndDiscountCurve curve = (YieldAndDiscountCurve) curveObject;
return curve;
}
protected final String getValueRequirementName() {
return _valueRequirementName;
}
} |
package org.batfish.question.filterlinereachability;
import static com.google.common.base.MoreObjects.firstNonNull;
import static org.batfish.common.bdd.PermitAndDenyBdds.takeDifferentActions;
import static org.batfish.question.filterlinereachability.FilterLineReachabilityRows.createMetadata;
import static org.batfish.question.filterlinereachability.FilterLineReachabilityUtils.getReferencedAcls;
import static org.batfish.question.filterlinereachability.FilterLineReachabilityUtils.getReferencedInterfaces;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDFactory;
import org.batfish.common.Answerer;
import org.batfish.common.NetworkSnapshot;
import org.batfish.common.bdd.BDDPacket;
import org.batfish.common.bdd.BDDSourceManager;
import org.batfish.common.bdd.IpAccessListToBdd;
import org.batfish.common.bdd.IpAccessListToBddImpl;
import org.batfish.common.bdd.PermitAndDenyBdds;
import org.batfish.common.plugin.IBatfish;
import org.batfish.common.util.CollectionUtil;
import org.batfish.datamodel.AclLine;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.ExprAclLine;
import org.batfish.datamodel.Interface;
import org.batfish.datamodel.IpAccessList;
import org.batfish.datamodel.LineAction;
import org.batfish.datamodel.acl.ActionGetter;
import org.batfish.datamodel.acl.CanonicalAcl;
import org.batfish.datamodel.acl.CircularReferenceException;
import org.batfish.datamodel.acl.FalseExpr;
import org.batfish.datamodel.acl.UndefinedReferenceException;
import org.batfish.datamodel.answers.AclSpecs;
import org.batfish.datamodel.questions.Question;
import org.batfish.datamodel.table.TableAnswerElement;
import org.batfish.specifier.FilterSpecifier;
import org.batfish.specifier.SpecifierContext;
/** Answers {@link FilterLineReachabilityQuestion}. */
@ParametersAreNonnullByDefault
public class FilterLineReachabilityAnswerer extends Answerer {
public FilterLineReachabilityAnswerer(Question question, IBatfish batfish) {
super(question, batfish);
}
@Override
public TableAnswerElement answer(NetworkSnapshot snapshot) {
FilterLineReachabilityQuestion question = (FilterLineReachabilityQuestion) _question;
FilterLineReachabilityRows answerRows = new FilterLineReachabilityRows();
SpecifierContext ctxt = _batfish.specifierContext(snapshot);
Map<String, Set<IpAccessList>> specifiedAcls = getSpecifiedFilters(question, ctxt);
SortedMap<String, Configuration> configurations = _batfish.loadConfigurations(snapshot);
List<AclSpecs> aclSpecs = getAclSpecs(configurations, specifiedAcls, answerRows);
answerAclReachability(aclSpecs, answerRows);
TableAnswerElement answer = new TableAnswerElement(createMetadata(question));
answer.postProcessAnswer(question, answerRows.getRows());
return answer;
}
private static final class AclNode {
private final class Dependency {
public final AclNode dependency;
public final Set<Integer> lineNums = new TreeSet<>();
public Dependency(AclNode dependency, int lineNum) {
this.dependency = dependency;
lineNums.add(lineNum);
}
}
private final IpAccessList _acl;
private final Set<Integer> _linesWithUndefinedRefs = new TreeSet<>();
private final Set<Integer> _linesInCycles = new TreeSet<>();
private final List<Dependency> _dependencies = new ArrayList<>();
private final Set<String> _interfaces = new TreeSet<>();
private IpAccessList _sanitizedAcl;
private List<AclLine> _sanitizedLines;
public AclNode(IpAccessList acl) {
_acl = acl;
}
/**
* Replaces match expr of the line at the given {@code lineNum} with a {@link FalseExpr}. Used
* to ignore lines with undefined or cyclic references.
*/
public void markLineUnmatchable(int lineNum) {
_sanitizedLines = firstNonNull(_sanitizedLines, new ArrayList<>(_acl.getLines()));
AclLine originalLine = _sanitizedLines.remove(lineNum);
// If the original line has a concrete action, preserve it; otherwise default to DENY
LineAction unmatchableLineAction =
firstNonNull(ActionGetter.getAction(originalLine), LineAction.DENY);
_sanitizedLines.add(
lineNum,
ExprAclLine.builder()
.setName(originalLine.getName())
.setMatchCondition(FalseExpr.INSTANCE)
.setAction(unmatchableLineAction)
.build());
}
public void sanitizeLine(int lineNum, AclLine sanitizedLine) {
_sanitizedLines = firstNonNull(_sanitizedLines, new ArrayList<>(_acl.getLines()));
_sanitizedLines.remove(lineNum);
_sanitizedLines.add(lineNum, sanitizedLine);
}
public void sanitizeCycle(ImmutableList<String> cycleAcls) {
// Remove previous ACL from referencing ACLs
int aclIndex = cycleAcls.indexOf(_acl.getName());
int cycleSize = cycleAcls.size();
// Remove next ACL from dependencies, and record line numbers that reference dependency
String nextAclName = cycleAcls.get((aclIndex + 1) % cycleSize);
int dependencyIndex = 0;
while (!_dependencies.get(dependencyIndex).dependency.getName().equals(nextAclName)) {
dependencyIndex++;
}
for (int lineNum : _dependencies.remove(dependencyIndex).lineNums) {
_linesInCycles.add(lineNum);
markLineUnmatchable(lineNum);
}
}
public List<AclNode> getDependencies() {
return _dependencies.stream().map(d -> d.dependency).collect(Collectors.toList());
}
public Map<String, IpAccessList> getFlatDependencies() {
Map<String, IpAccessList> ret = new TreeMap<>();
for (Dependency d : _dependencies) {
ret.put(d.dependency.getName(), d.dependency._sanitizedAcl);
ret.putAll(d.dependency.getFlatDependencies());
}
return ret;
}
public Set<String> getInterfaceDependencies() {
Set<String> interfaceDependencies = new TreeSet<>(_interfaces);
for (Dependency d : _dependencies) {
interfaceDependencies.addAll(d.dependency.getInterfaceDependencies());
}
return interfaceDependencies;
}
public void addDependency(AclNode dependency, int lineNum) {
for (Dependency d : _dependencies) {
if (d.dependency.getName().equals(dependency.getName())) {
d.lineNums.add(lineNum);
return;
}
}
_dependencies.add(new Dependency(dependency, lineNum));
}
public void addInterfaces(Set<String> newInterfaces) {
_interfaces.addAll(newInterfaces);
}
public void addUndefinedRef(int lineNum) {
_linesWithUndefinedRefs.add(lineNum);
markLineUnmatchable(lineNum);
}
public void buildSanitizedAcl() {
// If _sanitizedLines was never initialized, just use original ACL for sanitized ACL
_sanitizedAcl =
_sanitizedLines == null
? _acl
: IpAccessList.builder().setName(getName()).setLines(_sanitizedLines).build();
}
public IpAccessList getAcl() {
return _acl;
}
public Set<Integer> getLinesInCycles() {
return _linesInCycles;
}
public Set<Integer> getLinesWithUndefinedRefs() {
return _linesWithUndefinedRefs;
}
public IpAccessList getSanitizedAcl() {
return _sanitizedAcl;
}
public String getName() {
return _acl.getName();
}
}
private static void createAclNode(
IpAccessList acl,
Map<String, AclNode> aclNodeMap,
Map<String, IpAccessList> acls,
HeaderSpaceSanitizer headerSpaceSanitizer,
Set<String> nodeInterfaces) {
// Create ACL node for current ACL
AclNode node = new AclNode(acl);
aclNodeMap.put(acl.getName(), node);
// Go through lines and add dependencies
int index = 0;
for (AclLine line : acl.getLines()) {
boolean lineMarkedUnmatchable = false;
// Find all references to other ACLs and record them
Set<String> referencedAcls = getReferencedAcls(line);
if (!referencedAcls.isEmpty()) {
if (!acls.keySet().containsAll(referencedAcls)) {
// Not all referenced ACLs exist. Mark line as unmatchable.
node.addUndefinedRef(index);
lineMarkedUnmatchable = true;
} else {
for (String referencedAclName : referencedAcls) {
AclNode referencedAclNode = aclNodeMap.get(referencedAclName);
if (referencedAclNode == null) {
// Referenced ACL not yet recorded; recurse on it
createAclNode(
acls.get(referencedAclName),
aclNodeMap,
acls,
headerSpaceSanitizer,
nodeInterfaces);
referencedAclNode = aclNodeMap.get(referencedAclName);
}
// Referenced ACL has now been recorded; add dependency
node.addDependency(referencedAclNode, index);
}
}
}
// Dereference all IpSpace references, or mark line unmatchable if it has invalid references
if (!lineMarkedUnmatchable) {
try {
AclLine sanitizedForIpSpaces = headerSpaceSanitizer.visit(line);
if (!line.equals(sanitizedForIpSpaces)) {
node.sanitizeLine(index, sanitizedForIpSpaces);
}
} catch (CircularReferenceException | UndefinedReferenceException e) {
// Line contains invalid IpSpaceReference: undefined or part of a circular reference chain
node.addUndefinedRef(index);
lineMarkedUnmatchable = true;
}
}
// Find all references to interfaces and ensure they exist
if (!lineMarkedUnmatchable) {
Set<String> referencedInterfaces = getReferencedInterfaces(line);
if (!nodeInterfaces.containsAll(referencedInterfaces)) {
// Line references an undefined source interface. Report undefined ref.
node.addUndefinedRef(index);
} else {
node.addInterfaces(referencedInterfaces);
}
}
index++;
}
}
private static List<ImmutableList<String>> sanitizeNode(
AclNode node, List<AclNode> visited, Set<String> sanitized, Map<String, AclNode> aclNodeMap) {
// Mark starting node as visited
visited.add(node);
// Create set to hold cycles found
List<ImmutableList<String>> cyclesFound = new ArrayList<>();
// Go through dependencies (each ACL this one depends on will only appear as one dependency)
for (AclNode dependency : node.getDependencies()) {
if (sanitized.contains(dependency.getName())) {
// We've already checked out the dependency. It must not be in a cycle with current ACL.
continue;
}
int dependencyIndex = visited.indexOf(dependency);
if (dependencyIndex != -1) {
// Found a new cycle.
ImmutableList<String> cycleAcls =
ImmutableList.copyOf(
visited.subList(dependencyIndex, visited.size()).stream()
.map(AclNode::getName)
.collect(Collectors.toList()));
cyclesFound.add(cycleAcls);
} else {
// No cycle found; recurse on dependency to see if there is a cycle farther down.
cyclesFound.addAll(
sanitizeNode(aclNodeMap.get(dependency.getName()), visited, sanitized, aclNodeMap));
}
}
// Remove current node from visited list
visited.remove(node);
// Record found cycles in this node.
for (ImmutableList<String> cycleAcls : cyclesFound) {
int indexOfThisAcl = cycleAcls.indexOf(node.getName());
if (indexOfThisAcl != -1) {
node.sanitizeCycle(cycleAcls);
}
}
// Now that all cycles are recorded, never explore this node again, and sanitize its ACL.
node.buildSanitizedAcl();
sanitized.add(node.getName());
return cyclesFound;
}
/**
* Collects the list of specified filters that we need to process, based on the nodes desired, the
* filters desired, and whether generated filters are ignored
*/
static Map<String, Set<IpAccessList>> getSpecifiedFilters(
FilterLineReachabilityQuestion question, SpecifierContext ctxt) {
Set<String> specifiedNodes = question.nodeSpecifier().resolve(ctxt);
FilterSpecifier filterSpecifier = question.getFilterSpecifier();
return CollectionUtil.toImmutableMap(
specifiedNodes,
Function.identity(),
node ->
filterSpecifier.resolve(node, ctxt).stream()
.filter(f -> !(question.getIgnoreComposites() && f.isComposite()))
.collect(ImmutableSet.toImmutableSet()));
}
/**
* Generates the list of {@link AclSpecs} objects to analyze in preparation for some ACL
* reachability question. Besides returning the {@link AclSpecs}, this method adds cycle results
* to the answer and provides sanitized {@link IpAccessList}s without cycles, undefined
* references, or dependence on named IP spaces.
*
* @param configurations Mapping of all hostnames to their {@link Configuration}s
* @param specifiedAcls Specified ACLs to canonicalize, indexed by hostname.
* @param answer Answer for ACL reachability question for which these {@link AclSpecs} are being
* generated
* @return List of {@link AclSpecs} objects to analyze for an ACL reachability question with the
* given specified nodes and ACL regex.
*/
@VisibleForTesting
public static List<AclSpecs> getAclSpecs(
SortedMap<String, Configuration> configurations,
Map<String, Set<IpAccessList>> specifiedAcls,
FilterLineReachabilityRows answer) {
List<AclSpecs.Builder> aclSpecs = new ArrayList<>();
/*
- For each ACL, build a CanonicalAcl structure with that ACL and referenced ACLs & interfaces
- Deal with any references to undefined ACLs, IpSpaces, or interfaces
- Deal with any cycles in ACL references
*/
for (String hostname : configurations.keySet()) {
if (specifiedAcls.containsKey(hostname)) {
Configuration c = configurations.get(hostname);
Set<IpAccessList> acls = specifiedAcls.get(hostname);
HeaderSpaceSanitizer headerSpaceSanitizer = new HeaderSpaceSanitizer(c.getIpSpaces());
Map<String, Interface> nodeInterfaces = c.getAllInterfaces();
// Build graph of AclNodes containing pointers to dependencies and referencing nodes
Map<String, AclNode> aclNodeMap = new TreeMap<>();
for (IpAccessList acl : acls) {
String aclName = acl.getName();
if (!aclNodeMap.containsKey(aclName)) {
createAclNode(
acl,
aclNodeMap,
c.getIpAccessLists(),
headerSpaceSanitizer,
nodeInterfaces.keySet());
}
}
// Sanitize nodes in graph (finds all cycles, creates sanitized versions of IpAccessLists)
Set<String> sanitizedAcls = new TreeSet<>();
for (AclNode node : aclNodeMap.values()) {
if (!sanitizedAcls.contains(node.getName())) {
List<ImmutableList<String>> cycles =
sanitizeNode(node, new ArrayList<>(), sanitizedAcls, aclNodeMap);
for (ImmutableList<String> cycleAcls : cycles) {
answer.addCycle(hostname, cycleAcls);
}
}
}
// For each ACL specified by aclRegex, create a CanonicalAcl with its dependencies
for (IpAccessList acl : acls) {
String aclName = acl.getName();
AclNode node = aclNodeMap.get(aclName);
// Finalize interfaces. If ACL references all interfaces on the device, keep interfaces
// list as-is; otherwise, add one extra interface to represent the "unreferenced
// interface not originating from router" possibility. Needs to have a name different
// from any referenced interface.
Set<String> referencedInterfaces = node.getInterfaceDependencies();
if (referencedInterfaces.size() < nodeInterfaces.size()) {
// At least one interface was not referenced by the ACL. Represent that option.
String unreferencedIfaceName = "unreferencedInterface";
int n = 0;
while (referencedInterfaces.contains(unreferencedIfaceName)) {
unreferencedIfaceName = "unreferencedInterface" + n;
n++;
}
referencedInterfaces = new TreeSet<>(referencedInterfaces);
referencedInterfaces.add(unreferencedIfaceName);
}
CanonicalAcl currentAcl =
new CanonicalAcl(
node.getSanitizedAcl(),
node.getAcl(),
node.getFlatDependencies(),
referencedInterfaces,
node.getLinesWithUndefinedRefs(),
node.getLinesInCycles());
// If an identical ACL exists, add current hostname/aclName pair; otherwise, add new ACL
boolean added = false;
for (AclSpecs.Builder aclSpec : aclSpecs) {
if (aclSpec.getAcl().equals(currentAcl)) {
aclSpec.addSource(hostname, aclName);
added = true;
break;
}
}
if (!added) {
aclSpecs.add(AclSpecs.builder().setAcl(currentAcl).addSource(hostname, aclName));
}
}
}
}
return aclSpecs.stream().map(AclSpecs.Builder::build).collect(Collectors.toList());
}
private static class LineAndWeight {
private final int _line;
private final double _weight;
public LineAndWeight(int line, double weight) {
_line = line;
_weight = weight;
}
private int getLine() {
return _line;
}
private double getWeight() {
return _weight;
}
private static final Comparator<LineAndWeight> COMPARATOR =
Comparator.comparing(LineAndWeight::getWeight)
.reversed()
.thenComparing(LineAndWeight::getLine);
}
/**
* Info about how some ACL line is blocked: which lines block it and whether any of them treat any
* packet differently than the blocked line would
*/
public static class BlockingProperties {
@Nonnull private final SortedSet<Integer> _blockingLineNums;
private final boolean _diffAction;
public BlockingProperties(@Nonnull SortedSet<Integer> blockingLineNums, boolean diffAction) {
_blockingLineNums = blockingLineNums;
_diffAction = diffAction;
}
@Nonnull
SortedSet<Integer> getBlockingLineNums() {
return _blockingLineNums;
}
/**
* If true, indicates that some packet that matches the blocked line would be treated
* differently by some blocking line. (Does not require that the packet be able to reach that
* blocking line.)
*/
boolean getDiffAction() {
return _diffAction;
}
}
@VisibleForTesting
static BlockingProperties findBlockingPropsForLine(
int blockedLineNum, List<PermitAndDenyBdds> bdds) {
PermitAndDenyBdds blockedLine = bdds.get(blockedLineNum);
ImmutableSortedSet.Builder<LineAndWeight> linesByWeight =
ImmutableSortedSet.orderedBy(LineAndWeight.COMPARATOR);
// First, we find all lines before blockedLine that actually terminate any packets
// blockedLine intends to. These, collectively, are the (partially-)blocking lines.
// In this same loop, we also compute the overlap of each such line with the blocked line
// and weight each blocking line by that overlap.
// Finally, we record whether any of these lines has a different action than the blocked line.
PermitAndDenyBdds restOfLine = blockedLine;
boolean diffAction = false; // true if some partially-blocking line has a different action.
for (int prevLineNum = 0; prevLineNum < blockedLineNum && !restOfLine.isZero(); prevLineNum++) {
PermitAndDenyBdds prevLine = bdds.get(prevLineNum);
if (!prevLine.getMatchBdd().andSat(restOfLine.getMatchBdd())) {
continue;
}
BDD blockedLineOverlap = prevLine.getMatchBdd().and(blockedLine.getMatchBdd());
linesByWeight.add(new LineAndWeight(prevLineNum, blockedLineOverlap.satCount()));
diffAction = diffAction || takeDifferentActions(prevLine, restOfLine);
restOfLine = restOfLine.diff(prevLine.getMatchBdd());
}
// In this second loop, we compute the answer:
// * include partially-blocking lines in weight order until the blocked line is fully blocked by
// this subset.
// * also include the largest blocking line with a different action than the blocked line, if
// not already in the above subset.
ImmutableSortedSet.Builder<Integer> answerLines = ImmutableSortedSet.naturalOrder();
restOfLine = blockedLine;
boolean needDiffAction = diffAction;
for (LineAndWeight line : linesByWeight.build()) {
int curLineNum = line.getLine();
PermitAndDenyBdds curLine = bdds.get(curLineNum);
boolean curDiff = takeDifferentActions(curLine, blockedLine);
// The original line is still not blocked, or this is the first line with a different action.
if (!restOfLine.isZero() || needDiffAction && curDiff) {
restOfLine = restOfLine.diff(curLine.getMatchBdd());
answerLines.add(curLineNum);
needDiffAction = needDiffAction && !curDiff;
}
// The original line is blocked and we have a line with a different action (if such exists).
if (restOfLine.isZero() && !needDiffAction) {
break;
}
}
return new BlockingProperties(answerLines.build(), diffAction);
}
public static void answerAclReachabilityLine(
AclSpecs aclSpec, BDDPacket bddPacket, FilterLineReachabilityRows answerRows) {
BDDFactory bddFactory = bddPacket.getFactory();
BDDSourceManager sourceMgr =
BDDSourceManager.forInterfaces(bddPacket, aclSpec.acl.getInterfaces());
IpAccessListToBdd ipAccessListToBdd =
new IpAccessListToBddImpl(
bddPacket, sourceMgr, aclSpec.acl.getDependencies(), ImmutableMap.of());
IpAccessList ipAcl = aclSpec.acl.getSanitizedAcl();
List<AclLine> lines = ipAcl.getLines();
/* Convert every line to permit and deny BDDs. */
List<PermitAndDenyBdds> ipLineToBDDMap =
lines.stream().map(ipAccessListToBdd::toPermitAndDenyBdds).collect(Collectors.toList());
/* Pass over BDDs to classify each as unmatchable, unreachable, or (implicitly) reachable. */
BDD unmatchedPackets = bddFactory.one(); // The packets that are not yet matched by the ACL.
ListIterator<PermitAndDenyBdds> lineIt = ipLineToBDDMap.listIterator();
while (lineIt.hasNext()) {
int lineNum = lineIt.nextIndex();
PermitAndDenyBdds lineBDDs = lineIt.next();
if (lineBDDs.isZero()) {
// This line is unmatchable
answerRows.addUnmatchableLine(aclSpec, lineNum);
} else if (unmatchedPackets.isZero() || !lineBDDs.getMatchBdd().andSat(unmatchedPackets)) {
// No unmatched packets in the ACL match this line, so this line is unreachable.
BlockingProperties blockingProps = findBlockingPropsForLine(lineNum, ipLineToBDDMap);
answerRows.addBlockedLine(aclSpec, lineNum, blockingProps);
}
unmatchedPackets = unmatchedPackets.diff(lineBDDs.getMatchBdd());
}
}
private static void answerAclReachability(
List<AclSpecs> aclSpecs, FilterLineReachabilityRows answerRows) {
BDDPacket bddPacket = new BDDPacket();
for (AclSpecs aclSpec : aclSpecs) {
answerAclReachabilityLine(aclSpec, bddPacket, answerRows);
}
}
} |
package gov.nih.nci.cabig.caaers.rules.business.service;
import gov.nih.nci.cabig.caaers.domain.AdverseEvent;
import gov.nih.nci.cabig.caaers.domain.AdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.Study;
/**
*
* @author vinaykumar
* The RulesEngineService is a facade for authoring, deploying
* and executing the rules
*/
public interface AdverseEventEvaluationService {
public String assesAdverseEvent(AdverseEvent ae, Study study) throws Exception;
//public String identifyAdverseEventType()
public String evaluateSAEReportSchedule(AdverseEventReport aeReport) throws Exception;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.